title: Compile `.hex` files on Linux

text:
# Question
Title: Compile `.hex` files on Linux
I build `.hex` files for Arduino. How can I do this in Linux? I use the Linux distro Mint 17.2.

I need a program to make \[`.hex` files\] (in Linux).

Can anyone help me?

# Answer
You can download the Arduino IDE for Linux from the Arduino site.

As mentioned in Where are the hex files compiled by Arduino?, in the Arduino program: go to **Arduino -\> Preferences** and then select **Show verbose output during -\> compilation**.

> Finally, when you are compiling, the program will show you lots of data. At the last lines, you will find the path to the .hex file (Every time the path changes!).

If you want to upload this `.hex` file to your **ATmega328P** (the micro controller inside Arduino Uno), `avrdude` can do that for you.

Here, are few useful links:

1. Setup Avrdude on Linux
2. Programming your chip
3. Choosing a Programmer
4. Uploading your .hex file
> 2 votes

# Answer
How are you creating your `.hex` files? Where are they coming from? Are you cross compiling the `.hex` files on some other machine and then transferring them to the Linux box? What is your Arduino connected to, the Linux box, or some other machine? Why are you even bothering with the .hex files? Your question is a little unclear. As Mikael states in his comment, you do not need to *compile* the `.hex` files, they are already compiled, you merely need to *upload* them, which the Arduino IDE would do for you anyway...

As ARK points out in his answer, you may find the answers to the question Where are the hex files compiled by Arduino? useful, although it seems like you know where they are but you don't know how to upload them.

Why can you not just use the Arduino IDE, to write your sketch, and then allow it to *automatically* compile the sketch and upload the `.hex` file for you? That way you do not need to manually play with the `.hex` file. Maybe I am missing something.

Is the Arduino IDE bombing out and not uploading the sketch on to the Arduino board?

---

However, if you are merely asking, how can I upload a `.hex` file to an Arduino, in Linux without using the Arduino IDE, then you would use `avrdude`. Taking the answer from How do I upload a hex file firmware to a target board without using the arduino IDE?

```
avrdude -C/usr/share/arduino/hardware/tools/avrdude.conf -v -v -v -v -patmega328p -carduino -P/dev/ttyUSB0 -b57600 -D -Uflash:w:/tmp/build8135728863211847829.tmp/sketch_may21b.cpp.hex:i

```

or alternatively, taking the answer from Uploading Arduino hex file using avrdude

```
avrdude -U flash:w:[put-hex-file-path-here]:i -C avrdude.conf -v -p atmega328 -b 115200 -c stk500v2 -P [put-device-path-here]

```
> 2 votes

---
Tags: linux
---


# Question
Title: Connecting a motor to Arduino UNO Play breadboard
I am new to Arduino and have a small query. I am building a simple system that switches on a motor and switches it off after some time and repeats this in a loop.

The Arduino that I am using is a “DIY UNO Play Breadboard -ATMEGA328P with FT232 Breakout Board” (Rs. 825, or $12.38USD, from Mangalore). The Arduino board is similar in size to a Nano but without USB. The FT232 board has a USB B port on one end and serial pins on the other.  My query is whether I should connect the positive end of battery supply to the motor and then connect in series using a motor controller circuit to port 7 and connect the negative terminal to the gnd port.

Or do I need a separate voltage source for my Arduino, because this Arduino has no built in USB ports.

This is my code to switch on and switch off the motor:

`int motorPin = 7;
 pinmode(motorPin,OUTPUT);
 digitalWrite(motorPin,HIGH); //turn motor on
 delay(500); //wait
 digitalWrite(motorPin,LOW); //turn motor off
 delay(500); //wait`

# Answer
> 1 votes
Using same Voltage supply to power Arduino Board and motor simultaneously is usually not a good practice.

So, what you can do is use separate batteries to power Arduino and motor as shown in image below  However you can also power arduino and motor from single power supply, but in this case you should first think of current ratting of your battery and current consumption of your Arduino (normally 500mA) and motor. As shown below,  Hope it help. Any question Comment below.

# Answer
> 0 votes
You can use the same power supply for both if it can source enough current for both; USB ports usually can not. But what you must not do is try to supply motor current through the Arduino, from any power supply. You need the Arduino to control a transistor switch which manages the motor current.

---
Tags: arduino-uno, motor
---


# Question
Title: Problems coding a 12 pin 7 segment display and grove temperature sensor with Arduino Uno
I am trying to code my 12 pin seven segment display to display the temperature from my grove temperature sensor. I am new to this and I have been struggling, so if anyone could help that would be much appreciated.

My temperature sensor is displaying its information in the serial monitor, however I want the temperature displayed with the 7 segment display - that's where I need help.

```
//Temperature Variables
//thermistor = value of the thermistor
int a;
float temperature;
int thermistor=3975;
float resistance;
boolean DigitOn = LOW;
boolean DigitOff = HIGH;
boolean SegOn=HIGH;
boolean SegOff=LOW;

int DigitPins[] = {2, 3, 4, 5};
int SegmentPins[] = {6, 7, 8, 9, 10, 11, 12, 13};

//N is for numbers and NxP is a number with a decimal point behind
int BLANK[] = {LOW, LOW, LOW, LOW, LOW, LOW, LOW, LOW};
int N0[]    = {HIGH, HIGH, HIGH, HIGH, HIGH, HIGH, LOW, LOW};
int N0P[]   = {HIGH, HIGH, HIGH, HIGH, HIGH, HIGH, LOW, HIGH};
int N1[]    = {LOW, HIGH, HIGH, LOW, LOW, LOW, LOW, LOW};
int N1P[]   = {LOW, HIGH, HIGH, LOW, LOW, LOW, LOW, HIGH};
int N2[]    = {HIGH, HIGH, LOW, HIGH, HIGH, LOW, HIGH, LOW};
int N2P[]   = {HIGH, HIGH, LOW, HIGH, HIGH, LOW, HIGH, HIGH};
int N3[]    = {HIGH, HIGH, HIGH, HIGH, LOW, LOW, HIGH, LOW};
int N3P[]   = {HIGH, HIGH, HIGH, HIGH, LOW, LOW, HIGH, HIGH};
int N4[]    = {LOW, HIGH, HIGH, LOW, LOW, HIGH, HIGH, LOW};
int N4P[]   = {LOW, HIGH, HIGH, LOW, LOW, HIGH, HIGH, HIGH};
int N5[]    = {HIGH, LOW, HIGH, HIGH, LOW, HIGH, HIGH, LOW};
int N5P[]   = {HIGH, LOW, HIGH, HIGH, LOW, HIGH, HIGH, HIGH};
int N6[]    = {HIGH, LOW, HIGH, HIGH, HIGH, HIGH, HIGH, LOW};
int N6P[]   = {HIGH, LOW, HIGH, HIGH, HIGH, HIGH, HIGH, HIGH};
int N7[]    = {HIGH, HIGH, HIGH, LOW, LOW, LOW, LOW, LOW};
int N7P[]   = {HIGH, HIGH, HIGH, LOW, LOW, LOW, LOW, HIGH};
int N8[]    = {HIGH, HIGH, HIGH, HIGH, HIGH, HIGH, HIGH, LOW};
int N8P[]   = {HIGH, HIGH, HIGH, HIGH, HIGH, HIGH, HIGH, HIGH};
int N9[]    = {HIGH, HIGH, HIGH, HIGH, LOW, HIGH, HIGH, LOW};
int N9P[]   = {HIGH, HIGH, HIGH, HIGH, LOW, HIGH, HIGH, HIGH};
int MIN[]   = {LOW, LOW, LOW, LOW, LOW, LOW, HIGH, LOW};

//Array of pointers for the 4 digits
int* lights[4];

//char array coming from the serial interface
//4 numbers or chars, 4 optional decimal points, 1 end-of-line char
char incoming[9] = {};

void setup() {
  Serial.begin(19200);
  for (byte digit=0;digit<4;digit++) {
    pinMode(DigitPins[digit], OUTPUT);
  }

  for (byte seg=0;seg<8;seg++) {
    pinMode(SegmentPins[seg], OUTPUT);
  }

  //initialize display with 1.234
  lights[0] = N7;
  lights[1] = N9P;
  lights[2] = N3;
  lights[3] = N4;
}

void loop() {
  //Temperature Sensor
    a=analogRead(5);
    resistance=(float)(1023-a)*10000/a; //get the resistance of the sensor;
    temperature=1/(log(resistance/10000)/thermistor+1/298.15)-273.15;
//convert to temperature via datasheet ;
    //delay(1000);
    Serial.print("Current temperature is ");
    Serial.println(temperature);
    //delay(500);
  //read the numbers and / or chars from the serial interface
  if (Serial.available() > 0) {
    int i = 0;
    //clear the array of char
    memset(incoming, 0, sizeof(incoming));
    while (Serial.available() > 0 && i < sizeof(incoming) - 1) {
      incoming[i] = Serial.read();
      i++;
      delay(3);
    }
    Serial.println(incoming);

    //show the input values
    for (int y = 0; y < 4; y++) {
      Serial.print(y);
      Serial.print(": ");
      for (int z = 0; z < 8; z++) {
        Serial.print(lights[y][z]);
      }
      Serial.println("");
    }
  }

      //end if, i.e. reading from serial interface
      //This part of the code is from the library SevSeg by Dean Reading

  for (byte seg=0;seg<8;seg++) {
        //Turn the relevant segment on
    digitalWrite(SegmentPins[seg],SegOn);
    //For each digit, turn relevant digits on
    for (byte digit=0;digit<4;digit++){
      if (lights[digit][seg]==1) {
        digitalWrite(DigitPins[digit],DigitOn);
      }
      //delay(200); //Uncomment this to see it in slow motion
    }
    //Turn all digits off
    for (byte digit=0;digit<4;digit++){
      digitalWrite(DigitPins[digit],DigitOff);
    }
    //Turn the relevant segment off
    digitalWrite(SegmentPins[seg],SegOff);
  }
    //end of for
}

```

# Answer
Your temp sensor is obviously working if it displays the temp on the serial monitor. I would now write a new sketch, forgetting the temp sensor for the moment, and get numerical data on to the seven segment display correctly.

How many digits does the seven segment display have? What interface are you using, if any? How is the display connected to the Arduino? You need to provide the information in your question, to allow us to give you an accurate answer.

You may want to take a look at my answer to Programming 4-digit seven segment display using interrupts only on SE Robotics. I had the same issues, about a year ago, when I was trying to display data on a cheap seven segment display that I purchased in BKK, and I ended up writing an Arduino library in order to get it to work, see Dual Seven Segment Display Madness. However, I don't recommend that you write your own library, and instead use a pre-built one. Take a look at the SevenSeg library. That is what I used eventually.

I see that you are using some code from the SevSeg library, but you do not appear to include the header `SevSeg.h` in your sketch. If you are happy using the SevSeg library, then first write a sketch using the examples and the tutorials, so that you can get data displayed. Then integrate that software with your temperature sensor software.

You really do need to divide your project into two parts, the sensor and the display. Once you are happy with displaying data on the Seven Segment display, *then*, and only *then* can you think about getting the temperature sensor data displayed on it.
> 1 votes

