# Question
Title: Problem with inaccurate delays between sensor readings
During the last two months I have been working on a project that consists of using a Seeeduino Stalker V2.3, two AM2305 sensors, a TSL2561 sensor, an HC-05 XBee module, a 1,800 mAh 3.7V LiPo, a 7 cm x 7 cm 5V solar cell, and a waterproof suction box, to assemble a portable and waterproof environmental data logger that can be used to take samples on a continuous basis (1 sample every 30 minutes, 48 samples per day).

After struggling to make my logger work, I finally did it last week. It all runs fine, except that the intervals between readings are incorrect. When I program my board to store samples every 30 minutes (1,800,000), it takes them every 30 minutes and some extra seconds. When I try the same but with a rate of 1 sample every 10 seconds, my device logs data every 13 seconds more or less...

Here is the code I have been using:

```
#include "SPI.h"
#include "Wire.h"
#include "SD.h"
#include "DS3231.h"**

DS3231 clock;
RTCDateTime dt;

#include "DHT.h"

#define DHTPIN 8
#define DHTTYPE DHT21
DHT dht1(DHTPIN, DHTTYPE);
#define DHTPIN2 7
DHT dht2(DHTPIN2, DHTTYPE);
#include "TSL2561.h"
TSL2561 tsl(TSL2561_ADDR_FLOAT);

const int chipSelect = 10;
int XBEE = 5;
int FLASH = 4;

void setup() {
  pinMode(5, OUTPUT);
  digitalWrite(XBEE, HIGH);
  Serial.begin(9600);
  Wire.begin();
  clock.begin();
  analogReference(INTERNAL);
  pinMode(10, OUTPUT);
  pinMode(4, INPUT);
  SD.begin(10);
  dht1.begin();
  dht2.begin();
  Serial.println("EcoLOGGER DE PRUEBA PARA GENERACION DE DATOS ...");
  Serial.println(" ");
  delay(3000);
  Serial.println("RECUERDA QUE ESTE PROYECTO NO HUBIERA SIDO POSIBLE SIN LA AYUDA DE LA COMUNIDAD ARDUINO...");
  Serial.println(" ");
  delay(3000);
}

int counter = 0;

void loop() {
  float h = dht1.readHumidity();
  float t = dht1.readTemperature();
  float f = dht1.readTemperature(true);
  float h2 = dht2.readHumidity();
  float t2 = dht2.readTemperature();
  float f2 = dht2.readTemperature(true);
  dt = clock.getDateTime();
  if (tsl.begin()) {
  } else {
    while (1);
  }
  tsl.setGain(TSL2561_GAIN_0X);
  tsl.setTiming(TSL2561_INTEGRATIONTIME_402MS);
  uint16_t x = tsl.getLuminosity(TSL2561_FULLSPECTRUM);
  uint32_t lum = tsl.getFullLuminosity();
  uint16_t ir, full;
  ir = lum >> 16;
  full = lum & 0xFFFF;
  float vis = full-ir;
  Serial.print("Muestreo: ");
  Serial.println(counter);
  Serial.print("Fecha: ");
  Serial.print(dt.day);
  Serial.print('/');
  Serial.print(dt.month);
  Serial.print('/');
  Serial.println(dt.year);
  Serial.print("Hora: ");
  Serial.print(dt.hour);
  Serial.print(':');
  Serial.print(dt.minute);
  Serial.print(':');
  Serial.println(dt.second);
  Serial.print("Temperatura sistema: ");
  Serial.print(clock.readTemperature());
  Serial.println("*C ");
  Serial.print("Voltaje bateria: ");
  Serial.print(analogRead(A7) * (1.1 / 1024)* (10+2)/2);
  Serial.println(" V ");
  Serial.print("Carga bateria: ");
  Serial.print(-149.4 + 59.52 * (analogRead(A7) * (1.1 / 1024)* (10+2)/2));
  Serial.println("% ");
  Serial.print("Luz FULL: ");
  Serial.println(full);
  Serial.print("Temperatura ambiente: ");
  Serial.print(t);
  Serial.println(" *C ");
  Serial.print("Humedad relativa: ");
  Serial.print(h);
  Serial.println("%");
  Serial.print("Temperatura suelo: ");
  Serial.print(t2);
  Serial.println(" *C ");
  Serial.print("Humedad suelo: ");
  Serial.print(h2);
  Serial.println("%");
  Serial.println(" ");
  digitalWrite (FLASH, HIGH);
  File dataFile = SD.open("datalog.txt", FILE_WRITE);
  if (dataFile) {
    dataFile.print(" Muestreo: ");
    dataFile.print(counter);
    dataFile.print(",");
    dataFile.print(" Fecha: ");
    dataFile.print(dt.day);
    dataFile.print('/');
    dataFile.print(dt.month);
    dataFile.print('/');
    dataFile.print(dt.year);
    dataFile.print(",");
    dataFile.print(" Hora: ");
    dataFile.print(dt.hour);
    dataFile.print(':');
    dataFile.print(dt.minute);
    dataFile.print(':');
    dataFile.print(dt.second);
    dataFile.print(",");
    dataFile.print(" Temperatura sistema: ");
    dataFile.print(clock.readTemperature());
    dataFile.print("*C ");
    dataFile.print(",");
    dataFile.print(" Voltaje bateria: ");
    dataFile.print(analogRead(A7) * (1.1 / 1024)* (10+2)/2);
    dataFile.print(" V ");
    dataFile.print(",");
    dataFile.print(" Porcentaje carga: ");
    dataFile.print(-149.4 + 59.52 * (analogRead(A7) * (1.1 / 1024)* (10+2)/2));
    dataFile.print("% ");
    dataFile.print(",");
    dataFile.print(" Luz FULL: ");
    dataFile.print(full);
    dataFile.print(",");
    dataFile.print(" Temperatura ambiente: ");
    dataFile.print(t);
    dataFile.print(" *C ");
    dataFile.print(",");
    dataFile.print(" Humedad relativa: ");
    dataFile.print(h);
    dataFile.print("%");
    dataFile.print(",");
    dataFile.print(" Temperatura suelo: ");
    dataFile.print(t2);
    dataFile.print(" *C ");
    dataFile.print(",");
    dataFile.print(" Humedad suelo: ");
    dataFile.print(h2);
    dataFile.print("%");
    dataFile.println("");
    dataFile.close();
    digitalWrite (FLASH, LOW);
  } else {
    Serial.println("");
    Serial.println("IMPOSIBLE GUARDAR DATOS");
    Serial.println("");
  }
  counter++;
  if (counter > 5) {
    delay (1000);
    digitalWrite (XBEE, LOW);
    delay (1799000);
  } else
    digitalWrite (XBEE, HIGH);
  delay (10000);
}

```

I have been trying to find possible solutions, but I am just lost. Do any of you have an idea of what could be going on?

Thank you in advance :)

# Answer
The problem is that you are using `delay()`.

`delay()` will wait, from the moment `delay()` is called, for the given number of milliseconds.

That is, in more structured terms:

1. Do something
2. Do something else
3. Do something more
4. Wait 30 minutes

That will only take precisely 30 minutes if steps 1 to 3 take absolutely no time at all. And that will never be the case. Things take time. Reading from sensors, writing to SD cards, etc, all take time.

So waiting for 30 minutes between doing things means that every 30 minutes will be slightly later than the one before.

And as you saw the difference is more pronounced when you have 10 seconds instead - it ends up as 13 seconds. So your other actions - reading from sensors, writing to SD card, etc, must be taking about 3 seconds each time.

So instead of "Stop everything for half an hour", you need to think slightly differently:

1. Look at the time.
2. Decide if 30 minutes have passed since the last time you ran the code
3. Remember the time so you can know when 30 minutes have elapsed next time
4. Do your sensor/SD actions.

Since you're now keying things happening on the difference between now and when you last *started* to do things you get a 30 minute *total* delay, rather than a 30 minute delay *plus other bits*.

For an example of how this is done programatically you can look at the *BlinkWithoutDelay* example in the Arduino IDE.
> 3 votes

# Answer
The second problem is that delay() on the arduino uses the on-board clock cycle. This is powered by a resonator, which can be off by as much as 10%. If you need accurate timings and timestamps, you will want to use a Real-Time Clock (RTC) module.

Instead of using delay, the loop() asks the RTC what time it is, and uses that to determine if it's time to take another reading.

Another very common thing for this type of monitoring is for the arduino to go into sleep mode and be woken by a tick from the RTC every second (or longer), in order to extend the battery life.
> 2 votes

---
Tags: code-optimization
---


# Question
Title: How to run 5 wires hibrid stepper motor with arduino uno?
I have a question. How to run stepper motor (Nema 17) that has 5 wires with arduino and stepper driver. Here is the driver, stepper and Arduino when stepper has 4 wires. http://jdreyer.com/projects/Arduino/ArduinoEasyDriverStepperMotorv1\_Resize.png

