title: feather 32u4 servo

text:
# Question
Title: feather 32u4 servo
I am attempting a project where I use a feather 32u4 to control a servo. It is controlled using the buttons on an attached oled featherwing to set the servo to 3 different values. The code that was provided to me produces an error for this board. After messing with similar code, it appears the statement `#include <Servo.h>` produces an error. There is also a note in the messages about Wire.h but that appears to not be a problem any other time.

The error messages are as follows:

```
Arduino: 1.6.13 (Mac OS X), Board: "Adafruit Feather 32u4"

libraries/Servo/avr/Servo.cpp.o (symbol from plugin): In function `ServoCount':
(.text+0x0): multiple definition of `__vector_17'
libraries/RadioHead-master/RH_ASK.cpp.o (symbol from plugin):(.text+0x0): first defined here
collect2: error: ld returned 1 exit status
Multiple libraries were found for "Wire.h"
 Used: /Users/bsd194.lab102/Library/Arduino15/packages/adafruit/hardware/avr/1.4.13/libraries/Wire
 Not used: /Applications/Arduino.app/Contents/Java/hardware/arduino/avr/libraries/Wire
exit status 1
Error compiling for board Adafruit Feather 32u4.

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

```

I would attach the code but I don't know how to post it without it appearing oddly.

# Answer
The message `multiple definition of __vector_17` means, that in your code the interrupt vector 17 is defined multiple times. Often this happens, because 2 used libraries use the same hardware peripherals like the timers. Only one library can configure and use the hardware. If 2 try it, you get a compiler error.

On the Atmega32u4 the interrupt with number 17 is the TIMER1 CAPT (Capture interrupt of Timer1)(see the datasheet of the Atmega32u4, chapter "Interrupts"). The error message says, that the `Servo` library and the `RadioHead` library both define this interrupt. They both try to use the hardware Timer1.

The consequence is, that you cannot simply use these two libraries together. So what to do? This can get rather difficult. You could change one of the libraries to use a different timer (the Atmega32u4 has 4 timers). This may involve extensive changes (mostly changing the register names, but sometimes more complex changes, if the new timer is not the same type). Some libraries directly provide the possibility to use a different timer, but most don't. Fortunate for you, the `RadioHead` library provides a simple way to change the used timer to Timer2, tough you cannot simply do this, since on the 32u4 the next 16bit Timer is Timer3. This Adafruit forum thread mentions how to set the `RadioHead` library for Timer2 (by uncommenting the define `RH_ASK_ARDUINO_USE_TIMER2` in `RH_ASK.cpp`) and give a hint on how to then change to Timer3: Effectively by Changing all the `2`s in the timer register and bit names to `3`s. To be sure please check everytime, that the corresponding register/bit names really exist (you can see this in the register descriptions in the datasheet).
> 0 votes

---
Tags: servo, feather
---


title: serial data gets spoiled

text:
# Question
Title: serial data gets spoiled
I use this small program on my Raspberry Pi to recieve a string sent by my arduino.

```
import time
import serial

ser = serial.Serial('/dev/ttyACM0', 9600)

def check_for_command():
    bytestoread = ser.inWaiting()
    if bytestoread != 0:
        temp = ser.read(bytestoread)
        print(temp)

while 1:
    check_for_command()
    time.sleep(0.1)

```

the code on the arduino is rather simple:

```
void setup(){
Serial.begin(9600);
}

void loop(){
Serial.println(“Hello Pi”);
delay(2000);

```

the annoying part is. I recieve this:

> b'Hello Pi\r\n'

instead of the clean

> Hello Pi

How do I get rid of those extra bits without using a list for each character.

Thank in advance!

# Answer
The `b` prefix in Python 3 just means that it is a `bytes` literal. It's not part of the output, that's just telling you the type.

The `\r\n` is a common Carriage-Return and Newline line-ending characters. You can remove that from your string by calling `strip()`.

Since these are floating-point numbers being returned, I'm guessing you're going to want to use them in some way after they are read, too:

```
import serial

ser = serial.Serial('/dev/ttyACM0', 9600)
while True:
   value = float(ser.readline().strip())
   print('New value is {0:0.2f}'.format(value))

```

See also:
> 1 votes

# Answer
Use this line

```
temp = ser.readline(bytestoread).decode('ascii')

```

instead of

```
temp = ser.read(bytestoread)

```
> 0 votes

# Answer
As the bytes sent by Raspbian is encoded in UTF-8, use the following line in order to avoid a strip() at a later-on stage:

```
temp = ser.read(bytestoread).decode('utf-8')

```
> -1 votes

---
Tags: arduino-uno, serial, python, raspberrypi
---


# Question
Title: How will I display values from arduino to JTextArea (Java Netbeans)?
I want to display float values in JTextArea but it doesn't show any. It only displays on the systemout. Pls help me out. This is my Java code.

```
import jssc.SerialPort;
import jssc.SerialPortException;

    public ards() {
        initComponents();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jPanel1 = new javax.swing.JPanel();
        jButton1 = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();

        jLabel1.setText("jLabel1");

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jButton1.setText("jButton1");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jTextArea1.setEditable(false);
        jTextArea1.setColumns(20);
        jTextArea1.setRows(5);
        jScrollPane1.setViewportView(jTextArea1);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(319, 319, 319)
                        .addComponent(jButton1))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(154, 154, 154)
                        .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(140, 140, 140)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(157, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(74, 74, 74)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jButton1)
                .addGap(18, 18, 18)
                .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(94, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
         String str;

        //In the constructor pass the name of the port with which we work
        SerialPort serialPort = new SerialPort("COM6");

        try {
            //Open port
            serialPort.openPort();

            //We expose the settings. You can also use this line - serialPort.setParams(9600, 8, 1, 0);
            serialPort.setParams(SerialPort.BAUDRATE_9600,
                    SerialPort.DATABITS_8,
                    SerialPort.STOPBITS_1,
                    SerialPort.PARITY_NONE);

            Thread.sleep(1000);//Very important !!!

            //Read data from port
            for (int i = 0; i < 1000; i++) {
                str = serialPort.readString();

                if (str != null) {
                    System.out.println(str);
                   jTextArea1.setText(str);
                    jLabel2.setText(str);
                }

                Thread.sleep(500);
            }

            //Closing the port
            serialPort.closePort();

        } catch (SerialPortException ex) {
            System.out.println(ex);
        } catch (InterruptedException ex) {
            System.out.println(ex);
        }
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ards.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ards.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ards.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ards.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ards().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea jTextArea1;
    // End of variables declaration
}

```

And this is my Arduino code

```
const int model = 0;
void setup() {
Serial.begin(9600);
}

float sensitivity[] ={
0.185, // for ACS712ELCTR-05B-T
0.100, // for ACS712ELCTR-20A-T
0.066 // for ACS712ELCTR-30A-T } ;

void loop() {
static unsigned long count=0;
static float Vsum=0;
float Vave=0;
int volt = analogRead(A1);
float voltage= map(volt,0,1023, 0, 2500)/100.0;
Vsum=Vsum+voltage;

static float Csum=0;
float Cave=0;
 float milli = pow(10, -3);
 float current = (voltage / sensitivity[model]);
 float current1 = current*milli;
Csum=Csum+current1;
count++;
Vave=Vsum/count;
Cave=Csum/count;

Serial.print("Average voltage: ");
Serial.print(Vave,2);
Serial.println("V");
Serial.print("Average current: ");
Serial.print(Cave,3);
Serial.println("A");
Serial.println("-----");
delay(3000);

}

```

# Answer
In you code : str = serialPort.readString();

Change this as -\> str = serialPort.readStringUntil('\n');
> 1 votes

---
Tags: arduino-uno, display, java
---


# Question
Title: NodeMCU (ESP8266) Defining static IP, stops Firebase processing
Hello i am new to NodeMCU (ESP8266) i am building a small program to connect with WIFI (with internet) and if internet is not available i want to process request over IP address.

I am using firebase as a database / server to fetch the status. And process command through a URL like http://192.168.1.223/on?pin=04 if internet is connected then no problem i can update firebase entry, but with same network (LAN) connection over wifi i want to process i need to have static IP. But the concern is i am not able to make this IP address static, and if i make it static then my NodeMCU is not able to connect with firebase.

Here is how my code looks like:

```
#include <ESP8266WiFi.h>
#include <FirebaseArduino.h>
#include <ESP8266WebServer.h>

#define FIREBASE_HOST "pushst-56f2c.firebaseio.com"
#define FIREBASE_AUTH "mhBpzrNyhhwEGwmFxkVFTIEylwrXMw0gm"
#define PATH "/clients/devicename/watermotor"

IPAddress ip(192, 168, 1, 223);  //Node static IP
IPAddress dns(192, 168, 1, 223);
IPAddress gateway(192,168,1,1);
IPAddress subnet(255,255,255,0);

char ssid[] = "MyNetwork";
char password[] = "Qwert98!!";

int wifiStatus = WL_IDLE_STATUS;

ESP8266WebServer server(80);

void setup() {
      Serial.begin(115200);

      delay(100);
      Serial.println();
      Serial.println();
      Serial.print("Your are connecting to;");
      Serial.println(ssid);

      WiFi.begin(ssid, password);
      WiFi.config(ip, dns, gateway, subnet);

      while (WiFi.status() != WL_CONNECTED) {
        digitalWrite(WIFI_CONNECT_LED, HIGH);
        delay(500);
        Serial.print(".");
      }

      wifiStatus = WiFi.status();

      if(wifiStatus == WL_CONNECTED){
          digitalWrite(WIFI_CONNECT_LED, LOW);

         Serial.println("Your IP address is: ");
         Serial.println(WiFi.localIP());

         Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);
         Firebase.set("/clients/devicename/watermotor/name", "Motor");
         Firebase.set("/clients/devicename/watermotor/relay_status", "off");
         Firebase.set("/clients/devicename/watermotor/device_status", "online");
         Firebase.stream(PATH);

         server.on("/on", handleOnRequest); //Associate the handler function
         server.on("/off", handleOffRequest); //Associate the handler function

         server.begin(); //Start the server
      }
      else{
        Serial.println("");
        Serial.println("WiFi not connected");
      }

}

void loop() {
    server.handleClient();
    if (Firebase.failed()) {
      Serial.println("streaming error");
      Serial.println(Firebase.error());
      delay(1000);
      return;
    }

    if (Firebase.available()) {
        Serial.println();
        Serial.print("Firebase available");
        Serial.println();
        FirebaseObject event = Firebase.readEvent();
    }
}

```

I am not sure if its there is some problem with FirebaseLibrary or its just the ESP8266!

Any suggestions will be helpful, thanks in advance! :)

# Answer
> 0 votes
You have wrong DNS server IP address. In your sketch it is the same as the static IP address you assign to esp. Then the name of the firebase host can't be resolved by DNS.

The DNS server is usually the router/gateway.

```
IPAddress dns(192,168,1,1)

```