# Answer
You loop over the segments. For each segment you set the output high, then pull the digit output low for each digit that should have that segment lit.

The big issue I see is that you turn the digits off immediately after turning them on. The digits are on for only a few processor cycles. If you delay for a few ms before turning all the digits off, you'll probably see them better.

The usual way I've seen this code written, and written it myself, is to loop over digits in the outer loop and set all the segments for one digit at once. You're setting all the digits for one segment. The way you do it, if the display is showing all 8s with decimal points, each segment will be on 1/8 of the time. If you loop over digits, each segment will be on 1/4 the time, and the display will be brighter. Looping over digits lets you illuminate up to 8 segments at once instead of 4.

Finally, doing this with digitalWrite is very inefficient. If you connect the segments to digital ports 0-7 you can set them all simultaneously by writing a byte to PORTD.
> 0 votes

# Answer
The *simple* way is to use a MAX7219 chip which does most of the work for you.

You haven't said what LED device you have but an example of wiring it is:

That chip does the multiplexing for you. I have a detailed description here.

If you don't want to use another chip you could use 12 of your Arduino pins. It's a little tedious because you need to be refreshing the display even while you are doing other things. You could use a timer interrupt for that.

The code you posted looks like it might work. In what way does it not work?

> I have been struggling ...

That doesn't tell us much. Do all segments light up? None? Incorrect ones? Does it flicker? What is the problem exactly?

Please read How do I ask a good question?
> 0 votes

---
Tags: sensors, c++, temperature-sensor, 7-segment
---


# Question
Title: MatLab connection to Arduino using Bluetooth
I am attempting to send some information from MatLab to an Arduino Uno via Bluetooth with the following

MatLab program:

```
b=Bluetooth('HC-06',1);
fopen(b);
for i=1:1:15
  fprintf(b,i);
  out(i) = fscanf(b,'%d');
end
fclose(b)

```

and Arduino program

```
int matlabval=0;

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

void loop() {
  if (Serial.available() > 0) {
    matlabval = Serial.read();
    Serial.println(matlabval);
  }
}

```

the output of arduino is

1 10 2 10 3 10 4 10 5 10 6 10 7 10 8 10 9 10 10 10 11 10 12 10 13 10 14 10 15 10

The number 10 appears after each number. Why is that so?

Thanks in advance!

# Answer
> 1 votes
As discussed in the comments, the "problem" seemed to be Matlab adding a "New Line" which is a decimal 10 in ASCII.

> asciitable.com Decimal 10 is the ASCII code for a "New Line" so it appears your Matlab send code will add a "New-line" after each sent value. – Paul Apr 14 at 8:15
>
> > thank you very match the problem is solved – abbas hussien 5 hours ago

*You might want to accept this answer so that this question gets "closed" and the site's statistics will be more accurate. It will also avoid this question being bumped up by the system and people reading into something that has already been solved.*

---
Tags: bluetooth, matlab
---


# Question
Title: How is it possible that my skin temperature is so constant?
Here's the code

```
#include <OneWire.h>

int DS18S20_Pin = 3; //DS18S20 Signal pin on digital 3
unsigned long startTime = 0;
#define MEASURE_PERIOD 250
//Temperature chip i/o
OneWire ds(DS18S20_Pin);  // on digital pin 3

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

void loop() {
  if((millis() - startTime) >= MEASURE_PERIOD)
    {
        startTime += MEASURE_PERIOD;
        float temperature = getTemp();
        Serial.println(temperature);
    } //just here to slow down the output so it is easier to read

}

float getTemp(){
  //returns the temperature from one DS18S20 in DEG Celsius

  byte data[12];
  byte addr[8];

  if ( !ds.search(addr)) {
      //no more sensors on chain, reset search
      ds.reset_search();
      return -1000;
  }

  if ( OneWire::crc8( addr, 7) != addr[7]) {
      Serial.println("CRC is not valid!");
      return -1000;
  }

  if ( addr[0] != 0x10 && addr[0] != 0x28) {
      Serial.print("Device is not recognized");
      return -1000;
  }

  ds.reset();
  ds.select(addr);
  ds.write(0x44,1); // start conversion, with parasite power on at the end

  byte present = ds.reset();
  ds.select(addr);
  ds.write(0xBE); // Read Scratchpad

  for (int i = 0; i < 9; i++) { // we need 9 bytes
    data[i] = ds.read();
  }

  ds.reset_search();

  //byte MSB = data[1];
 // byte LSB = data[0];

  float tempRead = ((((int)data[1]) << 8) | data[0]); //using two's compliment
  float TemperatureSum = tempRead / 16;

  return TemperatureSum;

}

```

# Answer
Examine your code closely. It appears that you are partially implementing extended resolution calculations in this line of code:

```
  float TemperatureSum = tempRead / 16;

```

In the DS18S20 specifications the extended resolution equation used is:

```
 TEMPERATURE = TEMP_READ * 0.25 - ((COUNT_PER_C - COUNT_REMAIN) / (COUNT_PER_C))

```

Where COUNT\_PER\_C is a DS18S20 register containing a value of up to 16. Maybe that is where 16 originated?

I believe what you want to do is divide the recovered value by 2.0 base on table 1 from the DS18S20 specifications:

```
  float TemperatureSum = tempRead / 2.0;

```

Don't forget the "." in case the compiler you are using decides to do integer math dripping the "float" part before assigning it to TemperatureSum.
> 1 votes

# Answer
Try using Dallas Temperature Control Library for DS18S20. (Click Here, Download Library). Its simple and easy to use, and it comes with examples.

Here is tutorial.

Hope it helps.
> 0 votes

---
Tags: arduino-uno, temperature-sensor
---


# Question
Title: Library LiquidCrystal_I2C don't work in other class (Composition)
Good afternoon, I'm trying to use a class to streamline the writing on the LCD. In this class I have an private attribute (it's a pointer, do not know how I call him) called `LiquidCrystal_I2C* _lcd`, I instantiate it in the constructor, so far so good, but when I call the `_lcd-> begin (20, 4)` the code below is not executed, but no error is displayed.

Display.h:

```
class Display{
    public:
        Display();
        ...
    private:
        LiquidCrystal_I2C* _lcd;
        ...
}

```

Display.cpp:

```
...
Display::Display() {
    _lcd = new LiquidCrystal_I2C(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);
    _lcd->begin (20, 4);
}
...

```

Program.ino

```
#include "Display.h"

Display lcd;

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

void loop() {
    Serial.println("test");
    delay(3000);
}

```

Just I noticed the error when I saw that `Serial.println ("test");` was not running. If I comment the `_lcd->begin (20, 4);` everything works.

I tested writing everything in Program.ino and worked, has nothing to do with connections or something, just do not apply the concept of composition with this class.

Can someone help me? And sorry for the English, i'm from Brazil. Thanks.

# Answer
> 4 votes
# Most likely cause

You are hitting an insidious problem that even experienced C++ programmers frequently miss: order of initialization of global variables. In your case, `Display lcd` is initialized (*i.e.,* its constructor is called) before `main()` and subsequently `setup()` are executed. However, you almost certainly are `#include`ing whatever library is declaring the `LiquidCrystal_I2C` class, probably `Wire.h`, and so on. In many of these classes, a global variable of that type is also defined to make it easier to access stuff. For example, `Serial` (as in `Serial.println("foo")`) is really a global variable of the appropriate type of whatever serial implementation your particular core is using.

The problem you are hitting is that the C++ standard does **not** guarantee the execution order of the constructors of global variables. The order is an artifact of the compiler, the order in which object files were linked, and probably the phase of the moon :)

What is (almost certainly) happening is that the constructor for your `class Display` is being called, which initializes the LCD and the i2c bus, and then something else calls either the LCD constructor or the i2c constructor and messes things up.

OK, "how do I fix this?" I hear you ask. Simple: make the global lcd variable a *pointer*, and allocate the instance in `begin()`, like so:

```
#include "Display.h"

Display *lcd;

void setup() {
  Serial.begin(9600);
  lcd = new Display();
  // stuff
}

void loop() {
  // more stuff
  lcd->some_method(some_argument);
  // even more stuff
}

```

Now you are guaranteed that your code will be the last to touch any initialization code that might affect the display or the bus. Just keep accessing the `class Display` methods through the pointer.

# A less likely cause

It is still possible that your constructors are getting executed in the right order, but your hardware does not like being initialized twice (but test that anyway!), so you may have to figure out how to reset the hardware so you can initialize it again. If I understand your posting correctly, the loop never runs, which means that a second initialization probably either causes a exception (which you would not see unless you had some kind of additional debugging channel; in the case of the ESP8266, for example, that would be the output-only `Serial1` port, and even then, you'd have to explicitly turn on debugging. Each core has its own debugging stuff, I forget what the real Arduino does.)

Hope this helps.

/ji

---
Tags: lcd
---


title: Arduino Leonardo runs unusually hot

text:
# Question
Title: Arduino Leonardo runs unusually hot
I have a genuine (purchased from Adafruit) Arduino Leonardo that I have had for 2 years and I have not had any issues with. However, I have always noticed that it seems to be running suspiciously hot for a low power microcontroller, sometimes even too hot to comfortably touch. I measured the temperature today with an infrared thermometer at 121 degrees Fahrenheit (~49C). Based on observations by feeling the board, the 32U4 seems to be what is getting hot and everything else is cool to the touch. This happens when it is powered over USB as well as through the power jack. The chip gets hot even when nothing is connected to the I/O or power pins. The board is entirely working and does not appear visibly damaged. I am a bit worried about this as I may use this board in a project where it will be inside in enclosure and running for long periods of time. Any ideas why this is happening and if this normal?

# Answer
My Leonardo, which I leave on all the time, is not hot. The CPU chip feels at room temperature as far as I can tell. If you were powering something from it, maybe you are drawing too much current. If it gets hot just sitting there doing nothing, and with nothing connected, something is wrong.

Maybe you damaged it in the past? Maybe hooked up some LEDs without current-limiting resistors? If not, it sounds like a faulty device to me.
> 1 votes

---
Tags: arduino-leonardo
---


# Question
Title: How to make Arduino to stop updating i2c data when meet a condition and wait until it receives another serial input from processing?
I am currently making a robot with Arduino Uno, D6T omron thermal sensor (i2c sensor) and some other sensors. My thermal sensor will always update the data in array form. It will display 4 data arrays every 1 second.

I wish to have my Arduino send out a string "found" over serial when it meet a condition, and thermal sensor will stop updating my data. Thermal sensor and Arduino will just have to wait until the user sends a selection, jump to the selected function, and thermal sensor will start updating data again after that. I am new to coding, any suggestion on how to make my arduino and sensor to wait? Thank you guys! =)

Attached below is my code. (Arduino Sketch):

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

#define D6T_addr 0x0A
#define D6T_cmd 0x4C

int rbuf[35];
float tdata[16];
float t_PTAT;

const int S_DATATRANSFER = 0;
const int S_WAIT = 1;
const int S_STOPTRANSFER = 2;
const int S_CONFIRMATION = 3;
const int S_ALLSTOP = 4;

float left_sum, right_sum, center_sum;

//-----------------------------------------------------------------------------

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

}