I need help identifying the wires on my hibrid stepper motor. I will provide picture of dissasembled motor.

Questions are:

1. Wires identification?
2. How to connect it to ArduinoEasyDriver?
3. Code example desired.

**UPDATE**

> I am now thinking of making it bipolar (4 wires), because now in 5 wires configuration motor is unipolar. I did some research and this motor is HIBRID. It can be driven as unipolar or bipolar. I will try to troubleshoot the wiring and find the common wire. Ill keep you informed.

# Answer
> 3 votes
1) it is probably something like A1, A2, Common, B1, B2. You could confirm this with an ohmmeter. Common to any of the others would be a certain resistance X, while between any of the others (A1-A2, B1-B2, A1-B1, A1-B2, B1 A2) would be 2X.

2) You can't. It is a unipolar stepper.

The EasyDriver faq number 5.1 at http://www.schmalzhaus.com/EasyDriver/ says: "... The only kind you can't use is 5-wire stepper motors. (They need uni-polar drivers.)"

The difficulty with the 5-wire steppers is that they short the middle of the two coils together, which makes it hard to drive the coils independently.

Since you have the motor open, you might be able to do some surgery and disconnect the centers of the coils from each other, but you'll probably be better off getting a 4, 6 or 8 wire stepper instead.

# Answer
> 2 votes
On stepper motors there are a few types of wiring, but essentially there are two coils inside the stepper motor. To figure out where the wiring is you need a way to test if the coils are being connected. On your setup I would suggest to connect two of the wires together at a time and spin the shaft. If the shaft offers resistance then you have found the two wires for one coil.

For your stepper motor it looks like it may have three coils, but out of the 6 wires you may also only come up with 4 wires; which would equal 2 coils.

As far as connecting it to an easy driver, the easy driver only takes two coils. you would need to find a driver that can take three coils, or just connect two coils out of the three and hope for the best.

# Answer
> 1 votes
**Finding the ground pin**

We should start off by finding the Ground/GND pin.

Do you have an Ohm-meter? I believe one of the pins should be GND/ground, and should have low resistance when referenced to the other pins.

**Wiring the stepper**

Steppers have a coil and thus are an inductive load, you should really check your wiring with sources, to be sure they're valid. (At this point I can't give you a 100% accurate wiring diagram, but it should be easy to find, as wiring steppers is quite common.) You could use a pre-assembled stepper-driver. Having such a thing is usefull when you want to design the circuitry yourself.

**Driving the steppers**

You should generate a signal like this: https://en.wikipedia.org/wiki/Stepper\_motor#Phase\_current\_waveforms

(The source/link describes the different forms of stepping. Like "Wave drive (one phase on)" in which each coil is activated/deactivated in a rotary fashion, making the core turn around.)

**Extra**

Adafruit always has extremely well documented tutorials for beginners: https://learn.adafruit.com/all-about-stepper-motors/types-of-steppers

The wiki of RepRap should be a good source, since steppers are the hearth of 3D printers (RepRap is a 3D printer brand): http://reprap.org/wiki/Stepper\_wiring

# Answer
> 1 votes
Instead of doing surgery on your unipolar stepper, you can use it like a unipolar stepper. Some transistors to hook the motor to power (just get a darlington array chip), and four output pins on the arduino. Works fine.

---
Tags: arduino-uno, motor, electronics, stepper
---


# Question
Title: Change Servo Speed With RedBearLabs BLE Shield
I recently got the RedBearLabs BLE shield to use it to control two high spped continuous rotation servos. I have the BLE example sketch loaded and the ios controller app works. The problem is that the servos are too fast to control and I want to slow them down. I cannot use the app to slow them down. I was wondering how I could modify the example sketch or servo library to change the ax speed or something. Thanks in advance.

BLE Shield Homepage: http://redbearlab.com/bleshield/

BLE Libraries and Example Sketch: https://github.com/RedBearLab/nRF8001

# Answer
> 2 votes
The bi-directional Parallax High Speed Continuous Rotation Servo responds to “simple pulse-width modulation”, according to its web page. That is, pulse widths in the range from about 500 μs to 2500 μs will set the speed and direction, with some value near 1500 μs corresponding to zero RPM.

The code in the BLEControllerSketch uses the following bits of code, among others, to initialize servo-control data structures and to control them:

```
#include <Servo.h>
...
byte pin_servo[TOTAL_PINS];
Servo servos[MAX_SERVOS];
...
      case 'O': // set Servo
        {
          byte pin = ble_read();
          byte value = ble_read();

          if (IS_PIN_SERVO(pin))
            servos[PIN_TO_SERVO(pin)].write(value);
          pin_servo[pin] = value;
          reportPinServoData(pin);
        }
        break;

```

Thus, you will need to send an `O` message from your iOS app, together with servo pin number and control value, to set a servo's speed.

As noted on the ServoWrite page at arduino.cc, the parameter to Servo's `.write()` method is a number:

> On a standard servo, this will set the angle of the shaft (in degrees), moving the shaft to that orientation. On a continuous rotation servo, this will set the speed of the servo (with 0 being full-speed in one direction, 180 being full speed in the other, and a value near 90 being no movement).

You can find out a little more by looking at Servo's `.write()` method in Servo.cpp:

```
void Servo::write(int value)
{
  if(value < MIN_PULSE_WIDTH)
  {  // treat values less than 544 as angles in degrees (valid values in microseconds are handled as microseconds)
    if(value < 0) value = 0;
    if(value > 180) value = 180;
    value = map(value, 0, 180, SERVO_MIN(),  SERVO_MAX());
  }
  this->writeMicroseconds(value);
}

```

`SERVO_MIN()` and `SERVO_MAX()` are macros that access `min` and `max` fields in a `Servo` object and convert them to microsecond values. Because the code in BLEControllerSketch.ino lets those fields default, the range evidently will be from 544 to 2400 μs (see the values given in Servo.h).

Note that you can get better resolution – hence, better speed control – by sending values in that range of microseconds to your servos, instead of trying to control it using values in degrees. The `.write()` method will interpret such numbers as microseconds instead of as degrees. Servo.cpp appears to use half-microsecond timer ticks; and each degree corresponds to about 10 μs of pulse width; so resolution using microsecond values should be about 10 times better than using degrees.

In short, it appears that you should do some experimenting with `O` messages that send values around 1500, to find the values that correspond to slowest forward and backward speeds.

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


# Question
Title: Send AND Receive through i2c / set Arduino as master AND slave
For a project I'm using 2 Arduino Uno's, where Arduino#1 (master) sends raw data to Arduino#2 (slave). The slave should receive and encrypt the data and afterwards send the encrypted data back to the master. I'm building my project from the sketch found at arduino.cc.

How can I make the slave send back data, if he's the only one listening on incoming data, should both arduinos be listening to each other, and how to achieve this?

# Answer
> 1 votes
The I2C protocol is both read and write. Master/Slave depends on who initiates the communication. Typically the master will issue a read command to the slave to retrieve the results.

Cheers!

---
Tags: arduino-uno, serial, i2c
---


# Question
Title: How to split a string received via a GSM module (message)
I am doing a motorcycle security system. In this system, I will receive a message from GSM in the form `{password:operation (like start,stop,alarm):time}`. Example:(9990:start:30)

now i need to split each term seperately (a=9990,b=start,c=30).help me to solve

# Answer
> 3 votes
Simplest solution is to use sscanf().

```
  int password;
  char operation;
  int time;
  char* buf = "{14:C:123}";
  int n = sscanf(buf, "{%d:%c:%d}", &password, &operation, &time);
  Serial.print(F("n="));
  Serial.println(n);
  Serial.print(F("password="));
  Serial.println(password);
  Serial.print(F("operation="));
  Serial.println(operation);
  Serial.print(F("time="));
  Serial.println(time);

```

---
Tags: string
---


# Question
Title: how to solve Varing duty cycle value while using Pulsein()
Well im new to coding, but i do have the basic knowledge. I'm using an UNO to measure a duty cycle. The source of pulse is a Tektronic signal generator (Duty cycle set to 50.000 with frequency of 2khz). my code is as follows,

```
byte PWM_PIN = 3;
float pwm_value_H;
float pwm_value_L;
float D;

void setup() {
    pinMode(PWM_PIN, INPUT);
    Serial.begin(115200);
}

void loop() {
    pwm_value_H = pulseIn(PWM_PIN, HIGH);
    Serial.println(pwm_value_H);
    pwm_value_L = pulseIn(PWM_PIN, LOW);
    Serial.println(pwm_value_L);
    D = ((pwm_value_H) / (pwm_value_H + pwm_value_L)) * 100.0;
    Serial.print("D=");
    Serial.println(D);
    Serial.print("D=%");
}

```

but the problem is that my output value of "D" keeps on varying between 49.71, 49.90, 50.00 and 50.7 Is this because of PULSEIN() function ineffiency? or can anyone suggest a better way to measure the duty cycle with +/- 0.01 accuracy.

Regards, Cj

