title: Printing Time to Serial Port

text:
# Question
Title: Printing Time to Serial Port
I am reading sensory data that comes from the digital inputs(two DHT11 Humidity sensors using adafruit library.) and I would like to add a hh:mm:ss real time counts next to them. I try to use the time.h library but could not understand how to worked it in that way.

My code is;

```
#include "DHT.h"

#define DHT1PIN 4
#define DHT2PIN 7

#define DHT1TYPE DHT11
#define DHT2TYPE DHT11

DHT dht1(DHT1PIN, DHT1TYPE);
DHT dht2(DHT2PIN, DHT2TYPE);

void setup() {
  Serial.begin(9600);
  Serial.println("Humidity sensors DHT11 tests!");

  dht1.begin();
  dht2.begin();
}

void loop() {

  delay(2000);

  float h1 = dht1.readHumidity();
  float t1 = dht1.readTemperature();
  float h2 = dht2.readHumidity();
  float t2 = dht2.readTemperature();

  if (isnan(t1) || isnan(h1)) {
    Serial.println("Failed to read from DHT #1");
  } else {
    Serial.print(h1); Serial.print(" \t");
  }

  if (isnan(t2) || isnan(h2)) {
    Serial.println("Failed to read from DHT #2");
  } else {
    Serial.print(h2);
    Serial.print(" \t");
  }
  Serial.println();
}

```

and my serial port out is;

and I want it to be like that;

Any help will appreciated.

# Answer
> 0 votes
I solved the problem by using millis() function. And now I ca get results like these;

My code is;

```
#include <Sensirion.h>
#include "DHT.h"
unsigned long time;

#define DHT1PIN 4
#define DHT2PIN 7

#define DHT1TYPE DHT11
#define DHT2TYPE DHT11

DHT dht1(DHT1PIN, DHT1TYPE);
DHT dht2(DHT2PIN, DHT2TYPE);

const uint8_t dataPin =  9;              // SHT serial data
const uint8_t sclkPin =  8;              // SHT serial clock
const uint8_t ledPin  = 13;              // Arduino built-in LED
const uint32_t TRHSTEP   = 1000UL;       // Sensor query period
const uint32_t BLINKSTEP =  250UL;       // LED blink period

Sensirion sht = Sensirion(dataPin, sclkPin);

uint16_t rawData;
float temperature;
float humidity;
float dewpoint;

byte ledState = 0;
byte measActive = false;
byte measType = TEMP;

unsigned long trhMillis = 0;             // Time interval tracking
unsigned long blinkMillis = 0;

void setup() {
  dht1.begin();
  dht2.begin();
  Serial.begin(9600);
  Serial.println("In.(%) In.Tem(*C) Out.(%) Time");
  pinMode(ledPin, OUTPUT);
  delay(15);                           // Wait >= 11 ms before first cmd
  // Demonstrate blocking calls
  sht.measTemp(&rawData);              // sht.meas(TEMP, &rawData, BLOCK)
  temperature = sht.calcTemp(rawData);
  sht.measHumi(&rawData);              // sht.meas(HUMI, &rawData, BLOCK)
  humidity = sht.calcHumi(rawData, temperature);
  dewpoint = sht.calcDewpoint(humidity, temperature);
  logData();
}

void loop() {

  unsigned long curMillis = millis();          // Get current time

  // Rapidly blink LED.  Blocking calls take too long to allow this.
  if (curMillis - blinkMillis >= BLINKSTEP) {  // Time to toggle the LED state?
    ledState ^= 1;
    digitalWrite(ledPin, ledState);
    blinkMillis = curMillis;
  }

  // Demonstrate non-blocking calls
  if (curMillis - trhMillis >= TRHSTEP) {      // Time for new measurements?
    measActive = true;
    measType = TEMP;
    sht.meas(TEMP, &rawData, NONBLOCK);      // Start temp measurement
    trhMillis = curMillis;
  }
  if (measActive && sht.measRdy()) {           // Note: no error checking
    if (measType == TEMP) {                  // Process temp or humi?
      measType = HUMI;
      temperature = sht.calcTemp(rawData); // Convert raw sensor data
      sht.meas(HUMI, &rawData, NONBLOCK);  // Start humidity measurement

      float h2 = dht2.readHumidity();
      float t2 = dht2.readTemperature();

      Serial.print(humidity);
      Serial.print(" \t");
      Serial.print(temperature);
      Serial.print(" \t");

      if (isnan(t2) || isnan(h2)) {
        Serial.println("Failed to read from DHT #1");
      } else {
        Serial.print(h2);
        Serial.print(" \t");

        //time = millis();
        //prints time since program started
        Serial.println(curMillis);
      }
      Serial.println();
    }
    else {
      measActive = false;
      humidity = sht.calcHumi(rawData, temperature); // Convert raw sensor data
      dewpoint = sht.calcDewpoint(humidity, temperature);
      logData();
    }
  }
}

void logData() {
}

```

But the difference is that I am using SHT75 instead of another DHT11 so I am simultaneously acquiring data from the both of them. Thanks for everyone!

---
Tags: arduino-uno, serial, time
---


title: Is it safe to power the Uno with 18v?

text:
# Question
Title: Is it safe to power the Uno with 18v?
So I'm aware the Arduino Uno can take 6-20 volts, with a recommended voltage of 7-12. But I have an unregulated 12v power adapter, which puts out about 18v with no load.

Most of the time the Arduino won't be doing much of anything but powering a 16x2 LCD, which should take only a couple mA.\* I have a 10k ohm resistor on the back light, so it should only take 0.5mA.
<sup>\*I don't have a datasheet, but from what I've read 1-2mA is reasonable</sup>

The Arduino won't be doing anything else that would draw any meaningful amount of current (except looping to check for input, etc). Online sources generally indicate the power draw when not doing anything is a little under 50mA, so I'm guessing that's about what the current draw will be. Using the formula in this answer, I calculate the power dissipation by the voltage regulator to be (18v-5v)\*0.05A=0.65 Watts.

* Is this correct?
* Is the voltage regulator likely to overheat?

I'm not really concerned about power usage, because it will be plugged into the wall all the time. Also, the Arduino will be out of sight, but will have plenty of air around it to disipate heat (though not access to a breeze).

# Answer
It won't do any harm to try it at 18V for a while. Most voltage regulators have thermal protection and just cut out if they get a little too hot. If it works reliably, stay with it.

EDIT: Their Uno page warns against overheating the board, so I would test it for a short while and make sure there is no overheating or strong "plastic" smell coming from the board. If there's enough heat to worry, then it's best not to run like that for extended periods.

If 18V is too high, you could get a power resistor (I'd guess say a 10 watt resistor around 24 ohms) to waste approximately half an amp from the power supply. Connect this to the supply, in parallel with the Arduino. It's wasteful (unless your room needs heating anyway) but will lower the voltage (that reaches the Arduino) a little.
> 2 votes

---
Tags: power, current, heat
---


# Question
Title: TMC26XMotorTester:44: error: 'TMC26XStepper' does not name a type
I am working with a TOS-100 Stepper Driver Shield and am attempting to use the pre-written TMC26XMotorTester/Motor/Serial set of files to make it work.

I unzipped the files, copied the TMC26XStepper folder into the library directory in my Arduino folder, and restarted the Arduino IDE (as well as the Arduino and Driver Shield boards). I also switched the DIR and STEP pins (6 and 7 swapped to match the wiring on my board).

In the TMC26XMotorTester file, I wrote

```
    #include <TMC26XStepper.h>

```

so I'm assuming (given everything I've done), that the functions should be available given this file inclusion.

However, I get the error

```
    TMC26XMotorTester:44: error: 'TMC26XStepper' does not name a type

```

along with the complete list of functions from the TMC26XStepper.h/.cpp file that were not identified.

Any thoughts? I'm using Arduino-Uno version 1.6.9.

# Answer
> 1 votes
Arduino libraries are normally written as a C++ Class. When you start a sketch you normally tell the compiler where to find that Class and to Instantiate that class. If the compiler does not find the Class and you attempt to Instantiate it, the compiler will telly you it does not know what to do. That is, it will tell you the thing you are using (TMC26XStepper) does not describe anything or is not a Type.

Study the structure of Arduino libraries to make sure what you have installed agrees with the common Arduino library.

Also, newer version of the Arduino IDE can download and unpack libraries automatically given both the IDE and the library are setup to do this.

---
Tags: arduino-uno, stepper
---


# Question
Title: How can I connect mysql with Arduino using GSMshield
How can I include `mysql.h` library in IDE of Arduino to connect Arduino to mysql database by using GSM shield?

# Answer
> 2 votes
You can't. Arduino is too small to run `libmysqlclient` directly. There are few other solutions:

1. You can expose your database using REST API and call that.
2. Change hardware platform to Raspberry Pi - it runs full Linux system
3. Run your app on PC and call Arduino using some RPC library

# Answer
> 1 votes
You can turn on GPRS data connection on your GSM shield and perform HTTP GET or POST request to the web page script (for example PHP script), which in turn will access the MySQL database (write or read DB records). It is easier than implementing REST API.

---
Tags: arduino-uno, gsm
---


title: Peristaltic Pump Project

text:
# Question
Title: Peristaltic Pump Project
I am designing a peristaltic pump and need some advice for parts. I am using an Arduino Leonardo and also have an UNO and am planning on adding a temperature and pH sensor as well. I have two questions:

**1) I am planning to use a Stepper Motor but am unsure if I should use the *NEMA 17 or 23* or some other motor. I need a relatively "high" amount of torque maybe around 1 to 3 N-m.**

**2) Should I go with a Motor Shield or Motor Driver. I am currently looking at the *Big Easy Driver* or *A4988 Bipolar Driver* or the simple *Arduino Motor Shield*.**

Does anyone know which of these would be best or have any suggestions? Thank you very much!

# Answer
> 1 votes
The specifications for each stepper motor varies, with the larger models having the greater torque. With great torque comes the requirement of great power. A quick search for nema 17 stepper motors finds the torque figures on the low side of your request, while the nema 23 motors display a greater range, including your figures.

The additional power requirements may exceed the capabilities of the Arduino Motor Shield (2a per channel, 4a max), while the A4988 board specifies up to 2a per coil. Also note that to achieve the use of the higher power levels, these boards will require heat sinks.

If you expect to require the higher figure for torque, consider to research for a driver board that has a greater power limit, "just in case".

---
Tags: power, motor, shields, arduino-leonardo, current
---


# Question
Title: How do I stop the Arduino TX/RX LEDs from flashing? How do I turn off the "ON" LED?
I actually have a SparkFun RedBoard, but I think this question applies to Arduino Uno and other boards as well.

I'm wondering how much control the programmer has over the various LEDs on the board. First there's the "ON" LED which is very bright. Can this be turned off or dimmed, or do I need to resort to electrical tape?

More annoying is the "TX" and "RX" LEDs. These blink rapidly when data is being communicated over the USB-serial connection. I'm guessing these are not configurable, but I couldn't find the answer anywhere online.

I know that the "Pin 13 LED" can be controlled (via Pin 13!).

# Answer
> 2 votes
> I'm wondering how much control the programmer has over the various LEDs on the board. First there's the "ON" LED which is very bright. Can this be turned off or dimmed, or do I need to resort to electrical tape?

Remove it, remove the resistor inline with it, or cut the track powering it. Either that or resort to electrical tape (or blu-tack). You have absolutely no control over it.

> More annoying is the "TX" and "RX" LEDs. These blink rapidly when data is being communicated over the USB-serial connection. I'm guessing these are not configurable, but I couldn't find the answer anywhere online.

**If your board uses an ATMega16U2**

As above, or compile a custom version of the ATMega16U2 firmware and flash it on to the ATMega16U2 chip.

**If your board uses an FT232 chip**