void loop()
{

static int state = S_DATATRANSFER;

    switch(state)
    {

    case S_DATATRANSFER:
        //Calculate temp
        //serialprint temp
        int i;

        if (Serial.available() > 0)
        {
                      char inByte = Serial.read();
                      if (inByte == '1')
            {  //processing will send one byte to arduino if ready

                Wire.beginTransmission(D6T_addr);
                Wire.write(D6T_cmd);
                Wire.endTransmission();

            if (WireExt.beginReception(D6T_addr) >= 0)
                {
                    i = 0;
                    for (i = 0; i < 35; i++)
                    {
                        rbuf[i] = WireExt.get_byte();
                    }
                    WireExt.endReception();

                    t_PTAT = (rbuf[0]+(rbuf[1]<<8))*0.1;
                    for (i = 0; i < 16; i++)
                    {
                        tdata[i]=(rbuf[(i*2+2)]+(rbuf[(i*2+3)]<<8))*0.1;
                    }
                }

                right_sum= tdata[0]+ tdata[4] + tdata[8] + tdata[12];
                left_sum= tdata[3] + tdata[7] + tdata[11] + tdata[15];
                center_sum= tdata[5] + tdata[6] + tdata[9] + tdata[10];
                output_csv();

               }
                      }
        state = S_WAIT;
        break;

    case S_WAIT:
        if (center_sum > 35*4)
        {
        state = S_STOPTRANSFER;
        }
        else
        {
        state = S_DATATRANSFER;
        }
        break;

    case S_STOPTRANSFER:

        Serial.println("F");
                delay(300);

        state = S_CONFIRMATION;

        break;

    case S_CONFIRMATION:
        while (Serial.available())
        {
         char val = Serial.read();
            if (val == '2')
            {
                state = S_ALLSTOP;
            }
            else if (val == '3')
            {
                state = S_DATATRANSFER;
                }
                        else if (val == '1')
                        {
                                state = S_DATATRANSFER;
                        }
                }

        break;

        case S_ALLSTOP:

        break;

    }
}

void output_csv()
{
  for (int i = 0; i < 16; i++)
  {
    Serial.print(tdata[i]);
    if (i < 15)
    {
      Serial.print(",");
    }
    else
    {
      Serial.println();
    }
  }
}

```

Attached below is my code in processing:

```
import processing.serial.*;
import controlP5.*;
import javax.swing.JOptionPane.*;
import com.onlylemi.processing.android.capture.*;
ControlP5 cp5;
javax.swing.JOptionPane JOptionPane;

AndroidCamera ac;
PImage img;
Textlabel myTextlabelA, myTextlabelB;
boolean canStart = true;
boolean canInput = false;
boolean Start = false;
boolean Start_camera = false;
String typedText = "Comments: ";
PFont font;
String command = "";
String confirm;
String found;

PImage carImage;
float[] tdata = new float[17];
float tptat; // PTAT
String portName;
//int serialport = 0;

String buf;
float colourGreen; //change green in relation to temperature

int lbTemp = 25; //lowest relative temperature
int hbTemp = 35; //highest relative temperature
Serial myPort;  // Create object from Serial class

void setup() {
  size(1366,768);
  //background(#FFFFFF);
  background(ControlP5.BLACK);
  //println(Serial.list());
  //portName = Serial.list()[serialport];
  myPort = new Serial(this, "COM15", 9600);
  myPort.clear();
  cp5 = new ControlP5(this);
  ac = new AndroidCamera(720, 480, 30);
  ac.start();

  myTextlabelA = cp5.addTextlabel("label")
                    .setText("GUI of Alive Human Detection System.")
                    .setPosition(120,10)
                    .setColorValue(#FFFAF0)
                    .setFont(createFont("Georgia",20))
                    ;

  cp5.addButton("Start")
     .setPosition(115, 670)
     .setSize(100,30)
     ;

  cp5.addButton("Stop")
     .setPosition(375, 670)
     .setSize(100,30)
     ;
  cp5.addButton("Start Camera")
     .setPosition(799, 670)
     .setSize(100,30)
     ;
}

public void Start(int theValue) {
  println("Initialising...");
  println("Connected.");
  //start displaying
 // carImage = loadImage(".png");
  Start = !Start;
}

public void Stop(int theValue) {
  println("Shuting Down...");
  //finish = loadImage("robot.png");
  //image(finish,30,64);
  myPort.write(0x02);
  Start = !Start;
  //strokeWeight(0);
}

public void Start_camera(int theValue) {
  println("Initialising...");
  println("Connected.");
  //start displaying
 // carImage = loadImage(".png");
  Start_camera = !Start_camera;
}

void draw()
{
  //if (Start_camera){
  //img = ac.getCameraImage();
  //image(img, 610, 0);
  //}
  if (Start){

    myPort.write('1');
    delay(100);
    while (myPort.available() > 0) {
    delay(300);
    buf = myPort.readStringUntil('\n');
    if (buf.equals("F")){
    int dialogResult = JOptionPane.showConfirmDialog (null, "Human found? Please Confirm!!", "Alert!", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
    if(dialogResult == JOptionPane.YES_OPTION)
    {
    fill(255,0,0);
    rect(100,670,50,30);
    myPort.write('2');
    }
    else if(dialogResult == JOptionPane.NO_OPTION)
    {
    fill(0,255,0);
    rect(100,670,50,30);
    myPort.write('3');
    }
    }
    else{
    myPort.clear();
    tdata = float(split(buf, ','));
    for (int i = 0; i <16; i++) {
    colourGreen = map(tdata[i],lbTemp,hbTemp,255,0);
    fill (255,colourGreen,0);

      if (i == 0)
    { rect(450,64,150,150);}
      else if (i == 1)
    { rect(300,64,150,150);}
      else if (i == 2)
    { rect(150,64,150,150);}
      else if (i == 3)
    { rect(0,64,150,150);}
      else if (i == 4)
    { rect(450,214,150,150);}
      else if (i == 5)
    { rect(300,214,150,150);}
      else if (i == 6)
    { rect(150,214,150,150);}
      else if (i == 7)
    { rect(0,214,150,150);}
      else if (i == 8)
    { rect(450,364,150,150);}
      else if (i == 9)
    { rect(300,364,150,150);}
      else if (i == 10)
    { rect(150,364,150,150);}
      else if (i == 11)
    { rect(0,364,150,150);}
      else if (i == 12)
    { rect(450,514,150,150);}
      else if (i == 13)
    { rect(300,514,150,150);}
      else if (i == 14)
    { rect(150,514,150,150);}
      else if (i == 15)
    { rect(0,514,150,150); }

    if (tdata[i]<5) {fill(255);} else {fill(0);}
      if (i ==0)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]),525, 139);}
      else if (i == 1)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]),375, 139);
      }
      else if (i == 2)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]), 225, 139);
      }
      else if (i == 3)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]),75, 139);
      }
      else if (i == 4)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]), 525, 289);
      }
      else if (i == 5)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]), 375, 289);
      }
      else if (i == 6)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]), 225, 289);
      }
      else if (i == 7)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]), 75, 289);
      }
      else if (i == 8)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]), 525, 439);
      }
      else if (i == 9)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]), 375, 439);
      }
      else if (i == 10)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]), 225, 439);
      }
      else if (i == 11)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]), 75, 439);
      }
      else if (i == 12)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]), 525, 592);
      }
      else if (i == 13)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]), 375, 592);
      }
      else if (i == 14)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]), 225, 592);
      }
      else if (i == 15)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]), 75, 592);
      }
    }
    delay(350);
  }
    }
    }
}

```

# Answer
Implement a state machine first in your code for each state:

1) Sending i2c data.

2) Not sending i2c data.

And identify the conditions necessary to switch states:

1 to 2 when condition meet.

2 to 1 when command received.

Then drop your code into the state machine's code.

Read about state machines here and here.
> 2 votes

# Answer
Create a flow chart of the entire process you want to happen. Once you proof your flow chart to cover all possible functions, you can create the logic, control, and subroutines that are needed. If you have a good book on Arduino programming, and how I2C works, you will know that the I2c display will hold whatever data you wish until you change it. Also, you probably know that you can chain a whole bunch of I2c devices, no matter if they are displays, or anything else, so each device will hold its own data independent of the others. Any updating is under your control in programming. You might also look into using interrupts for some of your program control. Sensors don't push data, the processor reads the data, and your program is in control of how often and when the data is read, and what it does with the data. The exception to your program being in control, is when you use interrupts. You should be storing the data so you will always have access to it for program examination and possible decision making. Lastly, to increase the abilities of your system, consider using one master Arduino, and several slave Arduino's. Some of the slaves, depending on what you want them to do, can be very small. Look at the tiny85. Some of the boards with the Tiny85 are the size of a postage stamp. I hope some of these suggestions are helpful to you.
> 0 votes

---
Tags: serial, i2c, processing-lang
---


title: Avoiding float math to speed up arduino

text:
# Question
Title: Avoiding float math to speed up arduino
I read and heard that the floating point math is much slower than int math.

And I saw a converting process in here floath math to integer math

So I want to to convert my floating math calculations to integer math.

Here is the code that include floating math:

```
float sensval, lpf, lps;
float sensinitial; // used to store the initial sensor data
float x, y, z;
int heigh;
int dA;

void setup() {

  runSensor();
  sensval = readSensorData();
  sensinitial = sensval; // Setting the initial data
  lpf = lps = sensval;
}

void loop() {
  sensval =  readSensorData();
  heigh = (float)44330 * (1 - pow(((float) sensval/sensinitial), 0.190295));
  lpf = lpf + (sensval - lpf) * 0.1;
  lps = lps+ (sensval - lps) * 0.05;
  x = (lps - lpf) * 50;
  y = x+ (z - y) * 0.1;
  z = constrain(y, -500, 500);
  dA += z * 100 + 2000;
}

```

readSensorData(); returns 7 decimals maximum(752.4543 for example)

There is pow calculation too.

So how can I convert floath math to int math?

Any optimization code are welcome.

# Answer
> 4 votes
What you are asking for is not simple, especially since you have this power function that can be hard to approximate.

First, you have to figure out the range and the required precision of each of the floating point numbers you are manipulating. You wrote that `readSensorData()` returns 7 decimals. If by that you mean that you require a relative accuracy of 10−7, then I predict it will be *extremely* hard to optimize this as a fixed point calculation. If you can live with a much lower relative accuracy (say, around 10−3 or 10−4), then it may be worth trying something.

I would start by writing the expression of `height` as

```
height = f(sensval/sensinitial-1)

```

where

```
f(x) = 44330 * (1 - pow(1+x, 0.190295))

```

I would expect `sensval` and `sensinitial` to be close to one another, which would imply that *x* is small. At this point you should try to estimate the likely range for *x*, because the feasibility of what follows strongly depends on it. Next step is to approximate f() by a polynomial. A simple Taylor expansion gives:

```
f(x) ≈ -x*(8435.78-x*(3415.25-x*2060.2))