# Answer
> 2 votes
I would start by removing Serial interrupts from the pulseIn period.

```
void loop() {
    pwm_value_H = pulseIn(PWM_PIN, HIGH);
    pwm_value_L = pulseIn(PWM_PIN, LOW);
    Serial.println(pwm_value_H);
    Serial.println(pwm_value_L);
    D = ((pwm_value_H) / (pwm_value_H + pwm_value_L)) * 100.0;
    Serial.print("D=");
    Serial.println(D);
    Serial.print("D=%");
    Serial.flush();
}

```

For higher accuracy I would then look to the Timer based Input Capture.

Cheers!

# Answer
> 2 votes
There's two basic things wrong with what you are doing there:

1. `pulseIn()` isn't good for very accurate measurements
2. The signal is still happening while you're doing other things, such as printing the high/low times.

You're not actually measuring the duty cycle of one single cycle, but the HIGH time of one cycle followed by the low cycle of a later one. If you want to do it properly you will have to ditch `pulseIn()` and instead get your head around interrupts and timestamps.

The basic method is to present the signal to one of the INT pins, and attach an interrupt to that pin with the trigger set to CHANGE. The interrupt routine you specify will then be triggered every time the signal changes from HIGH to LOW or from LOW to HIGH.

Then the interrupt routine does very little. It basically records the time the interrupt happened (that must be the very first thing you do), then looks to see if it's a HIGH or a LOW signal on the pin. You then use the previous timestamp from the last time the interrupt was triggered to work out how long the previous phase lasted and set either a HIGH or a LOW variable depending on the current level of the state (if it's low set a high variable since that was the previous phase level, and if it's high set a low variable) with the time that phase lasted.

Then in your main loop you interrogate those variables periodically to display the duty cycle.

If that still isn't accurate enough then you should look at the hardware *Input Capture* module built into the MCU. That uses a hardware timer in much the same way as the interrupt but is able to capture a much more accurate time stamp for you since the time stamp is grabbed the moment the signal changes, rather than after a short delay once the interrupt routine has been called. Details can be found in the datasheet for the MCU on your Arduino.

---
Tags: arduino-uno, pwm, pulsein
---


# Question
Title: Pro Micro clone worked fine, now RxLED stays on and can't program it
I have burned out a few Pro Micro clones now. Initially I ran them using a 12VDC external raw power supply but two Pro Micro clones burned out pretty quickly this way. Another thread suggested that the Pro Micro clones use regulators that are not very robust. Since then, I've been using just USB power for my 5V/16MHz Pro Micro clones.

The third clone has been working fine on USB power only. I estimate that I uploaded a sketch I was working on about a dozen times. Suddenly the RxLED stayed lit and I can't upload to it anymore.

When I plug it in, Windows assigns a COM port successfully. The Arduino IDE sees the port and I can select it. This tells me the Pro Micro is not entirely dead. When I enable verbose mode for uploading in the Arduino IDE, here's what I get:

```
Sketch uses 3,914 bytes (13%) of program storage space. Maximum is 28,672 bytes.
Global variables use 148 bytes (5%) of dynamic memory, leaving 2,412 bytes for local variables. Maximum is 2,560 bytes.
Forcing reset using 1200bps open/close on port COM3
PORTS {COM3, } / {COM3, } => {}
[repeating 19 more times]
Uploading using selected port: COM3
C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avrdude -CC:\Users\Bartman\AppData\Local\Arduino15\packages\SparkFun\hardware\avr\1.1.2/avrdude.conf -v -patmega32u4 -cavr109 -PCOM3 -b57600 -D -Uflash:w:C:\Users\Bartman\AppData\Local\Temp\buildb15cf522f4023b15f86cbd1c900761d6.tmp/sketch_feb15a.ino.hex:i

avrdude: Version 6.0.1, compiled on Apr 15 2015 at 19:59:58
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2009 Joerg Wunsch

         System wide configuration file is "C:\Users\Bartman\AppData\Local\Arduino15\packages\SparkFun\hardware\avr\1.1.2/avrdude.conf"

         Using Port                    : COM3
         Using Programmer              : avr109
         Overriding Baud Rate          : 57600
         AVR Part                      : ATmega32U4
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PA0
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    20     4    0 no       1024    4      0  9000  9000 0x00 0x00
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0x00 0x00
           lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : butterfly
         Description     : Atmel AppNote AVR109 Boot Loader

Connecting to programmer: .

```

and after some time:

```
avrdude: butterfly_recv(): programmer is not responding
Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

```

On my working Pro Micro clone, I get the following after instead:

```
Found programmer: Id = "CATERIN"; type = S
    Software Version = 1.0; No Hardware Version given.
Programmer supports auto addr increment.
Programmer supports buffered memory access with buffersize=128 bytes.

Programmer supports the following devices:
    Device code: 0x44

avrdude: devcode selected: 0x44
avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% -0.00s

avrdude: Device signature = 0x1e9587
avrdude: reading input file "C:\Users\Bartman\AppData\Local\Temp\buildb15cf522f4023b15f86cbd1c900761d6.tmp/sketch_feb15a.ino.hex"
avrdude: writing flash (3914 bytes):

Writing | ################################################## | 100% 0.30s

avrdude: 3914 bytes of flash written
avrdude: verifying flash memory against C:\Users\Bartman\AppData\Local\Temp\buildb15cf522f4023b15f86cbd1c900761d6.tmp/sketch_feb15a.ino.hex:
avrdude: load data flash data from input file C:\Users\Bartman\AppData\Local\Temp\buildb15cf522f4023b15f86cbd1c900761d6.tmp/sketch_feb15a.ino.hex:
avrdude: input file C:\Users\Bartman\AppData\Local\Temp\buildb15cf522f4023b15f86cbd1c900761d6.tmp/sketch_feb15a.ino.hex contains 3914 bytes
avrdude: reading on-chip flash data:

Reading | ################################################## | 100% 0.04s

avrdude: verifying ...
avrdude: 3914 bytes of flash verified

avrdude done.  Thank you.

```

On the now non-functional one, I tried using a jumper from RST to GND, tapping this twice quickly in succession and uploading from the IDE in an attempt to recover the Pro Micro but this doesn't work.

I don't think it's a bootloader problem since the Pro Micro does get a COM port assigned to it but never-the-less, I tried burning a new bootloader from my working Pro Micro. Here's my Pro Micro to Pro Micro wiring:

In the IDE, I've selected:

> Board: SparkFun Pro Micro
> Processor: ATmega32U4 (5V, 16 MHz)
> Port: \[current COM port of working Pro Micro\]
> Programmer: Arduino as ISP

But when I select `Tools->Burn Bootloader`, I get the following error:

```
Arduino: 1.6.7 (Windows 10), Board: "SparkFun Pro Micro, ATmega32U4 (5V, 16 MHz)"

C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avrdude -CC:\Users\Bart_S\AppData\Local\Arduino15\packages\SparkFun\hardware\avr\1.1.3/avrdude.conf -v -patmega32u4 -cstk500v1 -PCOM6 -b19200 -e -Ulock:w:0x3F:m -Uefuse:w:0xCB:m -Uhfuse:w:0xD8:m -Ulfuse:w:0xFF:m

avrdude: Version 6.0.1, compiled on Apr 15 2015 at 19:59:58
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2009 Joerg Wunsch

         System wide configuration file is "C:\Users\Bart_S\AppData\Local\Arduino15\packages\SparkFun\hardware\avr\1.1.3/avrdude.conf"

         Using Port                    : COM6
         Using Programmer              : stk500v1
         Overriding Baud Rate          : 19200
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x03
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x03
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x03
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x03
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x03
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x03
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x03
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x03
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x03
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x03

avrdude done.  Thank you.

Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

```

Is it permanently damaged? What are the next steps to troubleshoot this Pro Micro clone?

# Answer
> 1 votes
After many hours of unsuccessful bootloader reprogramming attempts, I was able to revive the Pro Micro by trying different timing of double tapping RST while the IDE was compiling/uploading a sketch. After several attempts the Pro Micro suddenly took a sketch and seems to be working now. Not sure how long it will stay this way or how often I will loose it and have to go through these shenanigans again.

Thanks to all for the help.

# Answer
> 1 votes
To make things simpler, try flashing the Pro Micro firmware with another UNO (or compatible) hardware. I prefer an UNO clone with CH340 chip or a pro mini with a FTDI cable. Just to keep things simple.

Flash the UNO with Arduiono as ISP sketch. Use connection guidance from Arduino tutorial: Using an Arduino as an AVR ISP

Once this is done, AVRDUDE will see the source Arduino as **AVR ISP** and you can flash the firmware on the target Arduino.

You can also use this post for guidance as well.

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


# Question
Title: At what level does low dynamic memory effect performance?
I have a few Arduino sketches that take 70-90% of dynamic memory. It seems that over 70%, the compiler gives the warning:

```
Low memory available, stability problems may occur.

```

but otherwise I wasn't noticing any problems.