Download the FT232 EEPROM editing program from FTDI and use that to reconfigure the IO pins the LEDs are attached to so they do nothing. If you are on Linux you can use libftdi's `ftdi_eeprom` program.

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


# Question
Title: Why can't the OCR1A register be set to 1 to get a 8MHz PWM?
The max PWM frequency that can be achieved with an Arduino is by using the PWM fast mode with the pre-scaler set at 1 and the TOP counter value at 3, getting 4MHz

f\_OC = 16000000/(1(1 + 3)) = 4000000

Why can't be the TOP value set at 1?

# Answer
Because then you only have 1-bit PWM. And there aren't an awful lot of applications for 1-bit PWM.
> 2 votes

---
Tags: pwm
---


title: How do I lock a servo motor?

text:
# Question
Title: How do I lock a servo motor?
I am working on a robot which uses Ackermann's steering principle. Now the steering principal itself is in the development stage and the first prototype is pretty much good except for the fact that it can get turned very easily.

So I was hoping to find a way to lock the servo operating the steering mechanism so that it only rotates when the servo does. Any way to do that??

I'm using a UNO.

Thanks!

# Answer
A normale servo will stay in position when:

1. It's powered up (with enough current)
2. You are feeding the control signal into it.

And

3. It's rated for the amount of force applied.

Based on your comments, it seems that it's not a regular servo or could be faulty. I couldn't find the datasheet for your servo, so I can't tell if it's normal behavior, though it seems unlikely. (Servo's aren't made to bounce around)

Edit: It doesn't really make sense that it could be easily rotated by touching it, that would also mean that it can't lift anything? I would suggest trying another servo.
> 0 votes

---
Tags: arduino-uno, pwm, servo
---


# Question
Title: Get value from a website using Yún and a RPi
I have a project that requires opening a door remotely. I'm using an arduino Yún and a raspberry pi. I have a switch connected to the RPI and i'm sending it's value to a web server. How can I get the value from the website to the arduino, so that it can process it and see if an order to open the door is issued?

Thanks for any help :)

# Answer
You need to use the Process library that comes with the IDE.

That allows you to execute commands on the Linux portion of the Yun from within your Arduino code, and get data back from it.

You use that class to execute the `curl` command in Linux to fetch the content of a web page and return that content to the AVR code where you can deal with it.

If the content of the web page is complex it may be worth passing the output of `curl` through some other Linux based commands first (such as `grep` and `cut` or `awk`) to clean it up and reduce the amount of text you have to deal with at the AVR end.
> 0 votes

---
Tags: arduino-yun
---


# Question
Title: ESP8266 not able to communicate over serial connection with arduino UNO
## This is the code I uploaded in Arduino UNO:

```
#include<SoftwareSerial.h>
SoftwareSerial ESP(2,3); // RX, TX
//ESP RX-->3(UNO) TX-->2(UNO)

void setup() {
// Open serial communications and wait for port to open:

    Serial.begin(9600);
    while (!Serial) {
        ; // wait for serial port to connect. Needed for native USB port only
    }

    Serial.println("Goodnight moon!");

    // set the data rate for the SoftwareSerial port
    ESP.begin(9600);

}

void loop() {
    if (ESP.available()) {
        char inData = ESP.read();
        Serial.println("Got reponse from ESP8266: ");
        Serial.write(inData);
    }

    ESP.write("AT\r\n"); //Normally ESP responds to AT command with "OK"
}

```

---

But ESP is not able to receive the AT command properly...sometimes it recieves A, sometime T. It then responds with garbage value. Though we are able to give command to ESP through Serial Monitor and it responds pretty well. But when trying to communicate through code, the communication is not OK.

# Answer
> 4 votes
The problem is in your `loop()` function. On each iteration, you will receive **at most one** character from the SoftwareSerial, while writing the same AT command again and again. As a result, your slave device (ie. ESP8266) will overflow its UART buffers, resulting in garbage being sent and received.

You should keep receiving data from the slave for as long as it has data:

```
while (ESP.available()) {
    char inData = ESP.read();
    Serial.println("Got response from ESP8266: ");
    Serial.write(inData);
}

```

---
Tags: c, uart, esp8266
---


# Question
Title: Problems running several Arduinos off of one HC-05 Tx pin
TL;DR: Multiple Arduinos listening to a single serial rail are burning out my HC-05's TX pin. Arduinos are leaking voltage onto the signal rail. How do I stop, or isolate that to keep from burning out Bluetooth TX pin?

I'm trying to build an LED-based track light that uses an HC-05 to communicate with up to 8 Arduinos to control up to 16 LEDs total. Each Arduino can only control 2 LEDs because of the shape and form factor of the project.

The track has 3 rails, 12V, Ground and Signal and all Arduinos share the same rails. Hopefully the schematic below does a good job explaining it.

On to my issue. Initially, I was getting almost 5V from my pin 7 (SoftwareSerial pin) on the Arduinos, which was quietly ruining the TX pin on my HC-05. I lowered that to about 1v after using `pinMode(bluetoothTx, INPUT);`, which is good but not good enough. That voltage starts to add up as I add more and more Arduinos to the overall setup.

My solution in theory is to add diodes to pin 7 on the Arduinos, so they can't put voltage on the signal rail. This drops the voltage by 0.7v from what I've read, which most likely is why the Arduinos aren't reading a signal now, because that drops it below the logic level required, since the HC-05 is only putting out 3v3. So I think to add a level shifter on the HC-05 to pump up the signal to 5v, then the diode's voltage drop shouldn't matter right? See schematic below.

My solution seems unnecessarily convoluted and I don't even know if it would work. The more I read without bouncing the information off of others, the more confused I am becoming. Now after reformatting this post for an hour, I am thinking about a decoupling capacitor between the pin and ground... Will that have the effect I am looking for?

I also looked into using a pulldown resistor, but from everything I've seen (and from the first electronics course I've taken), it seems like an inappropriate solution. The examples I've seen usually use a switch, which makes sense, but for my application I am protecting the TX pin on my HC-05, so I think it would not give the effect I am looking for (tapping the line in between resistor and pin would not isolate the voltage, tapping in after the resistor would short the signal to ground).

I'm including my code for completeness, but the schematic is where I think I need help. Could someone point me in the right direction, I don't mind working for my answers but I've been going solo at this for over a month now, and I'm not even at the point in my education where we've covered much logic yet. I'm reaching a little here.

```
#include <EEPROM.h>
#include <SoftwareSerial.h>

byte address = 1; //change this to change light address
byte lightno = (address + 1); // variable to print light number
int addressShifter= ((address)*500); //This number will be subtracted from input
int bluetoothTx = 7; //btTX to pin 7 //input from HC-05
int bluetoothRx = 8; //btRX to pin 8 //not used
int led1 = 3; // the PWM pin LED1 is attached to
int led2 = 5; // the PWM pin LED2 is attached to
int brightness1 = EEPROM.read(0); //Recalling previous setting
int brightness2 = EEPROM.read(1); //Recalling previous setting
int thismodMin = (0 + addressShifter); //min two-byte looked for
int thismodMax = (499 + addressShifter); //max two-byte looked for

SoftwareSerial bluetooth(bluetoothTx, bluetoothRx); //naming it bluetooth and assigning it to the variables shown

void setup() {
    pinMode(led1, OUTPUT); // sets the pin as output
    pinMode(led2, OUTPUT); // sets the pin as output
    pinMode(bluetoothTx, INPUT); // sets the pin as input
    //Setup usb serial connection to computer
    Serial.begin(9600);
    //Setup Bluetooth serial connection to android
    bluetooth.begin(9600);
    analogWrite(led1, brightness1); //Set Led brightness from stored values
    analogWrite(led2, brightness2); //Set Led brightness from stored values
    Serial.println("SETUP COMPLETE, I am Light #"); //Identify self
    Serial.println(lightno);
    Serial.println("expecting Min "); //Min value listened for
    Serial.println(thismodMin);
    Serial.println("expecting Max "); //Max value listened for
    Serial.println(thismodMax);
}

void loop() {
    //---------Serial Communication---------
    if(bluetooth.available()>= 2) {
        unsigned int blu1 = bluetooth.read();
        unsigned int blu2 = bluetooth.read();
        unsigned int blueinput = (blu2 *256) + blu1;
        //I don't know why any of the above is neccesary but it will not read correctly without this conversion
        //Serial.println("blueinput = "); Not used
        //Serial.println(blueinput);  Not used
        if (((blueinput) >= (thismodMin)) && ((blueinput) < (thismodMax))){
            //If this blueinput is within this modules adress range, convert signal to PWM
            int thisMod = ((blueinput) - (addressShifter));
            //Convert blueinput to a value this module will work with (0-500)
            //-----------Lights---------
            if (((thisMod) >= 0) && ((thisMod) < 100)){ //0=off 1-100=on-Bright
                brightness1 = ((thisMod)*2.55); //converts percentage brightness to PWM value
                analogWrite(led1, brightness1); //apply brightness
                //      Serial.println("brightness1: "); //diagnostics
                //      Serial.println(brightness1); //diagnostics
                delay(10);
            } else if (((thisMod) >= 101) && ((thisMod) < 201)){ //101=off 102-201=on-Bright
                brightness2 = (((thisMod)-101)*2.55); //subtract starting value and then convert percentage brightness to PWM value
                analogWrite(led2, brightness2); //apply brightness
                //      Serial.println("brightness2: "); //diagnostics
                //      Serial.println(brightness2); //diagnostics
                delay(10);
            } else if ((thisMod) == (399)){ //if specific code recieved
                EEPROM.write(0, brightness1); //store brightness setting for light 1
                Serial.println("Epprom1 written");
            } else if ((thisMod) == (424)){
                EEPROM.write(1, brightness2); //store brightness setting for light 2
                Serial.println("Epprom2 written");
            } else{}
        }
    }
}

```

# Answer
> 2 votes
**first of all just to clarify some things.**

softwareSerial library sets PinMode for rx,tx declared pins internally so it should not have any impact on voltages you measure if you include `pinMode(bluetoothTx, INPUT);` and if this happens, as you describe, it indicates a problem.

a pin declared as INPUT is on a high impedance state which means that it will not (in general) affect signals connected to it.

an RX pin, by default is *pulled up* which means that when you do not have anything connected to it, you should measure 5V and when you connect it to GND you should read 0V.

---

i tried to reproduce your problem by implementing your first schematic utilizing 3 arduinos as receivers with the difference of having another arduino as transmitter instead of HC-05 and using a simplified version of your program (see it below). I could not reproduce it. Also, I suspect that parallel pull up resistors from ~8 arduinos may be the problem, so I would suggest:

* make sure communication between HC-05 and only one arduino works.
* try connecting HC-05 with two arduinos and see if both arduinos are able to read incoming data.
* keep adding arduinos and checking if every arduino can read incoming data.

also try with another arduino as transmitter instead of HC-05 in case you still have a problem and post the results so we can further investigate .

```
#include <SoftwareSerial.h>

int bluetoothTx = 7;    //btTX to pin 7 //input from HC-05
int bluetoothRx = 8;    //btRX to pin 8 //not used

SoftwareSerial bluetooth(bluetoothTx, bluetoothRx);  //naming it bluetooth and assigning it to the variables shown

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

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

        Serial.println("SETUP COMPLETE, I am Light #");  //Identify self
}

void loop()
{
        //---------Serial Communication------
        if(bluetooth.available() )
        {
             Serial.print(bluetooth.read(),HEX );
        }

}

```

---
Tags: serial, c++, arduino-nano, softwareserial, hc-05
---


# Question
Title: Any way to not explicitly include dependent libraries?
When I am including the `Adafruit_BMP280` library, Arduino IDE 1.7.10 complains that it wants all dependent libraries included:

```
Adafruit_Sensors.h
Wire.h
SPI.h

```

Isn't it possible to circumvent that? This question says to include the first library like

```
#include "Adafruit_BMP280"

```

but also with the full path, this doesn't work and just returns the same error.