```

You may start by trying this, just to see if it looks kind of OK or completely hopeless. You will notice that the above approximation is great when |*x*| is tiny, but it very quickly degrades as |*x*| increases. This is why you don't use Taylor expansions in real approximations, I showed it to you only to give you an idea of the feasibility of a polynomial approximation.

To do better than Taylor, you *must* specify the range of *x*, then you can scale that range to \[−1, 1\] and expand on the basis of the Chebyshev polynomials. And then you could fine-tune to get the optimal polynomial, but it's likely to be only marginally better than the Chebyshev expansion.

If all this works with a reasonable polynomial degree (say, no more than 5), then you can start converting to integer math. If it doesn't, you may try a different type of approximation, like interpolating over tabulated values. If the problem is the range of *x* being too large, you may instead write the power function as

ab = 2b × log2a

and write polynomial approximations to the base-2 exponential and logarithm (the polynomials only needs to cover one octave). If you try a rational fraction approximation, beware that divisions are slow on the AVR platform.

If all the above looks like too complex, or too much work, then just get a faster CPU, or try to live with your program being slow.

# Answer
> 1 votes
Since you are dealing with fractions, you can use fixed point arithmetic. For example, you can use `unsigned short _Accum` for `readSensorData()` if you only need 8 bits for the fraction part. http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1169.pdf tells you about fixed point types in c.

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


title: Need to buy a new breadboard?

text:
# Question
Title: Need to buy a new breadboard?
I'm new to Arduino and haven't done any education in electrical engineering before, so this might be a very dumb question.

I'm busy with a project to control two servo motors with Arduino. Now yesterday I connected the wires incorrectly to the breadboard, so the wires started smoldering. I didn't connect the resistor correctly, so I guess that might have been the problem.

Now I replaced the wiring, but it's not working and I don't know if the software might be the problem or the breadboard need to be replaced as well. I cannot see anything wrong with the breadboard, but it was warm so I don't know if it might be burned from the inside? The wiring of the servomotors seems to be okay, so I guess that I don't need to replace those I hope.

Any tips about how to check everything is still working?

Or might it be a good idea to buy an LED and add it to the breadboard to ensure it's okay?

EDIT: I guess I found some code to check that the servomotors are still okay. Just add them directly to the Arduino and run some code: Sweep

One other question: one of the servomotors doesn't have a black, red and yellow cable but a red, brown and orange. How can I know which ones the same as yellow, red and black?

# Answer
To answer your last question (for 99%):

```
red = +
brown = gnd
orange = pwm (speed)

```

To test: try measure resistance with multimeter, gnd and + should have the lowest resistance.

And to be save: buy a new breadboard, a bad partly melted breadboard, or pieces of solder spoiled, is a nightmare.

Otherwise you can test with a multimeter the resistance of your breadboard for columns (close to 0) and rows 1.
> 1 votes

# Answer
You could check the connections of the breadboard, using a multimeter (set to continuity check) and wires in the breadboard holes, with the + and - leads, from the meter, at either end of each row/column of connections, following the diagram below:

It might be a bit tedious, but it should only take thirty minutes maximum, and would give you peace of mind as well as saving you four Euros...

If you say that it was working before and now is not, then maybe the breadboard is damaged. However, it is unlikely that the whole breadboard is... try moving your components to a different part of the breadboard.

The breadboard could possibly get warm, as servos *can* use a fair bit of current, and breadboards aren't really designed for power circuitry. You *may* be better off using an **Arduino Servo shield** and connecting the servos directly to that, rather than using the breadboard. Why are you using a breadboard - can you, as Majenko states, provide a schematic diagram?

Answering the last part of your question - Taking the graphics from my answer to Code to control servo with shield, to show the different colours for the four different connector types:

Futaba and Airtronics connectors

Hitec and JR Radio connectors have the same pin out:

.

This means that the red, brown and orange leads go to a *JR Radios connector*.
> 2 votes

# Answer
Not all servo motors have the same color cables, that's the manufacturers choice, although they should be standardized. You can test them with a multi-meter, low resistance is usually ground, slightly higher one is usually is usually the power, the other will be the signal. Breadboards are generally cheap and if you suspect yours is not functioning properly, buy a new one. I have two of these and they work very well for $10. MPJA powered breadboard

Additionally, if you have a motor driver shield, they usually have a three pronged port for your servo cable to connect to. Try that as well.
> 0 votes

---
Tags: arduino-uno
---


# Question
Title: Programming problem I need both if else cases to work but only else loop is running
```
#include <SoftwareSerial.h>
#include <Servo.h>
Servo myservo1, myservo2, myservo3;

int bluetoothTx = 14;
int bluetoothRx = 15;

SoftwareSerial bluetooth(bluetoothTx, bluetoothRx);

void setup()
{
myservo1.attach(9);

//Setup usb serial connection to computer
Serial.begin(9600);

//Setup Bluetooth serial connection to android
bluetooth.begin(9600);
 }

void loop()
  {
    if(bluetooth.available()>0)
     {
      if(bluetooth.available()>=4)
       {
        char buffer[4];
          for(int i=0;i<4;i++)
         {
          buffer[i]=bluetooth.read();
         }
       int incomingValue = atoi(buffer);

      if(incomingValue>=1000 && incomingValue<=1360)
        {
           unsigned int servopos = bluetooth.read();
           unsigned int servopos1 = bluetooth.read();
           unsigned int realservo = (servopos1 * 256) + servopos;

         if (realservo >= 1000 && realservo < 1360)
          {
              int servo1 = realservo;
              servo1 = map(servo1, 1000, 1360, 0, 360);
              myservo1.write(servo1);
              Serial.println("servo 1 ON");
           delay(10);
            }
           }
          }
         if(bluetooth.available()==2)
          {
            char inbit=bluetooth.read();
            if(inbit=='A'||inbit=='D');
           {
            char myval= bluetooth.read();
            if(myval== 'A')
            {
              myservo1.attach(9);
            }

             if(myval== 'D')
              {
               myservo1.detach();
              }
             }
            }
           }
          }

```

# Answer
There are so many things wrong with that program I can't begin to sort it out.

Here's some of the most glaringly obvious errors:

```
if(bluetooth.read() >=0 && bluetooth.read() <=360)

```

Read a character. Check it's at least 0. Read a second character. Check it's less than 360. Since characters are between 0 and 255 that will always succeed if there is one character of any form to read (if there is no characters to read you get -1).

```
else if(bluetooth.read()=='A'||'B'||'C'||'D'||'E'||'F');

```

Read another character and compare it to 'A'. This if is true if the character read is A. It also succeeds if B, or if C or if D, etc. That's not "if it's equal to C", just "if C". C is a character literal, so it's equivalent to a number. Any number that is not 0 is TRUE, therefore it's equivalent to:

```
if character is A or TRUE or TRUE or TRUE...

```

Which of course is just true, so it will always succeed regardless.

```
char myval= bluetooth.read();
if(myval== 'A')

```

Read yet another character from bluetooth (I sure hope there are enough there...) then compare it to a list of characters that are the same as you looked at above. You're comparing a *new* character this time, not the one you compared with the list a few lines beforehand.
> 1 votes

---
Tags: programming, bluetooth
---


# Question
Title: Arduino continually resets when connected to external power supply, but not USB
I'm working on a seemingly simple Arduino project which plays a sound and flashes an LED when provoked by some trigger.

**The problem:**

When powered by an external power supply, the Arduino continually resets after playing ~1/4 seconds of audio. When powered from USB, it works fine (however the LED, being powered from the external power supply, of course does not work here).

**Wiring diagram**:

**Parts list**:

* Arduino Pro Mini 5V
* Adafruit MAX98306 3.7W amplifier
* Sparkfun FemtoBuck LED Driver
* 4 Ohm 3W speakers
* 3W LED

I am using a 9V 1A power supply. Again, when no speakers are connected, the Arduino and LED work as intended. It's only when a speaker is connected that the board resets over and over again. Playing roughly 1/4 of a second of audio and then resetting implies to me that there's insufficient current, however, the problem persists even after using a 2.5A power supply.

**Things I have tried:**

* Increasing the power supply to 12V 2.5A
* Desoldering the LED driver (even with the LED driver removed, the board still resets)
* Checking continuity and staring at the wiring for long periods of time while scratching my head

Overall, I'm at a loss as to why it would work when powered via USB instead of through my external power supply.

What am I doing wrong? Any insights are greatly appreciated!

# Answer
> 3 votes
Most likely lack of current - lack of current able to be provided by the Mini. The audio is powered from the onboard regulator on the Mini, which has limited current capacity.

If too much current is drawn it will either get too hot and go into thermal shutdown until it cools down enough, or it will drop the output voltage, making things reset and crash.

Power the audio system from an external 5V regulator.

# Answer
> 0 votes
your power supply may be faulty. try a another power supply which can supply more current and common the GND of arduino and power suply..it may have internal short circuit or lack of current.

---
Tags: led
---


# Question
Title: Arduino uno simulation software for windows
Could anyone help me for a good free arduino uno simulation software for windows.Hope I get an answer.

# Answer
Autodesk offers a service called 123D Circuits which works in a web browser provided you have an Autodesk account. It allows you to construct (simple) virtual circuits and run code on a virtual Arduino Uno. Regrettably, it doesn't offer very much in the way of diagnostics tools, isn't open source, and won't work offline. The advantage of a service like this is that it requires no installation and is functional for simple setups with a few components. It can be found at 123d.circuits.io
> -1 votes

---
Tags: simulator
---


# Question
Title: Arduino Digital Input. Trigger HIGH by 12V to 36V
I want to build a small circuit that will switch a LED on (for arguments sakes) when the cars ignition gets switched on. But I want to make it versatile so I can work with between 12V - 36V (Cars, Trucks, etc). What would be the best to read the Ignition status via the arduino. Know I have thought of an idea by working with voltage divider. Basically taking the principal of reading voltage Instructable Example and working from there. Any thoughts?

# Answer
Even easier:

* input - series 220 ohm resistor, and a 78L05 voltage regulator (check for maximum voltage). This allows you handling like 4..30V and get a solid "1" on digitalRead. (4V input makes like 3V output which is still logic high).
> 1 votes

# Answer
you can use transistor bias circuit, opto-couples circuits, op amp circuit or a simple relay circuit, to get 5V output signal when 12V-36V signal is triggered.
> 0 votes

---
Tags: arduino-uno, digital
---


# Question
Title: How to use Arduino Pro Mini without Programmer
I'm a software engineer, but I'm not too skilled at understanding hardware design yet. I'm trying to learn how to use an Arduino Pro Mini board without the programmer connected, so I can actually make fun toys, etc. Currently, the software will only run when connected to the programmer (or at a minimum with the SCK pins connected to each other). I have been searching online for days, and I think I need a crystal or resonator hooked up somehow, but I can't figure out how to hook them up (which pins). I bought 5 16 MHz ceramic resonators, and I have them right here with me, but I can't find the answers online how to hook it up and have the board run stand alone. Any ideas? Thank you in advance.

# Answer
You might be on the wrong track.

You do need a crystal (or not, it depends on), and an Atmel programmer if you want to program an empty chip.

However, all Arduino boards come with a chip pre-programmed with a bootloader. Then it is rather easy: you need an FTDI cable to connect the board to a PC. Then run Arduino IDE on the PC. (The FTDI cable is actually an USB-to-serial converter.)

The Arduino IDE lets you edit a C like code, complile it to binary, and send it out via the FTDI cable to the serial port (Rx, Tx) of the board. The microcontroller on the board comes with a bootloader. Bootloader is a small program which runs at power up, and will receive the data from the computer and put your program to the microcontroller. Then your program will run on the microcontroller.

So, you don't need an external programmer.

---

On the other hand, you may consider picking a different Arduino board. Arduino Micro, or Pololu A-star Micro (for half of the price of the Arduino Micro) offers a board with a direct USB connection. All you need is one USB cable.

These boards come with a much better microcontroller (32u4) which has a hardware USB connection (allowing you to make a mouse or a keyboard, and control PC (such as buttonbass.com) from your gadget).
> 3 votes

---
Tags: arduino-pro-mini, wires, programmer
---


# Question
Title: How to control 6 stepper motors with Arduino?
I would like to control 6 stepper motors (0.225A, 2 V) with Arduino. I was thinking to use motor drivers from Pololu website, for example DRV8834.

Is it possible?

Any suggestion for another type of motor driver?

We need to limit the current, but I also got the advice to use the PWM signal to control the stepper motor. Any advice for this?

# Answer
Yes it is possible, of course everything is possible!

These drivers need two IO lines at very minimum: DIR and STEP. Pulsing STEP makes one step movement forward or backwards (depending on DIR).

For 6 steppers you need therefore 12 outputs from Arduino. (Which Arduino please? pick one which has enough IO, or otherwise use an I2C output extender).

M0 and M1 controls microstepping mode - configure at your wish. CFG is high on this Pololu board, allowing the board to use as a stepper driver out of the box.

Steppers (if you want to get them working at full torque) require a constant-current drive. (Inexpensive solutions use a constant voltage drive, such as using an ULN2803 - however those can not get too much torque). Happily this driver can do this well, the potentiometer sets the maximum current.

Steppers need considerable current when starting movement to a next step. However, unlike DC motors, even a still position will consume current, which eventually makes the motor hot. Therefore you are supposed to limit the current when the motor is *not* moving. This is usually done from software (the driver does not known when it is time for a long period at stop).

The way for limiting motor current at stop can be either an analog limiter, or a PWM. This driver has no dedicated input for this purpose. You can do two things:

* use smaller drive current (use the potentiometer) - this can work well if you're satisfied with the torque
* use the sleep mode of the driver with a PWM from the Arduino side.

This latter solution needs you to:

* connect all EN pins of all 6 drivers, and connect it to one Arduino pin which has PWM (i.e. `analogWrite()`)
* drive this to 0, then start movements
* once movements are finished, use `analogWrite()` and set to say, 128 (usually half of the move current is a good guess for holding current)

This way when the motors are stopped, the holding current will be less, hence the motors don't get hot.
> 1 votes

# Answer
You could create your own custom shield with an Arduino mega and 6 Stepper sticks

http://www.amazon.com/Hobbypower-StepStick-4-layer-DRV8825-Stepper/dp/B00NCSK6T2/ref=sr\_1\_1?ie=UTF8&qid=1455740571&sr=8-1&keywords=DRV8825

Here is a link to the stepper sticks I was talking about. To make this work you would need to be able to solder the breadboard together and set up the arduino to accept pins from the breadboard. You would also need a 12v power supply to give the motors power
> 0 votes

---
Tags: arduino-uno, motor, pwm
---


# Question
Title: Receiving serial data in acsii, how to split it.
Hello I want to know how to split an incoming serial message that comes in this format CxxxLxxx, x=number, so i can take the 3 numbers after the C and save them and then take the 3 numbers after the L and also save it, i have a code for this but it doesn't always work, can anyone tell me where I´m wrong or is the approach I´m taking is not the right one. Thanks.

```
int value = 0;
int channel;
int x;
String str;
int y;
String str1;
int le;