Then I uploaded a sketch that took 89%, which logged String data to the serial port, and found that only newlines were being written out. When I commented out some global variables so that dynamic memory usage got to 88%, then it started printing out the data.

Is there any hard/fast rule on when this problem occurs? I was surprised by this problem, because the global variables I removed weren't even being used in the sketch, so I had thought the compiler would have removed or optimized them so they didn't waste any space. Are there any ways to automatically improve compilation efficiency and detect wasteful variables?

# Answer
The typical build memory statistics is:

```
Global variables use XXX bytes (X%) of dynamic memory,
leaving YYY bytes for local variables.
Maximum is ZZZ bytes.

```

What is all this about? First, the maximum number of bytes SRAM depends on the MCU. Arduino Uno is ATmega328 based and has 2K byte SRAM. Arduino Mega2560 has 8K byte. "Dynamic memory" in the print out is SRAM. It is not the heap (malloc/free). To avoid confusion I will use "data memory" below.

The compiler allocates memory for all global variable (objects, struct, etc). It also allocates memory for literal strings (character vectors). These are copied from program memory to data memory at startup. All static variables in functions are also allocated. The sum of all these allocations are the "Global variables".

To execute the sketch data memory is used for the stack. It contains the function parameters, local variables in called functions (that are not allocated to registers), saved registers such as return address to the caller, etc. The size of the frame is known by the compiler and may be found in the assembly listing of a sketch. The maximum stack size required is tricky to calculate as it is the call chain with the largest frame size sum. This is not necessarily the deepest call chain. Also the compiler does to a fair amount of inlining.

The heap (malloc/free) is used by classes such as String. The heap starts directly after the global variables in data memory and grows towards the stack. The heap is blocks of memory allocated and deallocated during the execution of the sketch. This behavior may give heap fragmentation.

Interrupt Service Routines (ISR) need to be able to execute "on top of" any function call. The ISRs are typically called on hardware events such as USART data received. The compiler has to generate code that stores the machine state on stack to execute the ISR. Depending on how many registers the ISR needs more or less of the machine state (registers) need to be stored. The worst case is all 32 registers.

The warning at 30% of SRAM is at approx. 600 bytes left (Arduino Uno, 2K byte). That has to cover the stack and possible heap usage together with ISRs. With a stack heap limit of 32-128 byte, ISR frame of 32-64 byte, that actually leaves worst case approx. 400 bytes for local variables in functions and possible usage of the heap (such as String).

Cheers!
> 4 votes

# Answer
The problems occur when you run out of memory. That all depends on what you are doing with the memory that is available.

String objects are not good and are wasteful of memory. They really should be avoided, since they use dynamic memory allocation, which uses the "spare" memory that is what's left over from what the compiler says is used.

There is no rule, other than "don't run out of memory", and tracking dynamic usage can be very hard, so try to avoid using it if you can.
> 1 votes

---
Tags: memory-usage
---


title: Arduino Due with Atmel Studio 7

text:
# Question
Title: Arduino Due with Atmel Studio 7
I was trying to switch to Atmel Studio for programming my Due project since it became more and more complex. I managed to use the Arduino Importer Wizard to load a blink.ino file and included all the requested libraries more or less my hand that were marked as missing during compiling. Now the compiling kind of works, but I still get this error:

```
Error       (inkerScript): No such file or directory    ECU arm-none-eabi-g++.exe   0

```

The `(inkerScript):` part is no typo. It is really like this in the console. Taking a look in the Toolchain Options I have these settings (which I am not able to edit):

Going into the Miscellaneous Part of the Options I can edit these fields:

By editing the Linker Flags field, I can change the error message from `(inkerScript): No such file or directory` to e.g. `HelloWorld: No such file or directory`.

Is there anything wrong with my options? What is the correct setting for "Linker Flags" and what are they doing?

Unfortunately I am not a pro with C++ Compiling / Linker Errors / Settings.

Thanks.

# Answer
I just encountered this. After looking at other examples in the compiler command line options, it looks like it should be $(LinkerScript) instead of ($LinkerScript).

In Atmel Studio, go to project properties, toolchain, ARM/GNU Linker, Miscellaneous to find the option to change.
> 1 votes

---
Tags: c++, arduino-due, atmel-studio
---


# Question
Title: Does the VCC Output pin always give out a consistent 5V Voltage supply? What is the current output?
Does the VCC Output pin always give out a consistent 5V Voltage supply? What is the current output?

This is the Chip I have. On the chip it says ProMini R160JAC6v. and When i program it. It programs under 5V 16MHz with ATmega 328

Here is the bluetooth chip I am powering:

# Answer
If you power from USB the vcc pin gives you the voltage that USB is providing. Somewhere between 4.75 and 5.25v.

If you use external power it provides 5v since that is what the regulator provides.

The current limit is either the limit of the usb port or the limit of the regulator on your board. Check the datasheet for that regulator (hint: read the schematic to find the model of the regulator).
> 1 votes

---
Tags: power, atmega328
---


# Question
Title: Is RX1 and TX0 the same thing as TX and RX? Will there be a difference in the way I program it?
I have an Arduino.

I'm not sure if RX1 and TX0 the same thing as TX and RX? Will there be a difference in the way I program it?

For example, do I treat RX1 and TX0 as RX and TX in the Arduino IDE when coding?

This is the chip I have. On the chip it says "ProMini R160JAC6v" and when I program it, it programs under 5V 16MHz with ATmega 328. Notice RST RX1 and TX0 are on the top left corner.

# Answer
> 5 votes
It's not RX1 and TX0 but RXI and TXO

That is receive input and transmit output,

Exactly the same as RX and TX just with the data direction explicitly shown in the lettering.

# Answer
> 1 votes
Yes you treat them the same, they are the same pins.

It looks like (in the photo) you're connecting a bluetooth module. Be careful when uploading your sketch. If you connect something to TX/RX (pins 0 & 1) it may be necessary to disconnect it for arduino-uploading to work.

You may find it a more convenient solution to declare a SoftwareSerial on different ports and use that for the bluetooth communications.

---
Tags: pins, atmega328, port-mapping, coding-standards
---


title: Arduino Due Port Not Found

text:
# Question
Title: Arduino Due Port Not Found
I've got an arduino due and I'm having great difficulty connecting to it. The problem seems to come and go, I was using it just fine only 3 or 4 hours ago but now it just won't connect. I've got the board set to the Arduino Due Native Port and the port set to the /dev/cu.usbmodem1421 (Arduino Due Native Port). Every time I try and upload the sketch however, it gives me this error:

```
    Arduino: 1.6.6 (Mac OS X), Board: "Arduino Due (Native USB Port)"

Sketch uses 10,316 bytes (1%) of program storage space. Maximum is 524,288 bytes.
processing.app.debug.RunnerException
    at cc.arduino.packages.uploaders.SerialUploader.uploadUsingPreferences(SerialUploader.java:130)
    at cc.arduino.UploaderUtils.upload(UploaderUtils.java:78)
    at processing.app.Sketch.upload(Sketch.java:1178)
    at processing.app.Sketch.exportApplet(Sketch.java:1152)
    at processing.app.Sketch.exportApplet(Sketch.java:1124)
    at processing.app.Editor$DefaultExportHandler.run(Editor.java:2452)
    at java.lang.Thread.run(Thread.java:745)
Caused by: processing.app.SerialException: Error touching serial port '/dev/cu.usbmodem1421'.
    at processing.app.Serial.touchForCDCReset(Serial.java:87)
    at cc.arduino.packages.uploaders.SerialUploader.uploadUsingPreferences(SerialUploader.java:119)
    ... 6 more
Caused by: jssc.SerialPortException: Port name - /dev/cu.usbmodem1421; Method name - openPort(); Exception type - Port not found.
    at jssc.SerialPort.openPort(SerialPort.java:167)
    at processing.app.Serial.touchForCDCReset(Serial.java:81)
    ... 7 more
Error opening serial port '/dev/cu.usbmodem1421'. (Port not found)

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

```

# Answer
Not sure what all that was but a simple restart of my computer seemed to fix it.
> 0 votes

---
Tags: arduino-due
---


# Question
Title: What isthe best programming language for embedded systems?
I would start to learn the best programming language for embedded systems to control devices. What I have heard about that is Assembly Language. I want to know if there is any better languages to code for embedded systems?

# Answer
> 2 votes
Before your question gets closed:

**There is no such thing as "the best"**

**Assembly** Assembly can be a very powerful language. But at the cost of some:

**C** C can be as powerful as assembly, only when used correct. In fact, in C (and C++) you can actually inline assembly. https://en.wikipedia.org/wiki/Inline\_assembler

**C++** C++ is mostly backwards compatible with C, any C compiler (should?) be able to interpret/compile C code. Which also means you could use inline assembly.

C++ also comes with a lot of usefull tools, though, when used wrongly it can actually backfire you. (Which is with most programming languages that allow a lot, but also give you the possibility to do a lot)