# Answer
> 1 votes
No, it is not possible. The IDE needs to know which libraries you are using so that it can compile the source code for them.

Other IDEs have got around the problem by recursively scanning the libraries themselves and building up a list of dependencies (such as UECIDE) but this is not something that the Arduino IDE has been programmed to do.

The only other possible option might be to create a single massive library that contains everything that the "main" library relies on, however this may cause problems with other libraries also wanting the same things and you ending up with massive conflicts.

---
Tags: library, adafruit
---


title: ESP2866 and java ServerSocket

text:
# Question
Title: ESP2866 and java ServerSocket
So I have an application that runs on the Arduino that passes info over serial. I'm using a ESP2866 to make it wireless.

```
Arduino->Serial->Esp2866->SocketConn->JavaSocket->Console

```

I have a working java socket server, that I can connect to with other applications. (Java, c++, ext.) And even across the network.

I just cant seem to get my ESP2866 to connect.

Iv tried several ESP2866 units, no success. Iv tried updating the firmware on each, nope.

```
AT                      ->  OK
AT+RST                  ->  ready
AT+CWMODE=1             ->  OK
AT+CWJAP="name","pass"  ->  CONNECTED,GOTIP,OK
AT+CIPMUX=0             ->  OK
AT+CIFSR                ->  192.168.0.30
AT+CIPSTART="TCP","192.168.0.9","4160"  ->  ERROR

```

The lack of debug info is... Aggravating. Iv Seen other examples of this that worked. So whats the problem?

Additional info:

```
netstat -tulpn | grep 4160
tcp6       0      0 :::4160          :::*      LISTEN      23058/java

```

(Edit 1:)Just tried restricting to IPV4 and rebinding the port. Nope.

```
InetAddress localAddress = Inet4Address.getByAddress(new byte[]{(byte) 192,(byte) 168,0,9});
System.setProperty("java.net.preferIPv4Stack", "true");
ServerSocket listener = new ServerSocket(port,20,localAddress);
//...Code to make socket work.

```

# Answer
The ESP trys to connect to port 4160, but the server is listing on port 20.
> 1 votes

---
Tags: arduino-uno, esp8266, linux, tcpip, java
---


title: Which (Official) Arduino IDE to use?

text:
# Question
Title: Which (Official) Arduino IDE to use?
I have bought an Arduino UNO that turned out to be the Italian version (Arduino SRL) not the American one (Arduino LLC).

Now when I go to arduino.org and arduino.cc, they both have different versions of the IDE!

So, which one should I use (if they are even different) ?

# Answer
> 1 votes
You can use both IDEs no matter of the origin of the UNO even fake ones runs with the IDEs. The arduino.org IDE is just a fork of the arduino.cc. But arduino.org has many Board which are only run with the .org IDE.

---
Tags: arduino-ide, ide
---


# Question
Title: Pro Micro - Measuring voltage between two pins, without using GND
Quite new to this but making pretty good ground. I have an issue I'm not sure how to solve. I want to add a Pro Micro to an RC Toy, I can easily power it from the toys GND and 5V power. But then I want to use the voltage going to an LED on the toy (uses a different ground) to trigger an event within the Pro Micro.

I can power the Pro Micro from USB and and accomplish what I need with AnalogRead(). But if I connect the GND from the toys main power input to the GND from the LED it no longer acts as it should. I'm thinking these GNDs are not common, or are a separate circuit.

What I'm wanting to know is.. I'm using PIN10 on the ProMicro for the AnalogRead(), can I make it so that maybe PIN11 is the GND for that reading?

Thanks.

# Answer
No, you cannot - the ATmega's ADC is referenced to its ground, and there are also some strict limits on providing inputs more than a little bit outside of the range between its power and ground.

You may be able to read two analog inputs and subtract them for a sort of "software differential" analog input, but the signal on an LED is unlikely to be meaningfully "analog" anyway - it might be pulsed with a duty cycle, but it will probably not have a steady reduced voltage.

It's actually quite likely that the anode of the LED is connected to the toy's positive supply, and it is the negative path to the cathode which is being switched - this is the most traditional way of doing things, because historically semiconductor switches suitable for "low side switching" have had better performance than those suited for "high side switching". There will probably be a resistor on one side or the other of the LED.

With care and verification of suitable voltage ranges, you may be able to read the voltage on the LED cathode as a digital signal and invert it in software.
> 3 votes

---
Tags: arduino-pro-micro
---


# Question
Title: Why can't my Arduino IDE recognize serial ports? (Mac El Cap, Ard. UNO)
My Arduino UNO I bought directly from Arduino.cc, so I'm pretty certain it's not a cheap clone. I have a MacBook Pro El Capitan 10.11.5. My Java is 1.8, but I'm pretty sure that doesn't matter. I have never used Arduino before, though I know a good bit of programming and some about computers. Whilst setting up Arduino, the only serial port my computer/Arduino recognizes is `/dev/cu.Bluetooth-Incoming-Port`. Please comment if there is more information I should provide.

My computer recognizes that I have a USB device as seen here:

Here is a screenshot of the Arduino IDE:

Finally, the command`ls /dev/tty.*` outputs only `/dev/tty.Bluetooth-Incoming-Port`. Is it possible no other serial ports exist for me? Sorry for the barrage of pictures but I thought they'd help.

Things I have tried:

1. Installing CH34x driver

**I'm convinced it's not a driver issue though, as users and Arduino say that OS X does not need drivers installed to run Arduino**

2. Turning off System Integrity with `csrutil --disable` and also tried `csrutil --enable without kext`
3. Installing a FTDI USB Serial Driver
4. Bought a new USB A/B cable, as many reported the cable was faulty. I am getting a green light on my board

Does anyone know why my computer and/or Arduino does not list more serial ports that work? It's as if I don't have any besides the one Bluetooth port. I've been getting frustrated over this for several hours, so a solution would be **much** appreciated :)! I've tried all the solutions I've seen on SE thus far, but maybe I'm missing something

Thank you ahead of time!

# Answer
"ATmega16u2 DFU" indicates a USB interface micro that is in a state to have new firmware downloaded to it (DFU), *not* one which is ready for operational use as a USB interface to program the Uno's ATmega328p target MCU. If this persists after power-cycling/re-plugging the board, it is probably faulty and at minimum needs firmware repair - though it might be worth trying on another computer (preferably with a different OS or version) just to be absolutely sure nothing in the host software is forcing it to this mode.

If this is a new board you have not modified in any way, you should probably return it as defective.

If you have modified it, or you want to try to fix things yourself, you would need to follow the instructions for reflashing the 16u2 via USB-DFU. Beware that this is a non-trivial task that looks like it is going to require installing macports and running some terminal commands, and on older boards some soldering.
> 1 votes

---
Tags: arduino-uno, serial, usb, ide, mac-os
---


title: How to modulate my IR sensor?

text:
# Question
Title: How to modulate my IR sensor?
I'm looking to use a simple IR sensor out in bright sunlight, which means hell lot of distortion. Is there any way I can modulate it using my Arduino UNO so that it isn't affected by sunlight and other ambient light sources?

The IR sensor is just like this one.

# Answer
There is little information on the Amazon page about these devices. Only that the output is digital (only on and off) and that the sensitivity is controlled manually by an on board pot. It would appear impractical to enhance this type of device with out detailed specifications and / or a schematic.

If you would prefer using software to solve some of the problems you listed, I would suggest you use an IR parallax (not the company, the technique) distance sensor with an analog output. That way the Arduino Uno's analog input can be used to read the sensor and software (sketch) can process (filter) the data before it is put to use.

Added later...

Here is an article describing how to use an IR parallax distance sensor. Here is an Arduino library design to work specifically with the Sharp IR parallax distance sensor.
> 0 votes

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


title: Arduino Pro Micro troubles

text:
# Question
Title: Arduino Pro Micro troubles
I recently bought a brand new Arduino pro micro from Amazon, I set it up according to the instructions on sparkfun, except that when I plug it in, Windows doesn't even show that it tried to install device driver software. I figured it might just be a windows 10 thing because the tutorial was written on windows 7, so I forged ahead, and updated the device driver for COM3 in device manager, and attempted to upload a simple test for HID emulation:

```
#include <Keyboard.h>

void setup() {
  Keyboard.write('z');
}

void loop() {
  Keyboard.write('a');
  delay(5000);
}

```

It compiled just fine, and the IDE said it started uploading to the device, However, as it was uploading (or so I thought) I read a little farther and realized that the IDE wasn't set to use the right voltage (3.3V instead of 5V) I closed the IDE and reopened my sketch, changed the voltage to match up, and tried uploading it again. Here, it got stuck on the `Uploading...` text and so again, I closed the IDE.

Only the LED closest to the USB port is on, and it's solid green. I've connected to my computer using a Micro USB to USB adapter, and I initially plugged the board into a USB 3.0, but then switched to 2.0 to see if it made a difference. I have also tried it on Ubuntu 14.04 with no luck. I don't think it's bricked because if it was, my computer would still recognize it, but not know what it was (according to sparkfun), and as a result, I have yet to try the debricking method they suggest. Any thoughts?

# Answer
The Pro Micro, like the Leonardo, cannot automatically reboot into the bootloader like boards such as the Uno and Mega. Instead it relies on the sketch running on it listening for a special combination of events (open the serial port, set the baud rate to 1200 baud, close the serial port) to activate the bootloader.

If, for whatever reason, you don't have a working sketch installed on the board (such as you aborted the upload part way through) then there will be nothing there to listen for the "reboot into bootloader" instructions.

So you need to manually enter the bootloader. Fortunately it should be easy enough, but timing is all important.

When you first plug the board in, or when you press the reset button, you get a few seconds where the board is in the bootloader. On the Leonardo that is signified by the LED glowing and pulsating - I don't know off hand what is shown on the Pro Micro.

As long as you press the reset button just before you compile and upload your sketch, and as long as the upload portion doesn't take too long to start (tip: compile it before uploading, it makes it faster) it should then install the sketch into the board and from then on the auto-reboot should start working.