void loop()
{
if (Serial.read() == le)
{ }
  else
       {
        str = Serial.readStringUntil('C');
        str1 = Serial.readStringUntil('L');
        channel = Serial.parseInt();
        value = Serial.parseInt();
      DmxSimple.write(channel, value);
      le = Serial.read();
      Serial.println();

       }
}

```

# Answer
> 0 votes
This:

```
if (Serial.read() == le)
{ }

```

looks very suspicious - sometimes it can read the C or L and therefore render the rest of your code useless.

Also Serial.parseInt shall be avoided - it returns the first thing which looks like a number, and will not wait for all three numbers.

However, your problem is likely the DMX write speed. While the DmxSimple.write is getting executed, no new incoming message can be processed. Depending on your actual Arduino board and chip, there is some buffer, but the solution is not rocket-proof at all.

You can:

* make a solid protocol between the PC and the Arduino, i.e. the PC sends one command, arduino sends it out over the DMX, and Arduino answers an OK to the PC. The PC will not send out any new command unless it has received an OK first.
* avoid these ad-hoc mess, i.e. serial-reads and serial.printlns here-and there.

For example, if you change the protocol so: CxxxLxxxE (E stands for end) you can utilize readStringUntil to read the input until a separator, and then use the toInt method to actually convert the read data to integer:

```
void loop() {
    strDummy = Serial.readStringUntil('C');
    strC = Serial.readStringUntil('L'); // xxx from CxxxL
    strL = Serial.readStringUntil('E'); // xxx from LxxxE
    channel = strC.toInt();
    value = strL.toInt();
    DmxSimple.write(channel, value);
}

```

### After learning that it is not possible to change the protocol, here is a new plan

```
int channel;
int value;
void loop() {
    if (Serial.read()=='C') { // wait for a C
        channel=Serial.parseInt(); // parse till first non-number
        value=Serial.parseInt(); // parse till first non-number
        DmxSimple.write(channel, value);
    }
}

```

See https://www.arduino.cc/en/Tutorial/ReadASCIIString for a tutorial. Note that Arduino Serial commands are pretty confusing sometimes :) for example, parseInt will actually consume one non-number character implicitly after parsing a number.

Also note that this solution works well if the command is sent as one batch. If you are trying to send the command manually, e.g. from a terminal window, character by character, parseInt may time out. Consider increasing the timeout to 10 seconds or more by https://www.arduino.cc/en/Serial/SetTimeout

---
Tags: arduino-uno, serial, programming
---


# Question
Title: Arduino sketch taking forever to upload, followed by multiple issues
I am using Arduino Uno board with Windows 10. From the tutorials on Arduino website, I am trying to upload the following code:

```
void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
  int sensorValue = analogRead(A0);
  Serial.println(sensorValue);
  delay(1);
}

```

It had undergone a series of issues:

First, `avrdude: ser_open(): can't open device "\\.\com3"`

I searched for his issue, and found that most common solution id to go to device manager and change the name of the port, then unplug and plug again the arduino board. I did that

Second,

```
C:\Program Files (x86)\Arduino\hardware\tools\axr\bin\avr-ar:
unable to rename 'core.a'; reason: file exists\\

```

I thiught it could be a memory problem. I used the reset button on the board, and repeated steps from the solution to the first problem. I tried to upload the code again.

But now, I am not getting any error message. But the problem is that it is taking forever to upload the code. I see `Uploading...` status since a long while. The green progress bar is also complete, but no uploading completed till now.

Any help to understand and solve this will be appreciated.

# Answer
When the Arduino IDE says its uploading but never uploads, it is most likely a COM port issue. Try plugging the Arduino in a different port and make sure you change the port in the IDE. The problem seems to be you have changed the Arduino port, but not in the IDE. The Arduino IDE registers the previous port as open and tries to upload the program to that port. Go to `Tools > Serial Port` and it should list the ports(example):

```
COM 2
COM 3
Arduino Uno at COM 4
•COM 4

```