I believe, that C++'s Object Oriented code, with the somewhat backward compatiblity and a little abstraction from the machine (being able to port it to other machines) would be the way to go. Though, a good C/assembly programmer will out-play an average C++ programmer.

**What about the other languages**

C/C++ could be considered as the standard for embedded devices.

Best thing would be, to ask for individual programming languages, and why one would be better than the other. Or what the differences are.

I havent yet found anything that could "compile" Java for embedded devices. Java typically runs in a "run-time evironment". Which would come down to the fact that it needs an OS or atleast some resources for the code to be run-time interpreted.

C/C++ is also known for being "hard real-time" or atleast deterministic qua timing. Which is probably because of the same reason, not needing another layer and being pre-compiled. (And not having an runtime environment)

By these arguments, I believe C++ or C or Assembly would be the best. Or atleast most widely accepted. You should check per project, which languages are known by your developers and which other requirements there are (porting to other platforms). And it's a bit of a taste issue. I think Object Oriented code is very usefull. But some may see it as excessive/annoying.

---
Tags: programming, home-automation, automatization
---


title: Iterate an Object Array

text:
# Question
Title: Iterate an Object Array
I'm trying to create an array of objects and later iterate over it and do something with each object. My C++ skills just don't go far enough.

Here's what I have so far. I've tried to strip out all the meaningless code. Whats wrong is my tr object is not what I expect it to be. It's numOfCars property is 0 so I know I'm not accessing the train object that I expected.

```
#include <stdlib.h>

class Train {
    public:
        int numOfCars;
        void init();
        void move();
};

void Train::init() {
    //code intentionally removed
}

void Train::move() {
    //code intentionally removed
}

const int trainCount = 2;
Train train1;
Train train2;
Train trains[trainCount] {train1, train2};

void setup() {
    Serial.begin(9600);
    train1.numOfCars = 5;
    train1.init();

    train2.numOfCars = 5;
    train2.init();
}

void loop() {
    for(int n = 0; n < trainCount; n++) {
        Train tr = trains[n];
        Serial.println(tr.numOfCars); //always prints 0
        tr.move();
    }
}

```

# Answer
You are not creating an array of references, you are creating the array from the objects; they are being copied. You can see that this by moving the line (and adding an equals)

```
Train trains[trainCount] = {train1, train2};

```

to the bottom of your setup method. However, that is beside the point, as you are not fully using the power of arrays. You needn't create separate objects everywhere, simply create an array of objects right off the bat with `new[]` and use them. Like this:

```
#include <stdlib.h>

class Train {
    public:
        int numOfCars;
        void init();
        void move();
};

void Train::init() {}
void Train::move() {}

const int trainCount = 2;
Train* trains = new Train[trainCount];

void setup() {
    // initialize trains
    for (int i = 0; i < trainCount; ++i) {
        trains[i].numOfCars = 5;
        trains[i].init();
    }
    Serial.begin(9600);
}

void loop() {
    for(int n = 0; n < trainCount; n++) {
        Serial.println(trains[n].numOfCars); //always prints 0
        trains[n].move();
    }
}

```
> 5 votes

# Answer
As uint128\_t has already put it, your problem is that you are creating an array of copies. You should really avoid copying trains around, especially if you are going to put a significant amount of data in them. Instead, just create them once in the array, and then you can either invoke them as array members directly (e.g. `trains[0].init();`) or use references.

For example, if you initialize your trains like this:

```
const int trainCount = 2;
Train trains[trainCount];
Train &train1 = trains[0];
Train &train2 = trains[1];

```

Then the "real" trains live in the array, and `train1` and `train2` are references to them. The rest of your code should work fine unchanged. I would however suggest to avoid copying the trains in loop:

```
void loop() {
    for(int n = 0; n < trainCount; n++) {
        Train &tr = trains[n];        // notice the '&'!
        Serial.println(tr.numOfCars);
        tr.move();
    }
}

```
> 2 votes

---
Tags: c++, array
---


title: Using Arduino IDE as an API

text:
# Question
Title: Using Arduino IDE as an API
I have a project where it would make a lot of sense to generate Arduino compatible source code, compile it and flash it based on some settings in the project software.

Is there any way to do this without having to rely on the user having installed the Arduino IDE/java?

The ideal would be a self-contained library that could be linked to my C/C++ program.

# Answer
Have you tried Arduino C Scaffold project?

> ...the scaffolding lives on Github in the Throw The Switch organization as the Arduino C Scaffold project. This should have everything you need to deploy a C project on an Arduino UNO without the Arduino IDE. If you know your way around Git, you can clone this repository and get to work. If you’d rather not mess with Git right now, you can download the latest revision of the scaffold in a zip file. Once you have the scaffold, take a look at the README. This will walk you through getting the AVR toolchain setup on your environment and describe some of the different ways to use the scaffold. -- https://spin.atomicobject.com/2011/10/15/taking-the-training-wheels-off-the-arduino/
> 1 votes

# Answer
For compiling and uploading Arduino code, you do not need Java, nor the Arduino IDE: you need avr-gcc, avr-libc, the Arduino core library and avrdude. With a proper Makefile, your program just needs to

```
system("make upload");

```

C.f. the tutorial Compiling Arduino sketches using Makefile. On an Ubuntu or other Debian-like OS, you would just `sudo apt-get install arduino-mk make` to get everything you need installed.
> 1 votes

---
Tags: c++, arduino-ide, compile, flash
---


title: Arduino Vending Machine problem

text:
# Question
Title: Arduino Vending Machine problem
Currently I'm working on a vending machine project. The vending machine works using 3 button on LCD Keypad Shield DFRobot where 1 button of it assigned as 0.10 cent,the other two 0.20 cent and 0.50 cent respectively. My problem here is how can my system keep track on the balance/coin inserted so that whenever I pressed `button 1 = balance 0.10` then later I pressed `button 2 = balance 0.30` (because 0.20 cent added to the system). Or if you have a better idea for my code, that should be great. This is my code so far:

```
    #include <LiquidCrystal.h>
    LiquidCrystal lcd(8, 9, 4, 5, 6, 7);
    int lcd_key     = 0;
    int adc_key_in  = 0;
    #define btnRIGHT  0
    #define btnUP     1
    #define btnDOWN   2
    #define btnLEFT   3
    #define btnSELECT 4
    #define btnNONE   5
    volatile float balance = 0.00;
    float number1 = 0.10;
    float number2 = 0.20;
    float number3 = 0.50;
    int read_LCD_buttons()
    {
    adc_key_in = analogRead(0);      // read the value from the sensor
    if (adc_key_in > 1000) return btnNONE;
    if (adc_key_in < 50)   return btnRIGHT;
    if (adc_key_in < 195)  return btnUP;
    if (adc_key_in < 380)  return btnDOWN;
    if (adc_key_in < 555)  return btnLEFT;
    if (adc_key_in < 790)  return btnSELECT;
    return btnNONE;
    }

    void setup()
    {
    lcd.begin(16, 2);
    lcd.setCursor(0,0);
    lcd.print("TouchNGo Machine");
    }

    void loop()
    {
    lcd.setCursor(0,1);
    lcd.print("Balance=");
    lcd.setCursor(10,1);
    lcd_key = read_LCD_buttons();
    balance = 0.00 ;

    switch(lcd_key)
    {
    case(btnLEFT):
    {
    balance = balance + number1  ;
    lcd.print("RM");
    lcd.println(balance);
    break;
    }
    case(btnRIGHT):
    {
    balance = balance + number2 ;

    lcd.print("RM");
    lcd.println(balance);
    break;
    }
    case(btnUP):
    {
    balance = balance + number3  ;
    lcd.print("RM");
    lcd.println(balance);
    break;
    }
    }
    }

```

I would love to hear any comment from you guys.Thanks for the help!

# Answer
> 1 votes
Remove "balance = 0.0;" from you main loop. It's always clearing your balance.

---
Tags: arduino-uno
---


# Question
Title: Dimmer on Due: digitalWrite on one pin affects digital value of another
I'm trying to make dimmer for heater using Arduino Due. I'm using a variant of this very common scheme:

My scheme has MOC3043 with zero-crossing detection.

I use two pins to control the dimmer: **detectorPin** to analyse input voltage wave and **controlPin** to drive optocoupler. The program is very simple thanks to zero-crossing MOC.

I attached an `interrupt` to the input **detectorPin** on `CHANGE` event. And **controlPin** is used as digital output. When I test detection with **controlPin** unplugged everything works fine. But when **controlPin** is connected, value which is read inside the interrupt becomes wrong! So my dimmer cannot detect any half-wave and reports errors. This happens at the moment when **controlPin** value is set to `HIGH` with help of `digitalWrite()` func. After nearly 40-50 milliseconds detected values go back to normal, so most of time my dimmer work as expected.

I measured current on the **controlPin**, it's only 3.2mA, which is lower than maximum possible current for Arduino Due.