(Note: I haven't used a Pro Micro - this is all from my experience with the Leonardo which I believe uses the same bootloader.)
> 1 votes

# Answer
You have to retrieve the VID/PID numbers your board actually has and change your boards.txt accordingly. On my Linux computer I made a USB connection with my corrupted pro micro clone, "lsusb" does not show it, but if I pull rst-pin down (pulse) "lsusb" does show it for a few seconds. Now I know the vid:pid numbers. I edited boards.txt (~/.arduino15/packages/Sparkfun/hardware/avr/1/1/5/:

promicro.build.vid=0x1b4f (edited 1b4f with vid outcome of "lsusb")

promicro.menu.cpu.16MHzatmega32U4.build.pid.0=0x9205 (9205 edited)

Then in Arduino IDE I gave a reset pulse, the port showed up. I loaded the sample blinky script from sparkfun (https://learn.sparkfun.com/tutorials/pro-micro--fio-v3-hookup-guide#faq-change-pid), clicked "upload" and once again gave a reset pulse. The upload succeeded and my pro micro clone is back to normal.
> 1 votes

---
Tags: arduino-pro-micro, clones, windows
---


# Question
Title: How to interpret analog values sent to Arduino from line scanner?
So I have a line scan camera attached to my Arduino Mega and I'm trying to send it a digital clock impulse and get an analog output back. The line scan camera is supposed to return 128 pixels.

So far I've been able to send the impulses and get analog values back which I am printing out. However, the values are different every time, which doesn't make sense because the camera didn't move so I assume that it should give back similar numbers.

Also, is there a way to determine what these numbers mean? Is there some way of turning analog signals into color pixels? My ultimate goals is to be able to determine if something has moved through the vision of the line scanner

Here is the datasheet for the line scanner: http://www.farnell.com/datasheets/315815.pdf

Here is my code:

```
void loop() {

  int delayTime = 20;
  digitalWrite(syncPin, HIGH);
  delayMicroseconds(delayTime);
  digitalWrite(clockPin, HIGH);
  delayMicroseconds(delayTime);
  digitalWrite(syncPin, LOW);
  delayMicroseconds(delayTime);
  digitalWrite(clockPin, LOW);
  delayMicroseconds(delayTime);

  for (int i = 0; i < 128; i++)
  {
    digitalWrite(clockPin, HIGH);
    pixelValue[i] = analogRead(dataPin);
    delayMicroseconds(delayTime);
    digitalWrite(clockPin, LOW);
    delayMicroseconds(delayTime);
  }

  digitalWrite(clockPin, HIGH);
  delayMicroseconds(delayTime);
  digitalWrite(clockPin, LOW);
  delayMicroseconds(delayTime);

  for (int j = 0; j < 128; j++)
  {
    Serial.print("I received: ");
    Serial.println(pixelValue[j]);
  }

}

```

# Answer
First, a preliminary note: according to the datasheet, the only time you need a delay in your program is after reading the whole array and before sending the next sync pulse. All the other timing requirements are shorter than a single CPU cycle of your Mega, so no need to add extra delays.

> the camera didn't move so I assume that it should give back similar numbers.

Similar: yes. Identical: no. You expect noise to make every reading slightly different, and you also will have variations due to uneven timing of your program (e.g. the timer interrupt kicking in from time to time).

> is there a way to determine what these numbers mean?

They are proportional to the amount of light collected by each pixel. That's about all you know about their meaning.

> Is there some way of turning analog signals into color pixels?

No. This is a B&W camera.
> 2 votes

---
Tags: arduino-mega, analogread, digital, analog-sampling, analogreadresolution
---


title: 7 segment with arduino

text:
# Question
Title: 7 segment with arduino
I am getting error with this. It is displaying those segments which are not to be displayed, i.e., 3.141 is dark and other segments are red. And I have checked that the seven segment module I am having is common anode type only.

```
#include "SevSeg.h"

SevSeg sevseg; //Initiate a seven segment controller object

void setup() {
    byte numDigits = 4;
    byte digitPins[] = {2, 3, 4, 5};
    byte segmentPins[] = {6, 7, 8, 9, 10, 11, 12, 13};
    sevseg.begin(COMMON_ANODE, numDigits, digitPins, segmentPins);
    sevseg.setBrightness(1000);
}

void loop() {
    sevseg.setNumber(3141, 3);
    sevseg.refreshDisplay(); // Must run repeatedly
}

```

# Answer
If you use this library, then use

```
sevseg.begin(P_TRANSISTORS, numDigits, digitPins, segmentPins);

```
> 1 votes

---
Tags: arduino-mega
---


title: Arduino Pi-3 Ubuntu MATE not compiling

text:
# Question
Title: Arduino Pi-3 Ubuntu MATE not compiling
When I try to upload a script to my Genuino Uno from the Linux ARM distro on genuino.cc/downloads it spits out this during compiling. `avrdude: ser_open(): can't open device "/dev/ttyACM0": Permission denied
ioctl("TIOCMGET"): Inappropriate ioctl for device`

Has anyone got any ideas?

Thanks, Caleb

# Answer
After following the advice left by Majenko, I went to https://www.arduino.cc/en/Guide/Linux and followed the instuctions at the bottom of the page:

If you get an error Error opening serial port ... you need to set serial port permission.

Open Terminal and type: `ls -l /dev/ttyACM*` you will get something like: `crw-rw---- 1 root dialout 188, 0 5 apr 23.01 ttyACM0` The "0" at the end of ACM might be a different number, or multiple entries might be returned. The data we need is "dialout" (is the group owner of the file).

Now we just need to add our user to the group: `sudo usermod -a -G dialout <username>` where is your linux user name. You will need to log out and log in again for this change to take effect.
> 1 votes

---
Tags: arduino-ide, raspberrypi, ubuntu
---


title: MPU6050 acceleration values not 16-bit?

text:
# Question
Title: MPU6050 acceleration values not 16-bit?
I'm looking at the little code snippet from this (many other projects also use similar code):

```
void loop(){
 mpu.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);

 ax = map(ax, -17000, 17000, -1500, 1500);
 ...

```

If my reading is correct, it's assuming the value of `ax` to be between -17000 and 17000. But isn't the value supposed to be 16-bit? If so, shouldn't the range be wider than -17000, 17000? Is the value capped?

Any thought appreciated.

# Answer
The ADC for the accelerometer is 16 bit, yes. Also the data being sent out is in 16 bit format.

But what you are confusing is *resolution* and *range*.

The accelerometer can be programmed to have a sensitivity of 2g, 4g, 8g or 16g. With it set to the least sensitive, that is 2g, the full range of -32768 to +32767 would equate to ±2g.

That's fine when you're measuring G-forces of up to 2g, but when all you are sensing is tilt then there is only 1g - the 1g the Earth exerts on it.

That 1g is half the 2g range, which is -16384 to +16363. So round that up and give a little extra headroom to your calculations, and you get -17000 to +17000. It gives enough range in your calculations to give the full ±1g range "plus a little bit".
> 2 votes

# Answer
No, the `map()` function does not cap it's input or output, you would need `constrain()` for that. With `map()` alone, there is no assumption about the range of the values, other than the calculation not overflowing 32-bit integers. Thus,

```
ax = map(ax, -17000, 17000, -1500, 1500);

```

simply multiplies x by the ratio 1500/17000. It is mathematically equivalent to

```
ax = map(ax, 0, 34, 0, 3);

```

or to

```
ax = ax * 3L / 34;

```

C.f. the documentation of `map()`.
> 0 votes

---
Tags: sensors, c, accelerometer
---


# Question
Title: How do I read the fuse bits from within my sketch?
How can I read the fuse bits from within my sketch?

# Answer
You can use the boot\_lock\_fuse\_bits\_get function from \<avr/boot.h\>.

```
#include <avr/boot.h>;

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

    cli();
    uint8_t lowBits      = boot_lock_fuse_bits_get(GET_LOW_FUSE_BITS);
    uint8_t highBits     = boot_lock_fuse_bits_get(GET_HIGH_FUSE_BITS);
    uint8_t extendedBits = boot_lock_fuse_bits_get(GET_EXTENDED_FUSE_BITS);
    uint8_t lockBits     = boot_lock_fuse_bits_get(GET_LOCK_BITS);
    sei();

    Serial.print("Low:  0x");
    Serial.println(lowBits, HEX);
    Serial.print("High: 0x");
    Serial.println(highBits, HEX);
    Serial.print("Ext:  0x");
    Serial.println(extendedBits, HEX);
    Serial.print("Lock: 0x");
    Serial.println(lockBits, HEX);
}

void loop()
{
}

```
> 9 votes

---
Tags: fuses
---


title: Code runs different on USB vs Battery

text:
# Question
Title: Code runs different on USB vs Battery
I have two Arduino, one is to handle the Bluetooth communication and send a signal to the other Arduino, and the other to interpret the signal and display or hide an image on the E-ink display.

It work just fine when they both are connected through the USB. But when I connect a 9V battery to the Arduino running the E-ink, instead of the USB, the image is displayed and cleared (looping), as if the IF ELSE conditions are not there.

I have tested if it actually runs the method by adding delay to the showImg()-method, and that seems to work.

I have also tested with connecting the USB cable to the E-ink Arduino to a 5V charger, and the case is the same.

Image:

Bluetooth code:

```
int ledPin = 13;
int state = 0;
int flag = 0;

void setup() {
 pinMode(ledPin, OUTPUT);
 digitalWrite(ledPin, LOW);

 Serial.begin(9600);
}

void loop() {

 if(Serial.available() > 0){
 state = Serial.read();
 flag=0;
 }

 if (state == '2') {
 digitalWrite(ledPin, LOW);
 if(flag == 0){
 Serial.println("Screen: off");
 flag = 1;
 }
 }

 else if (state == '1') {
 digitalWrite(ledPin, HIGH);
 if(flag == 0){
 Serial.println("Screen: on");
 flag = 1;
 }
 }
}

```

E-ink code:

```
#include <epd.h>

int displayed = 0;
int val = 0;

void showImg(void)
{
  Serial.print("showImg");
  displayed = 1;
  //epd_clear();
  epd_disp_bitmap("PIC9.bmp", 0, 100);

  epd_udpate();
  //delay(10000);
}

void clearImg(void){
  Serial.print("clearImg");
  displayed = 0;
  epd_clear();
  epd_udpate();

}

void setup(void)
{
  //Serial.begin(9600);
  epd_init();
  epd_wakeup();
  epd_set_memory(MEM_TF);
  pinMode(7, INPUT);

}

void loop(void)
{
  val = digitalRead(7);

  if(val == 1){

    if(displayed == 0){
      showImg();
    }

  }else {

    if(displayed == 1){
      clearImg();
    }
  }
  //Serial.println(val);
  //delay(3000);
}

```

I am a beginner when it comes to Arduino, So I hope someone can give me some hints to what may be wrong.

Thanks!

# Answer
> 4 votes
The USB provides the one thing that is missing from your diagram there: the **common ground**.

The GND pins of the two boards *must* be connected together. By using USB the USB becomes that connection. As soon as you use batteries there is no connection, so no communication happens.

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


# Question
Title: GPS logging on the intel edison breakout board
I'm working on my project car, and I have decided I would like to have a GPS and log some sensors too. I'm just at a bottle neck here, the sensors I have brought pull about 7v each where I can't pull that much from the breakout board that I have, and I can't seam to get the GPS to work.

I've tried using ths code but software serial isn't supported on the edison:

```
// GPS Setup
#define rxGPS 0
#define txGPS 1
SoftwareSerial serialGPS = SoftwareSerial(rxGPS, txGPS);
String stringGPS = "";

void setup() {
  pinMode(rxGPS, INPUT);
  pinMode(txGPS, OUTPUT);

  Serial.begin(9600);
  Serial.println("Started");

  // GPS Setup
  serialGPS.begin(4800);
  digitalWrite(txGPS,HIGH);

  // Cut first gibberish
  while(serialGPS.available())
    if (serialGPS.read() == '\r')
      break;
}

void loop()
{
  String s = checkGPS();
  if(s && s.substring(0, 6) == "$GPGGA")
  {
    Serial.println(s);
  }
}

// Check GPS and returns string if full line recorded, else false
String checkGPS()
{
  if (serialGPS.available())
  {
    char c = serialGPS.read();
    if (c != '\n' && c != '\r')
    {
      stringGPS  = c;
    }
    else
    {
      if (stringGPS != "")
      {
        String tmp = stringGPS;
        stringGPS = "";
        return tmp;
      }
    }
  }
  return false;
}

```

Any ideas or help would be much appreciated

# Answer
Try this:

```
String GPSLine;

bool checkGPS()
{
  while(serialGPS.available())
  {
    char c = serialGPS.read();
    if(c == '\n') return true;
    if(c == '\r') continue;

    GPSLine += c;
  }
  return false;
}

void loop()
{
  if(checkGPS())
  {
    Serial.println(GPSLine);
    GPSLine = "";
  }
}

```
> 1 votes

# Answer
You might try my NeoGPS library. It has a diagostic program and some good information in the Troubleshooting section. And NeoGPS doesn't use the `String` class, although you can safely waste lots of RAM on the Edison. :P

For an Edison build, you may have to change the PACKED\_DATA configuration item, described here.

(This is an Arduino product, right?)
> 0 votes

---
Tags: c, gps
---


# Question
Title: Arduino OBD library and software serial library
Can I use Arduino OBD library with "custom" software serial or it needs to be used with hardware UART only? For example if I have D5 and D6 pin as RX and TX in my code hooked on OBD board, how do I initialize OBD library from there?

This is the OBD library that I'm referring to.

And I'm using this Allpro OBD board.

**Update** Actually I would be satisfied with a answer how to know when entire response from the board is received, because this way is way too messy:

```
void getResponse(void){
 while(obdSerial.available()){
   Serial.write(obdSerial.read());
  }
}

```

Here I don't know when the message is received. And if I try to use example from **Sparkfun** **obd-ii-uart-hookup-guide** (different board doe) I ended up in infinite-loop since the board never return `\r`, if I send ELM command to use `\n` as terminator, and if I disable ELM to echo the command so that I use just one `getResponse` call I get some readings, but not all the time, I ended up in infinite-loop again.

# Answer
> 1 votes
That library is hard-coded to use the single Hardware Serial device on the Arduino Uno or the second Hardware Serial1 device on other boards.

```
#ifndef OBDUART
#if defined(__AVR_ATmega328P__) || defined(__AVR_ATmega168P__)
#define OBDUART Serial
#else
#define OBDUART Serial1
#endif
#endif

```

You can edit the library's header file `OBD.h` to define your own serial port though:

```
#include <SoftwareSerial.h>
extern SoftwareSerial mySerialPort;
#define OBDUART mySerialPort

```

And then in your sketch create the `mySerialPort` SoftwareSerial object.

---
Tags: arduino-uno, softwareserial, uart
---


# Question
Title: Does Serial.read() ever return a character?
I'm trying to program my Arduino Mega to work with a TSL1401 line scan module and while looking over someone else code I came across this:

```
void loop()
{
    int b = Serial.read();      //Reads incoming serial data. Returns the first byte of
                                //incoming serial data available (or -1 if no data is available)

    if (b == 's')
    {
        getCamera();
        delay(2000);
    }
}

```

For the most part I understand what it's doing but I got confused when I saw that he was setting the return value of `Serial.read()` equal to a variable and then checking to see if that variable was a character. To my understanding `Serial.read()` returns an integer so why would you compare it to a character?

# Answer
On an 8 bit arduino a character is a byte. A byte can represent values between -128 and 127, or between 0 and 255, depending on how you "look" at them (signed or unsigned).

The whole concept of a character is a purely human thing. The Arduino only knows numbers.

For instance the character 'A' is actually the number 65. We, as humans, choose to represent it as an 'A' and call it "ASCII".

Again, the character 'a' is actually the number 97. You can also subtract characters from each other. `'a' - 'A' = 32`
> 4 votes

# Answer
Part of the answer is in the comment in your given example:

```
int b = Serial.read();      //Reads incoming serial data. Returns the first
                            //byte of incoming serial data available
                            //(or -1 if no data is available)

```

If you're reading raw 8-bit data from the serial port (basically, could be any value from 0-255), how do you represent errors? Per the comment: if nothing is available, it returns -1. But... as @Majenko pointed out, -1 is a valid CHAR too, it all depends on how you look at the data (signed, or unsigned).

But an INT can hold a value from 0-255 easily, and also a -1 to represent 'nothing'. The Serial.read function is non-blocking (it doesn't WAIT for a data byte), so it needs to be able to return a status that indicates 'empty bucket', meaning there's actually 257 (256+1) different possible values... thus you need more than 8 bits.

It's a painful lesson with usage of **fgetc(3)**, **getc(3)** and similar functions. You need to be able to represent EOF, while also returning valid 8 bit data. Hence the use of INT's as return value size. Often someone (ok, me... but it was a *long* time ago!) will figure that since they're reading CHAR's, you can use a CHAR sized variable... but then EOF never seems to be found... oops!

Hope this helps.
> 2 votes

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


title: Character array weirdness

text:
# Question
Title: Character array weirdness
I'm using Energia to program one of TI's MCU. Since Energia is based off the Arduino IDE, I'm hoping someone can help me here.

I'm building a simple UDP packet sender and receiver app. The MCU starts up and connects to the local Wifi network and waits for a packet from another device on the same network.

This packet is collected in a char array `char packetBuffer[16];`

I want to split this array into two separate arrays each of 8 elements. These are `char lampCmdRead[8];` and `char pwdReadBuffer[8];` Now the network bit works great. I can send the packet through my desktop and receive it on the MCU. However when I split this array I see that the `pwdReadBuffer` shows the same contents as `packetBuffer` even though they are of different sizes. How is this possible?

Here is the code:

```
char packetBuffer[16];
char lampCmdRead[8];
char pwdReadBuffer[8];

// This is code from the 'void loop()' section
int packetSize = Udp.parsePacket();

if(packetSize) {
 int len = Udp.read(packetBuffer, 16);
 if (len > 0) packetBuffer[len] = 0;
 Serial.println();

 Serial.println("packetBuffer:");
 Serial.println(packetBuffer);
 Serial.println();

 for(ctr = 0; ctr < 8; ctr++) {
   pwdReadBuffer[ctr] = packetBuffer[ctr];
 }
 if (len > 8) pwdReadBuffer[len] = 0;

 for(ctr = 0; ctr < 8; ctr++) {
   lampCmdRead[ctr] = packetBuffer[ctr+8];
 }
 if (len > 8) lampCmdRead[len] = 0;

 Serial.println("pwdReadBuffer:");
 Serial.println(pwdReadBuffer);
 Serial.println();

 Serial.println("lampCmdRead:");
 Serial.println(lampCmdRead);
 Serial.println();
}

```

And here is the output:

```
Received packet of size 16
From 192.168.1.101, port 55056

packetBuffer:
2qZ@X51Rredledon

pwdReadBuffer:
2qZ@X51Rredledon

lampCmdRead:
redledon

```

# Answer
```
if (len > 8) pwdReadBuffer[len] = 0;

```

This line is unsafe. You declared pwdReadBuffer to be only 8 bytes in size, but this line of code will either do nothing, or write *outside* of the target buffer, with unpredictable results.

You make a related mistake here:

```
if (len > 8) lampCmdRead[len] = 0;

```

First the test should be `>=` but again, such a value would be beyond the end of the target buffer.

Also consider that if you receive 8 or more characters, you will have no room for a terminating null in pwdReadBuffer, and so cannot pass it to anything that expects a null terminated string.

If you want to use null-terminate storage for a string of up to 8 bytes size, you need 9 bytes of storage. And of course you need to only use in-range indices to access the elements.
> 0 votes

# Answer
This behavior (where contents of `pwdReadBuffer` print out the same as those of `packetBuffer`) is occurring because you haven't properly null-terminated your strings.

After you copy the first 8 characters of `packetBuffer` to `pwdReadBuffer` the statement `if (len > 8) pwdReadBuffer[len] = 0;` gets executed. It sets `pwdReadBuffer[16]` to 0, ie, references out of array bounds.

Apparently `lampCmdRead` is allocated directly after `pwdReadBuffer`, so when you copy the next 8 characters of `packetBuffer` to `lampCmdRead`, they are being copied, in effect, to `pwdReadBuffer[8] ... pwdReadBuffer[15]`, so that the `println` prints a 16-character string, `2qZ@X51Rredledon`.

For each of your three arrays, allocate an extra byte for a null terminator.
> 0 votes

---
Tags: array
---


# Question
Title: How to compile an official VS1003 / VS1053 example for Arduino / ESP8266?
Have anyone ever successfully run any of the official playback and recording examples for **VS1003** or **VS1053** on Arduino / ESP8266? I mean, I was able to play sound with VS1003, but I just can't make the official example compile on Arduino IDE... It looks like it should be no problem (just provide a few methods and copy the main method code from the PDF file to the `setup()` in sketch) but I'm just getting a bunch of stupid compiler or linker errors, like "undefined reference to 'VSTestInitHardware()' " while the player.h header file (containing it) is included. I'm not a C / C++ expert so it's either something stupid I do or it's just not possible on Arduino. Can anyone provide a compilable example? I'm trying it with ESP8266 currently (and it is my desired target CPU), but an Arduino Uno version could help too (it throws different errors but doesn't compile neither). Thank you.

# Answer
Ok, after long battle with C++ compiler I have a **working example** (at least for VS1003 and ESP8266) with a checklist how to recreate it (with minimal changes to the example files). I'm sure someone else will have this problem so I'm attaching it:

**The things that you need to do in player1003.c**:

* rename to player1003.h (change file extension only)
* remove all 5 includes from the top (stdio, string, stdlib, ctype, "player.h")
* turn off `REPORT_ON_SCREEN` (change `#if 1` to `#if 0`) if you don't want to have a lot of serial output
* mass replace "FILE \*" to "File " - mind the space (change type of file variables in all methods, mark "Case sensitive" to avoid errors in player1053!)
* mass replace `fopen(` to `fopen2(`
* mass replace `printf(` to `Serial.printf(`
* mass replace `fflush(stdout);` to `//fflush(stdout);` (or `Serial.flush();`)
* remove method: `VSTestInitHardware(void)`
* remove `SM_SDISHARE` flag from `WriteSci(SCI_MODE, SM_SDINEW|SM_SDISHARE|SM_TESTS|SM_RESET);` line (in `VSTestInitSoftware(void)` method)
* in `VSTestHandleFile()` at the bottom add `fp.close();` after `VS1003PlayFile(fp);` and `VS1003RecordFile(fp);` lines (especially after the record!). We don't want unclosed files on SD card.

**The main sketch (.ino):**

```
#include <SPI.h>
#include <SD.h>
#include "player.h"

using namespace std;

// I use these values below for ESP-12 (ESP8266):
#define MP3_xCS 2
#define MP3_xDCS 4
#define MP3_DREQ 5
#define MP3_xRESET 16
#define SD_CS 15
#define SPI_MOSI 11 //SPI
#define SPI_MISO 12 //SPI
#define SPI_CLK  13 //SPI

#define  WAIT_DREQ()  while(!digitalRead(MP3_DREQ))

File song;

int VSTestInitHardware()
{
  pinMode(MP3_DREQ, INPUT);
  pinMode(MP3_xCS, OUTPUT);
  pinMode(MP3_xDCS, OUTPUT);
  pinMode(MP3_xRESET, OUTPUT);
  pinMode(SD_CS, OUTPUT);

  digitalWrite(MP3_xCS, HIGH);
  digitalWrite(MP3_xDCS, HIGH);

  digitalWrite(MP3_xRESET, LOW); // chip off!
  delay(100);
  digitalWrite(MP3_xRESET, HIGH); // chip on!

  Serial.begin(115200);

  if (!SD.begin(SD_CS))
  {
    Serial.println("Can't initialize SD!");
    return -1;
  }
  Serial.println("SD OK!");

  SPI.begin();
  SPI.setClockDivider(SPI_CLOCK_DIV32);  // Bus SPI at 1MHz (for Arduino: 16MHz / 16 = 1MHz)
  SPI.transfer(0xFF);  // Write something to the bus
  delay(10);
  return 0;
}

void setup()
{
  if (VSTestInitHardware() || VSTestInitSoftware())
  {
    Serial.printf("Failed initializing VS10xx, exiting\n");
    exit(EXIT_FAILURE);
  }
  /* ... */
  /* Playback example. You can call these functions many times in a row
  because they leave VS1003 in a stable state. */
  VSTestHandleFile("TEST.mp3", 0);  // remember to use 8.3 file names format on SD!
  /* Recording example */
  VSTestHandleFile("RECORDED.WAV", 1);  // original example for VS1003 has a bug here (OGG extension)

  Serial.println("Playing recorded file...");
  VSTestHandleFile("RECORDED.WAV", 0);

  Serial.println("THE END");
}

void loop()
{
}

void WriteSci(unsigned char reg, unsigned char hsb, unsigned char lsb)
{
  // for debugging:
  Serial.printf("Setting %s to: %d (%X, %X)\n", RegName(reg), (hsb<<8) + lsb, hsb, lsb);

  WAIT_DREQ();
  digitalWrite(MP3_xCS, LOW);

  SPI.transfer(0x02);
  SPI.transfer(reg);
  SPI.transfer(hsb);
  SPI.transfer(lsb);
  WAIT_DREQ();
  digitalWrite(MP3_xCS, HIGH);
}

void WriteSci(u_int8 addr, u_int16 data)
{
  WriteSci(addr, data >> 8, data & 255);
}

uint16_t ReadSci (unsigned char reg)
{
  WAIT_DREQ();
  digitalWrite(MP3_xCS, LOW);

  SPI.transfer(0x03);
  SPI.transfer(reg);
  delayMicroseconds(10);

  char response1 = SPI.transfer(0xFF);
  WAIT_DREQ();
  char response2 = SPI.transfer(0xFF);
  WAIT_DREQ();

  digitalWrite(MP3_xCS, HIGH);

  unsigned int resultvalue = response1 << 8;
  resultvalue |= response2;

  // for debugging:
  if (reg != SCI_HDAT0 && reg != SCI_HDAT1)  // these registers are filtered out because they are intensively used during recording
    Serial.printf("%s is: %d (%X, %X)\n", RegName(reg), resultvalue, resultvalue >> 8, resultvalue & 255);

  return resultvalue;
}

int WriteSdi(const u_int8 *data, u_int8 bytes)
{
  WAIT_DREQ();
  digitalWrite(MP3_xDCS, LOW);

  for(int y = 0 ; y < bytes ; y++)
    SPI.transfer(data[y]);

  digitalWrite(MP3_xDCS, HIGH);
}

const char* RegName(uint8_t reg)
{
  switch (reg)
  {
    case 0x00: return "SCI_MODE";
    case 0x01: return "SCI_STATUS";
    case 0x02: return "SCI_BASS";
    case 0x03: return "SCI_CLOCKF";
    case 0x04: return "SCI_DECODE_TIME";
    case 0x05: return "SCI_AUDATA";
    case 0x06: return "SCI_WRAM";
    case 0x07: return "SCI_WRAMADDR";
    case 0x08: return "SCI_HDAT0";
    case 0x09: return "SCI_HDAT1";
    case 0x0A: return "SCI_AIADDR";
    case 0x0B: return "SCI_MIXERVOL";
    case 0x0C: return "SCI_AICTRL0";
    case 0x0D: return "SCI_AICTRL1";
    case 0x0E: return "SCI_AICTRL2";
    case 0x0F: return "SCI_AICTRL3";
  }
}

void SaveUIState(void)
{
}

void RestoreUIState(void)
{
}

int GetUICommand(void)
{
  while (Serial.available() > 0)
  {
    char c = Serial.read();
    if (c != 10 && c != 13)
      return c;
  }
  return -1;
}

void exit(int code)
{
  if (code == EXIT_SUCCESS)
    Serial.println("Exited with no error.");
  else
    Serial.printf("Terminated with error: %d\n", code);
  while (true) { yield(); }  // yield() is needed for ESP8266 only
}

File fopen2(const char* fileName, const char* mode)
{
  if (mode[0] == 'w')  // fast workaround!
  {
    Serial.printf("Opening for writing: %s\n", fileName);
    song = SD.open(fileName, O_WRONLY | O_TRUNC | O_CREAT);
  }
  else
  {
    Serial.printf("Opening for reading: %s\n", fileName);
    song = SD.open(fileName, O_RDONLY);
  }

  if (!(song))
  {
     Serial.printf("File not found: %s\n", fileName);
     return song;
  }
  Serial.printf("File opened: %s\n", fileName);
  return song;
}

size_t fread ( void * ptr, size_t size, size_t count, File stream )
{
  yield();  // this is needed for ESP8266 only (otherwise reboots)
  return stream.read(ptr, size * count);
}

int fseek ( File stream, long int offset, int origin )
{
  stream.seek(offset);
}

size_t fwrite ( const void * ptr, size_t size, size_t count, File stream )
{
  return stream.write((uint8_t*)ptr, size * count);
}

int fflush ( File stream )
{
  stream.flush();
  return 0;
}

#include "player1003.h"

```

(i had to manually clean this file out of my additional code, but I hope it will compile just fine).

**I have a request:**

If you run this example, please write me in comment whether the recording worked. I can't make my VS1003 module record sound. I have a suspicion that mic in my module is broken. That's why I was trying the official example (with the minimum changes as possible). It records only noise in my case, but plays mp3 perfectly. If you have a working example of recording, please share too.

And one more to the people with more rep (moderators): Please add a `VS1003` (and `VS1053` and `VS1063`) keywords and assign it to my questions about VS1003, because I'm unable to do it and it should be done. The chip deserves a keyword. (It's really good and not expensive.)
> 0 votes

# Answer
This is best given with an example.

`foo.h` contains:

```
#ifdef __cplusplus
extern "C" {
#endif
extern int foo(const char* s);
#ifdef __cplusplus
}
#endif

```

`foo.c` contains:

```
#include "foo.h"
#include <stdio.h>

int foo(const char* s) {
  printf("foo: %s\n", s);
  return 42;
}

```

So first, let's create a "library" from foo.c. Since we are compiling with a C, not a C++ compiler, the stuff in `#ifdef __cplusplus` is ignored.

```
$ gcc -c foo.c

```

This creates a file called `foo.o`, which we can then use to link with.

`as24823.cpp` contains:

```
#include "foo.h"
#include <iostream>

int main(int argc, char* argv[]) {
  int f = foo("called");
  std::cout << f << std::endl;
}

```

Now I can compile the C++ program (as24823.cpp) and use a C library (foo.c):

```
$ g++ -c ase24823.cpp
$ g++ ase24823.o foo.o
$ ./a.out
foo: called
42

```

*Why is this necessary?*, I hear you ask. Well, for reasons that are way beyond the scope of this posting, C++ mangles entry point names. Observe:

```
$ nm as24823.o
$ nm ase24823.o
...
                 U foo
0000000000000000 T main
...

```

(I've removed most of the output). What this is telling me is that the .o file has an *entry point* called "main", and an *undefined external reference* (something that will be provided by a library) called "foo". Now, if I remove the ifdefs from the foo.h file and recompile, this is what I get:

```
$ cat foo.h
extern int foo(const char* s);
$ g++ -c ase24823.cpp
$ nm ase24823.o
0000000000000000 T main
                 U _Z3fooPKc
....

```

What just happened? Because C++ no longer knows that it's supposed to call a *C* function, it has mangled the external so as to encode the types of its arguments (this is so that overloading can happen).

If you find this confusing, don't worry -- just edit the .h files that come with your C libraries and you'll be fine.
> 0 votes

---
Tags: c++, esp8266, c, compile
---


# Question
Title: Is there any reason not to solder power leads to the lugs for the power in socket on the reverse side of a mega 2560 rev 3 board?
I have a very tight space for a project that requires a mega board , the "power in" plug takes it over the space available. Are there safety or other concerns soldering to the lugs for the "power in" socket on the reverse of a mega 2560 rev 3 board board? the board is fitted with an elctrofreaks TFT LCD MEGA SHIELD v2.2 and a TFT\_320QVT LCD screen. (the elctrofreaks mega shield uses vin pin) 1 other PWM pin is used and an esP8266 board on a uart channel The power is from a regulated power supply. If I do this, am I correct that the regulator and polyfuse will still be used?

# Answer
Soldering to the underside of the connector is exactly the same as plugging something in to the connector.

Yes the regulator will be used.

No the polyfuse will not be used - that is in the USB power circuit not the barrel jack power circuit.
> 2 votes

---
Tags: arduino-mega, power
---


# Question
Title: Unable to issue any AT commands to BT BLE Breakout Board
I'm a programmer, more from the software side but I do have hardware working knowledge too. I've completed the Arduino Starter Kit's 15 projects, Now trying to build some things with ESP8266 and HM-10 BLE.

I was able to connect ESP8266 to my network and start a TCP server too via AT commands(using Arduino's Serial Monitor and FTDI 232RL USB to TTL converter)

I also have a HM-10 Bluetooth Breakout+connector board (Its based on CC2541 by TI (visible on the SMD chip)) brought from here.

Using the same setup I was able to issue AT commands successfully for ESP8266. However I tried many things, different baud rates and \r\n combinations; I just couldnt get the HM-10 to acknowledge my AT commands.

Setup: link

Connections:

```
Arduino +5V --> +ve input of LDO regulator --> 3.3v OUPUT to Vcc of HM-10
Common GND for LDO regulator input and output pins, FTDI 232RL and HM10

FTDI TX --> voltage divider (1k ohms --> connection output to HM 10 RX --> 1k ohms --> 1k ohms --> GND)

```

There is no code/sketch as of now. I'm just trying to hook up the HM-10 BLE chip. I can pair my Android phone to it but that's not the concern here.

The concern here is I cannot configure the HM-10 using AT commands.

The HM-10 does not reply an "OK" acknowledge for my "AT" command. Nothing happens in the serial monitor after hitting enter. Just a blank screen.

Is there a way by which I can determine what baud rate to use and what combination of \r and \n?

What am I missing here?

# Answer
> 2 votes
I found out that there is no need for a voltage divider to reduce the voltage being given to RX pin of BLE from FTDI's TX since both FTDI232RL and HM-10 are 3.3V devices (from here)

I connected the TX from FTDI directly to the RX of BLE using female to female jumpers.

Used `No Line Ending` and 9600 as the baud rate.

Then it worked fine, I got an `OK` acknowledge for my `AT` command.

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


# Question
Title: What is the sampling-rate of the `analogRead()`?
I am about to Fourier analyse some data I've taken, but i need to know at which sampling rate the data was written to the serial monitor. I've found a lot of threads about how to increase it and such but not a single one that lays down some information about what the sampling-rate is.

My code is very simple, here it is:

```
      // the setup routine runs once when you press reset:
  void setup() {
    // initialize serial communication at 9600 bits per second:
    Serial.begin(9600);
  }

  // the loop routine runs over and over again forever:
  void loop() {
    // read the input on analog pin 0:
    int sensorValue = analogRead(A0);
    // print out the value you read:
    Serial.println(sensorValue);
  }

```

# Answer
> 3 votes
The ADC in default configuration will take 104 µs to make a sample (which agrees with Edgar Bonet's comment of roughly 9600 per second).

You can speed that up somewhat by changing the ADC prescaler from the default of 128. See ADC conversion on the Arduino (analogRead). A prescaler of 32 will reduce that to 26 µs and still give quite acceptable results.

You can also run the ADC asynchronously (in the background) so you can transmit the previous result while obtaining the next one. A higher baud rate than 9600 baud would be highly recommended in this case.

People have been doing FFT analysis using the Arduino Uno and similar. I suggest you Google for relevant posts about that.

# Answer
> 1 votes
I loaded this program on an arduino uno and measured with oscilloscope the time from the rising edge to the falling edge of the signal on pin13.

```
void setup() {

    Serial.begin(9600);
    pinMode(13,OUTPUT);
}

void loop() {
    PORTB = B00100000; //pin13 HIGH
    int sensorValue = analogRead(A0);
    PORTB = B00000000; //pin13 LOW
}

```

results:

> time: 110.4 uS relevant freuency: 9.06 kHz

---

in case you are interested in fast analogRead with Due, I suggest you take a look at this. The author stated that an analogRead with Due takes about 40uS and he also describes a couple of ways to make it much faster.

---
Tags: serial, analogread
---


# Question
Title: counting ADC samples ( using a light sensor)
i am new to micro controller programming and in need of help. i have managed to interface a light sensor to a micro controller (atmega 32a) and can read the value i.e. (1023) as per the set prescale. however i intended to achieve a single decimal value as the result. in this case (1) every time the sensor is exposed to light and successively perform an incremented tally as lights go on and off around the sensor ( i am using a LDR for this). i am currently having problem getting my micro controller to do this. i have searched all over the internet but no seems to assist me on this... please any insight on how to achieve this will be much appreciated. i know its a simple thing,HELP :(

basically just a means of making my micro controller count the number of times light falls on the LDR

# Answer
> 2 votes
There are 2 common light sensor types. The photo diode and the photo resistor. The first produces small amounts of current and operates fast. The second changes resistance and operates (very) slowly.

There is a good stack exchange response here for how to use a photo diode. Often the photo diode output is small and additional hardware is used to amplify the signal. As discussed in this stack exchange response.

The photo resistor or cadmium sulphide cell or Light Dependent Resistor is much easier to interface with an Arduino. However, the response time is very slow. On the order of hundreds of milliseconds to seconds. This is acceptable when controlling street lights. But is not acceptable in applications requiring fast light detectors such as those used for communication.

Before going on, verify which device you are using in your design.

Generally, Arduinos contain a 10 bit ADC. This results in values from 0 to 210−1 or 0 to 1023. Should you consistently get a reading at or near the limits of the ADC check your hardware. Do this by measuring the voltage at the input of the ADC pin used. Do this under varying conditions to verify the hardware is operating as expected.

A good software design uses hysteresis to convert an analog value to a logical 1 or 0. Here is a stack exchange response about using hysteresis with Arduinos.

---
Tags: sensors
---


title: Can ESP8266 replace Arduino?

text:
# Question
Title: Can ESP8266 replace Arduino?
I’m a hobbyist and have used Arduino so far for simple projects. Now I want to build a project involving addressable LEDs, I want to write several programs on the Arduino for the LEDs and on my phone I select which ones to run.

I found ESP8266 as a good and cheap solution to talk to my Arduino. Searching on the web to learn getting it to work I found that It has its own mcu on it and I can write and upload my code in Arduino IDE! 20kB of RAM, 80MHz CPU and 4MB of flash for 3 USD (However I’m not sure of these numbers but even one fourth of it is great)!! If I just need a few GPIOs why should use an Arduino UNO? Is this module reliable?

# Answer
Well, the answer of the question "Can it replace Arduino" - yes, in many cases it can.
Whether it would be "the Arduino killer" - I doubt it.
There are multiple arduinos and ESPs in my home and 1 ESP in my office running 24/7 as a part of my self-made (and constantly under development) smart home solution, together with 1-2 PCs. On top of that I have several experiments / unfinished projects involving the ESP.
So, from my not-so-limited experience, here are the pros and cons of ESP compared to Arduino:
++++ Internet connectivity built in!
++ Faster clock and more memory.
\+ Runs on 3V3 (most, but not all Arduinos are 5V) so it can interface 3v3 devices (like most of the display modules) directly, without level shifters.
\+ The "basic" ESP-12E costs about as much as an Arduino nano or pro micro.
\- The "basic" ESP-12E is 2.0mm pitch, not 2.54mm, making it a pain in the ass to work with.
\- There are breakouts that make it easier for prototyping, but they increase the cost and take too much space on a breadboard / protoboard.
\- The most common breakout - NodeMCU - is more expensive and has pins remapped, major annoyance, unless you program it in Lua, which is only ok for very simple projects. IMO, it should be used for prototyping only.
\- They run on 3v3, making it hard to interface 5V modules, fully turn on most MOSFETs, etc.
\- They are extremely picky on their power supply.
\- They draw significantly more power than the Arduino when not transmitting and much more when transmitting.
\- They are almost always worse for battery operated projects - you need 3v3 regulator (which has quiescent current), you need to sleep a lot (and you need GPIO16 broken out for that) and at the end of the day an arduino + a low-power radio will do the same job while lasting significantly longer on battery.
\- They have less GPIO pins and some of them must have set voltages at startup (GPIO0 - high, GPIO2 - high or floating, GPIO15 - low), also they "wiggle" some of their IO pins on startup, often making them unusable for many devices.
\- They only have one ADC, and to my knowledge it is slower than the already slow Arduino ADCs, plus you can only use it with 0-1.1V (internal reference).
\- Many of the Arduino libraries work out of the box or are already ported, but many don't. You either have to port them yourself or wait for someone to do it. In general, the Arduino community is much bigger and more mature, so most "noob-friendly" tutorials, libraries, etc. are provided for the Arduino.
Having that said, the ESP8266 is still great and extremely useful. Even Lua is useful for quick small projects. In most cases where internet connectivity is required, they seem to be the best solution. In many other cases, whether you will use ESP or Arduino actually doesn't matter. And sometimes the Arduino (or the little ATTiny85) is the better choice.
As always, "the right tool for the job" is the way to go.
Or combination of tools.
> 13 votes

# Answer
If you can program it, then of course it is viable to directly control your lights. It doesn't have a large number of I/O pins like the Arduino does, but as long as you have enough to do the job, it certainly drops the cost, the size, and the power requirements.
> 1 votes

# Answer
Yes there are a few I/O pins, so in theory you could drive one or a few leds or use an I/O port expander (I2C) for example.

And yes you can develop software and download it into even the low cost modules. The Arduino-like angle is just one way to do this. It is not an ARM as one might be lead to believe. But there is a gnu toolchain for the esp8266, etc. Yes 80 or 160MHz, 32 bit RISC, some flash, some ram.
> 1 votes

# Answer
The Arduino Uno board and the ESP module are not the same, but as long as the GPIO of the ESP8266 provides the hardware that you need for your application it will work.

One of my concerns is certification. The product has received several certifications, you'ld need to check if your version is also certified. You can lookup the manufacturer's certifications (and some documentation) from the FCC Search Page by entering 2AC7Z as the grantee code. The board you use may depend on those or require their own certification.

As you noticed, it can be added as a board type to the Arduino tool which makes it a lot easier for hobiests to play with it.

I just checked the grants and all three of them require that the WiFi antenna is kept at least 20 cm of all persons.
> 1 votes

---
Tags: esp8266
---


# Question
Title: Arduino's digitalWrite, precautions for direct port manipulation?
I stumbled upon this piece in `digitalWrite`. I'm unsure why clearing interrupts and setting/resetting SREG is neccesary here.

Can anyone shed a light on this?

```
uint8_t oldSREG = SREG;
cli();

if (val == LOW) {
    *out &= ~bit;
} else {
    *out |= bit;
}

SREG = oldSREG;

```

I figure they don't want an interrupt to possibly change any of the bits in the output register while it executes `*out = *out & ~bit`?

And what would the SREG have to do with it? Could the code affect SREG and why would that matter?

When speed matters, I often use the direct port manipulation, I'd like to get an idea if it's neccesary for me to include these "precautions".

# Answer
> 5 votes
> I figure they don't want an interrupt to possibly change any of the bits in the output register while it executes \*out = \*out & ~bit?

Correct. That is known as a *critical section*.

> And what would the SREG have to do with it? Could the code affect SREG and why would that matter?

SREG is where the flag that says if interrupts are enable or not is stored. Basically that is storing the current state, disabling interrupts, then restoring the current state.

The upshot is:

* If interrupts are enabled to begin with, they are disabled, then re-enabled.
* If interrupts are disabled to begin with, they are again disabled, and they remain disabled.

It's a way of restoring the previous state without actually having to check what the state was and set or clear accordingly.

# Answer
> 2 votes
Answering only the last question, as the rest has been addressed by Majenko.

> I often use the direct port manipulation, I'd like to get an idea if it's neccesary for me to include these "precautions".

If you use *constant* values, like `PORTB |= _BV(2);` or the like, there is no need, since this compiles into a single CPU instruction. Even if you write things that take multiple instructions, like `PORTB |= _BV(2) | _BV(3);`, you probably know whether you are modifying the same register inside an interrupt handler or not. If not, no need for critical section either. The authors of the Arduino core cannot make any assumptions.

---
Tags: programming, c
---


# Question
Title: When using Arduino Uno as ISP does "Yikes! Invalid device signature" mean a bad connection, bad config, or bad version of avrdude?
I'm using an Arduino UNO to program a pre-compiled hex image to an ATTINY45, using the avrdude in the Arduino IDE directory, on Windows 7. The Uno has the ISP sketch loaded from the examples directory and that works- the heartbeat LED pulses nicely.

On the hardware side I have this setup, except the ATTINY is surface-mount, soldered to a surfboard with all its pins verified-soldered with a voltmeter. I use a header-pin strip, held by hand to get the pins touching the surfboard, to get the signals from the Uno to the ATTINY.

Here are the command lines, which I took from looking at the IDE's debugging output:

```
REM set the fuse for 8MHz, so the ISP programmer can work
C:\Progra~1\Arduino\hardware\tools\avr\bin\avrdude -CC:\Progra~1\Arduino\hardware/tools/avr/etc/avrdude.conf -v -v -v -v -pattiny45 -cstk500v1 -P\\.\COM7 -b19200 -e -Uefuse:w:0xff:m -Uhfuse:w:0xdf:m -Ulfuse:w:0xe2:m
REM load the program
C:\Progra~1\Arduino\hardware\tools\avr\bin\avrdude -CC:\Progra~1\Arduino\hardware/tools/avr/etc/avrdude.conf -v -pattiny45 -cstk500v1 -P\\.\COM7 -b19200 -Uflash:w:firefly.hex:i
REM set fuse for 1MHz, as the project requires
C:\Progra~1\Arduino\hardware/tools/avr/bin/avrdude -CC:\Progra~1\Arduino\hardware/tools/avr/etc/avrdude.conf -v -pattiny45 -cstk500v1 -P\\.\COM7 -b19200 -e -Uefuse:w:0xff:m -Uhfuse:w:0xdf:m -Ulfuse:w:0x62:m

```

-I try running those separately, but always get this error:

```
avrdude: Device signature = 0x000000
avrdude: Yikes!  Invalid device signature.
     Double check connections and try again, or use -F to override
     this check.

```

but sometimes the number is ff0000 or ffff00 or ffffff

I read that "Arduino uses a slightly modified version of avrdude to upload sketches to the Arduino board. The standard version queries for the board's device signature in a way not understood by the bootloader, resulting in this error." Does this mean that using the Arduino avrdude with a new ATTINY chip, no bootloader on it, would also cause that same error? In other words, is the modified avrdude incapable of querying a non-Arduino-bootloaded AVR chip?

Or does that error simply mean I don't have a good contact between all my programmer pins and the ATTINY?

And, are the fuse settings truly needed, can the Uno program the flash into an attiny running at 1MHz and thus save me some steps?

(I would just buy a "real" programmer, but need to get this code in the next two days, and am in a rural part of Nova Scotia)

# Answer
I soldered wires to pads to be sure the connection was good, and used those wires for programming from the Uno. Then the programmer worked, without any edits to the command lines as posted in the question. I ran a few variations and was able to answer all my questions, and a few more besides:

1. The "Yikes! Invalid device signature" error was being caused by poor contact between the programmer (Uno) and the ATTINY pins.
2. It had nothing to do with the bootloader not being on the new microcontroller. The new ATTINY45 chip doesn't need a bootloader for the in-circuit programmer to work.
3. The Uno can program the ATTINY45 configured to either of its speeds, 1MHz or 8MHz. The factory settings are fine, and don't require changing the fuses.
4. Both *avrdude* versions worked for programming- the 6.1 from the author's site, and the modified one from the Arduino IDE.
5. *avrdude* can program via the Uno using any of `-c avrisp`, `-c arduino`, or `-c stk500v1`, it doesn't matter which.

One little question I wasn't able to answer, was what speed the Uno programs at (communication speed between the Arduino I/O pins & microcontroller being flashed). Is it related to the serial port speed? But it turned out to be not pertinent to answering this problem. Someone else can ask it if curious enough.
> 12 votes

# Answer
I had *exactly* this problem. If the ATtiny is set for external clock, then the ArduinoISP will not be able to program it without an external crystal. Connected a 16 MHz crystal and 2 capacitors and worked perfectly.

(I was then able to set ATtiny to internal clock, remove the crystal, and then worked perfectly without the crystal.)
> 4 votes

# Answer
Add the board and their fuse description from what is already set and it will work.

For adding just `C:\Program Files\Arduino\hardware\arduino\avr\boards.txt` and add the board description.

```
########
############ Definitions for ATmega 8MHz
##############################################################
atmega16-8.name=Atmega16 (internal 8MHz clock)

atmega16-8.upload.tool=avrdude

atmega16-8.upload.protocol=stk500v1

atmega16-8.upload.maximum_size=14336
atmega16-8.upload.speed=19200

atmega16-8.bootloader.low_fuses=0xE8
atmega16-8.bootloader.high_fuses=0x99

atmega16-8.build.mcu=atmega16
atmega16-8.build.f_cpu=8000000L
atmega16-8.build.core=arduino:arduino
atmega16-8.build.variant=mega16

##############################################################
############################

```

I used it.
> 1 votes

---
Tags: attiny, avrdude, isp, arduinoisp
---


# Question
Title: Does serial communication between PC and Arduino has to be in a loop?
I am trying to send a few variables from my python script to my Arduino. I am using pySerial. I am able to send the variables to the Arduino, but my Arduino sketch runs only for a second and then stops. But if I put the `ser.write()` command in a while loop (which I want to avoid) the sketch runs fine.

For example, I wrote this script on my PC -

```
import serial
ser = serial.Serial('COM3',9600)
counter = 'Y'
ser.write(counter)

```

This script should pass a "Y" to the Arduino and should stop executing.

My Arduino code-

```
int flag = 0;
void setup() {
   Serial.begin(9600); // set the baud rate
   Serial.println("Ready"); // print "Ready" once
   pinMode(13, OUTPUT);
}

void loop() {
   char inByte = ' ';
   if(Serial.available()){
      inByte = Serial.read(); // read the incoming data
      Serial.println(inByte);
      flag ++;
   }
   if(flag == 1){
      digtalWrite(13, HIGH);
   }
}

```

Now according to me the Arduino should receive the data and increment the flag variable to 1. Next the program checks whether flag is one and if it is turns the onboard LED on. However when I run the python script, the onboard LED flashes for just a second and then goes blank. I again have to run the python script to make it light up or I have to put `ser.write` in a loop. I can't put `ser.write` in a loop as my script won't run further.

So how can a value be passed to an Arduino without having to put the `ser.write()` in a loop.

Thanks!

**EDIT :**

I wrote a new sketch, but it still doesn't work. Here's the sketch -

```
int ledPin = 13;
char data = ' ';

void setup(){
   pinMode(ledPin, OUTPUT);
   Serial.begin(9600);
}

void loop(){
   if (Serial.available()>0) {
      data = Serial.read();
   }
   if (data == 'Y'){
      digitalWrite(ledPin, HIGH);
   }
   delay(500);
}

```

Here's an image of the wiring -

# Answer
Just put a 10 µF capacitor between the 5v and RESET pins of your Arduino and do whatever you want, just make sure that the capacitor is connected after the board has been powered up, and also, remove the capacitor before uploading any code.
> 0 votes

---
Tags: arduino-uno, serial, sketch, python, windows
---


# Question
Title: I just fried my Arduino on a breadboard. Can I still use the breadboard?
So, I just fried my arduino nano on a breadboard. Can I still use the breadboard and usb cable?

# Answer
It really depends on the circumstances around its demise. If it went out in smoke and flames, maybe not. Assuming the chip quietly overheated and died, the breadboard and the cable are almost certainly ok. Either of them will stand more abuse than the chip will. What was the cause of failure?
> 0 votes

# Answer
you can test the breadboard if you have a multimeter. Even if you don't, you can place an LED, a resistor and a power source across the suspect portions of the breadboard. If you locate a trace or two that appear unreliable, you should be able to mark them appropriately and continue to use the board.
> 1 votes

---
Tags: arduino-nano
---


title: ADC timer interrupt when ready

text:
# Question
Title: ADC timer interrupt when ready
I have a microphone and I need as precise values as possible. I have been told by my teacher, that it is somehow possible to make a ADC timer interrupt, which would interrupt always when the value is ready, so that the reading itself would not slow the program down.
I know, how to use timer interrupts to read the analog value every other ms or something and I even have a code that lets the ADC read automaticly and takes the value, but I need to make it take the value always when it's ready, so that I would have every value the ADC read. I tried to look into the datasheet, but it's too complicated for me.
How can I achieve such thing? I am using arduino uno.

this is the code I have that sets up the ADC interrupt:

```
  ADCSRA = 0;
  ADCSRB = 0;
  ADMUX = 0;
  ADMUX |= (1 << REFS0) + (1 << REFS1);
  ADMUX |= (1 << ADLAR);

  ADCSRA |= (1 << ADATE); //enabble auto trigger
  ADCSRA |= (1 << ADIE); //enable interrupts when measurement complete
  ADCSRA |= (1 << ADEN); //enable ADC
  ADCSRA |= (1 << ADSC);
  ADCSRA |= 0b010;

ISR(ADC_vect) {//when new ADC value ready
  af = af + ADCH;
  aaf++;
}

```

I found this on the internet, but it didn't work as I expected.

# Answer
> I have been told by my teacher that it is somehow possible to make a ADC timer interrupt.

You might have asked him or he could explain it ;)

Generally, if you want to do anything with an Arduino, which isn't implemented by the Arduino libraries, you're going to have to roll your own code (or copy it from the internet).

The answer from Nick will most certainly be enough to help you with the problem. However, it'd be way more cooler to find out how you can solve these problems yourself.

**Getting started**

I couldn't find a duplicate of this question, though it's a rather common question. You should've checked some of the tutorials on the web, it'll get you started a lot faster.

But don't forget the datasheet and manuals of the ATMega328(P). In case you can't really find something that fits your needs, or if you want to check some background information.

**Setting registers (ADC)**

This piece of code (from Nick Gammon), sets up the ADC.

```
  ADCSRA =  bit (ADEN);                      // turn ADC on
  ADCSRA |= bit (ADPS0) |  bit (ADPS1) | bit (ADPS2);  // Prescaler of 128
  ADMUX  =  bit (REFS0) | (adcPin & 0x07);    // AVcc and select input port

```

Fair enough, but if you wanted to change anything of it, you'll think: "How did he ever come up with this."

These are the registers of the microcontroller. By setting bits in the right pattern, you can enable/disable functions or change settings of the microcontroller.

You should download the ATMega328(P) datasheet. You can very easily navigate through it (if you've got a PDF reader that supports "bookmarks").

Check for "24. Analog to Digital converter" you should read through it, and go to "24.9 (Analog to Digital converter) - Register description.".

Here you can see, which bits of (in example) the `ADCSRA` register you have to set to enable the adc (`ADEN`), start the conversion (`ADSC`). And enable interrupts for it (`ADIE`).

**Interrupts**

Since you also want behavior that has to do with interrupts. You should also check out the interrupts bookmark (#12). 12.1 will show you an table with all interrupt vectors.

It's quite a shame that they don't have a nice C example code, they do have an reference manual though, but you'll implement an interrupt handler like this (from Nick Gammon).

```
// ADC complete ISR
ISR (ADC_vect)
  {
  adcReading = ADC;
  adcDone = true;
  }  // end of ADC_vect

```

If you now want to interrupt on SPI you can check the datasheet or reference manual for the vector name. (`SPI_STC_vect`)
> 0 votes

# Answer
> it is somehow possible to make a ADC timer interrupt

The ADC and the timers are two different things. If you mean a timer interrupt, I'm not sure why you would want that. If you mean an ADC interrupt, yes you can do do that.

Here is some example code from my page about the ADC which shows using the interrupt (on a Uno):

```
const byte adcPin = 0;
volatile int adcReading;
volatile boolean adcDone;
boolean adcStarted;

void setup ()
{
  Serial.begin (115200);
  ADCSRA =  bit (ADEN);                      // turn ADC on
  ADCSRA |= bit (ADPS0) |  bit (ADPS1) | bit (ADPS2);  // Prescaler of 128
  ADMUX  =  bit (REFS0) | (adcPin & 0x07);    // AVcc and select input port

}  // end of setup

// ADC complete ISR
ISR (ADC_vect)
  {
  adcReading = ADC;
  adcDone = true;
  }  // end of ADC_vect

void loop ()
{
  // if last reading finished, process it
  if (adcDone)
    {
    adcStarted = false;

    // do something with the reading, for example, print it
    Serial.println (adcReading);
    delay (500);

    adcDone = false;
    }

  // if we aren't taking a reading, start a new one
  if (!adcStarted)
    {
    adcStarted = true;
    // start the conversion
    ADCSRA |= bit (ADSC) | bit (ADIE);
    }

  // do other stuff here

}  // end of loop

```

---

I should point out that if you do an `analogRead` it **blocks** until the read is done, so the very next line to be executed after `analogRead` will be when the data is ready.
> 1 votes

---
Tags: interrupt, adc
---


title: MPU6050 code explanation

text:
# Question
Title: MPU6050 code explanation
I'm new to arduino and electronics. I've been trying to use the MPU6050 with my arduino but I'm having difficulty understanding the code. I'm referring to the code put up on the arduino website (http://playground.arduino.cc/Main/MPU-6050#short). Is there any way I could get a line by line explanation of the code?

# Answer
I've added in a bunch of comments for you:

```
// MPU-6050 Short Example Sketch
// By Arduino User JohnChi
// August 17, 2014
// Public Domain
#include<Wire.h>
const int MPU_addr=0x68;  // I2C address of the MPU-6050
int16_t AcX,AcY,AcZ,Tmp,GyX,GyY,GyZ; // declare accellerometer and gyro variables
void setup(){
  Wire.begin(); // initiate i2c system
  Wire.beginTransmission(MPU_addr); // be sure we talk to our MPU vs some other device
  Wire.write(0x6B);  // PWR_MGMT_1 register
  Wire.write(0);     // set to zero (wakes up the MPU-6050)
  Wire.endTransmission(true); // done talking over to MPU device, for the moment
  Serial.begin(9600); // initialize serial port to 9600 bps so you can see your debug messages in Arduino IDE via debug channel
}
void loop(){ // main program loop
  Wire.beginTransmission(MPU_addr); // get ready to talk to MPU again
  Wire.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
  Wire.endTransmission(false); // done talking to MPU for the time being
  Wire.requestFrom(MPU_addr,14,true);  // request a total of 14 registers
  // all the fancy <<8| stuff is to bit shift the first 8 bits to
  // the left & combine it with the next 8 bits to form 16 bits
  AcX=Wire.read()<<8|Wire.read();  // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
  AcY=Wire.read()<<8|Wire.read();  // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
  AcZ=Wire.read()<<8|Wire.read();  // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
  Tmp=Wire.read()<<8|Wire.read();  // 0x41 (TEMP_OUT_H) & 0x42 (TEMP_OUT_L)
  GyX=Wire.read()<<8|Wire.read();  // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
  GyY=Wire.read()<<8|Wire.read();  // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
  GyZ=Wire.read()<<8|Wire.read();  // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L)
  // the above lines have gathered Accellerometer values for X, Y, Z
  //  as well as Gyroscope values for X, Y, Z

  Serial.print("AcX = "); Serial.print(AcX); // share accellerometer values over debug channel
  Serial.print(" | AcY = "); Serial.print(AcY);
  Serial.print(" | AcZ = "); Serial.print(AcZ);
  Serial.print(" | Tmp = "); Serial.print(Tmp/340.00+36.53);  //equation for temperature in degrees C from datasheet
  Serial.print(" | GyX = "); Serial.print(GyX); // share gyroscope values over debug channel
  Serial.print(" | GyY = "); Serial.print(GyY);
  Serial.print(" | GyZ = "); Serial.println(GyZ);
  delay(333); // delay a bit to not overwhelm you the user/programmer as you view the results
}

```
> 2 votes

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