# Question
Title: Entire arrays are not read by Processing sent by Arduino unless cord is unplugged and plugged back in?
I am using an Arduino to read sensors and then send the data to the serial port for Processing to read. It works totally fine when I first download the code and run the Processing program. But if I stop the Processing code and then start it again I will get the error ArrayIndexOutOfBounds. I print the array that Processing reads and it is only 3 indexes long, even though the Arduino code should be sending an array that's 7 long. This error happens because I am calling an index that doesn't exist, but it should exist, Processing just isn't receiving the entire array. If I unplug the USB cord from the Arduino and plug it back in this error won't happen and Processing will receive the entire array. I don't understand why this is happening. I have tried using the button on the Arduino to reset it each time before running the Processing code but this doesn't work, I actually need to unplug the cord and plug it back in.

If you have any input that would be great! Thanks in advance!

EDIT: I am posting the code because it was requested. There's a lot of unnecessary stuff on reading the sensors and creating graphics for in Processing. The gist is that the user interacts with a Processing program and clicks when the want the data sent by Arduino to be saved. I had been talking to someone else about the problems Ive been having and they think it may have to do with the serial buffer, and that I need to clear it or wait for it to be cleared. I have looked into this and am having trouble figuring out the proper way to do it. I have tried resetting the Arduino code using SoftRestart library, but that hasn't worked.

Here's the Arduino Code:

```
//need to include these libraries to be able to read from serial and read   the sensors
#include <SoftwareSerial.h>
#include <Wire.h>
#include "Adafruit_MCP9808.h"
#include <Adafruit_Sensor.h>
#include <Adafruit_BME280.h>
#include <AMS5915.h>
#include <AMS5812.h>
#include <Adafruit_ADS1015.h>

//Create sensor objects.
Adafruit_MCP9808 tempsensor18 = Adafruit_MCP9808(); //sensor with 0x18 address is Dry Bulb Temp
Adafruit_MCP9808 tempsensor19 = Adafruit_MCP9808(); //sensor with 0x19 address is Temp in chamber
Adafruit_BME280 bme; //pressure and humidity sensor
AMS5915 amsD; //sensor being used for reading differential pressure across the nozzle
AMS5812 amsS; //sensor being used to measure static pressure in the chamber
Adafruit_ADS1115 ads; //16-bit ADC sensor (actually 15-bit when used as a single-ended ADC)

//Initializing variables
float tableVals[]={0,0,0,0,0,0,0,0}; //an array that will hold sensor values. If more sensors or readings are added the size of the array needs to increase
float relHum=0;
float dryBulb=0;
float wetBulb=0;
float pressure=0;
float chamberTemp=0;
float pressureDiff;
float pressureStatic;
float rpm;
float correctedADC=0;
float correctedRPM;
float correctedADCx2=0;
float correctedRPMx2=0;
int counts=0;
const float AMS5915_0010_D_B_P_MIN = -10.0;     // minimum pressure, millibar (for sensor reading differential pressure)
const float AMS5915_0010_D_B_P_MAX = 10.0;      // maximum pressure, millibar (for sensor reading differential pressure)
const float AMS5812_0003_D_B_P_MIN = -0.3;      // minimum pressure, PSI (for sensor reading static pressure)
const float AMS5812_0003_D_B_P_MAX = 0.3;       // maximum pressure, PSI (for sensor reading static pressure)
const float AMS5812_0003_D_B_T_MIN = -25.0;     // minimum temperature, C (for sensor reading static pressure)
const float AMS5812_0003_D_B_T_MAX = 85.0;      // maximum temperature, C (for sensor reading static pressure)

//Setup function, will run one time. Initializes sensors
void setup() {
  Serial.begin(9600); //set baud rate
  amsD.getAddr_AMS5915(AMS5915_DEFAULT_ADDRESS);   // 0x28
  amsS.getAddr_AMS5812(AMS5812_DEFAULT_ADDRESS);   // 0x78
  ads.setGain(GAIN_ONE); //1x gain +/- 4.096V  1 bit = 0.125mV
  ads.begin(); //starting sensors
  amsD.begin();
  amsD.begin();
  if(!tempsensor18.begin(0x18) || !tempsensor19.begin(0x19)|| !bme.begin())    {  //wait until these sensors are ready
    while(1);
  }
}

//loop function keeps repeating
 void loop() {
  if (counts >100){  //will only enter conditional if counts variable is over 100
    readSensors(); //go to readSensors function below

    tableVals[0]= pressure; //set pressure to the first index in array
    tableVals[1]=relHum;  //rel hum to the second index in array
    tableVals[2]=wetBulb; //wet bulb to the third index in array
    tableVals[3]=dryBulb; //dry bulb to the fourth index in array
    tableVals[4]=chamberTemp; //chamber temperature to the fifth index in the array
    tableVals[5]=pressureDiff; //differential pressure to the sixth index in the array
    tableVals[6]=pressureStatic; //static pressure to the seventh index in the array
    tableVals[7]=rpm; //RPM is the eighth index in the array
    Serial.flush();
    Serial.print(tableVals[0]); //sending all the values to Processing, need commas so Processing can split into different values (don't totally know why I put everything in an array first, that's just how I saw it done in an example)
    Serial.print(",");
    Serial.print(tableVals[1]);
    Serial.print(",");
    Serial.print(tableVals[2]);
    Serial.print(",");
    Serial.print(tableVals[3]);
    Serial.print(",");
    Serial.print(tableVals[4]);
    Serial.print(",");
    Serial.print(tableVals[5],4);
    Serial.print(",");
    Serial.print(tableVals[6],4);
    Serial.print(",");
    Serial.print(tableVals[7]);
    Serial.println(","); //need this last comma for some reason or it gets messed up
    counts=0; //reset counts variable to 0
  }
  counts++; //increment counts
}

//This function is called in the loop() function. It reads all of the sensors
void readSensors(){
  dryBulb = tempsensor18.readTempC(); //read from temp sensor with 0x18 address
  relHum = bme.readHumidity();  //read humidity from bme sensor
  pressure = bme.readPressure()/100.0F; //read pressure, in hpa
  pressure = pressure * 0.029529983071445; //convert pressure to inches of mercury
  wetBulb = dryBulb*atan(0.151977*pow(relHum + 8.313659, 0.5)) + atan(dryBulb +relHum) - atan(relHum - 1.676331) + 0.00391838*pow(relHum,1.5)*atan(0.023101*relHum) - 4.686035; //equation finds approximate wet bulb temp from humidity and dry bulb temp
  chamberTemp = tempsensor19.readTempC(); //read from temp sensor with 0x19 address

  //this chunk of code gets the differential pressure reading and converts it to inches of water
  byte errorDiff;
  int8_t addressD;

  addressD = amsD.ams_i2cAddress;
  Wire.beginTransmission(addressD);
  errorDiff = Wire.endTransmission();
  if (errorDiff == 0){
    amsD.Measure_PressureAndTemperature(AMS5915_0010_D_B_P_MIN, AMS5915_0010_D_B_P_MAX);
    pressureDiff=amsD.getPressure();
    pressureDiff = pressureDiff * 0.40146307866177;
  }

  //this chunk of code gets the static pressure reading and converts to inches of water
  byte errorStatic;
  int8_t addressS;

  addressS = amsS.ams_i2cAddress;
  Wire.beginTransmission(addressS);
  errorStatic = Wire.endTransmission();
  if(errorStatic == 0){
    amsS.Measure_PressureAndTemperature(AMS5812_0003_D_B_P_MIN, AMS5812_0003_D_B_P_MAX, AMS5812_0003_D_B_T_MIN, AMS5812_0003_D_B_T_MAX);
    pressureStatic = amsS.getPressure();
    pressureStatic = pressureStatic*27.679904842545;
  }

  //the next chunk of code takes 300 readings from the ADC, averages them together. Applies two correction equations to the ADC and then converts it to the RPM that is sent to Processing
  float ADCcount=0;
  float ADCtotal=0;
  float finalADC=0;

  int16_t adc0;
  while(ADCcount<100){ //taking 100 ADC readings and averaging them
    adc0 = ads.readADC_SingleEnded(0);
    ADCcount=ADCcount+1;
    ADCtotal=ADCtotal+adc0;
  }

  finalADC=ADCtotal/ADCcount;
  rpm = (40740.0/32767.0)*finalADC;
}

```

Processing Code:

```
//initializing variables
import processing.serial.*; //need this library to read serial data
Serial myPort;
int signal=0; //this will signal what part of the draw function to read
Table table;
int count =-1;
int lf = 10; //10 is the ASCII number that represents an enter key
String d_string;
String m_string;
String y_string;
float countVals[];
float pressureVals[];
String voltage=""; //these variables need to be blank strings since these are the variables that come from user input
String current=""; //they will be changed to floats before being saved in the table
String fileName="";
String COM ="";
float Pdiff;
float Pstatic;

//Set up
void setup(){
  size(300,410); //creating the start graphics
  background(255);
  String s = "Click on the rectangle to start.";
  textSize(20);
  textAlign(CENTER);
  fill(25);
  text(s,10,10, 290, 150);
  fill(255, 0, 0);
  rectMode(CORNERS);
  rect(115,85,195,160); //drawing rectangle 'button'

  table = new Table();  //create new table
  table.addColumn("Date");  //make a Date column
  table.addColumn("Reading Number"); //make a Reading Number column
  table.addColumn("Voltage V");  //Voltage column
  table.addColumn("Current A");  //Current column
  table.addColumn("Pressure inHg"); //Pressure column
  table.addColumn("Humidity %");  //Relative Humidity column
  table.addColumn("Wet Bulb Temp. *C");  //Wet Bulb Temp. column
  table.addColumn("Dry Bulb Temp. *C");  //Dry Bulb temp. column
  table.addColumn("Chamber Temp. *C"); //Chamber Temp column
  table.addColumn("Static Pressure inH20");  //Static pressure column
  table.addColumn("Differential Pressure inH2O"); //Differential Pressure column
  table.addColumn("RPM");  //RPM column

  int day = day();  //Find the day
  int month = month(); //find the month
  int year = year();  //find the year
  d_string = str(day);  //convert these integers to strings
  m_string = str(month);
  y_string = str(year);
}

//Draw function is continuously looping
   void draw(){
      if(signal==1){ //if signal is 1 (set in keyPressed) ask the user to enter the COM
        background(255);
        String f = "Enter what number in the list of COM Ports the Arduino is plugged into (This is not necessarily the COM number.) \nPress ENTER to continue.";
        textAlign(CENTER); //center the text on the screen
        fill(25); //setting fill color
        stroke(0);  //setting stroke color
        textSize(14); //setting text size
        text(f,10,10,290,200); //displaying the instructions in the graphics box
        textSize(20); //resetting text size
        text(COM,10,125,290,200); //displaying the COM the user is typing
      }
      else if (signal==2){ //if signal is 2 (set in keyPressed) ask the user to enter the name of the CSV file where the data will be saved
        background(255);
        String f = "Enter the name of the CSV file where the data will be saved. \nThis will be located in the folder called 'data' that is in the same folder as this application. \nPress ENTER to continue.";
        textAlign(CENTER);
        fill(25);
        stroke(0);
        textSize(12);
        text(f,10,10,290,200); //displaying instructions to the user
        textSize(20);
        text(fileName,10,125,290,200); //displaying the user file name the user is typing
      }
      else if(signal==3){ //if signal is 3 (set in keyPressed) ask the user to input the voltage
        background(255);
        String f = "Enter the Voltage in Volts. Press ENTER to continue.";
        textAlign(CENTER);
        fill(25);
        stroke(0);
        textSize(20);
        text(f,10,10,290,200); //displaying instructions to the user
        text(voltage,10,125,290,200); //displaying the voltage the user is typing
      }
      else if(signal ==4){ //if signal variable is 5 (set in conditional above) ask the user to input the current
        background(255);
        String f = "Enter the Current in Amps. Press ENTER to continue.";
        textAlign(CENTER);
        fill(25);
        stroke(0);
        textSize(20);
        text(f,10,10,290,200); //displaying instructions
        text(current, 10,125,290,200); //displaying the current the user is typing
      }
       else if (signal ==5){ //if signal variable is 4 (set in mousePressed) then read the following chunk of code.
        String val=null;
        while (val==null){
          val = myPort.readStringUntil('\n'); //read serial data sent by Arduino
        }
            val = trim(val); //trim off any white space
            countVals = float(split(val, ',')); //split serial data into individual readings
            delay(500);
            signal =6; //set signal to 6 so next chunk of code will be read
      }
       else if (signal ==6){ //if signal is 6 (set in the above conditional) read the following chunk of code
        TableRow newRow = table.addRow(); //add a row to the spreadsheet
    newRow.setString("Date", m_string +"."+ d_string +"."+ y_string); //write data in the correct columns in the table
    newRow.setInt("Reading Number", count);
    newRow.setFloat("Pressure inHg", countVals[0]);
    newRow.setFloat("Humidity %", countVals[1]);
    newRow.setFloat("Wet Bulb Temp. *C", countVals[2]);
    newRow.setFloat("Dry Bulb Temp. *C", countVals[3]);
    newRow.setFloat("Chamber Temp. *C", countVals[4]);
    newRow.setFloat("Differential Pressure inH2O", countVals[5]);
    newRow.setFloat("Static Pressure inH20", countVals[6]);
    newRow.setFloat("Voltage V", float(voltage)); //values that were strings are converted to floats
    newRow.setFloat("Current A", float(current));
    newRow.setFloat("RPM", round(countVals[7]));
    saveTable(table, "data/"+fileName+".csv"); //saving the data in a folder called 'data' in a file with the user given name
    signal = 7; //signal variable back to 7 to read the next conditional
  }
  if(signal ==7){ //if signal is 7 (set in conditional above or in keyPressed), read serial port data and display graphics Draw function will continue to loop through this conditional until box is clicked so pressures are always updated.
    String pressures=null;
    while(pressures==null){
      pressures = myPort.readStringUntil('\n'); //read serial data sent by Arduino
    }
        pressures = trim(pressures); //trim off any white space
        pressureVals = float(split(pressures, ',')); //split serial data into individual readings
        println(pressureVals);
        background(255);  //reset graphics
        String s = "Click on rectangle to take a data point. Exit out of this box when done.";
        stroke(0);
        textSize(15);
        fill(25);
        textAlign(CENTER);
        text(s,10,10,290,100); //displaying instructions to user
        fill(50, 255, 200);
        rect(115,85,195,160);
        fill(0);
        textSize(12);
        textAlign(LEFT); //next line will display the previous data point if it is not the first data reading (counts needs to be 1 or greater)
        if (count>0) text("Previous Data Point: \n\t" +"Barometric Pressure inHg: " + str(countVals[0]) +"\n\tHumidity %: " +str(countVals[1]) + "\n\tWet Bulb Temp *C: " + str(countVals[2]) + "\n\tDry Bulb Temp *C: " +str(countVals[3]) +"\n\tChamber Temp *C: " + str(countVals[4])+"\n\tDifferential Pressure inH20: " + str(countVals[5]) +"\n\tStatic Pressure inH20: "+ str(countVals[6]) + "\n\tRevolutions Per Min: " + str(round(countVals[7])),10,190, 300,400);
        textAlign(10, 400);
        text("Static: " +str(pressureVals[6]) + " in.H20", 10,400); //display the static pressure on the bottom of graphics window
        textAlign(150, 400);
        text("Diff: "+ str(pressureVals[5]) + " in.H20", 150, 400); //display the differential pressure on the bottom of graphics window
  }
}

//mousePressed function will run when mouse is clicked in box
void mousePressed(){
  if(mouseX <= 195 && mouseX >= 115 && mouseY <=160 && mouseY >=85){ //if the mouse is clicked within the boundaries of the rectangle
     if(count>=0){ //if counts is greater or equal to 0 (counts starts at -1, this was b/c there were some glitches with the first click being registered)
       signal=5;
       String d= "DATA TAKEN"; //display "DATA TAKEN" to signal that a data point was taken
       textSize(15);
       fill(255,0,50);
       textAlign(LEFT);
       text(d, 107, 180);
    }
    else{   //will run if counts is not greater than or equal to 0 (so this will just be on the first click before data is taken)
      signal=1;
    }
    count++; //increment count
    mousePressed = false;  //set mousePressed to false to make sure this function doesn't run again.
  }
}

//keyPressed will run when a key on the keyboard is pressed
void keyPressed() {
  if(signal==1){ //if signal variable is 1...
    if(key==BACKSPACE){ //if the key pressed is BACKSPACE
      if(COM.length()>0){ //if length of what is being typed is greater than 0
        COM = COM.substring(0,COM.length()-1);  //then get rid of the last character
      }
    }
    else if (textWidth(COM+key) < width && key != ENTER){ //if what is being typed is not greater than the width of the graphics window and the key pressed is not ENTER
      COM = COM +key; //add the key pressed to the end of what is being typed
    }
    if(key ==ENTER){ //if ENTER is pressed
      signal=2; //change signal variable
      String portName = Serial.list()[int(COM)]; //COM is not necessarily the COM number the Arduino is plugged into. It's the number in the list of COMS that the COM is listed. I used trial and error to figure this out
      myPort = new Serial(this, portName, 9600);  //setting up baud rate
      myPort.bufferUntil(lf); //I don't know if this is actually necessary
    }
  }
  else if(signal==2){ //if signal variable is 2...
    if(key ==BACKSPACE){ //these first two conditionals for this signal number are the same for all the signal number conditionals.
      if(fileName.length()>0){
        fileName = fileName.substring(0,fileName.length()-1);
      }
    }
    else if (textWidth(fileName+key) < width && key !=ENTER) {
      fileName = fileName +key;
    }
    if (key == ENTER) { //If key pressed is ENTER
      signal=3;  //change signal
    }
  }
  else if(signal==3){ //If signal is 3...
    if(key ==BACKSPACE){
      if(voltage.length()>0){
        voltage = voltage.substring(0,voltage.length()-1);
      }
    }
    else if (textWidth(voltage+key) < width && key!=ENTER) {
      voltage = voltage +key;
    }
    if (key == ENTER) {
        signal=4;
    }
  }
  else if(signal ==4){ //if signal is 4...
    if(key == BACKSPACE){
      if(current.length()>0){
        current = current.substring(0,current.length()-1);
      }
    }
    else if (textWidth(current+key) <width && key != ENTER) {
      current = current + key;
    }
    if (key ==ENTER){
          signal=7; //change signal to 7 and display graphics to take a data point
      key = BACKSPACE;
      background(255);
      String s = "Click on rectangle to take a data point. Exit out of this box when done.";
      stroke(0);
      textSize(15);
      fill(25);
      text(s,10,10,290,100);
      fill(50, 255, 200);
      rect(115,85,195,160);
    }
  }
}

```

Sorry, this is probably very hard to follow. I do not have that much coding experience so I'm sure my logic isn't very good.

# Answer
> 3 votes
I would suggest that you are seeing reset-stutter from the serial. Basically the sketch is running and filling the serial buffer with data. Then you connect and the board resets, but some data is still in the USB chip's buffer. The sketch then starts running again, and new data is sent.

In effect I am guessing you may be seeing something like:

```
3.87,4.45,55.13,
19.44,43.12,14.56,1.01,23.87,4.45,55.13,
19.44,43.12,14.56,1.01,23.87,4.45,55.13,
19.44,43.12,14.56,1.01,23.87,4.45,55.13,
19.44,43.12,14.56,1.01,23.87,4.45,55.13,

```

where the first line is left over from the previous execution before the reset. You don't get that with a complete unplug and re-plug because there is no "previous" data in the USB buffer to send.

The simplest solution is just to handle it gracefully. Take a look at the `.length` of your float array and see if it's correct or not. Only if it has enough entries in it do you actually want to deal with the data - otherwise, you just throw it away and wait for the next line to arrive.

---
Tags: arduino-uno, softwareserial, array, processing-lang
---


# Question
Title: What's the problem? My motor works properly only when we press the left key and not others
```
int mf11=13;//motor1 1st terminal
int mf12=12;//motor1 2nd terminal
int mf21=9;//motor2 1st terminal
int mf22=8;//motor2 2nd  terminal
int fr=2;//front key
int bk=3;//back key
int rt=4;//right key
int lt=5;//left key

void setup() {
    pinMode(mf11,OUTPUT);
    pinMode(mf12,OUTPUT);
    pinMode(mf21,OUTPUT);
    pinMode(mf22,OUTPUT);
    pinMode(fr,INPUT);
    pinMode(bk,INPUT);
    pinMode(rt,INPUT);
    pinMode(lt,INPUT);
}

void loop() {
    int s = digitalRead (fr);
    int h = digitalRead (bk);
    int i = digitalRead (rt);
    int v = digitalRead (lt);
    if(s==HIGH) {
         digitalWrite(mf11,HIGH);
         digitalWrite(mf12,LOW);
         digitalWrite(mf21,HIGH);
         digitalWrite(mf22,LOW);
    }
    if (h==HIGH) {
        digitalWrite(mf11,LOW);
        digitalWrite(mf12,HIGH);
        digitalWrite(mf21,LOW);
        digitalWrite(mf22,HIGH);
    }
    if (i==HIGH) {
         digitalWrite(mf11,LOW);
         digitalWrite(mf12,HIGH);
         digitalWrite(mf21,HIGH);
         digitalWrite(mf22,LOW);
    }
   if (v==HIGH) {
        digitalWrite(mf11,HIGH);
        digitalWrite(mf12,LOW);
        digitalWrite(mf21,LOW);
        digitalWrite(mf22,HIGH);
   } else {
       digitalWrite(mf11,LOW);
       digitalWrite(mf12,LOW);
       digitalWrite(mf21,LOW);
       digitalWrite(mf22,LOW);
  }
}

```

# Answer
The reason your code only works for left, is because when v is LOW your else block gets executed and sets all pins to low! You need to use else if.

```
if(condition1)
{
  ...
}
else if (condition2)
{
  ...
}
else
{
  ...
}

```
> 3 votes

---
Tags: arduino-uno
---


title: Arduino relay. risks?

text:
# Question
Title: Arduino relay. risks?
I just started working with arduinos recently. I'm really interested in working with relays. I would like to turn a desk lamp on and off using an ios app or a web browser button. I have no experience working with relays but I would love to experiment with relays in order to turn a desk lamp on or off based on an external switch in like an IOS app or a browser.

I am wondering what are the risks in relays with arduino ? I would like to switch a desk lamp on or off using a relay but I don't really understand the risks with creating a desk lamp powered using a wall socket and turned on or off using a arduino relay module . What is the worst case scenario if I screw up ? What are the risks and precautions I should take while working with relays and trying to build a relay controlled desk lamp?

I live in an apartment and I am trying to make sure that my entire building does not lose electricity or I don't screw up the electricity in my unit. What are protective measures that I can take to minimize damages while working on this project?

# Answer
Basic safety precautions:

1. Always fully unplug the lamp before working on any wiring, even when working with the low-voltage side of things.
2. Invest in a proper enclosure and follow the rules of insulation and earthing: if the enclosure is metal or has exposed metal they have to be earthed. If it is plastic it is insulated and there is nothing to earth (plastic is best).
3. Use nylon bolts etc when situated near mains voltages.
4. A proper relay module with good screw terminals is recommended.
5. **Do not** tin your mains wires when screwing them into a terminal block
6. Do your mains wiring with your left hand in your pocket (an old electrician's trick: if you should get a shock the path to earth is down the side of your body and through your foot. If you have your left hand touching something the path to earth could well be straight across your chest, through your heart, and down your other arm, killing you. It has saved my life a few times...)
7. Keep mains voltages and low-voltage areas separate. Cable ties and self-adhesive nylon cable tie pads are great for keeping cables where they should be.
8. Shield any exposed mains connections from touch. Things like the underside of the relay module where the terminal blocks are soldered, that sort of thing.
9. Don't let the relay module wave around loosely. Keep it well secured in the enclosure.

I'm sure I could find more tips if I tried :)

The main thing to remember is that mains electricity is deadly and should be treated with the utmost respect.

For the ultimate in safety though you could get an *isolating transformer*. This separates your work from the main supply and means that the only way of getting a shock is by actively touching *both* outputs of the transformer at once - something you're not really likely to do - and even then it's usually a very localised path for the electricity (through a finger or two).

Adding an ELCB to the lamp's plug (if it is earthed) can be a good precaution while you are working too - and making sure the socket is connected to a ring main that is protected by an RCD is pretty much essential (in the UK it is the law that all ring mains are protected by an RCD - I would hope the same is the case where you live).
> 3 votes

# Answer
Read through the Sparkfun Beefcake Relay Hookup Guide. It points out many things to keep in mind.

The kit is quite good, I just finished putting one together to control a humidifier off an Arduino with a DHT-11 to keep ambient humidity within a range.

**As people have posted, don't ever do any work while the mains are plugged in!**

In your project, you'll be able to test the relay without the mains being plugged in, the relay will make a nice "clicking" sound and if you use the "Beefcake" kit, an LED will light up when the relay is "on".

Be sure to have everything in a "housing" and not flopping around. They sell blue plastic junction boxes for about $1 which is what I used. A GFI or GFCI socket is safer to use, though more expensive.

Good luck!
> 1 votes

# Answer
this is andrew. I saw your Question. Relay's are not even risky Electronic device , it can be controlled by 5v or 12 v.

On behalf, you can just run your simple led blink program to Start up your relay. Just use the Default (13th) pin for relay input. Run your Code. If your code runs successfully, the relay activates, led in the relay will light up and as well as Your default Led also light up in your arduino Board. After that you can give the output 220v power to control electronic Devices. if any doubt just ping me.
> -1 votes

---
Tags: relay, safety
---


# Question
Title: Running two NEMA 17 motors, one by one, using the Arduino Uno
I am new to Arduino. I am trying to run two stepper motors NEMA 17 through respective A4988 driver and controlling via Arduino Uno.

The thought is that first stepper motor will carry out a first horizontal scan and then as it reaches to its initial position, second stepper motor will move a single step in vertical direction. This is a kind of raster scan that I want to perform with both motors.

When I am running the code, only horizontal scan motor is running and vertical scan motor is not moving. I have checked my circuit, motors and drivers and everything is working fine. I think there is some mistake in my code. It is a basic level code and I would really appreciate the help for helping me out.

```
int x, y; //stepper motor 'x' and stepper motor 'y'
#define BAUD (9600)

void setup()
{
  Serial.begin(BAUD);
  pinMode(6,OUTPUT); // Enable for x
  pinMode(5,OUTPUT); // Step for x
  pinMode(4,OUTPUT); // Dir for x
  digitalWrite(6,LOW); // Set Enable low for x

  pinMode(9,OUTPUT); // Enable for y
  pinMode(8,OUTPUT); // Step for y
  pinMode(7,OUTPUT); // Dir for y
  digitalWrite(9,LOW); // Set Enable low for y
}

void loop()
{

  digitalWrite(9,LOW); // Set Enable low for y

  for(y = 0; y < 20; y++)
  {
     digitalWrite(6,LOW); // Set Enable low for x
     digitalWrite(4,HIGH); // Set Dir high for x - Clockwise

     Serial.println("CLOCKWISE HORIZONTAL SCANNING IN PROGRESS");

     for(x = 0; x < 50; x++) // Loop 50 times
     {
      digitalWrite(5,HIGH); // Output high for x
      delay(10); // Wait
      digitalWrite(5,LOW); // Output low for x
      delay(100); // Wait
     }

    digitalWrite(6,LOW); // Set Enable low for x
    digitalWrite(4,LOW); // Set Dir low for x - Anticlockwise

    Serial.println("ANTICLOCKWISE HORIZONTAL SCANNING IN PROGRESS");

    for(x = 0; x < 50; x++) // Loop 50 times
    {
      digitalWrite(5,HIGH); // Output high
      delay(10); // Wait
      digitalWrite(5,LOW); // Output low
      delay(100); // Wait
    }

    Serial.println("ONE STEP CLIMB ON VERTCAL AXIS");

    digitalWrite(7,HIGH); // Set Dir high for y

    digitalWrite(8,HIGH); // Output high for y
    delay(100); // Wait
    digitalWrite(8,LOW); // Output low for y
    delay(100); // Wait
  }

  digitalWrite(9,LOW); // Set Enable low for y
  digitalWrite(7,LOW); // Set Dir low for y

  Serial.println("RESETTING ON VERTCAL AXIS");

  for(y = 0; y < 20; y++) // Loop 20 times
    {
      digitalWrite(8,HIGH); // Output high for y
      delay(10); // Wait
      digitalWrite(8,LOW); // Output low for y
      delay(100); // Wait
    }

}

```

Do i need to look after the delay being provided??

# Answer
A minor issue that probably won't affect your result is that

```
Serial.println("ONE STEP CLIMB ON VERTCAL AXIS");
--> digitalWrite(9,LOW);  // This line 'needs' adding
digitalWrite(7,HIGH); // Set Dir high for y

```

I can't see anything in the code that will prevent the motors running, OK it will take ~13 seconds to start moving, but it should move.

So - without any hardware attached to the motor spindles - is it possible to switch the motors over to check for a wiring breakage issue? With one motor working and one not it implies to me that either the motor is broken, the wiring is broken or the driver circuit is broken. If the fault moves then its a motor/wiring fault if it stays the same then its a driver fault.
> 1 votes

---
Tags: arduino-uno, a4988
---


title: Caluclate lux value from LDR

text:
# Question
Title: Caluclate lux value from LDR
I am using an LDR (Iduino SE012) to measure light. It returns a 10-bit value of the incoming voltage and I don't know how to convert this into lux, lumen candela or any other light-intensity unit. I was googling for datasheets but nothing useful came up. So is there any way how I can extrapolate a light intensity from the voltage?

I mean one idea that I would have is to measure some things where I know the lux output, but since I don't have such things or a luxmeter I'm pretty stuck. It also returns 1024 pretty quick if you hold it into the sun (Altough the sun is very strong today and it has 36°C). Is there maybe a "minimal value" at wich it returns the full voltage? From that point I could calculate it for all the other values.

Here are some datasheets I found:

# Answer
> 1 votes
You can't.

The LDR has a spectral sensitivity which is *very different* from the human eye's. The definition of the lux, or any photometric unit for that matter, pretty much *requires* that your sensor is filtered in such a way as to have the human eye's spectral sensitivity.

---
Tags: sensors, arduino-micro
---


# Question
Title: Can't upload code to an Arduino LilyPad using FTDI
I've tried to upload my code to an Arduino LilyPad (328) using an FTDI basic breakout, but i get this:

```
avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x29

```

I tried to install the latest FTDI drivers from the FTDI website, tried another PC, tried to install the CDM-2.08.28 driver (latest I think) and nothing.

If I change the PC port the USB Serial Port doesn't change (is always COM3).

# Answer
> 1 votes
Does the Loopback test work? Connect Lilypad's Reset to Gnd, connect D0 to D1, open the serial monitor, see if typed text is echoed back. If, you have FTDI problems that you need to resolve.

---
Tags: programming
---


# Question
Title: Arduino Mega: Interrupt not working? Use any pin for interrupt?
I am using an arduino mega. I'm trying to use interrupts in one of my programs. I have 8 pins that I will need to make separate interrupts for.

The pins are 40 - 47. These pins are attached to limit switches, so when the limit switch is pressed or not it'll indicate that via digitalRead().

```
#define switch_1 43     // Pin 43 is connected to Switch 1 (1: X+)
#define switch_2 42     // Pin 42 is connected to Switch 2 (1: X-)
#define switch_3 41     // Pin 41 is connected to Switch 3 (1: Y+)
#define switch_4 40     // Pin 40 is connected to Switch 4 (1: Y-)
#define switch_5 46     // Pin 46 is connected to Switch 5 (2: FR)
#define switch_6 47     // Pin 47 is connected to Switch 6 (2: BL)
#define switch_7 45     // Pin 45 is connected to Switch 7 (2: BR)
#define switch_8 44     // Pin 44 is connected to Switch 8 (2: FL)
int interruptVar = 5;

```

In my set up function I have:

```
attachInterrupt(digitalPinToInterrupt(switch_6), tightenStrings1, CHANGE);

```

Then I have:

```
void tightenStrings1()
{
  interruptVar = 9;

}

```

When I change the status of the limit switches, by pressing them or unpressing them, this function never activates. The variable interruptVar is still 5.

What am I doing wrong?

Also, Serial isn't the problem in this case. I understand now not to use it though, but still doesn't solve the problem. Additionally I tried instead of CHANGE using RISING or FALLING and still no changes.

I have a feeling it's because the pins I'm using aren't technically interrupt pins...is there a way to make them usable as interrupt pins? I'm not allowed to change the pins being used, and using an interrupt is the best solution for the coding portion I'm working on.

# Answer
You are right when you say "technically they aren't interrupt pins".

The only pins you can use as interrupts are 2, 3, 18, 19, 20 and 21. There is no way of changing that. You can't magic more interrupts out of thin air.

However there is a *different* interrupt system that may help you out - the *pin change* interrupts. These are harder to work with since they are grouped into sets of pins that share the same interrupt, but there are far more pins with this kind of interrupt available. Note that you still have to be careful which pins you choose.

There are a couple of libraries available to help you configure the PCINT registers should you need it.
> 1 votes

# Answer
Limit switch implies some mechanical thing is closing the switches, which hardly needs an interrupt as that will be pretty slow electronically. Simple polling is probably more than sufficient at the top of loop() or similar.

You can declare all the pins as INPUT\_PULLUP, wire the switches to connect the pins to Gnd when pressed, then do digitalRead of each to determine its state, or put all 8 on one port and do a PORTx read

for example, and if the result is other than 0xFF, then one has been closed and you can act on it, or read it directly and act on like here for example:

```
switches = PORTL;
if (switches != 0xff){
switch(switches){
case 0b01111111:
//code for switch 7
break;
case 0b10111111:
// code for switch 6
break;
etc for 0b11011111, 11101111, 11110111, 111111011, 11111101, 111111110
}
}

```
> 0 votes

---
Tags: arduino-mega
---


# Question
Title: Getting 0 cm from ultrasonic sensor when nothing is in front
My Ultra sonic sensor (HC-SR04) is returning these types of values when it has nothing in front:

```
Ping: 144cm
Ping: 0cm
Ping: 0cm
Ping: 0cm
Ping: 105cm
Ping: 105cm
Ping: 94cm
Ping: 0cm
Ping: 378cm
Ping: 0cm
Ping: 0cm
Ping: 0cm
Ping: 0cm
Ping: 0cm
Ping: 0cm
Ping: 106cm
Ping: 106cm
Ping: 0cm
Ping: 0cm
Ping: 0cm
Ping: 106cm
Ping: 250cm
Ping: 0cm
Ping: 108cm
Ping: 0cm
Ping: 108cm
Ping: 0cm

```

I am not able to understand why I am getting 0 cm. This value is critical in the program that I am using. Here is a test code which gives me these output:

```
#include <NewPing.h>

#define TRIGGER_PIN  A5
#define ECHO_PIN     A4
#define MAX_DISTANCE 200

NewPing sonar(TRIGGER_PIN, ECHO_PIN);

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

void loop() {
  delay(1000);
  Serial.print("Ping: ");
  Serial.print(sonar.ping_cm());
  Serial.println("cm");
}

```

Because of these 0s my robot is making turns which are not expected.

Any idea why this might happen ?

# Answer
> 3 votes
The documentation for the NewPing library states:

> **Constructor**
>
> ```
> NewPing sonar(trigger_pin, echo_pin [, max_cm_distance]);
>
> ```

and

> max\_cm\_distance is optional \[default = 500cm\].

Then:

> `sonar.ping_cm();` \- Send a ping, returns the distance in centimeters or 0 (zero) if no ping echo within set distance limit

So it would seem that if there is nothing in front of your sensor closer than 500cm, this library returns 0cm. Probably not the best design, but at least it is disclosed.

Thus, you need to write your code such that a 0cm measurement is treated as no obstruction visible; more like an infinite cm measurement.

---
Tags: arduino-uno, hc-sr04
---


title: Updating ATmega16u2

text:
# Question
Title: Updating ATmega16u2
I have the UNO Mini Strong from www.diymore.cc. I am having the issue of keyboard.h not being recognized. I have been trying to find the firmware mentioned in https://www.arduino.cc/en/Hacking/DFUProgramming8U2 from here https://github.com/arduino/Arduino/tree/master/hardware/arduino/avr/firmwares/atmegaxxu2 but, page is gone!

Does anyone know where the firmware can be found and should this work on the board I am trying to use?

# Answer
> 1 votes
I tried to make a little research and it looks that the hardware folder was cleared (see here).

The json file made me think that now this is shipped like libraries, so through a dedicated package which gets downloaded later.

Consequently I checked in the installation folder and... there it is!

In the folder `<arduino install dir>\hardware\arduino\avr\firmwares\atmegaxxu2` you will find a lot of hex files (e.g. `Arduino-COMBINED-dfu-usbserial-atmega16u2-Uno-Rev3.hex`)

I checked on my portable installation of arduino 1.8.5, but it should be there also for installed versions

---
Tags: arduino-uno
---


# Question
Title: How to produce multiple DC voltages for a single project
So the title pretty much says it all, but for an example, I have an arduino board, 5-12 V, an LED bank 18 V, and an ultrasonic mister 24 V.

I know some brute force methods to power them from one outlet, but I was wondering if there is a more elegant way to get the voltage for each device with only one transformer instead of three. The solutions I've come up with are less than elegant, and only moderately compact.

I was just wondering what solutions you guys have employed and hoped I could find something helpful.

# Answer
First you want to take a regulated 24V supply. To that you want to add a switch-mode ("Buck") regulator to drop you down to 5V. You don't want to try using an LDO for this unless you are happy to have a heat sink the size of a small car. A good cheap choice is a "UBEC" that can take 24V in and give 5V out (I use these).

That 5V can then be fed direct into the Arduino.

Depending on what the "LED bank" is you may get away with an 18V (or adjustable) LDO, or an adjustable buck regulator. Or a simple (though high wattage) resistor may be all that is needed. You will have to provide more detail on this to get more help.
> 4 votes

# Answer
Typically you'll only have a single transformer in this sort of design, to get you down to your highest DC voltage. Then you'll create lower voltage rails from that. You can use any number of approaches depending on your needs, e.g. capacitive dropper (on the 24Vac output of the transformer), resistor divider (on your rectified 24Vdc).

But, most typically for hobbyist projects you'll want to be using a regulator IC, either a linear regular/LDO (low noise but poor efficiency) or a separate onboard SMPS IC (good efficiency but typically noisy).
> -1 votes

---
Tags: power, voltage
---


# Question
Title: How to write a library that support both HW and SW Serial communication and allow user to chose which one to use?
I'm working on a library for Arduino/ESP8266/Teensy that use serial to send AT commands. I want to make it as customizable as possible, so I avoided to hardcode the serial and I ask for a reference in the startup method:

```
void MyClass::init(HardwareSerial* hwSerialPtr)
{
   _serialPtr = hwSerialPtr;
   ...
}

```

On some devices, it will be useful to use `SoftwareSerial` instead of the HW one, due to only one serial is available and so keep it for debugging purposes or other features.

So my question is: how can I accept both types? I read both HW and SW serial have `Stream` as base-clase, but it does not have methods like `begin()` etc.

A possible solution I though is so have two pointers (one for HWSerial and one for SWSerial) then wrap some methods like `begin()`, `println()`, `...` in my class and, ond the base of which pointer has been set, use one or the other.

Something like this:

```
class MyClass{
   public:
      void init(HardwareSerial* hwSerialPtr);
      void init(SoftwareSerial* swSerialPtr);

   private:
      HardwareSerial* _hwSerialPtr;
      SoftwareSerial* _swSerialPtr;

      void begin(long baud);
      void println(const String &s)
};

```

then

```
void MyClass::begin(long baud)
{
   if( _hwSerialPtr != null ){ _hwSerialPtr->begin(baudrate); }
   else if( _swSerialPtr != null ){ _swSerialPtr->begin(baudrate); }
}

...etc...

```

but this solution seems to me very tricky and not optimized.

Any better ideas?

# Answer
> 6 votes
The trick here is to go "up a level". Both `HardwareSerial` and `SoftwareSerial` inherit from the `Stream` class. It is *that* class that provides the majority of the interface that you actually use.

So you can provide a constructor with a `Stream` object alone and use that:

```
class Foo {
    private:
        Stream *_dev;

    public:
        foo(Stream *dev) : _dev(dev) {}
        foo(Stream &dev) : _dev(&dev) {}

        void begin() {
            _dev->println("I am ready");
        }
};

Foo myFoo(Serial1);
SoftareSerial btSerial(11,12);
Foo myOtherFoo(btSerial);

```

What the `Stream` class *doesn't* provide, though, is `.begin()` for setting the baud rate. It has to be left to the user to configure the port before using it.

```
Serial1.begin(115200);
myFoo.begin(); // --> "I am ready" on Serial 1

```

or:

```
btSerial.begin(9600);
myOtherFoo.begin(); // --> "I am ready" on Software serial pins 11/12.

```

This is known as *polymorphism*, where an object is seen as one of the parent classes in the inheritance chain and is one of the most powerful aspects of object-oriented programming.

Not having `begin` in your library is no big deal really. It increases the flexibility (a user can more easily select their baud rate), and it means you don't force them to include SoftwareSerial if they don't need it.

There are other things that inherit `Stream`, as well, such as a networking `Client`. So instantly you class can be used with network connections as well as just serial.

So stick to using `Stream`. It's the accepted way of doing things, and perfectly normal. For example, it's how my ICSC library handles serial objects. (I used to use the multiple pointer method, but it really really got messy when trying to support other platforms. I ended up with `HardwareSerial`, `SoftwareSerial`, `USBSerial`, `Client`... a real mess. So much simpler to just use `Stream`.)

---

BTW, before you ask, I have two constructors with very slight differences so that you can construct an object either by passing a Stream object by reference (as I do in the examples) or as a pointer (which can be great if you want to use this in another class which itself has a pointer to a Stream object).

---

Another option is to combine the Stream pointer with a `dynamic_cast` to try and identify the type of object being passed.

```
void Foo::begin(int baud) {
    if (HardwareSerial *hs = dynamic_cast<HardwareSerial *>(_dev)) {
        hs->begin(baud);
    } else if (SoftwareSerial *ss = dynamic_cast<SoftwareSerial *>(_dev)) {
        ss->begin(baud);
    } else {
        // We don't know what to do here
        // so do nothing?
    }
}

```

In this way `dynamic_cast` is being used like Java's `instanceof` operator to work out what kind of object it is that is being used.

Of course, that then means that you're really restricting the library to only working with those two types of object, but it is still possible to pass other class types as long as the user pre-configures them before calling your begin function. Which gets confusing - which type does the user need to `.begin()` and which types have `.begin()` called for you? It's just cleaner to always have it as the user must call `.begin()` themselves - there's no ambiguity then.

# Answer
> 1 votes
I second Majenko's advice: inherit from `Stream` and let the user handle the call to `begin()` if at all possible. However, if you really insist in calling `begin()` from your class, then I suggest you make your class a template, like this:

```
// T is the type of the serial port, typically HardwareSerial or
// SoftwareSerial.
template<class T> class MyClass {
    public:
        MyClass(T& port) : port(port) {}
        void begin(unsigned long baud) { port.begin(baud); }
    private:
        T& port;
};

```

Your user would then instantiate it as

```
MyClass<HardwareSerial> myObject(Serial);
MyClass<SoftwareSerial> myOtherObject(mySerial);

```

Of course, it doesn't look nice, and it may confuse your users, but it has the advantage that it can work with anything that remotely looks like `HardwareSerial`, e.g. `AltSoftSerial` or other alternative software serial implementations.

---
Tags: serial, library, softwareserial
---


title: RX and TX pin in Arduino Uno

text:
# Question
Title: RX and TX pin in Arduino Uno
I have LED Cube Project, and I want to activate the LED with My Android apps (Bluetooth). The LED Cube used A0-A5 and D0-D13 Pins, and the Bluetooth need RX and TX (D0, D1).

Where I can put the RX and TX (for Bluetooth HC-05) while D0, D1, and all analog and digital pins are used by the LED?

# Answer
> You can't magic more pins out of thin air.

Yes you can!

You can have as many output (and even input) pins as you want. I managed to build 8x8x8 LED cube using ATTiny13 with just 6 output pins (using only 5 of them)

All it takes is a little extra coding and "shift registers". (For extending outputs use the one with "latch", but for LEDs normal one is enough)

You can use three (for example CD4094) 8 bit shift registers. You connect three Arduino pins to "DATA" (a.k.a. SERIAL DATA INPUT) pin of each register. Then one Arduino pin to three "CLOCK" pins and one Arduino pin to three "OUTPUT ENABLE" pins.

Then in the code you send a sequence of bits into the registers simulating the clock signal and when that's over just set output enable to make the registers output a value on their 8 output pins each.

This way you use just 5 pins, and when you chain the registers together (last "Q8" pin of one register can go to "DATA" pin of second one) you can theoretically have as many outputs as you need at the cost of output update speed.

This way you can free most of your Arduino pins including TX and RX.
> 2 votes

---
Tags: arduino-uno, led, rx-pin
---


# Question
Title: Why do COM port numbers between Arduino and Processing not match?
I have a Processing program that reads data sent to the serial port by an Arduino. When I go to device manager it shows that the Arduino is plugged into COM 4, however in order to get Processing to read the data the number I need for the COM in the following line is 2:

```
String portName = Serial.list()[2]

```

Why do the numbers not match?

Thanks!

# Answer
If you print out portName it should be **COM4** it seems you must have 3 COM ports on your machine otherwise you would use index 0; Serial.List() appears to return an array or list which you are taking the third item located at index 2.
> 3 votes

---
Tags: arduino-uno, serial, communication, processing-lang
---


# Question
Title: Posting TinyGPS++ co-ordinates as paramaters with GPRS
I'm able to view my co-ords on the Serial Monitor using `Serial.println(gps.location.lat(), 6);`

I believe the data type returned by `gps.location.lat()` is double. I need to pass this value to a webservice with AT commands over GPRS.

`double latitude = gps.location.lat()`

Later in my code I execute AT commands to begin HTTP POST. I would like to know how to pass these double values in my paramaters.

`gsm.println("AT+HTTPPARA=\"URL\",\"http://webservice/service1\"");
 gsm.println("AT+HTTPDATA=192,10000");
 gsm.println("latitude=" + latitude);` \< This is not allowed.

How can I pass this parameter to my web service.

# Answer
> 0 votes
One solution may be to split the commands:

```
gsm.print("latitude=");
gsm.println(latitude);

```

I'm not sure how you should pass multiple parameters; if it is the usual syntax you can write something like

```
gsm.print("latitude=");
gsm.print(latitude);
gsm.print("&longitude=");
gsm.println("longitude);

```

If I have the time I'll research into this a bit.

To check what is the problem, you may try to send "static" messages, like

```
gsm.println("latitude=12.345");

```

To check if this format is the correct one

EDIT: after a very quick research

It looks like the AT commands are a bit more complicated. In order to send the parameters, at least on a SIM800L, you should:

* send the HTTPDATA command (the first parameter is the length of the payload)
* wait for the board to send you the command DOWNLOAD
* Send the body of the request, which is formatted as a JSON object. This means you have to send something like `{ "latitude" : 12.345, "longitude": 98.765 }`

After all, it is much faster to use a library already developed for this, for instance ArduinoSIM800L (check a library available for your GPRS modem, or modify this one)

---
Tags: http, convert
---


# Question
Title: Connecting Arduino and Processing, how do I know what COM to read?
I'm using Processing to read data from the serial port that the Arduino sends. When I go to device manager it shows that the Arduino is in COM 4, but in order for Processing to read from the Arduino the COM I need to type in is 2:

```
String portName = Serial.list()[2]

```

Why do the numbers not match?

Thanks!

# Answer
> 1 votes
Because the two numbers are completely different types of numbers.

The number 4 for COM4 means that it is the fourth serial communications port as defined by which I/O ports are used to communicate with the actual hardware. I.e. you'll have COM1, COM2, COM3 and so on. It doesn't matter if the hardware is actually there or anything is connected - the names are the same.

The number 2 in Serial.list()\[2\] means that you're selecting the third (!) element of the array returned by Serial.list(). I.e. in this case we're counting from 0 instead of 1.

In addition to that, Serial.list() only returns available ports. I.e. if the hardware for COM3 is not installed physically, it will not be returned by Serial.list(). Also the list is not guaranteed to be sorted in any specific order.

You'll want to print out the contents of the array returned by Serial.list() and let the user select which of the ports he wants to use.

---
Tags: hardware, software
---


title: Hex/Byte Reversing and Conversion

text:
# Question
Title: Hex/Byte Reversing and Conversion
I'm working on an RFID system using a MFRC522 with this Library : https://github.com/miguelbalboa/rfid Here's the code I have right now:

```
int A=(mfrc522.uid.uidByte[0]);
int B=(mfrc522.uid.uidByte[1]);
int C=(mfrc522.uid.uidByte[2]);
int D=(mfrc522.uid.uidByte[3]);

Serial.println("UID is %x %x %x %x", A, B, C, D);

```

This results in the following output:

```
UID is 35 C5 5A 59

```

My issue is - how do I first reverse that UID : from `35 C5 5A 59 to 59 5A C5 35` \- and second convert and print the corresponding decimal value of that reversed UID. In this case, it would be 1499120949.

I should mention that I need it as a string at the end to add it to the end of a POST command.

# Answer
> 1 votes
A standard way to convert individual bytes to a number is to use bit shifts and bitwise OR, as shown in chrisl's answer. When doing this, however, one has to take care not to overflow the bit shifts. On the AVR-based Arduinos, an `int` is 16 bits long. Shifting it by 24 bit positions to the left is guaranteed to overflow, which in C++ leads to undefined behavior.

The solution, as explained in Majenko's comment, is to cast to the final type *before* shifting, like this:

```
uint32_t uid = (uint32_t) mfrc522.uid.uidByte[0] << 0
             | (uint32_t) mfrc522.uid.uidByte[1] << 8
             | (uint32_t) mfrc522.uid.uidByte[2] << 16
             | (uint32_t) mfrc522.uid.uidByte[3] << 24;

```

Note that I got rid of the useless intermediate variables `A` through `D`.

Once you have have the numerical value, you may try to use it without explicitly converting to a string. Instead, you rely on the `print()` or `println()` methods to implicitly do the conversion only when needed, as in

```
Serial.print("UID = ");
Serial.println(uid);

```

or even, on a network connection:

```
client.print(uid);

```

This will save you the memory needed to store the string. If you really need to have the converted string in memory, which could happen if you need to provide a Content-Length before sending the data, you can do so with the function `ultoa()` from the avr-libc:

```
char uid_str[11];  // max = 10 digits + terminating NUL
ultoa(uid, uid_str, 10);  // convert to base 10

```

Please note that `ltoa()` is **not** appropriate here, as calling it will implicitly convert the value to a **signed** `long`, which has the potential to overflow and yield a negative result.

This “C string” – a NUL-terminated character array – can then be converted to a String object if needed, but I advice you against doing so if at all possible. String objects are more convenient to manipulate, but they are absolutely not memory friendly, which can quickly become an issue on most Arduinos.

# Answer
> 0 votes
Your UID has 4 bytes, which correspond to 32 bits. To get a decimal value from these bytes, you have to put them together in one variable. For this you can use an `unsigned long`. To put the bytes together, you can shift the values to the byte boundaries:

```
unsigned long dec_value = (D << 24) | (C << 16) | (B << 8) | A;

```

`<<` shifts the bits of the byte by the specified amount of bits to the left; The bitwise OR `|` puts the now not overlapping bytes together in one value. I have reversed the order of the bytes in this code, as you wrote, that this is necessary.

To convert this `unsigned long` to a string you can use the function `ltoa()`:

```
char buf[50];
ltoa(dec_value, buf, 10);  // 10 is the base value not the size - look up ltoa for avr

```

If you want to use a `String` object (which should be avoided because of heap fragmentation), you can contruct the `String` directly from the `long` value:

```
String my_UID = String(dec_value);

```

# Answer
> 0 votes
To add a bit to the whole hex and decimal story: Those are just representations of numerical values your computer/microprocessor does not really care about.

```
int x = 0
int y = 0b0
int z = 0x0

```

these are all the same value and internally stored as binary, just like any other number.

You **specifically told** the println function to *display* said number(s) in hexadecimal representation with the format specifier `%x` `Serial.println("UID is %x %x %x %x", A, B, C, D);` using `%d` or `%i`(for integer) will print out decimal values for each number.

## Converting byte array to larger data type

If you actually want them to be reversed, you could simply cast the array variable (which is nothing but a pointer) to an uint32\_t pointer:

```
uint32_t dec_value = *(uint32_t*)mfrc522.uid.uidByte

```

Note the `*`s We first cast the pointer to a pointer of a different type `(uint32_t*)` and then access it's value, by prepending another `*`, which is then stored in `dec_value`, equaling 1499120949 now.

This works because in C/++ data structures in memory are guarenteed to be in the order you specified. Therefore, you essentially tell the computer to 'see' these very 4byte (32bit) as a single value rather than a independent bytes.

Usually, when converting byte arrays to larger data types, you will find the values you receive are not what you would expect. This is because they are stored in a different order (depending on the machine) known as endianness

Here is a function that addresses this issue (similiar to the other answers)

```
uint32_t bytearray_to_uint32(unsigned char *buffer)
{
    uint32_t value = 0;

    value |= (uint32_t)buffer[0] << 24;    // cast to target type before
    value |= (uint32_t)buffer[1] << 16;    // shifting to avoid overflow
    value |= (uint32_t)buffer[2] << 8;     // no parentheses needed due to operator precedence
    value |= buffer[3];

    return value;
}

```

Applying this function to your case would result in `902126169 (0x35c55a59)` instead of the desired `1499120949 (0x595ac535)`.

Also check out ntohl when dealing with endianness still puzzles you.

# Answer
> 0 votes
I think this does what you need. You already have the data in an array so to reverse it you go backwards through the list and assemble the number. To fit 4 bytes into 32bits you need to multiply each byte by (256 * its position), which is what the left shift `<<` does. So by placing the code in a small loop you get some compact code that should do the job.

```
int A=(mfrc522.uid.uidByte[0]);
int B=(mfrc522.uid.uidByte[1]);
int C=(mfrc522.uid.uidByte[2]);
int D=(mfrc522.uid.uidByte[3]);

Serial.println("UID is %x %x %x %x", A, B, C, D);
// ^ Your code
uint32_t reversed = 0;
for (int x = 3; x > -1; --x) // go backwards through the array
{  // Take the existing value and multiple by 256 (left shift by 8) then add the latest byte on.
   reversed = (reversed << 8) + mfrc522.uid.uidByte[x];
}
String decValue = String (reversed);  // Covert the number to a string

```

---
Tags: programming, rfid, bit, byte-order
---


# Question
Title: Cannot use radio transmitter after switching to LowPower library
My Arduino Mini board has DHT22 temperature sensor and 433MHz radio transmitter modules. I'm using `DHT` and `RCswitch` libraries to make use of them. Code looks like this:

```
void setup() {
  tempSwitch.enableTransmit(RADIO_PIN);
  dht.begin();
}

void loop() {
  float temp = dht.readTemperature();

  unsigned long message = createTemperatureMessage(SENSOR_ID, temp);
  tempSwitch.send(message, 32);

#ifdef MY_DEBUG
  unsigned int sleepCount = 1;
#else
  // 3600s / 2 / 8s == 225
  unsigned int sleepCount = 225;
#endif
  for (; sleepCount > 0; sleepCount--) {
    LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF);
  }
}

```

So I'm reading temperature and sending it using `RCswitch` library. Initially I just had `delay(1000);` instead of fancy `LowPower` sleep loop but I wanted to make my "device" more battery-friendly so I switched to low-power sleep.

The problem is that now Arduino is only sending data first time and after sleeping 30 minutes (in "release" mode) it does not send anything anymore. If I reduce 30 minutes to 8 seconds it is capable of sending data as well as if I replace sleep with `delay(30*60*1000);`.

From beyond it looks like something is not caching up after the sleep. Do I need to "wake" radio module in any special way? How to fix that?

# Answer
> 1 votes
I've never tried this, but if you are putting the Arduino to sleep I would expect it to cut power to the devices (does it?) if it does then after a 30 minute sleep I would expect the devices to come back up in the initial state. Guessing by your code the initial state of the radio is Tx Disabled, so try moving the

```
tempSwitch.enableTransmit(RADIO_PIN);

```

to before the

```
float temp = dht.readTemperature();

```

line.

I'd also be concerned that the DHT22 is not in the correct state after you wake up.

Can you try doing a 1 second LowPower sleep in debug mode, I suspect it would work more often.

---
Tags: power, sleep, arduino-mini
---


# Question
Title: MemoryFree library showing Irregular Behaviour..!
I simply burned the code written below but it is showing me irregular behaviour.. as in output's last paragraph, free memory increases after a runtime allocation, how it is possible? The output is attached :

```
#include <MemoryFree.h>
String str="rajat";
int flag=0;
void setup()
{
  // put your setup code here, to run once:

  Serial.begin(9600); Serial.println(freeMemory(), DEC);  // print how much RAM is available.
  Serial.println("Lets Start");
}

void loop()
{
    Serial.println("");
    Serial.println("Rajat0");
    Serial.println(freeMemory(), DEC);
    Serial.println("Rajat1");
    str=str+"rjt";
    Serial.println(str);
    Serial.println("Rajat2");
    Serial.println(freeMemory(), DEC);
    Serial.println("Rajat3");
    Serial.println("");
      delay(1000);
}

```

# Answer
> 1 votes
Free memory can be found in two forms:

* The free space between the heap and the stack. This is usually the main chunk of free memory.
* Heap “holes”, i.e. pieces of unallocated memory within the heap. The presence of these holes is called “heap fragmentation”.

There are various versions of the MemoryFree library. The simplest ones only report the main chunk between the heap and the stack. The more sophisticated ones walk the malloc()'s free list in order to also count the heap holes. Which approach is better? I would argue that the naive version is fine, as heap holes is something you should not count on, because it is never guaranteed that a particular allocation will fit in any of those holes.

You are visibly using one of the naive versions. As you grow your string, the object calls `realloc()`, which in some cases copies the string's character array and frees the original one, potentially creating a heap hole. Eventually, small holes can coalesce into a larger one big enough for the next allocation, and `realloc()` can end up using this large hole and freeing the chunk at the top of the heap. When this happens, the heap shrinks, and the main chunk of free memory gets larger, which is what `freeMemory()` is reporting to you.

In summary, it's normal and expected behavior. If you want something less surprising, use a version of the library that does count the holes. But then you may run into a more displeasing surprise: a heap–stack collision, or an out-of-memory condition, can happen even with loads of memory buried inside heap holes.

---
Tags: programming, arduino-ide, atmega328, memory-usage, memory
---


title: ESP8266 SPIFFS file not found

text:
# Question
Title: ESP8266 SPIFFS file not found
I have a simple HTML file that I have uploaded as sketch data using the ESP8266 sketch data upload tool in arduino IDE. The file is 7k in size.

In the set up, I refer to the following function to read the file:

```
String readTemplatefile(){
  String retval ="";
  File fr = SPIFFS.open("/templatecfg.htm", "r");

  if(!SPIFFS.exists("/templatecfg.htm")){

    Serial.println("Template file not available ");
    }
    while (fr.available()){
        retval += char(fr.read());
      }

fr.close();
Serial.println("Template file = ");
Serial.println(retval);
return retval;
}

```

I always get 'Template file not found'. I have

```
SPIFFS.begin();

```

at the beginning of the setup function

My board is an ESP8266EX. I have wondered if it the flash size settings in the IDE that could cause this not to be found. Can anyone offer any advice on this issue. I have tried lots of different combinations of Flash size and SPIFF sizes without any luck.

Thanks in advance to any help.

# Answer
SPIFFS will always claim to successfully open a file that begins with a slash even if that file does not exist. Remove the leading slash.
> 1 votes

# Answer
@dandavis Yes, I had SPIFFS.begin() in my setup routine.

I ran a sample sketch and was able to see the a file on the device, so I routed round the code some more and found than an included library was ending SPIFFS after it had performed a file read. This was the issue. Thanks all for your consideration, but the code I had was fine, just the included library was mis-behaving.
> -1 votes

---
Tags: esp8266
---


# Question
Title: How to change the default Slave Select pin (Digital pin 10) on Arduino UNO R3 for SPI communication?
Currently I am working on an Arduino based project. My project require interfacing 6 servo motors and an SD card module to my Arduino UNO. The problem is that I need all the six PWM pins for six servos (Including pin 10) which happen to be the default Slave Select Pin for SPI communication. I don't want to use software based PWM on a digital pin. I could not find any resource on how to change the default SS pin to any other pin. Any help in this regard will be highly appreciated. Thanks!

# Answer
Just declare it and use it:

```
byte ssPin = 7; // or any other pin, stay away from 0,1, leave those for Serial()
byte defaultSS = 10; // 53 on a 2560

pinMode (ssPin, OUTPUT);
digitalWrite (ssPIN, HIGH); // typical slave select OFF state
pinMode (defaultSS, OUTPUT);  // 10 MUST be an output for device to be SPI master (328P)
SPI.begin(); // default is 4 MHz speed, MSBFIRST
// takes care of SCK, MISO, MOSI, don't need define/declare those

digitalWrite (ssPin, LOW);
SPI.transfer (ledData, 0xAA); // example data going to a device
digitalWrite (ssPin,  HIGH);

```
> 1 votes

---
Tags: spi, arduino-uno
---


# Question
Title: Unable to upload to ESP32 LOLIN D32 board
I'm not able to upload a sketch to this board with the Arduino IDE. This is the error during upload:

```
Arduino: 1.8.5 (Windows 10), Board: "WEMOS LOLIN32, 80MHz, Default, 512000

Build options changed, rebuilding all
Archiving built core (caching) in: C:\Users\Karanbir\AppData\Local\Temp\arduino_cache_223140\core\core_espressif_esp32_lolin32_FlashFreq_80,PartitionScheme_default,UploadSpeed_512000_6da8d55d0c53c0ebef21ae478b9e06ba.a
Sketch uses 178072 bytes (13%) of program storage space. Maximum is 1310720 bytes.
Global variables use 13880 bytes (4%) of dynamic memory, leaving 313800 bytes for local variables. Maximum is 327680 bytes.
C:\Users\Karanbir\Documents\Arduino\hardware\espressif\esp32/tools/esptool/esptool.exe --chip esp32 --port COM3 --baud 512000 --before default_reset --after hard_reset write_flash -z --flash_mode dio --flash_freq 80m --flash_size detect 0xe000 C:\Users\Karanbir\Documents\Arduino\hardware\espressif\esp32/tools/partitions/boot_app0.bin 0x1000 C:\Users\Karanbir\Documents\Arduino\hardware\espressif\esp32/tools/sdk/bin/bootloader_dio_80m.bin 0x10000 C:\Users\Karanbir\AppData\Local\Temp\arduino_build_547051/Test.ino.bin 0x8000 C:\Users\Karanbir\AppData\Local\Temp\arduino_build_547051/Test.ino.partitions.bin
esptool.py v2.3.1
Traceback (most recent call last):
  File "esptool.py", line 2637, in <module>
  File "esptool.py", line 2630, in _main
  File "esptool.py", line 2355, in main
  File "esptool.py", line 193, in __init__
  File "site-packages\serial\__init__.py", line 88, in serial_for_url
  File "site-packages\serial\serialwin32.py", line 62, in open
serial.serialutil.SerialException: could not open port 'COM3': WindowsError(5, 'Access is denied.')
Failed to execute script esptool
the selected serial port Failed to execute script esptool
 does not exist or your board is not connected

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

```

This is displayed on the Arduino IDE's Serial Monitor on pressing the reboot button on the board:

```
ets Jun  8 2016 00:22:57

rst:0x1 (POWERON_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
configsip: 0, SPIWP:0xee
clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
mode:DIO, clock div:2
load:0x3fff0018,len:4
load:0x3fff001c,len:4436
load:0x40078000,len:0
load:0x40078000,len:11816
entry 0x4007a9fc
[0;32mI (358) cpu_start: Pro cpu up.[0m
[0;32mI (358) cpu_start: Single core mode[0m
[0;32mI (359) heap_init: Initializing. RAM available for dynamic allocation:[0m
[0;32mI (362) heap_init: At 3FFAE6E0 len 00001920 (6 KiB): DRAM[0m
[0;32mI (368) heap_init: At 3FFC4E70 len 0001B190 (108 KiB): DRAM[0m
[0;32mI (374) heap_init: At 3FFE0440 len 00003BC0 (14 KiB): D/IRAM[0m
[0;32mI (380) heap_init: At 3FFE4350 len 0001BCB0 (111 KiB): D/IRAM[0m
[0;32mI (387) heap_init: At 4008DE34 len 000121CC (72 KiB): IRAM[0m
[0;32mI (393) cpu_start: Pro cpu start user code[0m
[0;32mI (187) cpu_start: Starting scheduler on PRO CPU.[0m
OSError: [Errno 2] ENOENT
MicroPython v1.9.3-564-g9254f365 on 2018-04-26; ESP32 module with ESP32
Type "help()" for more information.
>>>

```

What can be wrong or needs correction?

# Answer
> 0 votes
I had the same problems with a USB cable of a length at 30cm
I took an other (10cm) and reduced the upload speed to 512000.
now it works

---
Tags: esp32
---


# Question
Title: Unable to get response for BLE AT commands in Arduino Uno
I am trying to establish connection between two BLE (BT43) through AT commands from an Arduino Uno. I am not getting any response from the AT commands. The connections are as follows:

Arduino Tx --\> BLE Rx Arduino Rx --\> BLE Tx Arduino 3.3v --\> BLEVcc Arduino Gnd --\> BLE Gnd

Can someone please help me with this? Thanks in advance! this is my code

```
#include <SoftwareSerial.h>
SoftwareSerial BTserial(6, 7); // RX | TX

const long baudRate = 115200;
char c=' ';
boolean NL = true;

void setup()
{
    Serial.begin(9600);
    Serial.print("Sketch:   ");   Serial.println(__FILE__);
    Serial.print("Uploaded: ");   Serial.println(__DATE__);
    Serial.println(" ");

    BTserial.begin(baudRate);
    Serial.print("BTserial started at "); Serial.println(baudRate);
    Serial.println(" ");
}

void loop()
{

    // Read from the Bluetooth module and send to the Arduino Serial Monitor
    if (BTserial.available())
    {
        c = BTserial.read();
        Serial.write(c);
    }

    // Read from the Serial Monitor and send to the Bluetooth module
    if (Serial.available())
    {
        c = Serial.read();
        BTserial.write(c);

        // Echo the user input to the main window. The ">" character indicates the user entered text.
        if (NL) { Serial.print(">");  NL = false; }
        Serial.write(c);
        if (c==10) { NL = true; }
    }

}

```

# Answer
> 0 votes
Since these modules are connected to their respective Arduinos to give them BLE capability, Rx and Tx should be connected to the same, not crossed.

# Answer
> 0 votes
You are missing critical info on page 10 datasheet i.e. not connecting CTS and RTS.

It maybe possible handshake is necessary for communicating to this module. Give it a try using with some board with Synchronous UART.

Also can try grounding CTS. i.e. connect blue-tooth moduls's CTS to 0V.

read this for more clarity.

Hope this solves your problem.

# Answer
> 0 votes
**EDIT**

Just found this\*:

> On **Arduino or Genuino 101** the current **maximum RX speed is 57600bps** *https://www.arduino.cc/en/Reference/SoftwareSerial

You may be over max speed for Uno.

What are you using to send data via Bluetooth? Are you sure data is being sent to the device?

**Android App**

You can try my android app that I created for this specific type of testing. You can get it at : http://raddev.us/btmessenger.apk

If you point your Android device at that, it will download the app and ask if you want to install it. In case you're afraid it is malicious you can get the Open Source code to the simple app at GitHub : https://github.com/raddevus/BTMessenger

To use:

1. pair your bluetooth device
2. Type a message in top TextEdit box.
3. Press the \[Send\] button.

**Baud Rate Issues**

Generally if you get the baud rate incorrect you'll just see garbage characters. Here's a write up I just did on setting up Bluetooth devices. It may help you work through some issues. https://www.codeproject.com/Articles/1254611/Bluetooth-Messenger

---
Tags: arduino-uno, bluetooth
---


title: Arduino Mega upload issue

text:
# Question
Title: Arduino Mega upload issue
I have made my own version of an Arduino Mega and I am encountering some issues. Whenever I try to upload any sketch to the Mega, I get the following error message:

avrdude: stk500v2 ReceiveMessage(): timeout

I can upload just fine to the 16u2 as well as the 2560 using ICSP and Nick Gammons Atmega\_Board\_Programmer sketch. I have the correct board and COM port selected, and the cable, computer, and USB(2.0) port can upload to other Arduino boards just fine.

I have had some other troubles with the board that have been solved, but this issue remains. Please see my Arduino forum post for more details on these issues.

My current guess is that there may some sort of issue with the transmission lines between the 16u2 and the 2560. Here is a picture of the pcb traces. Can anyone look them over to see if there are issues with the traces?

If the traces seem fine, can anyone think of another reason why the upload does not work?

# Answer
So as of right now the problem has been solved. The issue was that the decoupling capacitor on the reset line near the 2560 was designed to be a 22pF capacitor, but I had put a 100nF capacitor, which increases the time constant by a factor of 5000, prohibiting the auto-reset circuitry from operating correctly. Removing the 100nF and putting in the 22pF seems to have solved the issue of only being able to upload once after burning the bootloader.

Thank you everyone for your support.
> 0 votes

---
Tags: serial, arduino-mega, arduino-ide, uploading, avrdude
---


# Question
Title: LED does not light when inserted into round Lilypad board
Title: LED does not light when inserted into round Lilypad board.

very simple goal here: i want to plug in a blinking LED \[or 10\] into a round circuit board \[then solder them\], then power those LEDs. when i touch the - and + battery wires to the loose LED it lights. as soon as i insert the LED into the Lilypad round prototype board, those same battery wires will not light the LED. of course when i solder the LED in, then touching the battery - and + to two of the outer board contacts, nothing lights. the board is, "LilyPad Prototype Board ProtoBoard by AMX3d - Round Prototype Board for all DIY Electronics project", and the LEDs are, "100pcs 3mm Flat Top Water Clear Fast Rainbow Flash RGB flashing LED Diodes USA". it is like the board thwarts conductivity. thoughts?

board - https://www.amazon.com/gp/product/B01L9B9RSY/ref=oh\_aui\_detailpage\_o03\_s00?ie=UTF8&psc=1

LEDs - https://www.ebay.com/itm/121752435838

# Answer
> 4 votes
Your board has every pin directly connected to every other pin.

As it states in the description:

> 10 mil traces connect holes, **cut the ones you do not need** to create a breadboard with infinite possibilities

(Highlighting by me).

---
Tags: led
---


# Question
Title: How to control a DRV8266 motor controller with an ESP8266?
https://github.com/sparkfun/SparkFun\_MiniMoto\_Arduino\_Library/tree/V\_1.1.0

Will this library work on an esp8266? If not is there any way I can get this driver to work on the ESP?

# Answer
> 1 votes
As Ignacio kindly pointed out (+1), the answer to my original question is no.

---

The following code works to control a Sparkfun Minimoto board, though, or more generally the DRV8830. Just connect GPIO5 to SCL and GPIO4 to SDA. On some variants the default SDA/SCL pins are different though -- you can always use any pins (except for GPIO0, GPIO2, and GPIO15 -- see my recent post on using these pins) for your I2C bus and just call wire.begin(sda,scl) where sda and scl are the pin numbers you want.

```
#include <Wire.h>

#define MOTORA_WRITE 0x64
#define MOTORA_READ 0x65
#define CONTROL_addr 0x00
#define FAULT_addr 0x01

void setup() {
  Wire.begin();

  drive(20);//enter values from -63 to 63, where negative values are reverse
  delay(100);
  coast();//releases the motor
  delay(100);
  brake();//brakes the motor

}

void loop() {
  // put your main code here, to run repeatedly:

}

byte tsState = -99;//used so redundant calls of any of these methods don't do anything -- only new calls will trigger communication with the motor controller
void drive(int speed) {
  if (speed != tsState) {
    tsState = speed;
    // Write to the Fault Register to reset it
    Wire.beginTransmission(MOTORA_WRITE);
    Wire.write(FAULT_addr);
    Wire.write(0x80);
    Wire.endTransmission(true);

    // Write to the Control Register
    Wire.beginTransmission(MOTORA_WRITE);
    Wire.write(CONTROL_addr);
    byte regValue;
    regValue = (byte)abs(speed); // Find the byte-ish abs value of the input
    if (regValue > 63) regValue = 63;
    regValue = regValue << 2; // Left shift to make room for bits 1:0
    if (speed < 0) regValue |= 0x01; // Set bits 1:0 based on sign of input.
    else regValue |= 0x02;
    Wire.write(regValue);
    Wire.endTransmission(true);
  }
}
void brake() {
  if (tsState != -98) {
    tsState = -98;
    Wire.beginTransmission(MOTORA_WRITE);
    Wire.write(FAULT_addr);
    Wire.write(0x80);
    Wire.endTransmission(true);
    Wire.beginTransmission(MOTORA_WRITE);
    Wire.write(CONTROL_addr);
    byte regValue = (byte)63;
    regValue = regValue << 2;
    regValue |= 0x03;
    Wire.write(regValue);
    Wire.endTransmission(true);
  }
}
void coast() {
  if (tsState != -97) {
    tsState = -97;
    Wire.beginTransmission(MOTORA_WRITE);
    Wire.write(FAULT_addr);
    Wire.write(0x80);
    Wire.endTransmission(true);
    Wire.beginTransmission(MOTORA_WRITE);
    Wire.write(CONTROL_addr);
    byte regValue = (byte)0;
    Wire.write(regValue);
    Wire.endTransmission(true);
  }
}

```

# Answer
> 2 votes
No, since it uses AVR defines. Convert the code that uses these defines to the equivalent ESP8266 code instead.

---
Tags: esp8266, motor
---


# Question
Title: Safely powering a relay from same source as attiny/arduino?
My project involves using ATTINY to control a 5v relay (specifically JZC-11F and will be ground triggered) in an automotive setting.

I keep seeing the warnings of powering a relay from the same source as the ATTINY (or arduino), everything I can find says you need a completely separate source.

I'm still working on a 12~v to 5v power circuit that is safe from the issues that arise from being in an automotive setting (load dumps, noisy, reverse polarity protection..etc) but saying I have that figured out and I have a clean 5v source for power, do I have to duplicate that circuit just for the relay? or are there a ways of preventing the relay from eventually shorting out the ATTINY?

Plan B: What if I scratch the whole 5v relay and set it up to trigger an external standard 12v automotive relay (this is probably more ideal)? Is the ATTINY capable of triggering a 12v relay via ground? if not what are the recommended ways of making this happen?

side note: I'm know code I don't know EE but I'm trying. The end goal is to combine everything onto a custom pcb, so any suggestions about the 12v-5 using an off the shelf car usb adapter or a premade board are unnecessary (seems to be the go-to answer on that subject). I have a separate post regarding that circuit so if at all possible please stick to the relay questions.

# Answer
> do I have to duplicate that circuit just for the relay?

No, not really, no.

> Is the ATTINY capable of triggering a 12v relay via ground?

The ATTtiny is capable of triggering a transistor - the transistor is capable of triggering a 12V relay.

Unless your relay is incredibly high powered and the coil takes (and generates through back-EMF) massive amounts of current, there really is no problem running it alongside a small microcontroller. Just be sure you have the flyback diode, and maybe a damping capacitor as well to absorb noise.

TBH you're probably going to be getting more noise from contact spark than you are from the relay's coil.
> 1 votes

---
Tags: power, attiny, relay, attiny85
---


title: 3.3V from 5.0v outlet

text:
# Question
Title: 3.3V from 5.0v outlet
I am working with an Adafruit Feather 32u4 FONA board. I want to connect a GPS module I have worked with before (3.3V required) but am not having much luck. I have studied the pinout of the board and have tried the 3.3V pin but it is far too erratic in nature and cannot sufficiently power the module. There is a pin called USB which supplies 5.0V from the pin if a micro USB cable is connected. I have used an LM317 and a potentiometer to make a voltage regulator circuit to convert the 5.0V from the USB pin to the 3.3V I need for the GPS module. This works, as I have measured 3.3V successfully using a multimeter.

**The problem** is that when I connect the VCC and GND pins of the GPS module to the 3.3V regulated output, the module still doesn't get any power. I measured a significant drop to around 0.89V across GND and VCC after I connect the module. What could be causing this strange behavior?

The bottom left rail is what I am trying to use to power the GPS module, before I connect it I get **3.3V** as mentioned earlier, which is the required level.

# Answer
> 0 votes
A while has passed since I asked this question but in a bid to resolve it, I used my Buck regulator as suggested and this solved the problem.

# Answer
> 1 votes
According to the datasheet the LM317 has a minimum Vin to Vout of 3v so you'd only be able to get 2v out of it if you put 5v in. I'd recommend using either an AMS1117 3.3 or one of the cheap modules based on that chip that has an LED and capacitors on board. They definitely deliver 3.3v from 5v in.

---
Tags: voltage-level, voltage, convert
---


# Question
Title: Help me determine the power consumption/rating of the circuit below?
Please help me determine the circuit's power consumption from the battery and help me outline the steps to calculate?

# Answer
It's not a simple matter of "calculating the power". Instead you need to:

* Calculate (or obtain) the current consumption of each individual sub-module or component
* Calculate (or obtain) the current consumption of the main MCU for each power state it operates in
* Calculate the current consumption of static items such as voltage dividers and power LED

Then:

For each unit examine the percentage of time it spends in different power states. From that create an hourly average current for the unit.

And finally:

Sum up all the average hourly usages to get a final AH value for the whole circuit.

Most of the current values can be obtained either by calculation (e.g., Ohm's Law for resistive dividers and LEDs, etc), or from the datasheets for the devices you have attached.

Note that this will still only be an approximation, because (amongst other things) you have multiple power sources which will cause different drains on the system depending on which source is being actively used (different monitoring circuitry and components switched it), and that (I assume) is influenced by the weather.
> 1 votes

---
Tags: arduino-mega, power, pwm, electronics, solar
---


# Question
Title: What's the maximum number of keys in Yun Bridge?
The Yun has a Bridge for communicating between the Arduino and Linux processors via a key/value hash. The docs say this is actually stored on the Linux side, but it doesn't say what the limit is.

How many key/value pairs can the Bridge store? What are the practical limitations?

# Answer
The data is just stored in an array within the Python daemon. The ATMega32U4 just sends commands to set / get the values, so there is no limit imposed by the ATMega side of things.

The only limit is the size of the array in Python, and that is restricted by:

* The amount of available memory in Linux, and
* Whether or not you have swap space set up on the Yun

Since both those are very much variable (it depends what processes you have running, what your configuration is, etc) the answer can only really be:

* **Quite a few.**

Putting memory aside for a moment, an answer to this question on SO states:

> According to the source code, the maximum size of a list is PY\_SSIZE\_T\_MAX/sizeof(PyObject\*) . On a regular 32bit system, this is (4294967295 / 2) / 4 or 536870912. Therefore the maximum size of a python list on a 32 bit system is 536,870,912 elements.

So you have the smaller of:

* The maximum you can fit in Linux's memory, and
* 536,870,912
> 1 votes

---
Tags: arduino-yun
---


# Question
Title: freeMemory() function from memoryfree library not returning decreased value in arduino UNO
I burned the code written below, I expect that as we declare the local variable in the loop, freeMemory() function should return decreased value. But it remains constant..! please explain why..? The output is attached :

```
#include <MemoryFree.h>
void setup()
{
  // put your setup code here, to run once:

  Serial.begin(9600); Serial.println(freeMemory(), DEC);  // print how much RAM is available.
  Serial.println("Lets Start");
}
void jack();
void loop()
{
    char c=0;
    c++;
    Serial.println("");
    Serial.println("Rajat0");
    Serial.println(freeMemory(), DEC);
    Serial.println("Rajat1");
    int x=0;
    x++;
    Serial.println("Rajat2");
    Serial.println(freeMemory(), DEC);
    Serial.println("Rajat3");
    jack();
    Serial.println("");
    delay(1000);
}
void jack()
{
    Serial.println("jack0");
    int x=0;
    x++;
    Serial.println(freeMemory(), DEC);
    Serial.println("jack1");
}

```

# Answer
You are assuming that, just because you created a variable, it will be stored in memory. That is often not the case.

The compiler is reasonably intelligent. And there are lots of CPU registers in the AVR core. If there is a free register available for a temporary local variable like that, why would it waste time and effort putting it into memory when it can just keep it in a register?

Also, since you don't really *do* anything with the variable, chances are the compiler is just throwing it away.

Marking a variable `volatile` will remove both those problems, and you may see different results.
> 3 votes

# Answer
Function 'jack' also does not show any difference in allocation. Since `jack()` is called only within this one module (known, because the program only consist of one module), and only once, the compiler can replace the function-call with the actual code of the function, saving both the space and time of a call and return.

That optimization is called "inlining" (usually only useful for instructional purposes but learning appears to be the whole point of your sketch). You can suppress the inlining by prefixing both the function and its declaration with `__attribute__ ((noinline))`. (Note that this attribute is specific to the gcc compilers; other compilers may provide a different way to do it, or none at all):

```
__attribute__ ((noinline)) void jack();

...

__attribute__ ((noinline)) void jack(){
   ... etc ...
}

```
> 0 votes

---
Tags: programming, arduino-ide, atmega328, memory-usage, memory
---


title: mcufriend 2.4 TFT with ESP8266

text:
# Question
Title: mcufriend 2.4 TFT with ESP8266
I have this TFT:

Now, the problem is, I will not use this as a shield (i.e. I will not just put it on top of an Arduino Uno). I will use it with an ESP8266 (NodeMCU). I want to know how to wire them up together. There is this website (and a few more that say the same way). But the problem is I cannot find `SDI/MOSI` or `SDD/MISO` on the TFT above.

# Answer
You have an 8-bit parallel interface TFT display. It requires 13 GPIO pins - D0-D7 plus reset, chip select, read, write and register select. You can forego the "read" signal and tie it high to save a pin. You can probably do the same with the reset signal, meaning you need a minimum of 11 pins.

I am not sure the NodeMCU has that many available, does it? (maybe it does, I don't have one to hand right now), so you may want to try getting it going with an SPI or I2C IO expander (though slowly).

And then of course you have to find the right library for the chip on the display (there's a few it could be - I have seen at least 3 different ones on the same, or similar, carrier PCB) that works with the NodeMCU.
> 3 votes

# Answer
SD\_DI is the MOSI, and SD\_DO is the MISO. According to the datasheet.
> 3 votes

---
Tags: esp8266, shields, tft
---


title: Button Matrix Code and Wiring

text:
# Question
Title: Button Matrix Code and Wiring
Bear with me here, I'm new to arduinos, so what I'm saying might only make sense in my own mind.

I'm trying a button matrix and I not completely sure on my wiring and I have a few questions.

1. Is the diagram correct?
2. I wire D2 to D3 and set them to output and input respectively. In the code I digital write to D2 a HIGH, will D3 then read high?
3. What is the best way to read the state of each button? Is there a Library that can simplify it?

I'm sorry if this is all just confused gibberish.

EDIT: I got the idea from this video, which explains some of it, but no code. He however uses an arduino micro.

EDIT #2: I realized I wired the buttons incorrectly.

# Answer
@Jot commented to use the Keypad Library. Which I got to work using the tutorial. Took a few minutes to set up.
> 1 votes

---
Tags: arduino-uno, button
---


# Question
Title: Arduino Nano not responding with yellow led blinking fast
***Update****: I started playing with a genuine Deumilanove and exactly same problem happened to it - d13 led blinking, but avrdude says `stk500_recv(): programmer is not responding`*

I uploaded a largish sketch ~15kb to Arduino Nano v3.0 (clone) and that left the board in an unusable state. When connected to USB, a power LED goes on immediately and 1-2 seconds later the yellow "L" starts blinking really fast. Here's the board I use, it's a cheap clone, but it worked really well before today.

Now, when I try to upload a new sketch I get an error:

```
avrdude: stk500_recv(): programmer is not responding

```

I tried making and ISP programmer out of genuine Duemilanove, using nano's ISP pins and tried following official instructions (didn't use any capacitors/resistors). Either way when I click "Burn Bootloader" result is the same error:

```
avrdude: stk500_getsync(): not in sync: resp=0x15

```

I have connected "debug" leds to D7,8,9 and heartbeat fades in and out in idle, others stay dark. When I click "Burn Bootloader" all leds go dark then it does few quick blinks on 7, then similar pattern for 8, and then heartbeat resumes. Sometimes this sequence is repeated twice.

I also tried editing preferences.txt to bypass bootloader, but that didn't help.

**How do I restore this board or do a low level reset?** It seems to be in some failure mode, with pin 13 oscillating, but I don't know what that means.

# Answer
I successfully restored both boards using the reset button:

1. Power off the board (I disconnected the USB cable from computer)
2. Press and hold the reset button
3. Connect USB cable (keep holding the reset button)
4. Click "Upload Sketch"
5. Wait a second or two until Arduino software says "Uploading..." in the status bar
6. Release the reset button

Use these steps to upload any small sketch, Blink example is a good choice.
> 11 votes

# Answer
There is bug related to watchdog in original old Arduino bootloader. You can switch to different bootloader, e.g. "Optiboot".

Explanation of issue from ATmega48A/PA/88A/PA/168A/PA/328/P datasheet, section **10.10.5 Watchdog Timer**, page 48:

> If the Watchdog is accidentally enabled, for example by a runaway pointer or brown-out condition, the device will be reset and the Watchdog Timer will stay enabled. If the code is not set up to handle the Watchdog, this might lead to an eternal loop of time-out resets. To avoid this situation, the application software should always clear the Watchdog System Reset Flag (WDRF) and the WDE control bit in the initialization routine, even if the Watchdog is not in use.

Reset from button is not helping, only power off/on reset give device change to boot again (and flash new software). Explanation of this, from **11.9.1 MCUSR – MCU Status Register**, page 54:

> Bit 3 – WDRF: Watchdog System Reset Flag This bit is set if a Watchdog System Reset occurs. The bit is reset by a Power-on Reset, or by writing a logic zero to the flag.
> 1 votes

# Answer
Use "upload.verbose=true" in the preferences.txt of the Arduino IDE (File-\>preferences-\> Click on the file), this helps you to find the right moment to release the reset button (Step 5 of Paul's method).

```
avrdude: Version 6.3, compiled on Jan 17 2017 at 12:00:53
.
.
         Using Port                    : COM19
         Using Programmer              : arduino
         Overriding Baud Rate          : 57600
release here ^^^^

```
> 1 votes

# Answer
Try changing processor type to ATmega328(old bootloader) in Tools-\>Processor. My Nano board blinked led like it had bootloader but I couldn't upload sketch and that helped.
> 1 votes

---
Tags: bootloader, arduino-nano
---


# Question
Title: Every so often ESP8266 hangs... WifiClient seems to be at fault
This code works fine without any freezes:

```
#include <ESP8266WiFi.h>
#include <Servo.h>
#include <WiFiClient.h>
#include <ESP8266WiFiMulti.h>

Servo turn;

ESP8266WiFiMulti wifiMulti;

const char* host = "192.168.1.148";
WiFiClient client;

int turnPos = 90;
unsigned long ts = 0;

void setup() {
  startWiFi();
  turn.attach(14);
  turn.write(90);
}

void loop() {

  if (millis() - ts > 500 && millis() - ts < 1000) {
    turnPos = 160;
  }
  else if (millis() - ts >= 1000) {
    ts = millis();
  }
  else {
    turnPos = 20;
  }

  /*if (client.connected()) {
    }
    else {
    if (!client.connect(host, 3000)) {
    }
    }*/

  turn.write(turnPos);
  yield();
}

void startWiFi() {
  wifiMulti.addAP("DVW3201BE8", "###");   // password is filled in on mny version
  while (wifiMulti.run() != WL_CONNECTED) { // Wait for the Wi-Fi to connect: scan for Wi-Fi networks, and connect to the strongest of the networks above
    delay(250);
    Serial.print('.');
  }
}

```

While this code (with the wificlient bit commented out) freezes every so often:

```
#include <ESP8266WiFi.h>
#include <Servo.h>
#include <WiFiClient.h>
#include <ESP8266WiFiMulti.h>

Servo turn;

ESP8266WiFiMulti wifiMulti;

const char* host = "192.168.1.148";
WiFiClient client;

int turnPos = 90;
unsigned long ts = 0;

void setup() {
  startWiFi();
  turn.attach(14);
  turn.write(90);
}

void loop() {

  if (millis() - ts > 500 && millis() - ts < 1000) {
    turnPos = 160;
  }
  else if (millis() - ts >= 1000) {
    ts = millis();
  }
  else {
    turnPos = 20;
  }

  if (client.connected()) {
    }
    else {
    if (!client.connect(host, 3000)) {
    }
    }

  turn.write(turnPos);
  yield();
}

void startWiFi() {
  wifiMulti.addAP("DVW3201BE8", "###");   // password is filled in on mny version
  while (wifiMulti.run() != WL_CONNECTED) { // Wait for the Wi-Fi to connect: scan for Wi-Fi networks, and connect to the strongest of the networks above
    delay(250);
    Serial.print('.');
  }
}

```

Only difference is in the working one the WifiClient bit of code is commented out. How would WifiClient cause this problem?

# Answer
It is a bug and it was fixed in Arduino esp8266 core package 2.4.2 published 2 days ago.

see first line in ESP8266WiFi section of the changes list

> 2.4.2 ESP8266WiFi: Fix memory leak when reusing WiFiClient object (#4497, #4516, #4549)
> 2 votes

---
Tags: esp8266, networking
---


title: Ethernet socket impedes adding shields

text:
# Question
Title: Ethernet socket impedes adding shields
I just bought a KEYESTUDIO W5500 Ethernet Arduino without realizing that the Ethernet socket on the board impedes adding any additional shields to the device because:

1. Horizontally the socket runs right up next to the shield connector sockets
2. Vertically the socket is a good 1/4 inch higher that the shield connector sockets

Is there a good solution for extending the shield connector sockets vertically so that they clear this Ethernet socket?

# Answer
Plug some of these into the Arduino headers to add extra space.

They come in different lengths and can be cut to the required number of pins.

They also come in different pin lengths.

Google `long tailed pin headers`.
> 1 votes

---
Tags: arduino-uno, shields, ethernet
---


title: Software Gate on a PWM port

text:
# Question
Title: Software Gate on a PWM port
I'm using a PWM port and outputting a freq. Is it possible to pulse the PWM port using software to simulate a pulse gate. For example, I'd like to output a freq of 111hz, but would like to gate that freq at .5-7hz. Is this possible to do all in software without external hardware. I'm using a Teensy board which is similar to an Arduino, but has 3 independent PWM ports. Any ideas on whether this possible?

# Answer
> 1 votes
If you can configure the PWM to run at 111 Hz (I don't know how this is done on the Teensy), then “gating” it is as simple as turning the PWM on and off at the desired frequency:

```
uint32_t half_period;  // half the gating period in microseconds

void set_gate_frequency(float freq_in_hz)
{
    half_period = (1e6 / 2) / freq_in_hz;
}

void loop()
{
    static uint32_t last_toggle = 0;
    static bool pwm_is_on = false;
    if (micros() - last_toggle >= half_period) {
        if (pwm_is_on) {
            digitalWrite(PWM_PIN, LOW);
            pwm_is_on = false;
        } else {
            analogWrite(PWM_PIN, 128);  // PWM with 50% duty cycle
            pwm_is_on = true;
        }
        last_toggle += half_period;
    }
}

```

---
Tags: arduino-nano, pwm, teensy
---