I tested this with **detectorPin** = 51, and different **controlPins**: 52, 36, 31.

So, how do you think, what is the problem? Is my Arduino broken?

# Answer
The problem with wrong input was caused by floating base of optocoupler:

100k pull-down will fix it.
> 0 votes

# Answer
There are a few issues with your circuit.

~~First, you need to add a diode to your 4N25 circuit.~~ *See EDIT below*. You should still put a diode across your 4N25 LED. ~~Right now, your 4N25 diode (LED) gets a high voltage across it 1/2 of the time.~~ Because you have 60K (30K+30K) in the circuit, the LED is likely not damaged, however the LED isn't really designed to handle reverse voltage more than 6 volts. Depending upon the reverse characteristics of the Bridge diodes (leakage current), your 4N25 LED could be experiencing greater than 6 volts. Using devices beyond their "maximum specification" can produce unusual side effects.

Place the new diode (1N4007 is good, almost any diode will work) across the LED on your 4N25. Wire the new diode with new diode anode to the LEd cathode. Now, the LED will turn on during 1/2 cycle of the AC, and be protected against overvoltage during the other half of the cycle.

Second, rearrange your circuit for the Triac. The data sheet for your MOC3043 triac driver shows a typical schematic.

Notice the 39 ohm resistor and the 0.01 uf capacitor in the circuit. This is called a snubber and will reduce interference and voltage spikes. This type of interference is famous for disrupting low voltage circuits such as micro-controllers.

Without seeing your code, I can't say much on that. However, I presume that you are trying to detect the zero cross, and then waiting a certain amount of time AFTER the zero cross to turn on the Triac.

> I measured current on the controlPin, it's only 3.2mA

Your 3.2mA may not be enough to drive the LED in your dimmer circuit. You will likely need 10mA to assure proper operation. You can reduce the resistor to achieve higher current to the MOC3043.

EDIT : I just realized that your bridge rectifier protects the LED (4N25) from reverse voltage.
> 1 votes

---
Tags: arduino-due
---


title: Serial Monitor not displaying anything

text:
# Question
Title: Serial Monitor not displaying anything
I have a very basic script that is supposed to display something to the serial monitor but no matter what I try the serial monitor won't display anything...I;ve watched about 5 tutorials now and each one has failed to display anything. Any ideas what I'm doing wrong?

Here is my code:

```
char rx_byte;

void setup() {
  Serial.begin(115200);
  pinMode(13, OUTPUT);
  digitalWrite(13, LOW);
}

void loop() {
  if(Serial.available() > 0){
    rx_byte = Serial.read();
    Serial.print("You typed: ");
    Serial.println(rx_byte);
    digitalWrite(13, HIGH);
    delay(1000);
    digitalWrite(13, LOW);
  }
}

```

# Answer
> 2 votes
> Which one are you using?
>
> The one closest to the reset button, I believe its the native...

This is more confusing than I realized. The Due has two ports:

---

## Programming port

For programming, the programming port is easiest to use. **And** you can "talk" to the serial port using `Serial`, like this:

```
void setup ()
  {
  Serial.begin (115200);
  Serial.println ("Hello, world!");
  }  // end of setup

void loop ()
  {
  }  // end of loop

```

---

## Native USB port

This lets you emulate USB devices (eg. keyboard, mice). However if you want to use it for Serial communications you need to use a different class `SerialUSB` like this:

```
void setup ()
  {
  SerialUSB.begin(115200);
  while (!SerialUSB) ; // wait for it to become ready
  SerialUSB.println ("Starting ...");
  }  // end of setup

unsigned long i;

void loop ()
  {
  SerialUSB.print ("Hello, world! Count = ");
  SerialUSB.println (++i);
  delay (1000);
  }  // end of loop

```

It also helps to wait for the serial port to become ready, as I did in `setup`. Otherwise you may miss the first 10 lines or so of serial output.

# Answer
> 1 votes
You have to change the baud rate at the right bottom corner of the serial monitor to 115200 which you have assigned initially. I have tested it and It doesn't matter if its int/char

# Answer
> 0 votes
Try replacing the line `char rx_byte;` with `int rx_byte=0;`. Use `Serial.println(rx_byte,DEC);`

```
int rx_byte=0;

void setup() {
  Serial.begin(115200);
  pinMode(13, OUTPUT);
  digitalWrite(13, LOW);
}

void loop() {
  if(Serial.available() > 0){
    rx_byte = Serial.read();
    Serial.print("You typed: ");
    Serial.println(rx_byte,DEC);
    digitalWrite(13, HIGH);
    delay(1000);
    digitalWrite(13, LOW);
  }
}

```

---
Tags: serial, c++, arduino-due, display
---


# Question
Title: if(Serial) not working correctly on micro or pro micro
I have an arduino micro and several clone "pro micro"'s both of which are based on the 32u4, i'm trying to make my project have a debug mode which is only active when the serial port is open, the documentation states that using:

```
if (Serial)

```

on these boards should only return true if the port is open (on uart based connections it always returns true), i wrote my sketch to take advantage of that but it didn't seem to be working properly, so i stripped back to basics and wrote this sketch:

```
void setup() {
    // put your setup code here, to run once:
    pinMode(2, OUTPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
    if (Serial){
        digitalWrite(2, HIGH);
    }
    else{
        digitalWrite(2, LOW);
    }
}

```

I connected an LED to pin 2 and then tested it by connecting and disconnecting the arduino from the PC, and opening and closing the com port.

after freshly connecting the arduino to the PC the LED is off, when i open a connection to the virtual com port the LED turns on. however i would expect the LED to go out once the port is closed, but it remains on.

My questions are:
1) have i got an out of date bootloader?
2) if so how do i check?
3) is this intended behavior and if so why?
4) is this a bug in the arduino bootloader or libraries?
5) short of having to change my code to look for serial data to start and stop the debug mode (serial comms are being used for other things in the background) is there any way i can work around this? reading from hidden registers etc?

Edit:
should have mentioned i'm seeing this behavior with or without a call to `Serial.begin`

# Answer
> 1) have i got an out of date bootloader?

No. This has nothing to do with the bootloader.

> 2) if so how do i check?

See above.

> 3) is this intended behavior and if so why?

In a manner of speaking, yes - see below.

> 4) is this a bug in the arduino bootloader or libraries?

No. Elsewhere. See below.

> 5) short of having to change my code to look for serial data to start and stop the debug mode (serial comms are being used for other things in the background) is there any way i can work around this? reading from hidden registers etc?

Yes, you can, but only once you understand exactly what is going on.

The problem with USB serial (AKA CDC/ACM) communication is that there is no way of knowing if the port has been opened by the computer or not. That functionality was just never designed into the protocol.

However, there are two virtual modem signals that the computer can assert that the CDC/ACM device at the other end can examine - one is the equivalent of DTR and the other the equivalent of RTS.

The Arduino's CDC/ACM code examines those, and if either are asserted then it assumes the CDC/ACM port is open. If neither are asserted then it assumes the port is closed.

Now comes the tricky part: You have little or no control over when those signals are asserted or not. There are three separate factors that decide what happens:

1. The software being run can manually control the signals. The Arduino IDE does this to ensure boards that use DTR to reset (like the Uno, etc) actually do reset.
2. The drivers on the computer can decide to automatically control the signals when the port is opened or closed
3. The operating system itself can control the signals when the port is opened or closed.

Some software will control the RTS/DTR signals properly, some won't. Some drivers will control the signals for you, some won't. Some operating systems (such as Linux) will, unless otherwise instructed, default to automatically controlling the modem lines properly. Others, like Windows, won't.

So the only way you can be sure that these signals are being controlled properly is to manually control them from your own software used for debugging, or to find a specific terminal emulator that controls the lines properly.
> 9 votes

# Answer
I am experiencing the same problem. My environment is Windows 10 on the host side and Arduino 1.6.7 with a genuine Arduino Micro board.

In the OP's sketch, after compiling and uploading, the light does not go on until you open the serial monitor. This is as expected and shows that the Arduino side has some way of knowing that the serial monitor has started.

However if you close the serial monitor, the light stays on. It also stays on if you unplug the USB cable. It goes off when you plug the cable back in and goes back on when you restart the serial monitor.

With some further experimentation and poking around the code, I found that \_usbLineInfo.lineState \> 0 and thus Serial returns True if either DTR or RTS from the host is nonzero. DTR goes to 0 when the serial monitor is closed but RTS stays HIGH so Serial stays True.

The fix is to use the (undocumented) method Serial.dtr(). This is True only if the serial monitor is running.

\[edit\] If your system has external power so that it should keep working with the USB cable unplugged, testing Serial.dtr() works as long as you you always close the serial monitor before unplugging the USB cable. However it will remain True if the cable is unplugged before closing the serial monitor.

To detect the cable being unplugged, add the line

`USBCON |= 1<<OTGPADE;`

to setup(). This enables detection of an unplugged USB cable. Then in your loop

`(USBSTA & (1<<VBUS))`