Every time you unplug and replug the Arduino you should check your ports and select the appropriate one ( It usually says `Arduino *type* at COM *port number*`

```
COM 2
COM 3
•Arduino Uno at COM 4
COM 5

```
> 1 votes

---
Tags: arduino-uno
---


# Question
Title: Convert uint8_t array to ascii character for serial transmission
I am trying to send packets of via bluetooth data that include 6 bytes read from a sensor and stored in a uint8\_t array. Instead of sending over the data as numerical digital, I would like to send the ASCII character of each of the bytes. I am doing this to reduce the size of my data packets and make it easier to interpret the incoming data.

```
uint8_t* temp = readBufferData(FIFO);

for (int i = 0; i < 6; i++)
{
    Serial.write(temp[i]);

}

```

Read buffer data returns a pointer to a uint8\_t array read from a FIFO buffer. When I use Serial.print, I get the following output, which makes sense. 22163226094255 One question is, when I use Serial.print on a single character, is it transmitted a single byte, or is it actually sending the decimal digital of the number, anywhere from 1-3 bytes?

When I use the Serial.write, however, I get something like the following DÿÂ?ÁÏ?ÌÆ?Ûµ?Ë½?ÔÀ?Ð¿?ÃÕÓÑËÐTÿÀ?Ï3ÿÉ?¹4ÿÐ?Ê\<ÿ½?µfÿ¼?ìNÿÐ?×Â?ÊÚ?×¿?Å Also, these data display much more slowly on the screen, than normal.

How can I send each uint8\_t value by sending over the corresponding ASCII character for serial transmission?

Thanks!

# Answer
> 2 votes
You don't "convert" anything. A character is just a human representation of an 8-bit value.

Instead you just need to change what the compiler thinks the data represents (from a human perspective). The simplest way of doing that is to either cast the uint8\_t values to be char values, or to write each one individually as a raw value.

The latter way:

```
myBluetoothSerial.write(myData[0]);
myBluetoothSerial.write(myData[1]);
myBluetoothSerial.write(myData[2]);
myBluetoothSerial.write(myData[3]);
myBluetoothSerial.write(myData[4]);
myBluetoothSerial.write(myData[5]);

```

Or, with a loop:

```
for (int i = 0; i < 6; i++) {
    myBluetoothSerial.write(myData[i]);
}

```

or using a built-in variant of write that does the loop for you:

```
myBluetoothSerial.write(myData, 6);

```

# Answer
> -1 votes
Try changing Baud Rate. Most of the time garbage like this happens because of difference in baud rates of transmitter serial device and receiver serial device.

---
Tags: bluetooth, code-optimization, data-type
---


title: Arduino motor rotation

text:
# Question
Title: Arduino motor rotation
I am a beginner in Arduino. Below is my code to propel the fans of my motor. This happens in a clockwise direction but I wish to change the direction of rotation.

How can I modify it?

```
// Declare the pin for the motor
int motorPin = 9;

void setup() {
  // Define pin #9 as output
  pinMode(motorPin, OUTPUT);
}

void loop() {
  // Turn motor on
  digitalWrite(motorPin, HIGH);
  // Wait 250 ms
  delay(250);
  // Reanimate motor
  digitalWrite(motorPin, HIGH);
  // Wait 250 ms
  delay(250);
  // Turn motor off.
}

```

# Answer
I guess you have a DC motor in use. Likely a FET drives it on port 9.

This arrangement is enough to start or stop the motor, however to change direction, you need to swap the two wires on the motor.

I guess you may perfer to do this in software - and for that you need to replace the simple FET driver with a H-Bridge. H-Bridge is an arrangement of electric switches which allows you swapping motor polarity, and it usually comes pre-assembled to a chip.

There are a vast amount of h-bridge motor driver chips to choose from. Google for "pololu motor driver", or "adafruit motor driver".

You can find all the further details in the Arduino examples on the web, e.g.:

https://learn.adafruit.com/adafruit-arduino-lesson-15-dc-motor-reversing/overview
> 1 votes

---
Tags: arduino-uno
---


# Question
Title: Arduino Nano ESP8266 software serial problems
I have a problem with my Arduino Nano ATmega328 and my ESP8266 01 module. I have connected the ESP8266 on my Arduino board without FTDI.

I have made the following connection:

I an using a 5V Arduino Nano which of course is 5V. The ESP8266 is a 3.3V device and so I am using a voltage divider to bring the Arduino's 5V down to 3.3V. If you are using a 3.3V Arduino then you do not need the voltage divider.

* The wiring is very similar to the FTDI.
* Arduino pin 3 to voltage divider and then to ESP8266 RX
* Arduino pin 2 to ESP8266 TX
* Arduino GND to ESP8266 GND
* Pull CH\_PD HIGH with a 10K resistor to +3.3V
* +3.3V to Vcc

You only need the voltage divider on the Arduino TX pin. The 5V Arduino will read 3.3V as HIGH so you can connect the ESP8266 TX pin directly to the Arduino RX pin.

The problem I had and I can't handle is that when I start up the Arduino Tx and Rx LEDs work continuously so I can't have access to my serial monitor of the Arduino IDE. So with that problem I can't send or receive any command to/from the IDE. Also when I try to upload my program to the Arduino board, I have to disconnect the ESP. If I don't I can't upload it.

Any ideas guys? I would be grateful

I also try to implement code with `AltSoftSerial` but I have library issues - my laptop does not recognize it (I downloaded it and I put it in the same folder with my code).

```
  #include <SoftwareSerial.h>

    SoftwareSerial ESPserial(2, 3); // RX | TX
    void setup()
    {    Serial.begin(9600);     // communication with the host         computer

     // Start the software serial for communication with the ESP8266
     ESPserial.begin(9600);

     Serial.println("");
     Serial.println("Remember to to set Both NL & CR in the serial monitor.");
     Serial.println("Ready");
     Serial.println("");}

     void loop()
      {
      // listen for communication from the ESP8266 and then write it to the serial monitor
       if ( ESPserial.available() )   {  Serial.write( ESPserial.read();}  / / listen for user input and send it to the ESP8266
      if ( Serial.available() )       {  ESPserial.write( Serial.read()  );  }}

```

# Answer
Arduino Nano has its tx-rx serial port shared with the FTDI chip used by downloading and serial console. See https://www.arduino.cc/en/uploads/Main/ArduinoNano30Schematic.pdf This means that if you drive these pins from ESP, it will flash leds, and all communication on these pins will interfere with serial monitor and board programming as well.

You may:

* disconnect ESP during program downloading
* pick a different board, which has a separate hardware serial port, such as Arduino Micro, Leonardo, or any Pololu A-star 32u4 boards, this way you have a dedicated serial port to control your ESP
* wire the tx-rx of ESP to two *other* pins of your Arduino micro, and use a software serial library to bit-bang serial communication. (Note that serial receiving in software mode may require clever programming - since while your code does something *else* it can not receive *anything*).
> 1 votes

---
Tags: arduino-nano, esp8266, softwareserial
---


title: using enums in functions

text:
# Question
Title: using enums in functions
Given the following enums

```
enum RelayState { RELAY_OFF = HIGH, RELAY_ON = LOW };
enum class CrossingZoneState: uint8_t {
    CROSSINGZONE_CLEAR = 0, // no train in crossing area, also initialized state
    CROSSINGZONE_OCCUPIED = 1, // train detected by the entry sensor
    CROSSINGZONE_EXITING = 2  // train detected by the exit sensor, when sensor clears, state= Clear
};

```

Where RELAY\_OFF = HIGH, HIGH is #define HIGH 0x1 which I assume is a C++/Arduino constant? because I didn't define it. And RELAY\_ON = LOW, LOW is 0x0

in the following function I get the error that follows.

```
CrossingZoneState CheckEntrySensor(uint8_t esp) {
    //esp, short for entry sensor pin
    if (digitalRead(esp) == HIGH)
    {
        state = CrossingZoneState::CROSSINGZONE_CLEAR;
        return state;
    }
    else if (digitalRead(esp) == LOW)
    {
        state = CrossingZoneState::CROSSINGZONE_OCCUPIED;
        return state;
    }
    // if the digital read errs, return the current state so it re-runs
    return state;
};

boolean throwRelayAndCheckStatus(uint8_t relayNumber, RelayState relayState)    {

    int testInt = 0;
    if (relayState == RelayState::RELAY_OFF)
    {
        testInt = 1;
    }
    digitalWrite(relayNumber, relayState);
    if (digitalRead(relayNumber) == testInt) {
        return true;
    };
    return false;
};

```

I tried having RelayState be an enum class as well but was getting similar type errors. Here is the error from VS2015 with the code shown above.

> Compiling debug version of 'ModelRRXingStateMachine' for 'Arduino/Genuino Uno' ModelRRXingStateMachine.ino:11:55: error: 'RelayState' has not been declared :boolean throwRelayAndCheckStatus(uint8\_t relayNumber, RelayState relayState) ModelRRXingStateMachine.ino:2:1: error: 'CrossingZoneState' does not name a type :CrossingZoneState CheckEntrySensor(byte esp) Error compiling project sources

I'm not a professional programmer and am new to C++, usually writing in C# or VB.Net so I'm not sure what the compiler is looking for here, both enums are declared and one is declared with a type. Also, the VS code editor is showing no errors, the errors shown above show up in the error window when I try to build.

# Answer
> 2 votes
The solution was to move the enum declarations to a header file, due to the fact this was a VM add-in issue which will be resolved once they've implemented arduino version 1.6.8.

Adding this code to a header file and removing it from the main file resolved the issues and the code builds and runs.

```
// ModelRRCrossing.h

#ifndef _MODELRRCROSSING_h
#define _MODELRRCROSSING_h

#if defined(ARDUINO) && ARDUINO >= 100
    #include "arduino.h"
#else
    #include "WProgram.h"
#endif
#pragma once
// Arduino Digital I/O pin numbers for MEGA
//note: digital pins 30-45
//MEGA is a MUST for this project
enum {
    Relay1 = 30, Relay2 = 31, Relay3 = 32, Relay4 = 33, Relay5 = 34, Relay6 = 35,
    Relay7 = 36, Relay8 = 37, Relay9 = 38, Relay10 = 39, Relay11 = 40,
    Relay12 = 41, Relay13 = 42, Relay14 = 43, Relay15 = 44, Relay16 = 45
};

enum RelayState { RELAY_OFF = HIGH, RELAY_ON = LOW };
enum class CrossingZoneState : uint8_t {
    CROSSINGZONE_CLEAR = 0, // no train in crossing area, also initialized state
    CROSSINGZONE_OCCUPIED = 1, // train detected by the entry sensor
    CROSSINGZONE_EXITING = 2  // train detected by the exit sensor, when sensor clears, state= Clear
};

#endif

```

# Answer
> 0 votes
For one thing, you are using the variable state without defining it. Moreover, you have not declared the functions CheckEntrySensor() and throwRelayAndCheckStatus() . When you define a function without first declaring it, the arduino preprocessor builds its own declarations, but often does so in a defective way. This is one of the idiosyncracies of the arduino environment versus a plain C++ compiler.

The following compiles:

```
enum RelayState { RELAY_OFF = HIGH, RELAY_ON = LOW };
typedef enum RelayState RelayState_t ;

enum CrossingZoneState {
    CROSSINGZONE_CLEAR = 0, // no train in crossing area, also initialized state
    CROSSINGZONE_OCCUPIED = 1, // train detected by the entry sensor
    CROSSINGZONE_EXITING = 2  // train detected by the exit sensor, when sensor clears, state= Clear
};
typedef enum CrossingZoneState CrossingZoneState_t ;

CrossingZoneState_t CheckEntrySensor(uint8_t esp) ;
boolean throwRelayAndCheckStatus(uint8_t relayNumber, RelayState_t relayState) ;

CrossingZoneState_t CheckEntrySensor(uint8_t esp)
{
  CrossingZoneState_t state ;
    //esp, short for entry sensor pin
    if (digitalRead(esp) == HIGH)
    {
        state = /*CrossingZoneState_t::*/CROSSINGZONE_CLEAR;
        return state;
    }
    else if (digitalRead(esp) == LOW)
    {
        state = /*CrossingZoneState::*/CROSSINGZONE_OCCUPIED;
        return state;
    }
    // if the digital read errs, return the current state so it re-runs
    return state;
}

boolean throwRelayAndCheckStatus(uint8_t relayNumber, RelayState_t relayState)    {

    int testInt = 0;
    if (relayState == /*RelayState::*/RELAY_OFF)
    {
        testInt = 1;
    }
    digitalWrite(relayNumber, relayState);
    if (digitalRead(relayNumber) == testInt) {
        return true;
    };
    return false;
}

```

Or, if you want to avoid the use of typedef, you can use the following:

```
enum RelayState { RELAY_OFF = HIGH, RELAY_ON = LOW };
enum CrossingZoneState: uint8_t {
    CROSSINGZONE_CLEAR = 0, // no train in crossing area, also initialized state
    CROSSINGZONE_OCCUPIED = 1, // train detected by the entry sensor
    CROSSINGZONE_EXITING = 2  // train detected by the exit sensor, when sensor clears, state= Clear
};

enum CrossingZoneState CheckEntrySensor(uint8_t esp) ;
boolean throwRelayAndCheckStatus(uint8_t relayNumber, enum RelayState relayState) ;

enum CrossingZoneState CheckEntrySensor(uint8_t esp) {
    enum CrossingZoneState state ;
    //esp, short for entry sensor pin
    if (digitalRead(esp) == HIGH)
    {
        state = CROSSINGZONE_CLEAR;
        return state;
    }
    else if (digitalRead(esp) == LOW)
    {
        state = CROSSINGZONE_OCCUPIED;
        return state;
    }
    // if the digital read errs, return the current state so it re-runs
    return state;
}

boolean throwRelayAndCheckStatus(uint8_t relayNumber, enum RelayState relayState)    {

    int testInt = 0;
    if (relayState == RELAY_OFF)
    {
        testInt = 1;
    }
    digitalWrite(relayNumber, relayState);
    if (digitalRead(relayNumber) == testInt) {
        return true;
    };
    return false;
}

```

---
Tags: programming, arduino-mega, class
---


title: Using IR Sensor to sense movement?

text:
# Question
Title: Using IR Sensor to sense movement?
I was wondering if I could use a IR sensor with my Arduino to detect if someone is present in front of it.

Like, the emitter should emit continuously and if the receiver drop connection it should do something.

Will this work fine? or the emitter wide angle and a human body in front of it wont drop the signal?

# Answer
This will work fine. The easiest way to do this is using **IR Sensor Module**.

This will give you a digital output of whether there is someone in front of sensor or not. Use can use it as an Edge Trigger to detect Humans passing by.

You can buy one. They are both cheap and easily available.

Or you can create your own.
> 1 votes

# Answer
This works quite fine ! The "hardest" part is isolating the IR beam and especially the receiver with anti-reflective paint or paper (ie : a small hole in a cardboard)

You can make this by two (at least) ways :

* \[IRled\] \[human\] \[IRreceiver\]
* \[IRled and receiver pointing the same way\] \[human\] \[mirror\]

The second way is what you find in auto-flushing toilet rooms. But if the human is wearing quite reflective clothes, this will fool the receiver. This is great for long-range detection, but if you need a smaller range, go for the 1/.
> 0 votes

---
Tags: arduino-uno, ir
---


# Question
Title: exchanging data between two hc05 bluetooth modules
Iam working with gyroscope and Iam trying to send its values from one bluetooth(HC-05) module to another bluetooth module but the data exchange is not happening and I have used 2 arduino boards to do it.

Is there a simple way to do it?

# Answer
I think there is no simple answer for that. First you have to pair 2 HC-05 modules. To do so, you have to configure one HC-05 as slave, and other HC-05 as master.

**Steps for SLAVE:**

1. Be sure to select correct Baudrate in your Terminal Emulator (Arduino IDE or Terraterm etc.) for your module. There is no default baudrate... Different manufacturers set the baudrate on their HC-05's differently... 9600 and 38400 are good starting points.
2. Enter AT mode, by providing high level(3.3V or 5V) signal on KEY pin(PIO11)
3. Note the values of `AT+PSWD?`, `AT+NAME?` and `AT+ADDR?`(let's say 1111:22:123456) commands. You might set the password to 1234 for easy remembering. Issue `AT+PSWD=0000`...
4. Be sure to set the module to slave mode by issuing `AT+ROLE=0` command.

**Steps for MASTER:**

1. Be sure to select correct Baudrate in your Terminal Emulator (Arduino IDE or Terraterm etc.) for your module. There is no default baudrate... Different manufacturers set the baudrate on their HC-05's differently... 9600 and 38400 are good starting points.
2. Enter AT mode, by providing high level(3.3V or 5V) signal on KEY pin(PIO11)
3. Reset the module to its original state by issuing `AT+ORGL` command.
4. Remove the previous parings(if any) by issuing `AT+RMAAD` command.
5. Set same password as slave by issuing `AT+PASSWD=0000` command.
6. Change the role to master; `AT+ROLE=1`
7. Set connecting mode to any address it sees; `AT+CMODE=1`
8. Initialize the SPP profile lib ; `AT+INIT`
9. Be sure that you see the slave HC-05 module, `AT+INQ` command will list the modules you see.
10. Be sure that you see address of the slave module(1111:22:123456).
11. Last of all enter `AT+LINK=1111,22,123456`(note the commas).

With these steps you should exchange data...
> 1 votes

---
Tags: arduino-uno, bluetooth, gyroscope, hc-05
---


title: The most practical plug socket

text:
# Question
Title: The most practical plug socket
I am starting some Arduino's projects with different sizes (very small based on Arduino Nano and bigger using Arduino Mega). These projects will be manipulated by students and they will connect and disconnect many times the wires. I will try to not use breadboard if I can. In order to develop very versatile projects, the idea will be to use very useful plug sockets. Currently I have no idea of which kinds of plug sockets I can use.

Do you have any idea about the existing plug sockets (from 2 to 6/8 wires) and which one it is preferable to use?

**Complements:**

* Some shields and components I already have and want to use have sometimes some plugs sockets (similar to this) but sometimes only some classical pins
* I want also to build my own shields by integrating plug sockets to the arduino or to another shield
* Some parts will be also composed by small electrical circuit on which I want to integrate plug sockets aswell
* I will also use LiPo batteries (for example this one which have a connector I can't buy currently because I don't know the reference)
* Communications will be also achieved using SPI and I2C

# Answer
Ok, so more info from the OP:

* non-electrical engineering students needs a prototyping platform
* minimize possible damages, support hot plug-and-play
* not too expensive

## Dedicated connector

I suggest using standard subD9 connectors. Sensors shall have male pins, while the control board female socket (this makes very hard to do accidental short circuits on the control board). We were using these connectors in a daily basis in a lasershow system, and I was very statisfied. Inexpensive, easy to solder, works with a wide range of cables or separate wires.

In many cases, you can integrate the sensor into the housing of the connector. For example, an IR receiver, an accelerometer, etc. fits well.

You can use off-the-shelf serial cable extenders which makes it very versatile.

Since it is a D shaped connector, there is only one possible way to connect a sensor to the mainboard, and we're golden.

## Dedicated connector light

NSL25 and NSG25 are my favorites: http://www.soselectronic.hu/?str=371&artnum=4927&name=nsl-25-2-g
http://www.soselectronic.hu/?str=371&artnum=4934&name=-nsg-25-2

Although these are inexpensive wire to board connectors, it is very hard to misconnect them. Criping is a PITA, but you can purchase pre-crimped connectors with wires such as http://www.soselectronic.hu/?str=371&artnum=6175&name=-p-35003 One 3 wire female connector with wires costs about 50 USD cent.

Note though that in this case, the control board has the male connectors. By accidentally dropping a coin to the connector, or using a screwdriver, it is easy to run into short circuits. This leads us to the next plan...

## Any inexpensive connector with proper electric protection

Probably the most inexpensive solution is to use standard headers and pins. Here you may also wish to buy ready made cables, than start crimping yourself: http://www.soselectronic.hu/?str=371&artnum=6171&name=-p-2543

This however opens up a can of worms of misconnection:

* connection by one or multiple pin off
* connection in reverse direction
* shorting the pins on the board

Against sorting, you shall have a multifuse on the power pins, say, 250mA. On each IO pin, you shall have a series resistor of 470 ohm, this ensures that no miswiring can destroy the Arduino.

On the sensor-side, things are a little more tricky. You need a shottky (or an equivalent P fet diode) to ensure that reverse polarity connection will not destroy your sensor. If the sensor has output pins, also use a series 470 ohm resistor.

Considering all the hassle, using a standard subD9 connector is a way easier:

* it has enough dedicated pins for I2C, SPI, and a generic IO for dumb sensors
* the pins can handle more current, and there are more pins you can connect in parallel to have enough power for small motors
* it is impossible to misconnect (once all sensor sockets use identical wiring)

## Don't forget ESD protection

In any case, it is a good idea to have some sort of ESD protection whenever you have connectors, and wires, and rough external world.

Have at least a TVS diode on the power pins (say, an 5.8V or 6V unidir TVS will do). On IO pins you can use a simple series resistor, or you can opt for a TVS.

During hot plug and play, it may happen that sensitive sensors get powered in a strange way. E.g. first 5V then the sensor output is getting connected, but no GND for a short moment. Some sensor may get damaged in this case. Use diodes to fix this.

For sensors requiring sudden current peaks (e.g. WIFI, or a motor), add at least 470uF/16V electrolyte capacitor right to the sensor end of the connector. This way once the sensor is connected to a long extension wire, you still have acceptable power to use in sudden current peaks.

Some sensors (e.g. IR receivers) are sensitive to power glitches. Consult their datasheet, use the suggested RC filtering network on the power pins.
> 1 votes

---
Tags: wires
---


# Question
Title: Driver shield providing 24+ pins at 100mA (for Mega 2560)
Do any shields (or similar boards) exist to let the Mega 2560 (or Due) output a full 100mA per pin on at least 24 pins, in a digital on/off fashion? I know there is a motor shield, but it looks to have only a handful of outputs. It seems very common that people need to output higher current than the MCU can provide safely (if at all), but there do not appear to be any shields for this. Of course individual transistors are fine for a few outputs, and some chips can do up to 8, but what about the rest of us who want to use all those nice pins on the Mega, Due, or similar but who need more power?

# Answer
> 1 votes
You can:

* use a driver chip, e.g. ULN2803 which gives you 8 outputs of up to somewhat 500mA from 8 digital pins
* use a serially addressible power+logic chip, such as TPIC6A595NE which gives you 8 outputs, each can drive 350mA, and has a built-in *short circuit protection*. You can cascade these, 3 chips give 24 outputs, and need only three pins to drive all 24 (or more if you use more chips) outputs.
* There are 24 output devices, however not in this current range. 24 output devices are usually i2c or spi based led controllers - some of them gives you goodies like rock solid hardware PWM on all 24 ports - but none of them gives you 100mA output.

# Answer
> 0 votes
You'll likely have to use an https://www.arduino.cc/en/Main/ArduinoProtoShield with 3+ of those chips you like that do up to 8.

---
Tags: arduino-mega, shields, current, stepper
---


# Question
Title: Wi-Fi from Arduino to computer serial COM
I am somewhat new to the Arduino world and so far having fun. I am making a gardening watering system for my first project. I am at the final stages of completion and want to add a Wi-Fi module on the Arduino to send to my computer and display via serial COM the soil moisture and other relevant measurements I have going.

Now my question is, is it possible the simple analog information from my Arduino to my computer's serial COM with the Wi-Fi module ?

# Answer
I would recommend using Bluetooth, as Bluetooth communication is mostly done by using **COM** Ports.

You can use **HC05**/**HC06** **Bluetooth** Modules with Arduino. You can easily pair your PC with these Bluetooth Modules.

Now, you write an application in any programming language to get & send data to your Arduino via Bluetooth COM ports.
> 1 votes

# Answer
you can use ESP8266 with ESP-LINK firmware.

There is nothing to it.Check out github.com/jeelabs/esp-link for documentation, examples and such.

Connect ESP8266 to Arduino URXD: connect to TX of microcontroller UTXD: connect to RX of microcontroller GPIO0: connect to RESET of microcontroller GPIO2:

optionally connect green LED to 3.3V (indicates wifi status) And that about it. Everything else is done over WiFi
> 0 votes

---
Tags: wifi, analogwrite
---


# Question
Title: Can't retrieve data from X-NUCLEO-IKS01A1 using I2C protocol
So I bought this nucleo expansion board, the X-NUCLEO-IKS01A1, and on the package it says it is compatible with Arduino Uno.

My goal here is to read data from any sensor on this board. (When I can read one, I can probably read the others too using the same structure)

Here's my code.

```
#include <Wire.h>

#define ADDRESS 0x1E
#define REGISTER 0x16

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

void loop() {
  // put your main code here, to run repeatedly
  Serial.println(I2CreadByte(ADDRESS, REGISTER));
  delay(5000);
}

uint8_t I2CreadByte(uint8_t address, uint8_t subAddress)
{
  uint8_t data; // `data` will store the register data

  Wire.beginTransmission(address);
  Wire.write(subAddress);
  Wire.endTransmission(true);
  Wire.requestFrom(address, (uint8_t) 1);

  data = Wire.read();
  return data;
}

```

This should return the temperature in 2's complement. But all it returns is a 1 (I can guarantee you it's not that cold in my room).

I have the board plugged on my Arduino.

Can anyone tell me what I'm doing wrong?

Here's the datasheet for the sensor I'm trying to communicate with.

Datasheet

The sub addresses are on page 33 and the I2C explantation on 27. It's called the LSM6DS0.

Thanks sooo much in advance.

# Answer
> 1 votes
You're using a wrong slave address. From the datasheet:

> The Slave ADdress (SAD) associated to the LSM6DS0 is 110101xb. The SDO/SA0 pin can be used to modify the less significant bit of the device address. If the SDO/SA0 pin is connected to a voltage supply, LSb is ‘1’ (address 1101011b), else if the SDO/SA0 pin is connected to ground, the LSb value is ‘0’ (address 1101010b). This solution permits to connect and address two different inertial modules to the same I2C bus.

This means your sketch should contain:

```
#define ADDRESS 0x6A  // if SDO pin is pulled down

```

or:

```
#define ADDRESS 0x6B  // if SDO pin is pulled up

```

It's also a good idea to check if there's actually anything in the Wire buffer (with `Wire.available()`) before you attempt reading.

Finally, I suggest you read both `OUT_TEMP_H` and `OUT_TEMP_L` registers, in order to calculate the temperature correctly. The datasheet says the temperature output is zero at 25 degrees Celsius and that the sensitivity is 16 LSB/C. This means you have to read both registers, combine their results to get a 16-bit signed integer (`OUT_TEMP_H` is the MSB), divide it by 16 to get the temperature offset, and add the result to 25 degrees Celsius to get absolute temperature.

---
Tags: arduino-uno, sensors, i2c
---


# Question
Title: ESP8266 sending GET Request and getting 408 Timeout error
I am using esp8266 to send a **GET** Request but I am getting 408 Timeout error.

Here is a screenshot of my output.

# Answer
I assume you're doing all this from the serial monitor. You can't use escape sequences like `\r` in the serial monitor entry box. Everything you enter is evaluated as a string of separate ASCII characters; `\r` is just a backslash character followed by lowercase r. To send a HTTP request, you make the serial monitor send the `\r\n` for you.

* First set the serial monitor to `BOTH NL & CR` permanently; it will serve you well for commands and HTTP requests as it appends `\r\n` to everything you send.
* Count the number of bytes in the your HTTP request, including the carriage return and newline characters. I count 61 characters in your request.
* Use this count in `AT+CIPSEND`
* Type the first line of your request, and stop right before the first `\r\n`, and click Send. Because of your setting, the monitor will now send what you typed *with* `\r\n` suffixed to it.
* Type and send each line of the request, just like you sent the first line, until you've sent the last line.
* Since there is an additional `\r\n` after the last line, you click Send again, without typing anything. And since the module requires `\r` to indicate the end of the data packet, you click Send one last time.

Hopefully, this should give you the right results.
> 0 votes

---
Tags: arduino-uno, arduino-ide, esp8266
---


# Question
Title: Oddness with #define and #ifdef in a sketch
I'm putting together a simple sketch to read a few sensors and have come across some odd behaviour associated with `#define` and `#ifdef`.

Here are some snippets from my code:

```
// Defines
//#define DEBUG 1
#define ACCELEROMETER 1
#define GYROSCOPE 1
#define GPSSYSTEM 1
#ifdef GPSSYSTEM
  unsigned int Mth=0;
  unsigned int Day=0;
  char TMZ[2];
#endif

```

With this snippet the rest of the sketch compiles, but with this:

```
// Defines
//#define DEBUG 1
#define ACCELEROMETER 1
#define GYROSCOPE 1
//#define GPSSYSTEM 1
#ifdef GPSSYSTEM
  unsigned int Mth=0;
  unsigned int Day=0;
  char TMZ[2];
#endif

```

The compile fails, claiming that the error is in some functions further down.

BTW, `Mth`, `Day` and `TMZ` are not used anywhere yet, not are they defined anywhere else. What is even more odd is that the error messages are announcing the erroneous line numbers to be about 12 lines removed from where they really exist in the sketch, and have no association with the declarations here. Now, this gives a clean compile:

```
// Defines
//#define DEBUG 1
#define ACCELEROMETER 1
#define GYROSCOPE 1
#define GPSSYSTEM 1
//#ifdef GPSSYSTEM
  unsigned int Mth=0;
  unsigned int Day=0;
  char TMZ[2];
//#endif

```

as does this:

```
// Defines
//#define DEBUG 1
#define ACCELEROMETER 1
#define GYROSCOPE 1
//#define GPSSYSTEM 1
//#ifdef GPSSYSTEM
  unsigned int Mth=0;
  unsigned int Day=0;
  char TMZ[2];
//#endif

```

I've been chasing this weirdness for a day now and am getting nowhere.

# Answer
> The **#ifdef** Directive you are using is one of Conditional Directive. This directive checks whether the identifier is currently defined.

In general, it has following syntax:

```
#ifdef identifier newline

```

For Arduino, you can modify your **#ifdef**s to following code:

```
#if defined(GPSSYSTEM)
    //Code here
#endif

```

> Explaining your code snippets behaviors:

In your first code snippets, **GPSSYSTEM** has been defined by following line of code:

```
#define GPSSYSTEM 1

```

Now, For this code snippets, **#ifdef GPSSYSTEM** is **true**, and following variables are defined.

But, when you comment this **#define GPSSYSTEM 1** line in your 2nd code snippets, **GPSSYSTEM** is no more defined and so **#ifdef GPSSYSTEM** is **false**, and thus following variables are not defined which result in compilation errors in your code.

Following same logic, behavior of your 3rd and 4th code snippets can be explained easily.
> 2 votes

---
Tags: programming, c++, arduino-ide
---


title: Am I multiplexing my LEDs correctly?

text:
# Question
Title: Am I multiplexing my LEDs correctly?
I am new to electronics. I have a good amount of programming under my belt however.

I want to know if I am multiplexing correctly or not. My intended output is how I want it, but I am not sure if I implemented it how it's supposed to be, i.e. am I potentially damaging my equipment.

I have 6 RGB LEDs hooked up to my arduino, let's called them L1 - L6.

I have each R, G, and B pin on L1 - L3 connected in parallel, and the same for L4 - L6. Then I have ground on L1 and L4 connected in parallel, and the same for L2 to L5, and L3 to L6.

So this gives me 6 pins to supply voltage to, to which I put a 220 ohm resistor in each one. Then it gives me 3 different spots for ground.

My question is about the ground. How should I control the different 'pins' for ground.

This is what I have right now, and it works, but I don't know if this is dangerous to my equipment for some reason.

I have the 3 ground pins connected to the Arduino in 3 different pins, 7, 4, and 2.

In `Setup()` I configure these 3 pins as outputs, and I later found out in order to keep them all 'off' I need to set them all to high.

So then in order to turn L1 on to red, I need to turn its red pin to high, but turn its ground pin to low, then L1 turns on.

Using this same technique, I am able to get every LED to every desired color. So I mean it works. But why is this? Is this how I should be doing it? I understand LEDs polarity matters, but why would supplying its cathode with voltage make it turn off? That's the part I'm worried about, am I destroying my LEDs by doing this?

Any and all help much appreciated!

Here is how I have it all wired up for clarity.

# Answer
> 1 votes
> So I mean it works. But why is this?

It works because the LED inside the RGB LED, all three of the LEDs inside have the characteristic of a diode, this means it will allow current flow in one direction, but will stop, or restrict it in the opposite direction. *Also are you asking why it works because of your specific wiring?*

> Is this how I should be doing it?

Yes, how you are doing it is fine. Although I would suggest you use NPN transistors to drive your cathodes of the LEDs.

* This will at least remove any worry of applying 5v to the cathode.
* It will also reduce the amount of current your I/O pins have to handle.
* You should also move the resistors from the cathodes to the anodes as this is more reliable and pretty much the norm.

> I understand LEDs polarity matters, but why would supplying its cathode with voltage make it turn off?

This works because of the theory of the p-n junction, (inside construction of a diode), this means that because of the construction of the diode it requires the voltage on the Cathode to be at a lower potential. So that means when you set the output `HIGH` the 5v on the anode and the 5v on the cathode "stop" current flow because it stops the breakdown within the p-n junction.

> That's the part I'm worried about, am I destroying my LEDs by doing this?

No you are not, the LED acts as a diode and when the potentials are the same, current doesn't really flow and thus doesn't do anything to the LED.

# Answer
> 1 votes
LEDs are not powered by a particular voltage level, but by the **voltage difference** between anode and cathode. That's why you need to drive cathode pins (7, 4, and 2) LOW to switch the LEDs ON and HIGH to switch them off. A truth table could help:

```
╔═══════╦═════════╦══════════════════════════╦═══════════╗
║ anode ║ cathode ║ voltage anode to cathode ║ led state ║
╠═══════╬═════════╬══════════════════════════╬═══════════╣
║ LOW   ║ LOW     ║ 0V                       ║ OFF       ║
╠═══════╬═════════╬══════════════════════════╬═══════════╣
║ LOW   ║ HIGH    ║ - 3.3V                   ║ OFF       ║
╠═══════╬═════════╬══════════════════════════╬═══════════╣
║ HIGH  ║ LOW     ║ + 3.3V                   ║ ON        ║
╠═══════╬═════════╬══════════════════════════╬═══════════╣
║ HIGH  ║ HIGH    ║ 0V                       ║ OFF       ║
╚═══════╩═════════╩══════════════════════════╩═══════════╝

```

Your schematic looks safe to me, but be aware that if you decide to illuminate L1, L2 and L3 to the same color simultaneously (e.g drive red line HIGH and pins 7, 4, and 2 LOW), your LEDs will not have uniform brightness. Only one of the cathode pins should be LOW at a time, otherwise you will end up in the situation described here.

---
Tags: led
---


# Question
Title: Send a file from PC to Arduino using HC-06 module
I want to send a file from my Laptop using its own Bluetooth transmitter to Arduino. Arduino has HC-06 module as receiver.Arduino has SD Card fore store the file. I was able to send bytes using Python application. How to send a file using a Python application to Arduino?

# Answer
> 1 votes
* Open the file in `rb` mode in your Python code.
* Since the Arduino SoftSerial RX buffer is 64 bytes in size, sending 60 bytes per packet to the Arduino is okay. You basically call `out = file.read(60)` in python to read 60 bytes from the file and then write these bytes to the Arduino with `ser.write(out)`. You can have the python program wait for acknowledgement from the Arduino, perhaps indicating how many bytes it actually received (after a given timeout period) or what byte was last received. This is just very minor error detection.
* The Arduino saves the 60-byte packet to an array and writes everything at once to a file on the SD card, that you've already opened.
* After receiving acknowledgement from the Arduino, the Python program reads the next 60 bytes and forwards to the Arduino like before. Continue till the file is exhausted. You could send some sort of signature byte to inform the Arduino that no more bytes are coming and to close the file. Alternatively, a timeout period can be used.

Note: It'll be more efficient if you wrote to the SD card in chunks, where the chunk size is a factor of the card's sector size. 64 bytes is the highest you can do with the default RX buffer size, but thats living dangerously as you risk buffer overflow if anything goes bump. This can be avoided though, by reading bytes from the RX buffer and into your own array, as soon as they arrive.

Chunks of 32 bytes is safer but it will naturally take longer to send the whole file. Test and judge for yourself.

---
Tags: arduino-uno, python, hc-06
---