# Answer
> 0 votes
I also placed the same problem(If I set the static IP means it's not getting internet)But Then I added the DNS "IPAddress dns(192,168,1,1)" for that also it didn't connect to the Internet. But I connected to the Internet after adding the "IPAddress dns(8,8,8,8)".

This is my Code

```
#include <ESP8266WiFi.h>
const char* ssid = "Varaprasad";
const char* password = "varara";
int red = D6; int green = D7; int blue = D8;
const char* host = "18.221.215.201";
IPAddress staticIP(192,168,1,78);
IPAddress gateway(192,168,1,254);
IPAddress dns(8, 8, 8, 8);
IPAddress subnet(255,255,255,0);
void setup()

{
 pinMode(red,OUTPUT); pinMode(green,OUTPUT); pinMode(blue,OUTPUT);
Serial.begin(9600);
Serial.println();
Serial.printf("Connecting to %s\n", ssid);
WiFi.begin(ssid, password);
WiFi.config(staticIP,dns, gateway, subnet);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
Serial.println();
Serial.print("Connected, IP address: ");
Serial.println(WiFi.localIP());
}
void loop() {
  if(WiFi.status() == WL_CONNECTED){
  WiFiClient client1;
    if (client1.connect(host,80))
      {
         client1.stop();
      analogWrite(red,0); analogWrite(green,1023); analogWrite(blue,0);
      }
      else{
      analogWrite(red,1023); analogWrite(green,0); analogWrite(blue,0);
      client1.stop();
      }
    }
  }

```

---
Tags: esp8266, nodemcu
---


title: Powering a MKR with regulated 3.3v

text:
# Question
Title: Powering a MKR with regulated 3.3v
I've a low power consumption regulator to get 3.3V from two 1.5V batteries. I'm going to use it for powering an arduino MKR (MKRFOX1200), so my question is where I should connect it, to the battery connector or directly to VCC.

Looking at schematics it's not clear to me which is the best option in terms of power saving, as VCC seems better but I don't know if it's ok to use that pin to give power

# Answer
You don't really need your regulator. That board has a connection (X1) intended for directly connecting two AA batteries (according to the schematic).

However, if you want to keep it regulated at 3.3V for other reasons (the MCU will happily run from as low as about 1.62V) then sure - use your regulator. But just treat it like batteries regardless. Connect the output of your 3.3V regulator to the battery connector, which goes via the power switching and control circuitry to the 3.3V rail of the board.
> 1 votes

---
Tags: mkr1000, mkrzero
---


# Question
Title: hexadecimal 1 to float 1 - Compare the float 1 with a predefined float 2 - If the float 1 and float 2 are the same - Print hexadecimal 2
I want to input a hexadecimal data from cool terminal say like (05 00 02 03 00 04 00 E5) And convert the data to a float value say 45.3. Now that I have to preassign a float value say 45.3 in my program so that I can compare the converted float value with the preassigned float value. If the two values match I need to print another hexadecimal value i.e( 05 03 00 01 00 02 04 4F).

I have managed to do the conversion of hexadecimal to float. Can someone please help me in comparing the two float values?

# Answer
> 1 votes
Comparing floating point values is notoriously difficult. This is because floating point is only an approximation.

You should first define an error margin - a value which is how close together the two values need to be before you consider them to be the same.

For example 1.000000 and 1.000001 could be considered to be the same value in many circumstances.

The simplest method is to just subtract one value from the other, take the absolute value of the result, and see if it is below the error margin.

```
bool almost(float a, float b, float margin) {
  float diff = fabs(a - b);
  return (diff < margin);
}

```

---
Tags: c++, float
---


# Question
Title: How to use H3LIS331DL 3-Axis Linear Accelerometer with arduino to detect Harsh braking of vehicle
I am a newbie here, Recently I was working with H3LIS331DL 3-Axis Linear Accelerometer I²C Mini Module

Here is code for the X, Y, Z-axis.

```
 #include <movingAvg.h>
 #include <Wire.h>

// H3LIS331DL I2C address is 0x18(24)
 #define Addr 0x18

       movingAvg xAxisAverage(5);

       int readingIndex=0;
       int readingArray[10];
       int firstFiveReadingAverage;
       int lastFiveReadingAverage;

    void setup()
   {

      // Initialise I2C communication as MASTER
         Wire.begin();
     // Initialise Serial Communication, set baud rate = 9600
        Serial.begin(9600);

    // Start I2C Transmission
       Wire.beginTransmission(Addr);
   // Select control register 1
      Wire.write(0x20);
  // Enable X, Y, Z axis, power on mode, data output rate 50Hz
     Wire.write(0x27);
  // Stop I2C Transmission
     Wire.endTransmission();

// Start I2C Transmission
   Wire.beginTransmission(Addr);
// Select control register 4
   Wire.write(0x23);
 // Set full scale, +/- 100g, continuous update
  Wire.write(0x00);
 // Stop I2C Transmission
  Wire.endTransmission();
  delay(300);

   }
 void loop()
 {

   unsigned int data[6];
   for(int i = 0; i < 6; i++)
  {
    // Start I2C Transmission
    Wire.beginTransmission(Addr);
    // Select data register
    Wire.write((40+i));
    // Stop I2C Transmission
    Wire.endTransmission();

    // Request 1 byte of data
     Wire.requestFrom(Addr, 1);
    // Read 6 bytes of data
    // xAccl lsb, xAccl msb, yAccl lsb, yAccl msb, zAccl lsb, zAccl msb
     if(Wire.available() == 1)
       {
       data[i] = Wire.read();
      }
    }
   delay(300);

     // Convert the data
       int xAccl = ((data[1] * 256) + data[0]);
       int yAccl = ((data[3] * 256) + data[2]);
       int zAccl = ((data[5] * 256) + data[4]);

    if(readingIndex<10)
  {
     readingArray[readingIndex]=xAccl;
     readingIndex++;
     if(readingIndex == 10)
  {
    firstFiveReadingAverage=(readingArray[0]+readingArray[1]+readingArray[2]+readingArray[3]+readingArray[4])/5;
    lastFiveReadingAverage= (readingArray[5]+readingArray[6]+readingArray[7]+readingArray[8]+readingArray[9])/5  ;
   if(lastFiveReadingAverage>firstFiveReadingAverage)
    {
     Serial.print("Hardbrake Pressed");
     Serial.println();
    }
     readingIndex=0;
    }
    }

  //int avg = avgAccl.reading(xAccl);
  // calculate the moving average

     // Output data to serial monitor
        Serial.print("Acceleration in X-Axis : ");
        Serial.println(xAccl);
        Serial.print("Acceleration in Y-Axis : ");
        Serial.println(yAccl);
        Serial.print("Acceleration in Z-Axis : ");
        Serial.println(zAccl);
        delay(300);
        Serial.println();

     int average=xAxisAverage.reading(xAccl);

    if (average < -1000)
    {
     Serial.print("Hardbraking: ");
    //Serial.print(average/100.0);
      Serial.print(average);
      Serial.println();
        }
       }

```

I have changed the code, but values are keeps on repeating when I trigger the hard braking and it keep on repeating even I released the brake.

Here is the output

# Answer
A harsh braking is nothing more than a strong negative acceleration, so you could compare your accelaration values to a threshold. Let's assume, that the positive x-axis is the moving direction of your vehicle. This means, that braking will give an acceleration in the negative x direction. Then you first define a specific threshold for the acceleration. An acceleration in the negative x direction above this level means, that it is a "harsh" braking (you will have to test yourself, what value you want for this). Then you test, if the read values are below the negative of our threshold (since acceleration in the negative direction will be presented by negative number).

```
int braking_threshold=1000;
...
void loop(){
    ...
    // Convert the data
    int xAccl = ((data[1] * 256) + data[0]);
    int yAccl = ((data[3] * 256) + data[2]);
    int zAccl = ((data[5] * 256) + data[4]);

    if(xAccl < -1*braking_threshold){
        // Do whatever you want to do at a harsh braking here
    }
    ...
}

```

Note, that often the accelerometer data is rather noisy, especially, when mounted on a vehicle, that will vibrate during the motion (due to motors and such). You might need to apply some filter to the read values, before you can use them. That can be as easy as averaging some values, but can also go on to more complex filter algorithms, depending on how noise free you need the data. You will have to test, what values you realistically get in your application and how noisy they are. But data noise reduction is a complete different topic and thus off-topic for this question.

Also note, that your accelerometer measures a range of 200g. That's quite much I would say. When measuring relatively low accelerations the signal to noise ratio will be rather bad. So I hope, that you really want to measure accelerations, that fill this range, rather than only using a very small percentage of the range.
> 0 votes

---
Tags: programming, arduino-nano, accelerometer
---


# Question
Title: Nano can't get reply from ENC28J60 Ethernet Shield
My Arduino Nano can't get a reply from my new ENC28J60 Ethernet Shield - I can't get any library examples to work. Using the UIPEthernet lib, and running the EchoServer example with logging turned up, I get:

```
ENC28J60::init DEBUG:csPin = 10
ENC28J60::init DEBUG:miso = 12
ENC28J60::init DEBUG:mosi = 11
ENC28J60::init DEBUG:sck = 13
ENC28J60::init DEBUG:Use Native hardware SPI
Enc28J60Network::writeOp(uint8_t op, uint8_t address, uint8_t data) DEBUG_V3:Function started
ENC28J60::init DEBUG_V3:Before readOp(ENC28J60_READ_CTRL_REG, ESTAT)
Enc28J60Network::readOp(uint8_t op, uint8_t address) DEBUG_V3:Function started
...

```

so it gets nicely into the Enc28J60Network::init function. But shortly after, it does a phyWrite, tries to read a response, and then times out.

```
ENC28J60::init DEBUG_V3:Before phyWrite(PHCON2, PHCON2_HDLDIS)
Enc28J60Network::phyWrite(uint8_t address, uint16_t data) DEBUG_V3:Function started
... lots of attempts to read
Enc28J60Network::phyWrite ERROR:TIMEOUT !!

```

And then it all starts to fail, and it never gets better. I tried the EtherCard lib, too, and it fails in a similar way.

I put the scope on the SPI pins, and I see reasonable stuff: activity on SCK and MOSI, nothing on MISO, and the SS (pin 10) switching ok - and the shield claims to use pin 10 (I briefly tried pin 8 as I flailed in confusion, but no luck there either).

So at this point, either I'm misunderstanding something, or the shield is DOA.

*Update*: Earlier, I strongly suspected the SCK line because it showed a very poor signal on my scope. But it turned out to be poor grounding on the scope probe, and the signal was actually fine, a red herring. Thanks to @Majenko for drawing my attention to it.

*Update 2*: After getting no SPI response from the shield under any circumstances, my working hypothesis is that it was DOA. I've gone back to my UNO with W5100: all working fine. I have ordered more Nano ethernet shields, to arrive in a week or two, so I'll try with those, and provide updates/answers then.

# Answer
> 0 votes
Thanks to @Riad, who posted this as a comment. The problem appears to be a design fault in the "DK ectronics" V1.0 Ethernet Shield.

> Perhaps this could bring some solution. https://www.mikrocontroller.net/topic/477142

The site is in German, so here's a brief translation of the key parts:

> I bought an ENC28J60 for the Arduino Nano, but it does not respond from the programmed IP.
>
> The shield has "NANO Ethernet Shield V1.0 DK ectronics" inscribed on the underside (spelling error in the original). There there is a via on the bottom between pins D11 and D12, missing from a (different) working shield. This via connects D12 line to GND from the AMS1117 on the top (easy to check D12 to GND with a multimeter). If that's the case with your shield, then this is the problem: we just have to cut out the via connection. I have Do this with a 1mm drill by placing the top copper layer in the via very gently (really gently!) Mill it away. If you drill too deep, you break the D12 connection completely and must possibly solder on a new wire. Keep checking D12 and GND for continuity to see whether you've milled away enough. Work really carefully!
>
> After I did that, and tried the TCP Server example in the UIPEthernet library on the Arduino, the shield was reachable.
>
> -- Christoph K

I haven't yet tried to make the changes described above, because they are fiddly and I have a new batch of working shields. But my device is exactly as described by Christoph and his photos, and the fault description matches mine.

# Answer
> 2 votes
The ENC28j60 shield for Nano has reset of the ENC28j60 chip on the pin 7 of the shield/Nano. Try to set the pin 7 HIGH.

---
Tags: arduino-nano, spi, shields, ethernet-shield
---


# Question
Title: Connecting multiple load cells to the same microcontroller
This is my first post and I am a little bit confused about one thing. I would need to do the following project: have about 5-6 load cells to be connected to a microcontroller. I am not sure if there is a way to connect multiple load cells to the same arduino. I would need each load cell to act individually, so I would need an individual result from all each load cell.

I believe I would need to connect 1 load cell to 1 load cell amp and then connect the load cell amp to the Arduino and repeat this process 5-6 times (for each load cell that I need)

I'm not sure if this is possible using one Arduino or I would need 1 Arduino for each individual load cell.

The main idea of the project is to have a load cell to be placed under different kitchen supplies (1 load cell to continuously check the weight of Flower, another one to check for bread, another to check for paprika, and so on)

After this is read from the sensors, I need to write the weight of each item in a table / DB every 30 minutes.

Also, if this can be done with another board, like a microcontroller (Raspberry Pi) I'm open to that.

# Answer
All you need is the following :

* Arduino (Mega, if you need alot of inputs.)
* Load Cell Amplifier
* Load Cells (I recommend only using four wire cells)
* Resistors (Only if you are connecting one cell to one amplifier)

If you are using only one load cell per "Scale" , you would connect it as you say correctly. One load cell to each load cell amplifier and then to the Arduino.

Yes, a single Arduino can in theory take as many scales as the number of Digital inputs you have can provide. You can use the Analog inputs as well but from my experience I would recommend you only use the Digital inputs. You can just share the power and ground sources.

Usually each Load Cell Amplifier will need to use two(2) Digital inputs.

If you want to use multiple load cells together (to improve accuracy) to act as a single scale, you would connect them together in what they call a Quarter, Half or Full Bridge wiring configuration depending on how many you would like working together.

You can write to a DB if you want sure. What I personally like to do is send the readings to the cloud using dweet.io or ThingSpeak. ThingSpeak.com would probably be best for you.

I usually use the NodeMCU arduino boards that have WiFi built in. They are cheap and work great.

I hope this helps.
> 1 votes

# Answer
I had a similar project awhile back that involved multiple flex sensors. I ultimately had to use multiple op amps to boost each signal from the flex sensors. Some IC contain multiple op-amps though which will lessen your circuit footprint.
Each output of the op amp was run to a separate ADC channels on an Arduino. Depending on your Arduino you should have 8 (mini) - 16 (mega) analog pins to read your sensors.
> 0 votes

# Answer
You can use multiplexers to multiplex the loadcells and you can select the loadcells using only less selector pins
> 0 votes

---
Tags: sensors
---


title: Code help in Arduino ( Serial data)

text:
# Question
Title: Code help in Arduino ( Serial data)
I Need a help in this code

I am trying to assign the serial.write(OutData\[i\]) to byte data\[\]. Can anyone help me assign it.

Here is my code

```
#define ECHOPIN 11// Pin to receive echo pulse
#define TRIGPIN 12// Pin to send trigger pulse
int distance=0;
 byte OutData[] = {0x05, 0x03, 0x04, 0x43, 0x65, 0xBA, 0x7D, 0x04, 0xE8};
#include <Crc16.h>
Crc16 crc;
void setup()\
{
  Serial.begin(9600);
 pinMode(ECHOPIN, INPUT);
  pinMode(TRIGPIN, OUTPUT);
  digitalWrite(ECHOPIN, HIGH);
}
void loop() {
digitalWrite(TRIGPIN, LOW); // Set the trigger pin to low for 2uS
  delayMicroseconds(2);
  digitalWrite(TRIGPIN, HIGH); // Send a 10uS high to trigger ranging
  delayMicroseconds(10);
  digitalWrite(TRIGPIN, LOW); // Send pin low again
  distance = pulseIn(ECHOPIN, HIGH,26000); // Read in times pulse
  distance= distance/58;
  Serial.print(distance, HEX);
   OutData[3] = 0x00;

  OutData[4] = 0x00;

  OutData[5] = 0x41;

  OutData[6] = distance;
for (int i = 0; i <= sizeof(OutData); i++) {

    Serial.write(OutData[i]);

    byte data[] = OutData[i];
    crc.clearCrc();
  for(byte i=0;i<9;i++)
  {
     Serial.print("byte ");
     Serial.print(i);
     Serial.print(" = ");
     Serial.println(data[i]);
     crc.updateCrc(data[i]);
  }
  unsigned short value = crc.getCrc();
  Serial.print("crc = 0x");
  Serial.println(value, HEX);

  Serial.println("The crc Check of the byte array");

  //Modbus
  value = crc.Modbus(data,0,9);
  Serial.print("Modbus crc = 0x");
  Serial.println(value, HEX);

  while(true);
}
int calcrc(char *ptr, int count)
{
    int  crc;
    char i;
    crc = 0;
    while (--count >= 0)
    {
        crc = crc ^ (int) *ptr++ << 8;
        i = 8;
        do
        {
            if (crc & 0x8000)
                crc = crc << 1 ^ 0x1021;
            else
                crc = crc << 1;
        } while(--i);
    }
    return (crc);
}

```

My Error is :

```
C:\Users\system3\AppData\Local\Temp\arduino_modified_sketch_307616\sketch_dec13a.ino: In function 'void loop()':

sketch_dec13a:34:25: error: initializer fails to determine size of 'data'

     byte data[] = sizeof(OutData);

                         ^

sketch_dec13a:34:25: error: array must be initialized with a brace-enclosed initializer

sketch_dec13a:60:1: error: a function-definition is not allowed here before '{' token

 {

 ^

sketch_dec13a:77:1: error: expected '}' at end of input

 }

 ^

Multiple libraries were found for "Crc16.h"
 Used: C:\Users\system3\Documents\Arduino\libraries\Crc16-master
exit status 1
initializer fails to determine size of 'data'

```

# Answer
> 0 votes
The following code block does not make sense:

```
for (int i = 0; i <= sizeof(OutData); i++) {
    Serial.write(OutData[i]);
    byte data[] = OutData[i];
    crc.clearCrc();
} // I added this bracket for you.

```
1. It is formally wrong to create an array this way. The compiler does not have any way to know, how big the array should be. I think the declaration with `[]` works only, when you initialize the array, but you are simply assigning 1 byte value to it. `byte` is not the same as array of `byte`. So this cannot work. To make it formally correct, you can either change `data` to a simple `byte` variable (not an array), or define the size of the array via `byte data[3];` and then assigning the `OutData[i]` value to one of it's elements in the next line;
2. Above I added the closing curly bracket for you after the first for loop. It seems, that you forgot it, thus you would get more errors due to imbalanced brackets.
3. You are create a variable/array inside your for loop, that is not used anywhere. As soon as the current for loop iteration is finished, the variable/array is out of scope and will vanish. You have to declare it outside of the for loop (either inside the `loop()` function or globally), so that you can use it in the following code.
4. It seems, that you try to copy the data from the `OutData` array into the `data` array to output the values in the later code and calculate the CRC value. I don't see, why you are doing this. Is there a reason, why you could not do this directly with the `OutData` array? I don't see the need for copying the data in an extra array.
5. The following line can easily be a problem:

```
OutData[6] = distance;

```

`distance` is defined as an `int`, which is a 16bit/2byte signed number. `OutData` is defined as an array of `byte`, which is a 8bit/1byte unsigned number. `pulseIn()` returns an `unsigned long` (32bit/4byte unsigned number). Since you have configured a timeout of 26000, you won't get in conflict there, but easily, when trying to assign the `distance` value to an element of `OutData`. You can get distance values up to 448, but a `byte` can only hold numbers between 0 and 255. So you will get an overflow and thus garbled data. You will have to send both bytes of `distance` to always get the full value. (You can easily google how to get the individual bytes of an int; The Arduino framework even has defines for this, `lowByte` and `highByte`, I think).

# Answer
> 0 votes
`byte data[] = OutData[i];` is an invalid statement.

You try to initialize an array with unknown size `[]` with a single element.
you must use an array to initialize an array and not a single element.

`byte data[] = { 0xca, 0xfe, 0xba, 0xbe };`

would initialize data with an array of four elements.

---
Tags: arduino-uno, float
---


# Question
Title: How to send data to multiple slave at a time
I have one master and three slave devices and i need to send data to all the slaves at a time.is that possible if so how to check which slave has recieved the data first

# Answer
> 2 votes
The I2C protocol implements the general call/broadcast address for this purpose. If you send data to the address `0` (zero), this is interpreted as general call by all slaves. All slaves, that can receive data, will respond by pulling the SDA line to low in the acknowledgement cycle (the timing is set up by the masters clock so all slaves will do it at the same time, thus no problem with garbled data). Note, that you cannot read from the general call address, since then all slaves might transmit at the same time. As the `Atmega328P`s (the microcontroller on the Arduino Uno) datasheet states:

> Note that transmitting the general call address followed by a Read bit is meaningless, as this would cause contention if several slaves started transmitting different data.

I think the `Wire` library does not do any read operations on the general call address to prevent this, so this would not block up the I2C bus.

> how to check which slave has recieved the first

Not, because all slaves receive the data at the same time. The I2C bus is much like the IP protocol in this topic. A master/sender is sending out packages of data with the address of the intended target. But it is up to the slaves/receivers to decide, on which address they want to listen. So on every I2C transmission you are sending data over the bus, that could be read by all slaves. Only that in normal operation a slave will decide to only listen to the bus, when it sees it's own address (or the general call address).

# Answer
> 1 votes
In the IP protocol there is something called "broadcast address" when a packet contains this address all devices read it. You can do the same with i2c. Each slave has it's own address, but you can program them to also look for a "broadcast address" of your choosing. A single master can then send a single i2c message that will be read by all slaves at the same time.

---
Tags: i2c
---


# Question
Title: Can I power an NodeMCU trough VIN providing 5v
I have a spb 8266 board, an ESP-12E NodeMCU. I broke my micro USB.

There's this piece of information but my case is unclear:

Can I use the micro usb's 5v to power the board through the VIN or do any solution require more equipment than that ?

(The board only has 3.3V and **no** 5V)

# Answer
> 4 votes
> Can I use the micro usb's 5v to power the board through the VIN or do any solution require more equipment than that ?

Yes. That is the pin's purpose. You can use any voltage from about 4.5V up to 20V, although higher voltages will cause more heat from the on-board 3.3V regulator.

VIN just connects to the 5V of the USB.

# Answer
> 2 votes
If you are working with the "v3" (Lolin) pcb, USB v5 pin is not directly connected to Vin, but to VU. Vin has a S4 SMD diode (aka Schottky 40V1A 1N5819) between it and the USB v5 pin.

---
Tags: esp8266
---


# Question
Title: Motor shield and Arduino Led not turning on when connected to laptop and Arduino is heating up
I have a problem like that....As I connect my Arduino to the laptop with the usb cable and the motor shield connected, my led won't turn on neither does the led on the Arduino. And the small chip like thingy beside the usb cable also heats up really bad...please help!

# Answer
> 1 votes
0

You might have burned one of the onboard voltage regulators. In my case, it was AMS1117 which was burned and my Arduino was behaving similarly. You will notice that the Arduino will work with an external power supply connected to the Vin pin of Arduino and it will not become hot.
In short, the small chip which is getting hot is a voltage regulator may be AMS1117 and you have to replace it manually or buy a new Arduino

---
Tags: arduino-uno
---


# Question
Title: HELP with making code size smaller for Attiny13a
Iam making an awesome christmas present a custom pcb badge. Everything works great with hooked up uno, but its heart is actually a Attiny13a, where I get ONLY around 1024bytes (mine code has 1944) 64bytes of variabels (I somehow managed to make few things copy on run so i barely get to it at 59 bytes)

The thing is how can I make this even smaller??

```
void setup() {
  pinMode(3, INPUT_PULLUP);
}

void charlie(int a[])
{

  if(a[0] < 0){

    pinMode(5, INPUT);
  }else
  {
    pinMode(5, OUTPUT);
    digitalWrite(5, a[0]);
  }
  if(a[1] < 0){

    pinMode(6, INPUT);
  }else
  {
    pinMode(6, OUTPUT);
    digitalWrite(6, a[1]);
  }
  if(a[2] < 0){

    pinMode(2, INPUT);
  }else
  {
    pinMode(2, OUTPUT);
    digitalWrite(2, a[2]);
  }
  if(a[3] < 0){

    pinMode(4, INPUT);
  }else
  {
    pinMode(4, OUTPUT);
    digitalWrite(4, a[3]);
  }
}

void copy(int* src, int* dst, int len) {
    memcpy(dst, src, sizeof(src[0])*len);
}
void resetP()
{
  pinMode(5, INPUT);
  pinMode(6, INPUT);
  pinMode(2, INPUT);
  pinMode(4, INPUT);
}
void loop() {

  int koz1[4] = {-2,LOW,HIGH,-2};
  //int koz2[4] = {-2,HIGH,LOW,-2};

  int koz2[4];
  copy(koz1, koz2, 4);
  koz2[1] = HIGH;
  koz2[2] = LOW;

  int koz3[4] = {LOW,HIGH,-2,-2};
  //int koz4[4] = {HIGH,LOW,-2,-2};
  int koz4[4];
  copy(koz3, koz4, 4);
  koz4[0] = HIGH;
  koz4[1] = LOW;

  int koz5[4] = {LOW, -2,-2,HIGH};
  //int koz6[4] = {HIGH, -2,-2,LOW};
  int koz6[4];
  copy(koz5, koz6, 4);
  koz4[0] = HIGH;
  koz4[3] = LOW;

  int cap[4] = {-2, HIGH,-2,LOW};

  int oko1[4] = {LOW, -2,HIGH,-2};
  //int oko2[4] = {HIGH, -2,LOW,-2};

  int oko2[4];
  copy(oko1, oko2, 4);
  oko2[0] = HIGH;
  oko2[2] = LOW;

  // put your main code here, to run repeatedly:

  static long oldTime = 0;
  long Ctime = millis();
  long diffT = Ctime - oldTime;
  oldTime = Ctime;

  static bool holdButt = false;
  static long holdTime = 0;
  static long shortPressATime = 0;
  //static long longPressATime = 0;
  static bool kozichOn = true;

  //charlie(oko1);
  //charlie(oko2);

  if(digitalRead(3) == LOW)
  {
    holdButt = true;
    holdTime = holdTime + diffT;
  }
  else if (holdButt && digitalRead(3) == HIGH){
    holdButt = false;
    if(holdTime > 1000){
      //longPressATime = 5000;
      kozichOn = !kozichOn;
    }
    else
    {
      shortPressATime = 5000;
    }
    holdTime = 0;
  }

  if(shortPressATime > 0)
  {
    shortPressATime = shortPressATime - diffT;
    /*charlie(koz1);
    charlie(koz2);
    charlie(koz3);
    charlie(koz4);
    charlie(koz5);
    charlie(koz6);
    charlie(cap);
    */
    if(((round(shortPressATime/100) / 2) & 1) == 0){
      charlie(oko1);
      charlie(oko2);
      resetP();
    }
    else{

    }

  }

  /*
  else if (longPressATime > 0)
  {
    longPressATime = longPressATime - diffT;
    charlie(oko1);
    delay(5000/longPressATime);

    charlie(oko2);
    delay(5000/longPressATime);

    longPressATime = longPressATime - 5000/longPressATime;
    longPressATime = longPressATime - 5000/longPressATime;
  }*/
  else{
    if(kozichOn){
      charlie(koz1);
      charlie(koz2);
      charlie(koz3);
      charlie(koz4);
      charlie(koz5);
      charlie(koz6);
      charlie(cap);
    }
    charlie(oko1);
    charlie(oko2);
  }
  resetP();
}

```

EDIT: Guys you are awesome together with those on arduino forums it looks like I finally achieved it, I will try to optimize little bit more as its 1010bytes 98%. But I thank you all. You teached me in 1 hour more practical things, than I could read in a week.

```
void setup() {
  pinMode(3, INPUT_PULLUP);
}

void charlie(byte a[])
{

  if(a[0] == 0x0F){

    pinMode(5, INPUT);
  }else
  {
    pinMode(5, OUTPUT);
    digitalWrite(5, a[0]);
  }
  if(a[1] == 0x0F){

    pinMode(6, INPUT);
  }else
  {
    pinMode(6, OUTPUT);
    digitalWrite(6, a[1]);
  }
  if(a[2] == 0x0F){

    pinMode(2, INPUT);
  }else
  {
    pinMode(2, OUTPUT);
    digitalWrite(2, a[2]);
  }
  if(a[3] == 0x0F){

    pinMode(4, INPUT);
  }else
  {
    pinMode(4, OUTPUT);
    digitalWrite(4, a[3]);
  }
}
/*
void copy(int* src, int* dst, int len) {
    memcpy(dst, src, sizeof(src[0])*len);

}
*/
/*
void resetP()
{
  pinMode(5, INPUT);
  pinMode(6, INPUT);
  pinMode(2, INPUT);
  pinMode(4, INPUT);
}
*/

void loop() {

  byte koz1[4] = {0x0F,LOW,HIGH,0x0F};
  //int koz2[4] = {null,HIGH,LOW,null};

  byte koz2[4];
  //copy(koz1, koz2, 4);
  memcpy(koz2, koz1, sizeof(koz1[0])*4);
  koz2[1] = HIGH;
  koz2[2] = LOW;

  byte koz3[4] = {LOW,HIGH,0x0F,0x0F};
  //int koz4[4] = {HIGH,LOW,2,2};
  byte koz4[4];
  //copy(koz3, koz4, 4);
  memcpy(koz4, koz3, sizeof(koz3[0])*4);
  koz4[0] = HIGH;
  koz4[1] = LOW;

  byte koz5[4] = {LOW, 0x0F,0x0F,HIGH};
  //int koz6[4] = {HIGH, 2,2,LOW};
  byte koz6[4];
  //copy(koz5, koz6, 4);
  memcpy(koz6, koz5, sizeof(koz5[0])*4);
  koz4[0] = HIGH;
  koz4[3] = LOW;

  byte cap[4] = {0x0F, HIGH,0x0F,LOW};

  byte oko1[4] = {LOW, 0x0F,HIGH,0x0F};
  //int oko2[4] = {HIGH, 2,LOW,2};

  byte oko2[4];
  //copy(oko1, oko2, 4);
  memcpy(oko2, oko1, sizeof(oko1[0])*4);
  oko2[0] = HIGH;
  oko2[2] = LOW;

  // put your main code here, to run repeatedly:

  static uint16_t oldTime = 0;
  uint16_t Ctime = millis();
  uint16_t diffT = Ctime - oldTime;
  oldTime = Ctime;

  static bool holdButt = false;
  static uint16_t holdTime = 0;
  static uint16_t shortPressATime = 0;
  //static long longPressATime = 0;
  static bool kozichOn = true;

  //charlie(oko1);
  //charlie(oko2);

  if(digitalRead(3) == LOW)
  {
    holdButt = true;
    holdTime = holdTime + diffT;
  }
  else if (holdButt && digitalRead(3) == HIGH){
    holdButt = false;
    if(holdTime > 1000){
      //longPressATime = 5000;
      kozichOn = !kozichOn;
    }
    else
    {
      shortPressATime = 5000;
    }
    holdTime = 0;
  }

  if(shortPressATime > 0)
  {
    shortPressATime = shortPressATime - diffT;
    if(((uint16_t(shortPressATime/128) / 2) & 1) == 0){
      charlie(oko1);
      charlie(oko2);

    }
    else{

    }

  }
  else{
    if(kozichOn){
      charlie(koz1);
      charlie(koz2);
      charlie(koz3);
      charlie(koz4);
      charlie(koz5);
      charlie(koz6);
      charlie(cap);
    }
    charlie(oko1);
    charlie(oko2);
  }
  pinMode(5, INPUT);
  pinMode(6, INPUT);
  pinMode(2, INPUT);
  pinMode(4, INPUT);
}

```

# Answer
The first thing I would try is to get rid of the Arduino core, and program instead at the avr-libc level:

* use direct port access instead of `digitalRead()`/`digitalWrite()`
* setup a timer and measure time in units of timer overflows instead of using `millis()`.

Also, use `int8_t` for all small ints (especially in arrays), and `uint16_t` for time management if you don't need to handle durations larger than 65,535 time units.

---

**Edit**: Here is my attempt at translating your code to plain C + avr-libc. Note that, as I don't know the pinout of the core you are using (what is pin 6?), I am making one up. I also implemented Michel Keijzers suggestion about factoring duplicated code into a function, which I called `set_pin()`. Completely untested:

```
#include <stdbool.h>
#include <string.h>
#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/atomic.h>

#define INPUT 0x0f
#define LOW   0x00
#define HIGH  0x01

// Configure Timer 0 to count milliseconds, assuming F_CPU = 8 MHz.
static void init_timer() {
  OCR0A  = 125 - 1;     // period = 125*64 = 8000 CPU cycles
  TCCR0A = _BV(WGM01);  // CTC, TOP = OCR0A
  TCCR0B = _BV(CS00)    // clock @ F_CPU/64
         | _BV(CS01);   // ditto
  TIMSK0 = _BV(TOIE0);  // enable timer overflow interrupt
}

volatile uint16_t millis_counter;

// Count a millisecond on each timer overflow.
ISR(TIM0_OVF_vect) {
  ++millis_counter;
}

// Read the milliseconds counter avoiding race conditions.
static uint16_t millis() {
  uint16_t millis_counter_copy;
  ATOMIC_BLOCK(ATOMIC_FORCEON) {
    millis_counter_copy = millis_counter;
  }
  return millis_counter_copy;
}

static void setup() {
  PORTB |= _BV(PB4);  // pullup on PB4
  init_timer();
  sei();
}

// Set a pin as either INPUT, LOW or HIGH.
static void set_pin(uint8_t pin_mask, uint8_t state) {
  if (state == INPUT) {
    DDRB &= ~pin_mask;     // INPUT
    PORTB &= ~pin_mask;    // no pullup
  } else {
    if (state)
      PORTB |= pin_mask;   // HIGH
    else
      PORTB &= ~pin_mask;  // LOW
    DDRB |= pin_mask;      // OUTPUT
  }
}

static void charlie(uint8_t a[])
{
  set_pin(_BV(PB0), a[0]);
  set_pin(_BV(PB1), a[1]);
  set_pin(_BV(PB2), a[2]);
  set_pin(_BV(PB3), a[3]);
}

void loop() {

  uint8_t koz1[4] = {INPUT,LOW,HIGH,INPUT};

  uint8_t koz2[4];
  memcpy(koz2, koz1, sizeof(koz1[0])*4);
  koz2[1] = HIGH;
  koz2[2] = LOW;

  uint8_t koz3[4] = {LOW,HIGH,INPUT,INPUT};
  uint8_t koz4[4];
  memcpy(koz4, koz3, sizeof(koz3[0])*4);
  koz4[0] = HIGH;
  koz4[1] = LOW;

  uint8_t koz5[4] = {LOW, INPUT,INPUT,HIGH};
  uint8_t koz6[4];
  memcpy(koz6, koz5, sizeof(koz5[0])*4);
  koz4[0] = HIGH;
  koz4[3] = LOW;

  uint8_t cap[4] = {INPUT, HIGH,INPUT,LOW};

  uint8_t oko1[4] = {LOW, INPUT,HIGH,INPUT};
  uint8_t oko2[4];
  memcpy(oko2, oko1, sizeof(oko1[0])*4);
  oko2[0] = HIGH;
  oko2[2] = LOW;

  static uint16_t oldTime = 0;
  uint16_t Ctime = millis();
  uint16_t diffT = Ctime - oldTime;
  oldTime = Ctime;

  static bool holdButt = false;
  static uint16_t holdTime = 0;
  static uint16_t shortPressATime = 0;
  static bool kozichOn = true;

  if (bit_is_clear(PINB, PB4))
  {
    holdButt = true;
    holdTime = holdTime + diffT;
  }
  else if (holdButt && bit_is_set(PINB, PB4)){
    holdButt = false;
    if(holdTime > 1000){
      kozichOn = !kozichOn;
    }
    else
    {
      shortPressATime = 5000;
    }
    holdTime = 0;
  }

  if(shortPressATime > 0)
  {
    shortPressATime = shortPressATime - diffT;
    if(((shortPressATime/128 / 2) & 1) == 0){
      charlie(oko1);
      charlie(oko2);
    }
  }
  else{
    if(kozichOn){
      charlie(koz1);
      charlie(koz2);
      charlie(koz3);
      charlie(koz4);
      charlie(koz5);
      charlie(koz6);
      charlie(cap);
    }
    charlie(oko1);
    charlie(oko2);
  }
  DDRB &= ~(_BV(PB0) | _BV(PB1) | _BV(PB2) | _BV(PB3));
}

int main(void) {
  setup();
  for (;;)
    loop();
}

```

Compiling with avr-gcc 5.4.0, I get 642 bytes of flash and 31 bytes of RAM (data + BSS, not counting the stack).
> 2 votes

# Answer
When I compile it, I get:

```
Sketch uses 2630 bytes (8%) of program storage space. Maximum is 32256 bytes.
Global variables use 64 bytes (3%) of dynamic memory, leaving 1984 bytes for local variables. Maximum is 2048 bytes.

```

I removed all commented lines, and changed the integers to bytes (according to Edgar Bonet's answer as a start.

Than I get the code (added at end) and the following results:

```
Sketch uses 2432 bytes (7%) of program storage space. Maximum is 32256 bytes.
Global variables use 24 bytes (1%) of dynamic memory, leaving 2024 bytes for local variables. Maximum is 2048 bytes.

```

According to the specs, an AtTiny85 has 8 KB Program memory and 512 bytes SRAM, so you should be safe.

Note however, if you want to count SRAM memory (24 bytes counted by the IDE), but also you have to add:

1. Bytes for the calling depth of functions (e.g. `loop` calls `copy` and this calls `memcpy`, the total memory is for `copy`: + 2 (byte\*) + 2 (byte\*) + 1 (byte) bytes, and for memcpy: + dst (2) + src (2) + sizeof (1) byte. You have to check the most 'worse' call (so check the deepest invocation with all arguments added). This is all added to the so-called stack.
2. Also you have to add the cost of local variables (once per function), because these are also added to the stack.
3. If you use dynamic variables (malloc) you also have to add them, but this is not used in your sketch.

The bytes used for items 1 to 3 are not mentioned (because these are allocated at runtime).

```
void setup() {
  pinMode(3, INPUT_PULLUP);
}

void charlie(byte a[])
{
  if(a[0] < 0){

    pinMode(5, INPUT);
  }else
  {
    pinMode(5, OUTPUT);
    digitalWrite(5, a[0]);
  }
  if(a[1] < 0){

    pinMode(6, INPUT);
  }else
  {
    pinMode(6, OUTPUT);
    digitalWrite(6, a[1]);
  }
  if(a[2] < 0){

    pinMode(2, INPUT);
  }else
  {
    pinMode(2, OUTPUT);
    digitalWrite(2, a[2]);
  }
  if(a[3] < 0){

    pinMode(4, INPUT);
  }else
  {
    pinMode(4, OUTPUT);
    digitalWrite(4, a[3]);
  }
}

void copy(byte* src, byte* dst, byte len) {
    memcpy(dst, src, sizeof(src[0])*len);
}

void resetP()
{
  pinMode(5, INPUT);
  pinMode(6, INPUT);
  pinMode(2, INPUT);
  pinMode(4, INPUT);
}
void loop() {

  byte koz1[4] = {-2,LOW,HIGH,-2};
  byte koz2[4];
  copy(koz1, koz2, 4);
  koz2[1] = HIGH;
  koz2[2] = LOW;

  byte koz3[4] = {LOW,HIGH,-2,-2};
  byte koz4[4];
  copy(koz3, koz4, 4);
  koz4[0] = HIGH;
  koz4[1] = LOW;

  byte koz5[4] = {LOW, -2,-2,HIGH};
  byte koz6[4];
  copy(koz5, koz6, 4);
  koz4[0] = HIGH;
  koz4[3] = LOW;

  byte cap[4] = {-2, HIGH,-2,LOW};
  byte oko1[4] = {LOW, -2,HIGH,-2};

  byte oko2[4];
  copy(oko1, oko2, 4);
  oko2[0] = HIGH;
  oko2[2] = LOW;

  static long oldTime = 0;
  long Ctime = millis();
  long diffT = Ctime - oldTime;
  oldTime = Ctime;

  static bool holdButt = false;
  static long holdTime = 0;
  static long shortPressATime = 0;
  static bool kozichOn = true;

  if(digitalRead(3) == LOW)
  {
    holdButt = true;
    holdTime = holdTime + diffT;
  }
  else if (holdButt && digitalRead(3) == HIGH){
    holdButt = false;
    if(holdTime > 1000){
      //longPressATime = 5000;
      kozichOn = !kozichOn;
    }
    else
    {
      shortPressATime = 5000;
    }
    holdTime = 0;
  }

  if(shortPressATime > 0)
  {
    shortPressATime = shortPressATime - diffT;

    if(((round(shortPressATime/100) / 2) & 1) == 0){
      charlie(oko1);
      charlie(oko2);
      resetP();
    }
    else{
    }
  }
  else{
    if(kozichOn){
      charlie(koz1);
      charlie(koz2);
      charlie(koz3);
      charlie(koz4);
      charlie(koz5);
      charlie(koz6);
      charlie(cap);
    }
    charlie(oko1);
    charlie(oko2);
  }
  resetP();
}

```
> -1 votes

---
Tags: sketch-size
---


# Question
Title: ESP8266 Webserver ESP8266WebServer move Handler-Function in separate .h .c file
The plan is to create a bigger project and to split the ESP8266 webserver-code over several modules (.h .c files). The main problem is that the ESP8266WebServer **server** is not declared in the index.h and index.c files.

What I've been trying to do:

Content main.c

```
#include <ESP8266WiFi.h>
#include "ESP8266WebServer.h"
#include "index.h"

ESP8266WebServer server(80);
const char* ssid =     "test";
const char* password = "12345678";

void setup()
{
  WiFi.softAP(ssid, password);
  server.on("/", handleRoot(server));           // <-- use of deleted function 'esp8266webserver::ESP8266WebServerTemplate<WiFiServer>::ESP8266WebServerTemplate(const esp8266webserver::ESP8266WebServerTemplate<WiFiServer>&)'
  server.begin();
}

void loop()
{
  server1.handleClient();
}

```

Content index.h:

```
void handleRoot(ESP8266WebServer server);

const char htmlIndex[] PROGMEM = R"=====(
<html>
  <head>
    <meta http-equiv="content-type" content="text/html;charset=UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Test</title>
  </head>
  <body>
    <h1>Hello World!</h1>
  </body>
</html>
)=====";

```

Content index.c:

```
#include "webpages/index.h"

void handleRoot(ESP8266WebServer server)
{
  Serial.println("GET /");
  server.send(200, "text/html", htmlIndex);
}

```

How can I use the ESP8266WebServer **server** created in the main.c in index.c?

# Answer
Move the webserver to index.c and include the webserver type:

```
ESP8266WebServer server(80);

```

Add an external reference in index.h and include it:

```
#include "ESP8266WebServer.h"

extern ESP8266WebServer server;

```

Index.h is included by both main.c and index.c so it will know about server being an ESP8266WebServer type, but does not allocate memory for it; that is done in index.c

This is called a forward reference.
> 1 votes

---
Tags: esp8266, programming, web-server, code-review
---


# Question
Title: Arduino Zero to Arduino Zero SPI configuration
I am in the planning stage of chaning two ATSAMD21 with a Zero or Nano 33 bootloade r in a SPI connection. The rational for this is that i am in need of 30 pin GPIO expansion and using 2 mcp23s17 takes a fair bit amount of space and also slightly bit more expensive. Since the ATSAMD21 has theoretical 37 GPIOs why not use that. having not owned a zero board yet, i would like to know if:

Is it easily doable, just connecting the appropriate pins?

If so, i have read in the Arduino SPI documentation that the zero doesnt have any Slave Select for Master and Slave, does this mean i can use whatever i want? And just code it to detect that pin

Does the built in SPI library capable of handling the slightly higher clock speed of the zero ?

# Answer
A zero has the same number of IO pins then a UNO, they use the same header layout. So I believe you want to use the chips on a self made PCB. (?)

Based on this, I think a second SAMD21 is not the best solution.

They are easily connectable as they use the same Voltage. I used the SPI lib on a zero, so yes, I think its programmable with Arduino techniques. And you can use a CS pin of your choice. The SPI lib uses Arduino header files for the selected platform. So the MCU clock speed shouldn't be a problem.

But you have to program the master and the slave and maintain this firmware. An MCP23(s/0)17 is ready to use.

Two MCP23S17 (QFN packages) don't take that much space.

SAMD21 is capable of driving max. 3.6 V; MCP can handle 5.5 V. (But if you want to use 5V you have to level shift the connection between your Arduino zero and the MCP.

And adding two more MCP23S17 is way easier that adding a third SAMD21, when even the old firmware must be reprogrammed.

A MCP23S17 can drive and sink 25 mA on each pin.

A SAMD21 can handle 14 mA source current and 19.5 mA sink current per IO cluster (there are 6 clusters each of them has between 2 and 16 pins).

On the other hand, if you are sure, you don't need more than 3.6 volts and ~1 mA per pin and the number of the additional IO pins is enough, there is no reason not to use a second SAMD21.

If you need capacitive touch pins, or more I2S ports or other capabilities of the SAMD21, then the second SAMD21 is even the better choice.

Have you seen the Arduino DUE? It has all the features of a zero and way more IO pins (54) and 12 analog inputs and 2 real analog outputs.
> 2 votes

---
Tags: spi, arduino-zero
---


# Question
Title: Continuous servo speed control with Arduino Uno controller and servo shield
It is very simple device, 2 continuous servos FS5113R, rotates continuously in one direction. Here is device original content, which is this servo shield it looks like russian, and here is library, I have added to Arduino IDE, also I have original code, which runs this device, given below.

I'm trying to figure out, what can I do with speed, to run it slower, I've tried change delay(15); number to 1000, but it moves with same speed. I've tried increment variable in `while (z < 2) loop` and pass it with interval, but speed is same:

```
#include <Wire.h>
#include <Multiservo.h>

#define SERVO_COUNT 2

Multiservo servo[SERVO_COUNT];

int pos1 = 0;
int pos2 = 0;

int z = 1;

void setup(void)
{
  Wire.begin();

  for (int i = 0; i < SERVO_COUNT; ++i)
  {
    servo[i].attach(i);
    servo[i].write(0);
  }
}

void loop(void)
{
    while (z < 2){
        pos1 + 1;
        pos2 + 1;
        servo[1].write(pos1);
        servo[2].write(pos2);
        delay(15);
    }
}

```

Any advice, guide or example would be useful

# Answer
The speed of your servo is controlled by the pulswidth of a square wave signal. According to the datascheet of the servo the motor stops on a pulsewith of about 1500 µSec (+- 5 µSec).

From 1500 to 900 μSec the motor turns clock wise. And it getting faster with decreasing pulsewidth.

From 1500 to 2100 μSec the motor turns counter clock wise. And it getting faster with increasing pulsewidth.

Next we have to check whether your shield and the library can handle that values and which value you have to give to the `servo[i].write(?)` function. I can read cyrillic but I do not understand russian good enough to read the f. manual. So I have to look into the code on GitHub (https://github.com/amperka/Multiservo/blob/master/library/Multiservo ).

Et voila:

```
Multiservo::attach(int pin, int minPulse, int maxPulse)

```

You can define the min and max pulseWidth, that's great. Let's do it:

```
#include <Multiservo.h>
#define SERVO_COUNT 2

Multiservo servo[SERVO_COUNT];
// speed is 0 ( full speed CW )
int speed = 0;

void setup(void)
{
  for (int i = 0; i < SERVO_COUNT; ++i)
  {
    servo[i].attach( i, 900, 2100);
    // 900 - 2100 is mapped from 0 to 180
    // so 90 is the middle where the motor stopps
    // 180 the motor runs as fast as possible CCW
    // 0 the motor runs as fast as possible CW
    servo[i].write( speed );
  }
}

void loop(void)
{
   // Here I halt the program if the motor stops.
   // If you use a lower value than 89 you can halt the program
   // at the corresponding speed. If you use a higher value instead of 89
   // the motor starts rotating counter clockwise.
   // Do not use a value greater then 179 or less than 1.
   if ( ++speed > 89 ) speed = 90;

   servo[1].write( speed );
   servo[2].write( speed );

   delay(25);
}

```

Ah, of cause I have not hte hardware, so I can not test the program. Use it as an example.
> 2 votes

---
Tags: arduino-uno, continuous-servo
---


# Question
Title: ESP8266 Webserver ESP8266WebServer variable html page (not as one const char)
The aim is to display a non-static html page depending on some variable condition.

The code I created hast the problem, that the esp8266 is ressetting in the moment I request the page.

```
const char htmlIndexHeader[] PROGMEM = R"=====(
<html>
<head>
    <meta http-equiv="content-type" content="text/html;charset=UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Test</title>
</head>
<body>
  <p>Hello World</p>
  <ol>
)=====";

const char htmlIndexProgress1[] PROGMEM = R"=====(
        <li>lorem</li>
)=====";

const char htmlIndexProgress2[] PROGMEM = R"=====(
        <li>ipsum</li>
)=====";

const char htmlIndexFooter[] PROGMEM = R"=====(
        </ol>
</body>
</html>
)=====";

char htmlIndexAll[2000];

void handleRoot()
{
  Serial.println("GET /");

   strcpy(htmlIndexAll, htmlIndexHeader);

   if(var1==true)
   {
     strcat(htmlIndexAll, htmlIndexProgress1);
   }

   if(var2==true)
   {
     strcat(htmlIndexAll, htmlIndexProgress2);
   }

   strcat(htmlIndexAll, htmlIndexFooter);

  server.send(200, "text/html", htmlIndexAll);
}

```

If I display a static page the esp8266 does not restart at page request.

# Answer
Compiler can't differentiate the PROGMEM strings from constant strings in SRAM strings. Both are `const char*`. But the PROGMEM string must be handled differently. For that reason \_P variants of functions exists.

You should use stcpy\_P and strcat\_P functions.

Note: On esp8266 some functions of Arduino core use a trick to identify PROGMEM strings by their specific address range.
> 2 votes

---
Tags: esp8266, programming, web-server, code-review
---


# Question
Title: Powering LED Strip at both ends shorts my psu?
I've got a 200 LEDs strip of sk9822's hooked up to a 5V 8A power supply. As expected, at full white, there's considerable voltage drop and the far end of the strip turns from white to amber.

I wanted to hook up another set of V+ and GND at the far end of the strip, but doing so trips my psu? The strip blinks full white as a result.

Hooking up ONLY GND or ONLY V+ at the far end significantly improves the drop off where only the middle of the strip turns slightly amber-ish.
But! I do notice a faint buzzing from the PSU if I do this.

Am I doing something wrong here?

# Answer
> 1 votes
Put a diode to every psu cable or just take only one psu but make a connection between the input and the far end eith a cable of more than 0,5 mm^2... Spesker csble or so.

Problem with two psu is: one gives 5,00 Volt, the other 5,05... And there is s power of 0,05 Volt / 8 Ampere running.

Second problem can be the influrnce of different PSU switching frequencies. Regards, Michael

---
Tags: power, led, led-strip
---


# Question
Title: Running in loop or once according to a slide switch position
I have a question.

I made a system which includes a servo, a stepper and a wiper motor :) All these parts has one job to do and I can code it. But, I want to make 2 modes in this system Single Operation, Loop operation.

for example position 1-single operation, 2-loop operation. I can code the loop operation thanks to arduino syntax :)

But I cannot code single one. I can read switch state detection. I want to do exactly same things, but only one time when slide switch on the position.

The code is really long and it includes Turkish defines. If you need to see the code, let me know.

# Answer
Let's assume the switch is on pin 9, that the pinMode() has already been set, and that the switch reads HIGH for loop operation.

```
#define MODE_SWITCH  9
#define DO_LOOP  HIGH

// This loop will execute once if the mode-switch is off, or
// will execute continously if the mode-switch is on:
do {
  servo_things();
  stepper_things();
  motor_things();
} while( digitalRead(MODE_SWITCH) == DO_LOOP );

```

in C/C++, 'do-while' loops always execute at least once, since the condition isn't tested until after the first pass through the loop. If the 'while' condition is satisfied (or TRUE), the loop will execute again, otherwise the loop will exit.
> 3 votes

---
Tags: switch, loop
---


# Question
Title: programming STM32 with arduino IDE issues
I'm currently trying to program an STM32 with arduino, but along the way, i encountered some issues with pin modes. To be more specific, programming certain pins to certain modes. Some pins have consistent digital outputs like PC13, while others have wonky outputs like PA11 and PA12, despite being able to be used as digital outputs.  here is what i get from PA12  here is what i get from PA11

i've read the pinout diagrams, and im not too sure if both mentioned pins can be used digitally according to this pinout diagram :

can anyone help me explain what is going on, how do i program an STM32 with Arduino IDE exactly (stm32duino programming procedures, rule of thumb, etc), and can an stm32duino be used to do complex programs like an arduino like for example driving a motor with PWM in a balancing robot or do we have to use C or C++ using atollic TrueSTUDIO and all of those software?

# Answer
> 1 votes
> others have wonky outputs like PA11 and PA12, despite being able to be used as digital outputs.

As the pinout diagram you included in the question yourself shows, PA11 and PA12 provide the USB interface.

You can't use those pins for both USB and other GPIO roles at the same time.

Your Arduino core and add-on bootloader are presumably using the USB port for programming and communication with the host PC. Custom projects which did not use the pins for USB would be possible, but you'd likely be largely on your own and unable to use those particular Arduino components (or at least not without heavily modifying them).

There are other pins which have key purposes, too, for example those which support external clock crystals, those which provide the SWD debug interface, those which could provide serial UART output, etc - some designs can use these as generic I/O's but only by forgoing the unique functionality which many designs need them to provide.

---
Tags: stm32
---


title: What type of Arduino is this?

text:
# Question
Title: What type of Arduino is this?
I found a bunch of Arduinos (seemingly), but I can't identify the type.

I first thought of a **Micro**, but the chip is a MEGA328PAU and the Micro should have a MEGA32U4 instead:

I know it's also not a **Nano**, because the Nano is a bit longer:

Next, I looked up the List of Board Specs. Based on the chip, the following models remain:

* Lilypad, can easily be excluded due to its shape
* Lilypad SimpleSnap, can easily be excluded due to its shape
* Uno, can easily be excluded due to its size
* Ethernet, can easily be excluded, because of the Ethernet port
* Mini
* Pro
* Pro Mini

So I am left with **Mini**, **Pro Mini** and **Pro**. The back of the board is not very helpful, since it IMHO misses the markers in the silk sceen:

It definitely looks like the **Pro Mini** from Arduino Store, but the Arduino store seems not to offer the Mini and Pro, so I don't have a comparison.

What type of Arduino is this? And, if possible, do you have a visual comparison of the three remaining types?

# Answer
It is a version of Pro Mini. here in DIY MORE shop

The Mini has regulator. Power it over RAW pin with 7 to 12 V and measure the Vcc pin if it shows 5v or 3.3 V.

To determine the frequency, look at the resonator (the component next to pin 2).

EDIT: the resonator markings are hard to read and very cryptic. to determine the frequency you could install Sparkfun boards package. There you can select the different variants of Pro Mini. Upload Blink. If the upload is successful and it Blinks in 1 second intervals, you have the right setting.
> 5 votes

---
Tags: board
---


# Question
Title: How can I combine this two codes in one program? And use it in javafx application
The first one reads from sensors and displays it, the second code receives an incoming byte to control LEDs. I tried to combine it but i don't know why it doesn't work. Please help me out. I need it for my project to run both of them.

In my java netbeans i have two GUIs. For monitoring(first code) and controlling(second). I want it both to run with only one combined code in arduino.

I tried to use if else statement for the arduino to know what to do. Not working also. I think i just missed something

```
const int model = 0;

void setup() {
Serial.begin(9600);

}

float sensitivity[] ={
      0.185,// for ACS712ELCTR-05B-T
      0.100,// for ACS712ELCTR-20A-T
      0.066// for ACS712ELCTR-30A-T

     } ;

void loop() {
static unsigned long count=0;
static float Vsum=0;
float Vave=0;
int volt = analogRead(A1);

float voltage= map(volt,0,1023, 0, 2500)/100.0;
Vsum=Vsum+voltage;

static float Csum=0;
float Cave=0;
 float milli = pow(10, -3);
 float current = (voltage / sensitivity[model]);
 float current1 = current*milli;

Csum=Csum+current1;
count++;
Vave=Vsum/count;
Cave=Csum/count;
float watts = Vave*Cave;

long milisec = millis();
long time=milisec/1000;

 float energy = (watts*time)/3600;
Serial.print(energy,6);
Serial.println("Wh");
delay(1000);

}

```

And this is the second code. This receives byte from java to control LEDs

```
int incomingByte;

void setup() {
  Serial.begin(9600);
  pinMode(LED_BUILTIN, OUTPUT);
  pinMode(13, OUTPUT);
  pinMode(12, OUTPUT);
  pinMode(11, OUTPUT);
  pinMode(10, OUTPUT);
  pinMode(9, OUTPUT);
  pinMode(8, OUTPUT);
  pinMode(7, OUTPUT);
  pinMode(6, OUTPUT);
  pinMode(5, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(3, OUTPUT);
  pinMode(2, OUTPUT);
  pinMode(1, OUTPUT);
  pinMode(0, OUTPUT);

}

void loop() {
 // if (Serial.available()>0) {
    incomingByte = Serial.read();

    if(incomingByte == 0x01){
      digitalWrite(13, HIGH);
     Serial.println("ON");

    }else if(incomingByte == 0x00){
      digitalWrite(13, LOW);
       Serial.println("OFF");
    }

    if(incomingByte == 0x02){
      digitalWrite(12, HIGH);
    }else if(incomingByte == 0x03){
      digitalWrite(12, LOW);
    }

    if(incomingByte == 0x04){
      digitalWrite(11, HIGH);
    }else if(incomingByte == 0x05){
      digitalWrite(11, LOW);
    }

    if(incomingByte == 0x06){
      digitalWrite(10, HIGH);
    }else if(incomingByte == 0x07){
      digitalWrite(10, LOW);
    }

    if(incomingByte == 0x08){
      digitalWrite(9, HIGH);
    }else if(incomingByte == 0x09){
      digitalWrite(9, LOW);
    }

    if(incomingByte == 0x10){
      digitalWrite(8, HIGH);
    }else if(incomingByte == 0x11){
      digitalWrite(8, LOW);
    }

    if(incomingByte == 0x12){
      digitalWrite(7, HIGH);
    }else if(incomingByte == 0x13){
      digitalWrite(7, LOW);
    }

    if(incomingByte == 0x14){
      digitalWrite(6, HIGH);
    }else if(incomingByte == 0x15){
      digitalWrite(6, LOW);
    }

    if(incomingByte == 0x16){
      digitalWrite(5, HIGH);
   }else if(incomingByte == 0x17){
      digitalWrite(5, LOW);
    }

    if(incomingByte == 0x18){
      digitalWrite(4, HIGH);
    }else if(incomingByte == 0x19){
      digitalWrite(4, LOW);
    }

    if(incomingByte == 0x20){
      digitalWrite(3, HIGH);
    }else if(incomingByte == 0x21){
      digitalWrite(3, LOW);
    }

    if(incomingByte == 0x22){
      digitalWrite(2, HIGH);
    }else if(incomingByte == 0x23){
      digitalWrite(2, LOW);
    }

    if(incomingByte == 0x24){
      digitalWrite(1, HIGH);
    }else if(incomingByte == 0x25){
      digitalWrite(1, LOW);
    }

    if(incomingByte == 0x026){
      digitalWrite(0, HIGH);
    }else if(incomingByte == 0x027){
      digitalWrite(0, LOW);
    }

  delay(100);
}

```

This is my sample code from javafx application

```
    try {
        if (tbLED12.isSelected()) {
            if (arduinoPort != null) {
                arduinoPort.writeByte((byte) 0x02);
                System.out.println("LED 12 ON");
            } else {
                System.out.println("arduinoPort not connected!");
            }
        } else {
            if (arduinoPort != null) {
                arduinoPort.writeByte((byte) 0x03);
                System.out.println("LED 12 OFF");
            } else {
                System.out.println("arduinoPort not connected!");
            }
        }
    } catch (SerialPortException ex) {
        Logger.getLogger(JavaFXApplication11.class.getName())
                .log(Level.SEVERE, null, ex);
    }

```

# Answer
Combining this code is all about synchronizing the reading of the sensors with the control sequences that are sent from the Java program.

The second program reads the Serial port continuously in the loop method. A better way would be to use a serial interrupt for this. Let me give you an example.

My code is written without an IDE so it is just an untested example. But hopefully I did not include errors ;-).

I use the first program as a base:

```
const int model = 0;
float sensitivity[] = {
  0.185,// for ACS712ELCTR-05B-T
  0.100,// for ACS712ELCTR-20A-T
  0.066// for ACS712ELCTR-30A-T
} ;

unsigned long count = 0;
float         Vsum  = 0;
float         Csum  = 0;

long startTime = 0;

void setup()
{
  Serial.begin(9600);
  // setting the LED pins to output
  // I use a loop
  for ( int i = 2; i < 14; i++ )
  {
    pinMode( i, OUTPUT );
  }
}

void loop()
{
  float Vave = 0;
  float Cave = 0;
  // pow is to expensive for the loop
  // I use a constant
  float milli = 0.001;

  if ( startTime = 0 ) startTime = millis();

  float voltage = map( analogRead( A1 ), 0, 1023, 0, 2500 ) / 100.0;
  Vsum = Vsum + voltage;

  float current  = ( voltage / sensitivity[ model ] );
  float current1 = current * milli;

  Csum = Csum + current1;

  count++;

  Vave = Vsum / count;
  Cave = Csum / count;
  float watts = Vave * Cave;

  // you did not use a time delta here,
  // but energiy it work over a time period
  long timeDelta = ( millis() - startTime ) / 1000;

  float energy = ( watts * timeDelta ) / 3600;
  Serial.print( energy, 6 );
  Serial.println( "Wh" );

  serialHandler();

  delay( 1000 );
}

void serialHandler()
{
   delay( 200 );
   while ( Serial.available() )
   {
     // get the new byte:
     int inByte = Serial.read();

     if(inByte == 0x01)
     {
       digitalWrite(13, HIGH);
       //Serial.println("ON");
     }
     else if(inByte == 0x00)
     {
       digitalWrite(13, LOW);
       //Serial.println("OFF");
     }
     else if(inByte == 0x02) digitalWrite(12, HIGH);
     else if(inByte == 0x03) digitalWrite(12, LOW);
     else if(inByte == 0x04) digitalWrite(11, HIGH);
     else if(inByte == 0x05) digitalWrite(11, LOW);
     else if(inByte == 0x06) digitalWrite(10, HIGH);
     else if(inByte == 0x07) digitalWrite(10, LOW);
     else if(inByte == 0x08) digitalWrite(9,  HIGH);
     else if(inByte == 0x09) digitalWrite(9,  LOW);
     else if(inByte == 0x10) digitalWrite(8,  HIGH);
     else if(inByte == 0x11) digitalWrite(8,  LOW);
     else if(inByte == 0x12) digitalWrite(7,  HIGH);
     else if(inByte == 0x13) digitalWrite(7,  LOW);
     else if(inByte == 0x14) digitalWrite(6,  HIGH);
     else if(inByte == 0x15) digitalWrite(6,  LOW);
     else if(inByte == 0x16) digitalWrite(5,  HIGH);
     else if(inByte == 0x17) digitalWrite(5,  LOW);
     else if(inByte == 0x18) digitalWrite(4,  HIGH);
     else if(inByte == 0x19) digitalWrite(4,  LOW);
     else if(inByte == 0x20) digitalWrite(3,  HIGH);
     else if(inByte == 0x21) digitalWrite(3,  LOW);
     else if(inByte == 0x22) digitalWrite(2,  HIGH);
     else if(inByte == 0x23) digitalWrite(2,  LOW);
     //else if(inByte == 0x24) digitalWrite(1,  HIGH);
     //else if(inByte == 0x25) digitalWrite(1,  LOW);
     //else if(inByte == 0x26) digitalWrite(0,  HIGH);
     //else if(inByte == 0x27) digitalWrite(0,  LOW);
   }
}

```

**EDIT:**

I changed the code a little bit according to Juraj comments. I also commented the \`Serial.println' s that had reported the LED 13 state.
> 1 votes

# Answer
```
void serialEvent();
const int model = 0;
float sensitivity[] = {
  0.185,// for ACS712ELCTR-05B-T
  0.100,// for ACS712ELCTR-20A-T
  0.066// for ACS712ELCTR-30A-T
} ;

unsigned long count = 0;
float         Vsum  = 0;
float         Csum  = 0;
float         DecPowerRate = 9.8623 ;//kWh
long          startTime = 0;
float         no_voltage = 0.00;
//float           address = 0;
float         no_CURRENT = 0.000;
float energy;
long timeDelta;float consumption;float Kwatts;
void setup()
{
  Serial.begin(9600);
  // setting the LED pins to output
  // I use a loop
  for ( int i = 2; i < 14; i++ )
  {
    pinMode( i, OUTPUT );
  }
}

void loop()
{
  float Vave = 0;
  float Cave = 0;
  float milli = 0.001;// pow is to expensive for the loop

  if ( startTime = 0 ) startTime = millis();

  float voltage = map( analogRead( A1 ), 0, 1023, 0, 2500 ) / 100.0;

  if( voltage >no_voltage){
  Vsum = Vsum + voltage;

  float current  = ( voltage / sensitivity[ model ] );
  float current1 = current * milli;

  Csum = Csum + current1;

  count++;

  Vave = Vsum / count;
  Cave = Csum / count;
  Kwatts = (Vave * Cave)/1000;
  }
    if (Cave >no_CURRENT){
  // you did not use a time delta here,
  // but energiy it work over a time period
  timeDelta = ( millis() - startTime ) / 1000;
  energy = ( Kwatts * timeDelta ) / 3600;
  consumption = energy * DecPowerRate;
}

  //Serial.print( energy, 6 );
 // Serial.println( "kWh" );

  Serial.print( "P " );
  Serial.print( consumption, 6 );
  Serial.println( "/kWh" );
  delay( 1000 );

}
// naming convention for a serial interrupt
void serialEvent()
{
   while (Serial.available())
   {
 // get the new byte:
 int inByte = Serial.read();

 if(inByte == 0x01)
 {
   digitalWrite(13, HIGH);
   //Serial.println("ON");
 }
 else if(inByte == 0x00)
 {
   digitalWrite(13, LOW);
   //Serial.println("OFF");
 }
 else if(inByte == 0x02) digitalWrite(12, HIGH);
 else if(inByte == 0x03) digitalWrite(12, LOW);
 else if(inByte == 0x04) digitalWrite(11, HIGH);
 else if(inByte == 0x05) digitalWrite(11, LOW);
 else if(inByte == 0x06) digitalWrite(10, HIGH);
 else if(inByte == 0x07) digitalWrite(10, LOW);
 else if(inByte == 0x08) digitalWrite(9,  HIGH);
 else if(inByte == 0x09) digitalWrite(9,  LOW);
 else if(inByte == 0x10) digitalWrite(8,  HIGH);
 else if(inByte == 0x11) digitalWrite(8,  LOW);
 else if(inByte == 0x12) digitalWrite(7,  HIGH);
 else if(inByte == 0x13) digitalWrite(7,  LOW);
 else if(inByte == 0x14) digitalWrite(6,  HIGH);
 else if(inByte == 0x15) digitalWrite(6,  LOW);
 else if(inByte == 0x16) digitalWrite(5,  HIGH);
 else if(inByte == 0x17) digitalWrite(5,  LOW);
 else if(inByte == 0x18) digitalWrite(4,  HIGH);
 else if(inByte == 0x19) digitalWrite(4,  LOW);
 else if(inByte == 0x20) digitalWrite(3,  HIGH);
 else if(inByte == 0x21) digitalWrite(3,  LOW);
 else if(inByte == 0x22) digitalWrite(2,  HIGH);
 else if(inByte == 0x23) digitalWrite(2,  LOW);

   }
}

```

This worked! Thanks for the help! \<3
> 0 votes

---
Tags: arduino-uno, sensors, led, java
---


title: String to Dynamic Byte array

text:
# Question
Title: String to Dynamic Byte array
I'm new in Arduino stuck in String to a dynamic byte array.

My String:

```
String Finalval="6D616320747820636E662031352033300D0A";

```

Dynamic Byte array:

```
byte ft[]={0x6D,0x61,0x63,0x20,0x74,0x78,0x20,0x63,0x6E,0x66,0x20,0x31,0x35,0x20,0x33,0x30,0x0D,0x0A};

```

# Answer
Common C-string to byte array functions as shown in https://stackoverflow.com/questions/3408706/hexadecimal-string-to-byte-array-in-c work perfectly fine.

```
Source hex string: 6D616320747820636E662031352033300D0A
Conversion OK buff 0x289 len 18
output byte array:
  00 6d 61 63 20 74 78 20 63 6e 66 20 31 35 20 33 30  mac tx cnf 15 30
  10 0d 0a                                            ..

```

```
#include <Arduino.h>

void hexDump (const char *desc, const void *addr, const int len);

bool convert_hexstr_to_bytearray(const char* source, uint8_t* &output,
        size_t& output_len) {
    size_t len = strlen(source);
    //cannot convert non-even string length
    if ((len % 2) != 0) {
        return false;
    }
    //dynamically allocate output buffer
    output_len = len / 2;
    output = (uint8_t*) malloc(output_len);
    const char* curPos = source;
    for (size_t count = 0; count < len; count++) {
        sscanf(curPos, "%2hhx", output + count);
        curPos += 2;
    }
    return true;
}

String Finalval="6D616320747820636E662031352033300D0A";

void setup() {
    Serial.begin(115200);
    Serial.print("Source hex string: ");
    Serial.println(Finalval);
    Serial.flush();

    uint8_t* buffer = nullptr;
    size_t buffer_len = 0;
    if(convert_hexstr_to_bytearray(Finalval.c_str(), buffer, buffer_len)) {
        Serial.println("Conversion OK buff 0x" + String((long)buffer,HEX) + " len " + String(buffer_len));
        hexDump("output byte array", buffer, buffer_len);
    } else {
        Serial.println("Conversion failed\n");
    }

    //free memory
    if(buffer)
        free(buffer);
}

void loop() {
}

void PrintHex8(const uint8_t *data, uint8_t length) // prints 8-bit data in hex
{
     char tmp[length*2+1];
     byte first;
     byte second;
     for (int i=0; i<length; i++) {
           first = (data[i] >> 4) & 0x0f;
           second = data[i] & 0x0f;
           // base for converting single digit numbers to ASCII is 48
           // base for 10-16 to become lower-case characters a-f is 87
           // note: difference is 39
           tmp[i*2] = first+48;
           tmp[i*2+1] = second+48;
           if (first > 9) tmp[i*2] += 39;
           if (second > 9) tmp[i*2+1] += 39;
     }
     tmp[length*2] = 0;
     Serial.print(tmp);
}

void hexDump (const char *desc, const void *addr, const int len) {
    int i;
    unsigned char buff[17];
    const unsigned char *pc = (const unsigned char*)addr;

    // Output description if given.
    if (desc != NULL) {
        Serial.print (desc);
        Serial.println(":");
    }

    if (len == 0) {
        Serial.print("  ZERO LENGTH\n");
        return;
    }
    if (len < 0) {
        Serial.println("  NEGATIVE LENGTH: " + String(len));
        return;
    }

    // Process every byte in the data.
    for (i = 0; i < len; i++) {
        // Multiple of 16 means new line (with line offset).

        if ((i % 16) == 0) {
            // Just don't print ASCII for the zeroth line.
            if (i != 0) {
                Serial.print ("  ");
                Serial.println((char*)buff);
            }

            // Output the offset.
            Serial.print ("  ");
            PrintHex8((uint8_t*)&i, 1);
        }

        // Now the hex code for the specific character.
        Serial.print(" ");
        PrintHex8(pc + i,1);

        // And store a printable ASCII character for later.
        if ((pc[i] < 0x20) || (pc[i] > 0x7e))
            buff[i % 16] = '.';
        else
            buff[i % 16] = pc[i];
        buff[(i % 16) + 1] = '\0';
    }

    // Pad out last line if not exactly 16 characters.
    while ((i % 16) != 0) {
        Serial.print ("   ");
        i++;
    }

    // And print the final ASCII bit.
    Serial.print ("  ");
    Serial.println((char*)buff);
}

```
> 0 votes

---
Tags: arduino-uno, c++, c
---


# Question
Title: How can I save my float 'ave' on the EEPROM continuously?
How can I save my output continuously to EEPROM? Or is this even possible? Please help me out.

```
void setup() {
  Serial.begin(9600);
}

void loop() {
  static unsigned long count = 0;
  static float sum = 0;
  float ave = 0;
  int volt = analogRead(A1);
  float voltage = map(volt, 0, 1023, 0, 2500) / 100.0;
  Serial.print("Voltage: ");
  Serial.println(voltage, 2);
  sum = sum + voltage;
  count++;
  ave = sum / count;
  Serial.print("Average: ");
  Serial.println(ave, 2);
  Serial.println("-----");
  delay(3000);
}

```

# Answer
It's possible, but it's certainly not advised.

EEPROM has a limited number of writes before it's dead. By writing continuously to the EEPROM you will kill it in no time at all.
> 1 votes

# Answer
The answer is: Read the Arduino Reference and find EEPROM.put

But your actual problem is that

1) if you write to eeprom every 3 seconds, the Arduino eventually won't survive you

2) you eventually rather want to write the sum and the count, in your case ?

You should also think about how to initialize from EEPROM after Restart.

Perhaps it's sufficient to save restart values only once after 1 minute / 1 hour / daily if it still changes?

BTW the "Update only if it changed" is already built into the put() method.
> 1 votes

---
Tags: arduino-uno, eeprom
---


# Question
Title: Connecting 12V WS2811 RGB LEDs to Arduino Uno & 5V Power Source (Breadboard needed?)
I have an Arduino Uno, 12V WS2811 RGB LEDs (from Mokungit), a 5V power source, and DC power connector. I do not have a breadboard and hope I don't need one.

This is almost exactly what I need to follow this tutorial to build a Stranger Things wall. The LED strip listed shares the same name as the one I have, but the wiring is different.

Here's a photo from the Instructables site:

However, the wires coming from my strip don't match up to the instructions, and I can't seem to figure out how to get these bad boys burning.

Thanks to anyone who can help me get started!

# Answer
> 2 votes
This image, from here, shows which pins are what:

Note the flat *key* next to the 12 V and GND pins. In addition:

* the GND wire has a black broken line printed along it;
* the data line is in the middle.

If you trust the image then you should be able to wire them up correctly.

# Answer
> 2 votes
That picture is for a 5 Volt rgb led strip. You have to use a 12 Volt power supply for your led and power the uno with another 5volt source. A computer power supply would be great for supplying power both 5 Volt and 12 Volt.

# Answer
> 1 votes
The signals are clear on the bulb pcb. Take a multimeter in continuity mode and probe to see which pins on the round connector is DI, GND and +12v.

Then connect DI to the arduino. +12v to the strip. GND from the Arduino, LED strip and your +12v source should all be conected together.

---
Tags: arduino-uno, led
---


# Question
Title: Student Code: map function not functioning
We made this code in class:

```
 int red = 6;
  int green = 7;
  int blue = 8;
  int pot = A0;
  int potVal = 0;
  int chosenColor = 0;

void setup() {
  // put your setup code here, to run once:
  pinMode(red, OUTPUT);
  pinMode(green, OUTPUT);
  pinMode(blue, OUTPUT);
  pinMode(pot, INPUT);
  Serial.begin (9600);
}

void loop() {
  // put your main code here, to run repeatedly:
  potVal = analogRead(pot);
  chosenColor = map(potVal, 0, 1023, 1, 3);
  if(chosenColor = 1) {
    redCycle();
  }

  else {
    analogWrite(red,255);
  }

  if(chosenColor = 2) {
    greenCycle();
  }

  else {
    analogWrite(green,255);
  }

  if(chosenColor = 3) {
    blueCycle();
  }

  else {
    analogWrite(blue,255);
  }
  Serial.println(chosenColor);
  Serial.println(potVal);
  delay(500);
}

void redCycle() {
    analogWrite(red,0);
  for(int i=0; i < 256; i+=5) {
    analogWrite(red, i);
  }
}

void greenCycle() {
  analogWrite(green,0);
  for(int i=0; i < 256; i+=5) {
    analogWrite(green, i);
  }
}

void blueCycle() {
  analogWrite(blue,0);
  for(int i=0; i < 256; i+=5) {
    analogWrite(blue, i);
  }
}

```

When we open the serial monitor we find that chosenColor is always 3 regardless of what the potVal is reading. I am sure is something simple but we can't find where is the error. Please help.

# Answer
> 3 votes
As Edgar Bonet pointed out, “`chosenColor = 3` means 'let chosenColor take the value 3'”. That is, your `potVal = analogRead(pot); chosenColor = map(potVal, 0, 1023, 1, 3);` sequence may very well be working, but by the time you get to `Serial.println(chosenColor);` you have changed `chosenColor` to 3.

First, the statement `if(chosenColor = 1) {...}` changes `chosenColor` to 1. Then the statement `if(chosenColor = 2) {...}` changes `chosenColor` to 2. Finally, `if(chosenColor = 3) {...}` changes `chosenColor` to 3, just before you print out the current value of `chosenColor`.

When you wish to compare two numeric values for equality, use `==` instead of `=`.

# Answer
> 1 votes
You are confusing `=` (assign) with `==` (compare).

eg.

### Wrong! ...

```
if (chosenColor = 3)  // this assigns 3 to chosenColor

```

### Correct:

```
if (chosenColor == 3)   // compare

```

---

> Still not sure why the map function is not working.

You just *assumed* it is not working. Before making assumptions like this do a Serial print to show what the return value of the map function is. (Directly after calling `map` \- not later on in the code).

# Answer
> 0 votes
Although not related to your main problem, I would like to point out that there *is* an issue with your use of the `map()` function. Or maybe I should say, with the `map()` function itself. Since it works with integer arithmetic, and integer division by default rounds towards zero, you get a mapping that may be quite different from what you expect.

In the table below, I am showing the result of `map(potVal, 0, 1023, 1, 3)`. The column labeled “not rounded” is what you would get if the mapping was done in floating point. The last column is the rounded value you actually get out of `map()`:

```
potVal  not rounded  rounded
----------------------------
    0     1.00000       1
            ...
  511     1.99902       1
  512     2.00098       2
            ...
 1022     2.99804       2
 1023     3.00000       3

```

As you see, you have 512 possible values of `potVal` mapped to 1, 511 values mapped to 2 and one single value mapped to 3.

I assume you would rather have one third of the range mapped to each value. This can be achieved by writing `map(potVal, 0, 1024, 1, 4)`:

```
potVal  not rounded  rounded
----------------------------
    0     1.00000       1
            ...
  341     1.99902       1
  342     2.00195       2
            ...
  682     2.99805       2
  683     3.00098       3
            ...
 1023     3.99707       3

```

This gives 342 values mapped to 1, 341 values mapped to 2 and 341 values mapped to 3. Now, the problem is that this way of using `map()` is confusing. You may prefer to write something more explicit instead, like:

```
if (potval < 1023/3) chosenColor = 1;
else if (potval < 1023*2/3) chosenColor = 2;
else chosenColor = 3;

```

# Answer
> 0 votes
Not sure if this helps but I wanted a slider with a range of 0 to 200 to give 3 values; 0 for the first third of movement, 1 for the second third and 2 for the last third

I used map(slider value, 0, 134, 0, 2)

---
Tags: arduino-uno, arduino-ide, code-review
---


title: expected '}' at end of input

text:
# Question
Title: expected '}' at end of input
hi i am getting this error, im guessing i have a bracket missing or one in the wrong place. any help is appreciate, still new at this. thank you

(code bellow)

```
#include <Wire.h>
#include <Adafruit_PWMServoDriver.h>
#include <XBOXRECV.h>

Adafruit_PWMServoDriver pwm1 = Adafruit_PWMServoDriver(0x40);

USB Usb;
XBOXRECV Xbox(&Usb);

// our servo # counter
// You can change the value from 0 to 15 (servo 1 through 16)
uint8_t util1servo = 0;
uint8_t util2servo = 1;
uint8_t ldoorservo = 2;
uint8_t rdoorservo = 7;
uint8_t sdoorservo = 3;
uint8_t mdoorservo = 8;

//Servo limits definition.
//You will have to figure out which numbers match your servo be carefull with these,
//it can break your servo if you go beyond the limits. The ones listed here are for my own setup
#define UTIL1MIN  150 // Close position of the Top Utility arm
#define UTIL1MAX  310 // Open position of the Top Utility arm
#define UTIL2MIN  140 // Close position of the Bottom Utility arm
#define UTIL2MAX  300 // Open position of the Bottom Utility arm
#define LDOORMIN  390 // Close position of the Left door
#define LDOORMAX  550 // Open position of the Left door
#define RDOORMIN  555 // Close position of the Right door
#define RDOORMAX  360 // Open position of the Right door
#define SDOORMIN  492 // Close position of the Small door
#define SDOORMAX  200 // Open position of the Small door
#define MDOORMIN  550 // Close position of the Mid door
#define MDOORMAX  380 // Open position of the Mid door

//Status for each door open/close
int LDOORSTATUS = 0; // Status 0 = Closed, 1 = Open
int RDOORSTATUS = 0; // Status 0 = Closed, 1 = Open
int SDOORSTATUS = 0; // Status 0 = Closed, 1 = Open
int MDOORSTATUS = 0; // Status 0 = Closed, 1 = Open

void setup() {

   pwm1.begin();

  pwm1.setPWMFreq(60);  // Analog servos run at ~60 Hz updates

  Wire.begin();

}

void loop() {

//Left door
if (Xbox.getButtonClick(LEFT, 0)){
  if (Xbox.getButtonPress(R1, 0)) {
    if(LDOORSTATUS == 0){
          for (uint16_t lpulselen = LDOORMIN; lpulselen < LDOORMAX; lpulselen++){
          pwm1.setPWM(ldoorservo, 0, lpulselen); //Open the door
          delay(1);
          }
          LDOORSTATUS = 1;
          }
        else if (LDOORSTATUS == 1){
             for (uint16_t lpulselen = LDOORMAX; lpulselen > LDOORMIN; lpulselen--){
             pwm1.setPWM(ldoorservo, 0, lpulselen); //Close the door
             delay(1);
             }
             LDOORSTATUS = 0;
     }

```

# Answer
> 2 votes
Auto-formatting produced the following - look at your `loop()` function and you'll see the problem:

```
#include <Wire.h>
#include <Adafruit_PWMServoDriver.h>
#include <XBOXRECV.h>

Adafruit_PWMServoDriver pwm1 = Adafruit_PWMServoDriver(0x40);

USB Usb;
XBOXRECV Xbox(&Usb);

// our servo # counter
// You can change the value from 0 to 15 (servo 1 through 16)
uint8_t util1servo = 0;
uint8_t util2servo = 1;
uint8_t ldoorservo = 2;
uint8_t rdoorservo = 7;
uint8_t sdoorservo = 3;
uint8_t mdoorservo = 8;

//Servo limits definition.
//You will have to figure out which numbers match your servo be carefull with these,
//it can break your servo if you go beyond the limits. The ones listed here are for my own setup
#define UTIL1MIN  150 // Close position of the Top Utility arm
#define UTIL1MAX  310 // Open position of the Top Utility arm
#define UTIL2MIN  140 // Close position of the Bottom Utility arm
#define UTIL2MAX  300 // Open position of the Bottom Utility arm
#define LDOORMIN  390 // Close position of the Left door
#define LDOORMAX  550 // Open position of the Left door
#define RDOORMIN  555 // Close position of the Right door
#define RDOORMAX  360 // Open position of the Right door
#define SDOORMIN  492 // Close position of the Small door
#define SDOORMAX  200 // Open position of the Small door
#define MDOORMIN  550 // Close position of the Mid door
#define MDOORMAX  380 // Open position of the Mid door

//Status for each door open/close
int LDOORSTATUS = 0; // Status 0 = Closed, 1 = Open
int RDOORSTATUS = 0; // Status 0 = Closed, 1 = Open
int SDOORSTATUS = 0; // Status 0 = Closed, 1 = Open
int MDOORSTATUS = 0; // Status 0 = Closed, 1 = Open

void setup() {

  pwm1.begin();

  pwm1.setPWMFreq(60);  // Analog servos run at ~60 Hz updates

  Wire.begin();

}

void loop() {

  //Left door
  if (Xbox.getButtonClick(LEFT, 0)) {
    if (Xbox.getButtonPress(R1, 0)) {
      if (LDOORSTATUS == 0) {
        for (uint16_t lpulselen = LDOORMIN; lpulselen < LDOORMAX; lpulselen++) {
          pwm1.setPWM(ldoorservo, 0, lpulselen); //Open the door
          delay(1);
        }
        LDOORSTATUS = 1;
      }
      else if (LDOORSTATUS == 1) {
        for (uint16_t lpulselen = LDOORMAX; lpulselen > LDOORMIN; lpulselen--) {
          pwm1.setPWM(ldoorservo, 0, lpulselen); //Close the door
          delay(1);
        }
        LDOORSTATUS = 0;
      }

```

---
Tags: servo, code-review
---