will be True if the USB cable is plugged in and has power.
> 2 votes

---
Tags: serial, arduino-micro, arduino-pro-micro
---


# Question
Title: Use only one pin as serial output/input with arduino
I'm looking for a way to use Arduino UNO's as serial outputs or input "individually", I don want to have an RX pin for each TX pin. I know the library *SoftwareSerial*, but I'm not sure if it is posible to achieve my objective with it.

I have also read that in this library "If using multiple software serial ports, only one can receive data at a time". Is there any library or method I can use to achieve both of my objectives, using pins "individually" and receiving data from more than a pin at a time?

Thank you for your time.

# Answer
> I don't want to have an RX pin for each TX pin ...

I adapted the SoftwareSerial library a while ago to omit the receiving part. You can download that from:

http://www.gammon.com.au/Arduino/SendOnlySoftwareSerial.zip

You use that like SoftwareSerial but if you read you will always get -1 returned, and `available` always returns 0.

The constructor only has the transmit pin:

```
  SendOnlySoftwareSerial(uint8_t transmitPin, bool inverse_logic = false);

```

---

> Is there any library or method I can use to achieve both of my objectives, using pins "individually" and receiving data from more than a pin at a time?

You don't want an Rx pin, but you want to receive from more than one pin at a time? Now you've lost me.

Sounds like an X-Y Problem \- maybe describe this requirement in more detail.

Having said that, hardware serial can receive from one pin while the processor is doing something else. If you have a Mega you could receive from 4 ports at once (it has 4 x hardware serial ports).
> 1 votes

# Answer
AVR304, "Half Duplex Interrupt Driven Software UART on tinyAVR and megaAVR devices" describes how to implement a half-duplex software UART using 2 pins. Simply omit the half of the UART that you do not need in your own implementation.
> 1 votes

# Answer
Serial ports do not require both directions to work. You can connect just one if you want. Of course you won't be able to reply or receive but you know that. Multiple TX from a microcontroller is easy. Just send the data at the speed required. RX is harder because you have to be able to read multiple high speed random inputs at the same time. It requires careful and complicated coding and will not be small or simple. You may not be able to do it and the rest of your project as well.

There are ICs or setups that can multiplex serial lines though. See https://electronics.stackexchange.com/questions/111491/multiplexing-ttl-serial-lines-with-transistors
> 0 votes

---
Tags: serial, pins, library
---


title: ESP 8266 web server using arduino

text:
# Question
Title: ESP 8266 web server using arduino
I have built a system using arduino and Ethernet shield. It gets rgb values through URL and changes an rgb led's value. Today I bought an ESP 8266 12E. I want to change to wifi but I cannot find an arduino library that uses spi to connect the arduino to the ESP. I do not want to use only the ESP. Do you know any libraries to do the job or any tutorials.

# Answer
> 4 votes
The ESP communicates using the UART, not SPI. It uses modem-like AT commands. Unless you write your own ESP firmware, in which case how it communicates is up to you - and so is the accompanying Arduino library.

# Answer
> 0 votes
The following link is a great resource for learning how to use the WiFi module. It has all the commands you are likely to need. The guide is written with the intent that the user will use the module as a standalone device without the Arduino, but at the end of the guide the commands given are all the same. This is the reference I use for projects like this. ESP8622 Quick Start Guide

---
Tags: esp8266
---


# Question
Title: DCMotorTest from the Adafruit site – got fatal error exit status 1
New to Arduino, I plugged in DCMotorTest from the Adafruit site and got this error message: a fatal error exit status 1

```
/*
This is a test sketch for the Adafruit assembled Motor Shield for Arduino v2
It won't work with v1.x motor shields! Only for the v2's with built in PWM
control

For use with the Adafruit Motor Shield v2
---->   http://www.adafruit.com/products/1438
*/

#include <Wire.h>
#include <Adafruit_MotorShield.h>
#include "utility/Adafruit_MS_PWMServoDriver.h"

// Create the motor shield object with the default I2C address
Adafruit_MotorShield AFMS = Adafruit_MotorShield();
// Or, create it with a different I2C address (say for stacking)
// Adafruit_MotorShield AFMS = Adafruit_MotorShield(0x61);

// Select which 'port' M1, M2, M3 or M4. In this case, M1
Adafruit_DCMotor *myMotor = AFMS.getMotor(1);
// You can also make another motor on port M2
//Adafruit_DCMotor *myOtherMotor = AFMS.getMotor(2);

void setup() {
  Serial.begin(9600);           // set up Serial library at 9600 bps
  Serial.println("Adafruit Motorshield v2 - DC Motor test!");

  AFMS.begin();  // create with the default frequency 1.6KHz
  //AFMS.begin(1000);  // OR with a different frequency, say 1KHz

  // Set the speed to start, from 0 (off) to 255 (max speed)
  myMotor->setSpeed(150);
  myMotor->run(FORWARD);
  // turn on motor
  myMotor->run(RELEASE);
}

void loop() {
  uint8_t i;

  Serial.print("tick");

  myMotor->run(FORWARD);
  for (i=0; i<255; i++) {
    myMotor->setSpeed(i);
    delay(10);
  }
  for (i=255; i!=0; i--) {
    myMotor->setSpeed(i);
    delay(10);
  }

  Serial.print("tock");

  myMotor->run(BACKWARD);
  for (i=0; i<255; i++) {
    myMotor->setSpeed(i);
    delay(10);
  }
  for (i=255; i!=0; i--) {
    myMotor->setSpeed(i);
    delay(10);
  }

  Serial.print("tech");
  myMotor->run(RELEASE);
  delay(1000);
}

```

***My error message was:***

```
Arduino: 1.6.7 (Mac OS X), Board: "Arduino/Genuino Uno"

/Users/student/Downloads/Adafruit_Motor_Shield_V2_Library-master/examples/DCMotorTest/DCMotorTest.ino:11:34:
 fatal error: Adafruit_MotorShield.h: No such file or directory
 #include <Adafruit_MotorShield.h>
                                  ^
compilation terminated.
exit status 1
Error compiling.

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

```

# Answer
Based on the error report it seems that you have just opened the example program from the downloaded folder. In order to add library files (which includes the header files, c++ source code, etc.) you have to move the *Adafruit\_Motor\_Shield\_V2\_Library-master* folder to the libraries folder.

> Documents \> arduino \> libraries

If no such folder exist, then create a new folder and name it *libraries*.

To check weather the libraries have been installed, open arduino IDE goto

> file \> example and check weather the example programs are added (you will see "adafruit" in the list)

Now, restart the arduino IDE and things should get going.

**Note:** Do not use "-" and do not include space while naming a folder, as the compiler may throw up error. Instead you are free to use "\_","$". Name of a folder should always start with a letter.

For more detail visit https://learn.adafruit.com/adafruit-all-about-arduino-libraries-install-use/how-to-install-a-library
> 1 votes

---
Tags: adafruit, arduino-motor-shield
---


title: Serial not working with I2C

text:
# Question
Title: Serial not working with I2C
I have been working on a hydroponic garden that is controlled with Arduinos. I have everything working except for the user interface. What I would like to do is have an LCD screen paired with a rotary encoder for use on the garden, and an ESP8266 WiFi module set as a server working with a custom Android app that I am writing.

I have been working on writing the app and the code that will allow the Arduino and the app to talk to each other, but I have been running into a problem. Sometimes the serial data between the ESP266 and the Arduino is not being picked up by the Arduino. I have verified that the data coming out of the WiFi module is correct, but the Arduino seems to be missing characters. This seems to happen almost at random. Sometimes it will work, and other times it will simply get stuck. I used a SoftwareSerial library to add an extra serial port and printed what the Arduino was receiving from the WiFi module, and it just seems to be missing random characters.

Up until now I have had the WiFi module connected and the LCD screen. I was using the LCD screen to display debugging messages. I took the LCD screen off and deleted all the LCD code and now everything seems to work just fine.

The LCD screen uses I2C.

Why does disconnecting the LCD screen solve the issue? Is there a way to make both run at the same time? The LCD uses I2C. I am unaware of anything that would prevent this from working.

Thanks.

# Answer
> 0 votes
**Explanation**

The SoftwareSerial library requires continually polling the serial ports over short periods of time therefore it presents a problem of having to parse received data into something usable, which is going to be nearly impossible as your program is going to be too busy trying to keep up with all the incoming NMEA characters to assemble it all into something meaningful.

So in your situation the data from the ESP8266 module is probably fine as you say, but parsing it and sending it to the lcd over I2C is a lot of work and sometimes it will "lose" data it simply doesn't have time to process. This explains why the data loss is hit and miss, and gets resolved when you reduce the processing workload of your program by removing the lcd component.

**Solution**

What you need here is to use an interrupt-driven SoftwareSerial library instead, which works by filling a buffer in the background with received data and allows a little breathing room to process the serial data. A great example is the NewSoftwareSerial library. This link will show you how to use the library , also expand into the details my answer to give you a deeper understanding.

---
Tags: arduino-uno, serial, i2c, lcd, esp8266
---


# Question
Title: Need some explain before desigin my own custom Arduino Due board
I'd like to ask you some questions about ARM processor from Atmel like the SAM3X8E, the one used in the Arduino Due. I have found this \[AVR programming guide\] from abcminiuser on avrfreaks very helpful.

Q1. Why are there no ICSP pins in Arduino Due to use it to program the SAM3X8E from an external programmer instead of the USB port in the Due board?

Q2. If I want to program an Arduino Due from an external programmer which of the programmers in abcminiuser guide will do the job and give me the ability to program 8/16/32bit AVR and ARM chips from Atmel at the same time?

Q3. On the Arduino Due website I read this:

> "Uploading sketches to the SAM3X is different than the AVR Microcontrollers found in other Arduino boards because the flash memory needs to be erased before being re-programmed. Upload to the chip is managed by ROM on the SAM3X, which is run only when the chip's flash memory is empty. "

What is that mean?

# Answer
> 3 votes
1. Because it is not needed. The chip comes with the bootloader pre programmed in ROM, not in Flash. It cannot be replaced, upgraded, removed, etc like other more sensible chips. So there is no real need for ICSP since the main use for that is putting the bootloader on.
2. Unknown.
3. Unlike the AVR chips, whose bootloader always runs first for about 2 seconds, the SAM3X's boot loader only runs if the flash is empty. As a result there is a way to empty the flash built in to the Arduino code, so that it can be erased by software. That means that the software has to be working right though, which isn't always the case, since people write bad code which crashes the chip. As a result they added a erase button to the board so you can manually erase the chip and get the bootloader to run.

I have always maintained that the SAM3X is a really idiotically designed chip and I wouldn't ever use it in a design of my own.

---
Tags: arduino-due, icsp
---


title: Atmega168 interrupt error handling

text:
# Question
Title: Atmega168 interrupt error handling
I'm using an Atmega168 in a project that involve using the ISRs from multiple sources. I have an ISR hooked up to an external button and a timer, to use it as a reset button after a predetermined hold time.

I'm also using an ISR hooked upto UART. The UART is connected to an external Linux based SoC. Upon receiving specific commands from the linux machine, the atmel will perform certain functions.

In very rare occasions, the linux hangs up during tranmission and is always sending out the UART commands. This saturates the ISR and it also prevents the reset button ISR to function.

Although this happens rarely, I would like to take measures for this. As far as I know, there are no way to set priority in avr ISRs. So what can I do if the UART ISR is always called and prevents the rest of the board from functioning?

EDIT: I think the problem arises when the linux machine sends an empty string to the atmel. the UART\_receive() on the atmel gets stuck at: `while ( !(UCSR0A & (1<<RXC0)) );`

Any way I can avoid this?

```
unsigned char USART_Receive_string(unsigned char *x, unsigned char size)
{
unsigned char i = 0;

if (size == 0) return 0;            // return 0 if no space

while (i < size - 1) {              // check space is available (including additional null char at end)
    unsigned char c;
    while ( !(UCSR0A & (1<<RXC0)) );  // wait for another char - WARNING this will wait forever if nothing is received
    c = UDR0;
    if (c == '\0') break;           // break on NULL character
    x[i] = c;                       // write into the supplied buffer
    i++;
}
x[i] = 0;                           // ensure string is null terminated

return i + 1;                       // return number of characters written
}

```

# Answer
> Any way I can avoid this?

I think the whole concept of reading "n" bytes is flawed. It will indeed hang if you don't get the number you expect.

Why not just do what normal serial comms does. Accept bytes as they arrive in an ISR, and put them in a buffer? Then use the line-terminator to know when you have enough to process.

> So what can I do if the UART ISR is always called and prevents the rest of the board from functioning?

The UART ISR won't be called if there is no data, so it won't be "always called".
> 1 votes

# Answer
```
while ( !(UCSR0A & (1<<RXC0)) );  // wait for another char - WARNING this will wait forever if nothing is received

```

The comment hits the nail on the head.

It'll wait forever, but it's so because it has been "designed" in such a way.

You've got 2 options:

* Re-think your "design":

Do not make your UART wait for an n-amount of characters. You could buffer the received characters, and handle/clear the buffer. There should be a lot of info about this on the web.

* Quick and dirty fix:

Add a timeout to the waiting.

```
for (unsigned int timeout = 16000; (!(UCSR0A & (1<<RXC0))) && timeout > 0; timeout-- );

```

This isn't very efficient, but should work. Be sure to check for what reason the waiting stopped (if the timeout ran out, or if you actually received something), to avoid pushing in nonesense that's in the UDR0 at that moment (when you timeout).
> 0 votes

---
Tags: atmega328, uart, isr, atmel-studio
---


# Question
Title: Store TinyGPS++ latitude value into a variable of type string or float
I want to get the GPS ordinates in degrees with 6 decimal accuracy. I can obtain this by creating a gps object with TinyGPS library. but In the TinyGPS example codes, its written

```
Serial.println(gps.location.lat(), 6);

```

But I actually want to store this latitude degrees in a variable of type string or float. when i write this;

```
double Tiny_latitude = (gps.location.lat());
Serial.print("Tiny lat:");
Serial.println(Tiny_latitude);

```

it returns me Tiny lat:33.55 on serial monitor. But i want 33.546600. How do I do that ?

# Answer
> it returns me Tiny lat:33.55 on serial monitor. But i want 33.546600. How do I do that?

The issue is simply the number of decimal places. That can be added to the Serial.println().

```
double Tiny_latitude = (gps.location.lat());
Serial.print("Tiny lat:");
Serial.println(Tiny_latitude, 6);

```

> Now if i want to make a String "your location is \nlat:33.546600 \nlong: 75.456912" , i.e. my String variable are stored in Tiny\_latitude and Tiny\_longitude and want to make a string my\_Location. How do i do that?

I would use sprintf() for that but as that requires some additional build parameters the easiest way is to use String. Some special care is needed to increase the number of decimal places.

```
void loop()
{
  ...
  float latitude = 33.546600;
  float longitude = 75.456912;
  String buf;
  buf += F("your location is \nlat:");
  buf += String(latitude, 6);
  buf += F("\nlong:");
  buf += String(longitude, 6);
  Serial.println(buf);
  ...
}

```

Cheers!
> 0 votes

---
Tags: arduino-mega, gps, tinygps, float
---


# Question
Title: How to append float value of into a string ?
I have a float variable lng = 33.785469 and lat = 78.126548. Now can I convert them to String and append in a String variable "my\_location" as "your location is \nlng = 33.785469 \nlat = 78.126548". I was trying to do this with

```
    char charVal[5];               //temporarily holds data from vals
    String stringVal = "";     //data on buff is copied to this string

    dtostrf(lng , 4, 2, charVal);  //4 is mininum width, 2 is precision; float value is copied onto buff
    //convert chararray to string
    for(int i=0;i<sizeof(charVal);i++)
    {
    stringVal+=charVal[i];
    }
    GPS_string = GPS_string + "Car location: \nlat:" + stringVal;
    stringVal = "";

```

and it given me an error :

```
error: cannot convert 'String' to 'double' for argument '1' to 'char* dtostrf(double, signed char, unsigned char,

```

# Answer
This has been answered in the previous question but I can repeat it here:

```
void loop()
{
  ...
  float latitude = 33.546600;
  float longitude = 75.456912;
  String buf;
  buf += F("your location is \nlat:");
  buf += String(latitude, 6);
  buf += F("\nlong:");
  buf += String(longitude, 6);
  Serial.println(buf);
  ...
}

```

An alternative is to use dtostrf() as in your snippet:

```
void loop()
{
  ...
  float latitude = 33.546600;
  float longitude = 75.456912;
  const int BUF_MAX = 64;
  char buf[BUF_MAX];
  const int VAL_MAX = 16;
  char val[VAL_MAX];
  strcpy_P(buf, (const char*) F("your location is \nlat:"));
  dtostrf(latitude, 8, 6, val);
  strcat(buf, val);
  strcat_P(buf, (const char*) F("\nlong:"));
  dtostrf(longitude, 8, 6, val);
  strcat(buf, val);
  ...
}

```

Cheers!
> 5 votes

---
Tags: arduino-uno, c, string, float
---


# Question
Title: Is there a practical way to broadcast and receive ascii payloads over ethernet or wifi?
How best might arduino nodes pass incoming serial ascii messages out as ascii network broadcasts for all others to receive and pass out through their serial ports?

ie: typing a msg from the IDE serial monitor of any ethernet node should cause that msg to be output to the serial monitors of all other nodes.

# Answer
The magical trick you are looking for is Ethernet UDP Broadcast. By chance there is an example sketch in the Arduino Tutorial. I cannot say if it is up to date but this will help you get started.

Cheers!
> 1 votes

---
Tags: serial, wifi, ethernet, networking
---