title: Which Arduino board to buy?

text:
# Question
Title: Which Arduino board to buy?
I need an Arduino Mega 2560 (that is the one that has more pins). I went to eBay and there are a lot of different boards. I'm thinking of buying an ATmega2560-16AU CH340G MEGA 2560 R3 Board + Free USB Cable for Arduino. Is this one good? I mean, does it do the work? Is it compatible with the Arduino IDE? Anything I need to know?

# Answer
> 4 votes
The Chinese boards generally work just fine with the official Arduino IDE. One thing to be careful for though is the bootloader. Most the time the Chinese vendor had written a custom bootloader, which may make certain pins behave funny. e.g. a common thing is for pin 13 (the default LED) is permanently high.

I would be very cautious ordering these boards though. Most if not all of these breech the terms of the open source license which Arduino is released under. Besides that, ordering these boards you are supporting the Chinese slave labour gone into manufacturing this board for extremely low prices.

Why not purchase the official Arduino boards? Not only do you get quality boards, but you are also supporting the open source community, and ethically manufactured electronics.

# Answer
> 5 votes
The Arduino creators have spelled out their position on clones in a fairly lucid blog post a few years ago.

Your board comes pretty close to being a legitimate clone, but the claims about being manufactured in Italy are almost certainly false and possibly illegal.

I bought a CH340G based board myself, and apart from needing to install a different driver, it's pretty close to the original (There are a few projects that reprogram the 16U2 on a real Arduino board, but the vast majority of projects use the 16U2 as a straight serial converter, and the CH340G seems to do that job OK).

As other answers have pointed out, clone makers don't contribute to the community, so consider buying a real board occasionally. On the other hand, Arduino Mega clones are literally 25% the price of the original, so for that board, going with a clone is certainly tempting.

# Answer
> 2 votes
There is no way to know the quality of the Arduino clones on eBay. They may be fine but you never know.

I recommend buying an official Arduino from one of the official distributors.

There are good quality Arduino compatible boards like the SparkFun Redboard or the Adafruit Trinket. But these are not made to look like official Arduino boards. (Neither of these would work for you since they don't have as many pins as the Mega)

# Answer
> 1 votes
You could buy an official board, but if you're worried about the price, I wouldn't go for the EBay ones. There are other better clones out there. For example, I know that SparkFun makes their own Arduino Uno board, and while it's not called the Uno, it works exactly like it's supposed to, without any surprises. From what I remember, it's cheaper than the official Uno too.

# Answer
> 0 votes
It's a counterfeit, and counterfeits are never a good choice. Scroll this down to the Pricing paragraph to see where your money goes when you buy an official board.

# Answer
> 0 votes
I bought some of those boards and have had no problems with them. They are not as some claim, counterfeit boards. If they were, that would mean that the 'arduino' boards are not open source. I have also never seen any boards claiming to be built from italy. They are specifically labeled "Made In China".

---
Tags: arduino-mega
---


# Question
Title: How much current does an Arduino Mega draw from a LiPo battery (5,000 mAh)?
I went through Sparkfun's website on how to power a project because I wanted to calculate how much battery capacity I needed for my project. I saw an ATmega 328 micro-controller that is used as the brains for the circuit: it draws about 20mA under normal conditions.

So that got me thinking: how much current will an Arduino Mega draw from a LiPo battery of 7.4V with 5,000 mAh 2s 25C under normal condition? Please anyone do help me out and pardon me, I am new to this.

# Answer
> 4 votes
The important thing to realize here is that the capacity of the battery does not affect the amount of current drawn. Your Mega will draw the same whether it is connected to a 1000 mAh battery or a 5000 mAh battery. The larger battery will just last longer.

Tests on my Mega2560 Arduino show that (with no peripherals connected) it draws about 70 mA from a 7V supply, and slightly more (72 mA) from a 12V supply (the voltage regulator has to throw away some of the extra voltage as heat). *(However, see below)*

The exact amount it would draw in practice would be strongly correlated to what things you have connected. For example, LEDs, motors, shields, other devices.

I have a page about power saving that you might find useful if your objective is to minimize power usage.

---

## Edited to add more about power consumption

It appears that my initial claim that the current consumption goes up with an increase in voltage was wrong. With Majenko's help I made up a detailed set of automated tests, increasing the Mega2560 power input by increments of 200 mV, taking a reading from both the power supply and my multimeter, averaging each one over ten readings, and plotting the results. This is what I got:

The two measurements seem to be consistently different by 0.2 mA. What this shows is that at 7V, the current consumption is 65.3 mA, and at 12 it is 64.1 mA, about a milliamp less.

I do, however, stick by my original assertion that the capacity of the battery will not affect consumption, and a larger battery will just last longer.

# Answer
> 0 votes
You may be right that AtMega chip will draw relatively small amount of energy. But there are other components in the Arduino that will draw much more. (Voltage regulator as a best example.) In the end, the current drawn can (and will) be 10x larger.

And there is another problem, you have to know how much power will connected sensors draw.

What you can do is build your own 'less greedy' Arduino and use sleep abilities of AtMega chips.

Here are some links to go through:

https://openhomeautomation.net/arduino-battery/

https://circuits.io/circuits/1717500-power-rail-blocking-with-an-arduino/

http://www.gammon.com.au/power

# Answer
> 0 votes
> I saw an ATmega 328 microcontroller that is used as the brains for the circuit: it draws about 20mA under normal conditions.

the datasheet provides the best guidance on that. typically 10ma - 20ma is fairly standard for 8-bit mcus. other components on the board, like opamps, or regulators, leds, may consume a little bit more so I would say 20ma - 30ma total is a good estimate for the board.

> So that got me thinking: how much current will an Arduino Mega draw from a LiPo battery of 7.4V with 5,000 mAh 2s 25C under normal condition? Please anyone do help me out and pardon me I am a newbie to this.

the datasheet showed 20ma typical so I would put the board to 30ma total. 5000mah/30ma = ...

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


title: Stepper Motor Power Supply

text:
# Question
Title: Stepper Motor Power Supply
Just a quick question. Picking up some stepper motors, but confused at what voltage/current things are running off.

Ordering:
2 x Stepper Motor
2 x EasyDriver

An article says

> You need some 12V source to the EasyDriver (the motor in this article is 12V) - This will be powering the stepper - Im using a 12V adapter - similar to the one in the illustration. Just make sure it is rated at least 750ma - A higher rating is better, and just means it wont burn out.

So does that mean if I got a plug which is regulated 12V 1A and powered the Arduino from that I could power a rail with VIN pin and that would safely supply the EasyDrivers? And I could then use the 5V pin to power everything else?

Just don't want to break anything! Thanks

# Answer
As generic rule: avoid powering one device through another. It can cause strain on the middle-man device and it *will* be inefficient. The only few cases where this might make sense are when it's topologically inconvenient to connect everything to the centralized power supply. Or if the cascaded device requires a voltage that is not available from the power supply.

In your case you can power both the easy driver and the Arduino from the regulated 12v.

And you won't risk drawing too much current through the Arduino.
> 0 votes

# Answer
Stepper Motor Control - one step at a time

This program drives a unipolar or bipolar stepper motor.
The motor is attached to digital pins 8 - 11 of the Arduino.

The motor will step one step at a time, very slowly. You can use this to test that you've got the four wires of your stepper wired to the correct pins. If wired correctly, all steps should be in the same direction.

Use this also to count the number of steps per revolution of your motor, if you don't know it. Then plug that number into the oneRevolution example to see if you got it right.

```
#include <Stepper.h>

const int stepsPerRevolution = 200;  // change this to fit the number of steps per revolution
// for your motor
// initialize the stepper library on pins 8 through 11:
Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);
int stepCount = 0;         // number of steps the motor has taken

void setup() {
    // initialize the serial port:
    Serial.begin(9600);
}

void loop() {
    // step one step:
    myStepper.step(1);
    Serial.print("steps:");
    Serial.println(stepCount);
    stepCount++;
    delay(500);
}

```
> 1 votes

# Answer
The Vin pin is after the M7 protection diode, so you won't get quite 12 V out of Vin. Also, depending on the load, the diode might get warm.

I've also found that powering an Arduino from 12 V input (the maximum recommended) tends to get the voltage regulator hot.

Your other issue is that the motor power will be going through the Arduino board, to an extent (in the plug, through the diode, and out Vin) so any noise generated by the motor will be close to the processor.

I don't think your idea would *break* anything, it just might not be particularly reliable.
> 0 votes

---
Tags: power
---


# Question
Title: ATtiny85 MIDI IN with less than 3V -can it be done?
I've been trying to add a MIDI INput to an ATtiny-based synthesizer, powered by a CR2032 battery (3v) and running softwareSerial.

Currently I'm using an H11L1 optocoupler, which works fine at 5v, but I am missing notes at 3V; I'm not sure whether the problem is the optocoupler, or that the ATtiny can't establish proper communication on that voltage; any pointers will be much appreciated :)

# Answer
The H11L1's minimum supply voltage is 3 V. There are low-power optocouplers like the TLP2361, but event those do not go below 2.7 V. (And those limits are actually designed for 3.3 V ± 10 % or 3.0 V ± 10 %.)

To get a high-speed optocoupler for lower voltages, you have to build it yourself from discrete parts, e.g.:

(R1 is sized for the PC817-A's minimum CTR of 50 %; higher CTRs should use a lower value for R1. Q1 can be any random small-signal transistor. Adjust R2 for about 1 mA, depending on VCC.)
> 2 votes

---
Tags: midi, opto-isolator
---


# Question
Title: RESET and RESUME case in Arduino mega 2560 code (PUSHBUTTON AS INTERRUPT)
I am working on Arduino Mega 2560 which is controlling four steppers with BT6560 Driver, six pushbuttons and four limitswitches.

I want to code Arduino such that when I press RESET button (not talking about RESET button on Arduino), Arduino should run the code again from beginning.

And when I press RESUME button, Arduino should run the code from the moment I pressed the RESET button (like any song is resumed).

How can I be able to do this?

Below is a code I am working on:

```
int dirH_T1 = 3;
int steppin_T1 = 4;
int dirpin_F1 = 5;
int dirH_F1 = 6;
int steppin_F1 = 7;
int dirpin_T2 = 8;
int dirH_T2 = 9;
int steppin_T2 =10;
int dirpin_F2 = 11;
int dirH_F2 = 12;
int steppin_F2 =13;
int PB17ACW=23;
int PB17ACCW=22;
int PB17BCW=25;
int PB17BCCW=24;
int S01 = 34; // SENSOR INPUTS
int S02 = 35;
int S03 = 36;
int S04 = 37;

void setup()
{
    pinMode(dirpin_T1, OUTPUT);
    pinMode(dirH_T1, OUTPUT);
    pinMode(steppin_T1, OUTPUT);
    pinMode(dirpin_F1, OUTPUT);
    pinMode(dirH_F1 , OUTPUT);
    pinMode(steppin_F1, OUTPUT);

    pinMode(dirpin_T2, OUTPUT);
    pinMode(dirH_T2, OUTPUT);
    pinMode(steppin_T2, OUTPUT);
    pinMode(dirpin_F2, OUTPUT);
    pinMode(dirH_F2 , OUTPUT);
    pinMode(steppin_F2, OUTPUT);

    pinMode(PB17ACW,INPUT_PULLUP);
    pinMode(PB17ACCW,INPUT_PULLUP);
    pinMode(PB17BCW,INPUT_PULLUP);
    pinMode(PB17BCCW,INPUT_PULLUP);

    pinMode(S01,INPUT);
    pinMode(S02,INPUT);
    pinMode(S03,INPUT);
    pinMode(S04,INPUT);

}
void loop()
{
    if(digitalRead(PB17ACW)==LOW &&  digitalRead(PB17ACCW)==LOW) {
// STOP MOTOR WHEN NO KEY PRESSED
    }

// FOR FILAMENT 1 FORWARD FEEDER
    if(digitalRead(PB17ACW)==HIGH &&  digitalRead(PB17ACCW)==LOW) {
        digitalWrite(dirpin_T1, LOW);      // Set the direction.
        digitalWrite(dirH_T1, LOW);
        delay(1000);

        for(int i = 0; i<32767; i++) {      // Iterate for 4000 microsteps.(32767)
            digitalWrite(steppin_T1, LOW);  // This LOW to HIGH change is what creates the
            digitalWrite(steppin_T1, HIGH); // "Rising Edge" so the easydriver knows to
            when to step.
            delayMicroseconds(50);
        }

        digitalWrite(dirpin_F1, LOW);      // Set the direction.
        digitalWrite(dirH_F1, LOW);
        delay(1000);

        do {
            digitalWrite(steppin_F1, LOW);  // This LOW to HIGH change is what creates the

            digitalWrite(steppin_F1, HIGH); // "Rising Edge" so the easydriver knows to when to step.
            delayMicroseconds(50);

        } while(digitalRead(S01)==LOW);

        delay(1000);

        digitalWrite(dirpin_T1, LOW);      // Set the direction.
        digitalWrite(dirH_T1, HIGH);
        delay(1000);

        for(int i = 0; i<32767; i++) {      // Iterate for 4000 microsteps.(32767)
            digitalWrite(steppin_T1, LOW);  // This LOW to HIGH change is what creates the
            digitalWrite(steppin_T1, HIGH); // "Rising Edge" so the easydriver knows to
            when to step.
            delayMicroseconds(50);

        }
    }

// FOR FILAMENT 1 BACKWARD FEEDER
    if(digitalRead(PB17ACW)==LOW &&  digitalRead(PB17ACCW)==HIGH) {
        digitalWrite(dirpin_T1, LOW);      // Set the direction.
        digitalWrite(dirH_T1, LOW);
        delay(1000);

        for(int i = 0; i<32767; i++) {      // Iterate for 4000 microsteps.(32767)
            digitalWrite(steppin_T1, LOW);  // This LOW to HIGH change is what creates the
            digitalWrite(steppin_T1, HIGH); // "Rising Edge" so the easydriver knows to when to step.
            delayMicroseconds(50);

        }

        digitalWrite(dirpin_F1, LOW);      // Set the direction.
        digitalWrite(dirH_F1, HIGH);
        delay(1000);

        do {
            digitalWrite(steppin_F1, LOW);  // This LOW to HIGH change is what creates the
            digitalWrite(steppin_F1, HIGH); // "Rising Edge" so the easydriver knows to when to step.
            delayMicroseconds(50);
        } while(digitalRead(S02)==LOW);

        delay(1000);
        digitalWrite(dirpin_T1, LOW);      // Set the direction.
        digitalWrite(dirH_T1, HIGH);
        delay(1000);

        for(int i = 0; i<32767; i++) {      // Iterate for 4000 microsteps.(32767)
            digitalWrite(steppin_T1, LOW);  // This LOW to HIGH change is what creates the
            digitalWrite(steppin_T1, HIGH); // "Rising Edge" so the easydriver knows to when to step.
            delayMicroseconds(50);
        }
    }

    // FOR FILAMENT 2 FORWARD FEEDER
    if(digitalRead(PB17BCW)==HIGH &&  digitalRead(PB17BCCW)==LOW) {
        digitalWrite(dirpin_T2, LOW);      // Set the direction.
        digitalWrite(dirH_T2, LOW);
        delay(1000);

        for(int i = 0; i<32767; i++) {      // Iterate for 4000 microsteps.(32767)
            digitalWrite(steppin_T2, LOW);  // This LOW to HIGH change is what creates the
            digitalWrite(steppin_T2, HIGH); // "Rising Edge" so the easydriver knows to when to step.
            delayMicroseconds(50);
        }

        digitalWrite(dirpin_F2, LOW);      // Set the direction.
        digitalWrite(dirH_F2, LOW);
        delay(1000);

        do {
            digitalWrite(steppin_F2, LOW);  // This LOW to HIGH change is what creates the
            digitalWrite(steppin_F2, HIGH); // "Rising Edge" so the easydriver knows to when to step.
            delayMicroseconds(50);
        } while(digitalRead(S03)==LOW);

        delay(1000);

        digitalWrite(dirpin_T2, LOW);      // Set the direction.
        digitalWrite(dirH_T2, HIGH);
        delay(1000);

        for(int i = 0; i<32767; i++) {      // Iterate for 4000 microsteps.(32767)
            digitalWrite(steppin_T2, LOW);  // This LOW to HIGH change is what creates the
            digitalWrite(steppin_T2, HIGH); // "Rising Edge" so the easydriver knows to when to step.
            delayMicroseconds(50);

        }
    }

// FOR FILAMENT 2 BACKWARD FEEDER
    if(digitalRead(PB17BCW)==LOW &&  digitalRead(PB17BCCW)==HIGH) {
        digitalWrite(dirpin_T2, LOW);      // Set the direction.
        digitalWrite(dirH_T2, LOW);
        delay(1000);

        for(int i = 0; i<32767; i++) {      // Iterate for 4000 microsteps.(32767)
            digitalWrite(steppin_T2, LOW);  // This LOW to HIGH change is what creates the
            digitalWrite(steppin_T2, HIGH); // "Rising Edge" so the easydriver knows to when to step.
            delayMicroseconds(50);
        }

        digitalWrite(dirpin_F2, LOW);      // Set the direction.
        digitalWrite(dirH_F2, HIGH);
        delay(1000);

        do {
            digitalWrite(steppin_F2, LOW);  // This LOW to HIGH change is what creates the
            digitalWrite(steppin_F2, HIGH); // "Rising Edge" so the easydriver knows to when to step.
            delayMicroseconds(50);

        } while(digitalRead(S04)==LOW);

        delay(1000);

        digitalWrite(dirpin_T2, LOW);      // Set the direction.
        digitalWrite(dirH_T2, HIGH);
        delay(1000);

        for(int i = 0; i<32767; i++) {      // Iterate for 4000 microsteps.(32767)
            digitalWrite(steppin_T2, LOW);  // This LOW to HIGH change is what creates the
            digitalWrite(steppin_T2, HIGH); // "Rising Edge" so the easydriver knows to when to step.
            delayMicroseconds(50);
        }
    }
}

```

# Answer
> 2 votes
Doing the "hibernate" thing in a general fashion you need to:

1. Capture the relevant status of the whole system (Arduino + modules). That include registers, the stack and all variables in your program.
2. Write it to some storage medium (EEPROM, SD, whatever).
3. Upon **resume**, restore registers, stack, variable and reinicialize all modules (sensors, relays, ...)

Arduino can't do that.

Your only alternative is to use, as @Majenko says, a *finite state machine* and take care yourself to restore execution to the point where button was pressed.

---
Tags: arduino-mega
---


# Question
Title: Will 5V to input pin damage the Arduino board?
I am fairly new to Arduino. When I am experimenting with circuits, do i need to worry about shorting out a pin if I accidentally connect the +5V pin on Arduino to an input pin on Arduino without a resistor? I just want to make sure I avoid destroying the board when learning how to create circuits.

# Answer
> 3 votes
No, no short. Arduino (Atmega) pins default to inputs. Pins configured this way are said to be in a high-impedance state. Input pins make extremely small demands on the circuit that they are sampling, equivalent to a series resistor of 100 megohm in front of the pin.

*Answer provided by Look Alterno and converted from a comment.*

# Answer
> 0 votes
Apply 5V directly, without any resistor:

**5 V socket**

it is directly connected to the regulator’s output, thus the 5 V to power external loads to Arduino can be drawn from it. In the case voltages are not applied to the USB Port or to the JACK socket, the 5 V socket can be even used to power Arduino directly, if having an external stabilized 5 V source. One has to consider that, in general, regulators do not like voltages being applied to their output, but in this particular case this situation turns out to happen even when powering Arduino from the USB port, therefore we may assume that the designers judged this problem as harmless. Even in this case there is no form of protection, since both the diode and the PTC fuse are found above this socket and thus they do not have any active function. As in the case of the Vin socket, the voltage negative pole can be found on the board’s GND sockets.

NOTE: regardless of the input used, Arduino has a 3.3 V output socket to power loads operating at this voltage; in fact a second regulator, right for the purpose of generating 3.3 V, is directly connected to the 5 V. This socket cannot be used as input.

---
Tags: arduino-uno
---


# Question
Title: 2D Tracking of an object - which sensor?
I'm currently working on a project for which I require a sensor. I've made a quick and simplified drawing of what the result is supposed to do:

Basically, I want one LED of a LED-Strip to light up dependent on the location of a moving object. If the object in above image (say a slow rolling ball) were to move from bottom to top, then the LED strip should also light up from bottom to top. I have no problem getting the LED strip to light up adequately, however I'm not sure which sensor actually can pick up objects as required in this case.

As I've understood regular IR sensors can only detect *if* there is an object and how far it is away, however they can't pick up said object's relative position on the y-axis. Is there any way to do this rather easily, perhaps with triangulation? I've looked into Bluetooth and RFID but haven't found anything particularly useful.

# Answer
> 1 votes
I feel that an array of IR transmitters and receivers could work for you.

If you put the transmitters/receivers in an recessed tube with (black, non-ir reflectant) separations, you can avoid crosstalk. You should be wary that it may require some tweaking to find the right sensitivity.

Here is a video (and here) that shows this in practice. I like the fact that you don't need sensors on either side of the object.

You may also consider video-processing, but that's out of scope for Arduino. Or use a Lidar.

# Answer
> 0 votes
There are many solutions to the problem. For a free moving ball confined to a square flat surface with sides:

1. Choose IR LEDs mounted at such a height and distribution to be blocked by the rolling ball. Make sure at least 1 IR LED is blocked by the ball no matter where it is located.
2. Line two adjacent sides with strips of these IR LEDs.
3. Use the Arduino to light each LED one at a time at a frequency of about 40KHz. Scan all LEDs within a second. This should be adequate to locate a slow moving ball in 2D space.
4. On the two opposite sides mount a ASK Remote Control receiver. A common device easily harvested from old entertainment equipment or bought from electronics part supply houses.
5. Use the Arduino to sense when the ASK Remote Control receiver detected or did not detect the flashing IR LED.
6. When the Arduino finds an IR LED that is not detected, the ball can be assumed to be between the IR LED and the ASK Remote Control receiver.

Note, the patter of intersecting lines will look more like two sets of bicycle tire wheal spokes. Not like a checker board. It may be better to confine the ball to a smaller square then that of the square where the transmitting IR LEDs and ASK Remote Control receiver are mounted on.

---
Tags: sensors, led
---


# Question
Title: Why can I measure two pins simultaneously?
I would like to do an action if both buttons on my arduino pro micro are depressed simultaneously. I'm getting some strange results:

```
// Buttons
Bounce button0 = Bounce();
Bounce button1 = Bounce();

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

  pinMode(2, INPUT_PULLUP);
  button0.attach(2);
  button1.interval(1);

  pinMode(3, INPUT_PULLUP);
  button1.attach(3);
  button1.interval(1);

  Serial.println("Setup Complete");
}

void loop() {
  button0.update();
  button1.update();

  if (button0.fell()){
     Serial.println("button0 fell");
  } else if (button0.rose()) {
    Serial.println("button0 rose");
  }

  if (button1.fell()){
     Serial.println("button1 fell");
  } else if (button1.rose()) {
    Serial.println("button1 rose");
  }

  if (button0.fell() & button1.fell()){
    Serial.println("buttons fell");
  } else if (button0.rose() && button1.rose()) {
    Serial.println("buttons rose");
  }
}

```

Here is the output to the Serial console:

```
Setup Complete
button0 fell
button1 fell
button0 rose
button1 rose

```

Why isn't this branch being executed? `button0.fell() & button1.fell()` For the life of me I cannot figure this out. Thank you!

# EDIT

This doesn't work either, which is crazy:

```
void loop() {
  button0.update();
  button1.update();

  if (button0.fell()) {
    if (button1.fell()) {
      Serial.println("buttons fell");
    }
  }

  if (button0.rose()) {
    if (button1.rose()) {
      Serial.println("buttons rose");
    }
  }
}

```

# EDIT

Thank you for the answers! Unless the person was to push both buttons in the exact same iteration of the loop, my code would never work. Here is what I ended up using:

```
if ((button0.fell() && !button1.read()) || (button1.fell() && !button0.read())) {

```

# Answer
You can test it easily by calling the function twice directly after each other. If the first time a true is returned and the second time a false, the state is internally reset.

But probably because after you call the fell function, the internal state is reset, so after the call not a new fell has been happened.

So store the return value of the fell and rose functions and use those instead.

Update:

I'm not sure if this is the actual implementation but I found for fell/rose and see this:

```
bool Bounce::rose()
{
    return ( state & _BV(DEBOUNCED_STATE) ) && ( state & _BV(STATE_CHANGED));
}

bool Bounce::fell()
{
    return !( state & _BV(DEBOUNCED_STATE) ) && ( state & _BV(STATE_CHANGED));
}

```

So as long as the state has not changed it returns false (which is similar/equal as 'resetting the internal state'. Except this reset is done at a different location (but checked in the fell and rose function).

Update:

See remarks from gre\_gor below
> 3 votes

# Answer
https://github.com/thomasfredericks/Bounce2/wiki

I'm not familiar with the Bounce(2) library, but looking at the above site, it looks like "fell" is more of an "instant" thing, where it isn't something that maintains state over the Arduino loop.

Seeing as we are human, we can't (normally) push buttons at the same exact time. This means that we would usually end up pushing the buttons within milliseconds, plural, of each other, but your simple example could loop multiple times between the first button and the 2nd button being triggered.

Don't forget that the Arduino Uno runs at 16mHz. This is extremely slow compared to today's computers, but it's still running millions of operations a second. My first computer, the IBM XT, ran at 4.77 mHz and that was *the* standard computer for years.

https://en.wikipedia.org/wiki/IBM\_Personal\_Computer\_XT

I suggest putting in a loop counter to help you discover if this is the case. Trying to display it every loop may slow the loop down, so only display the counter on your current displays. If your "button0 fell {#}" display shows a different number than your "button1 fell {#}", then you know what's going on. You may also want to display the actual contents of "button{01}.fell()".

IDK if this library does it, but in app programming, sometimes getting the value of an event like this will cause the event to be flushed and reset the value. This would mean that calling a method the first time would render a different value than calling it a second time, even if the second time was immediately following the first call. Setting "button{01}.fell()" to a variable might be a better option than trying to call it twice.
> 3 votes

# Answer
> I'm getting some strange results:

your code doesn't really measure the two pins "simultaneously". instead, it measure the two pins sufficiently fast and it appears to be simultaneously.

use input capture for that.
> 1 votes

# Answer
Maybe I missed something but the branch doesn't execute because

```
button0.fell() & button1.fell()

```

should be

```
button0.fell() && button1.fell()

```

the *else if* clause also never executes.
> 1 votes

---
Tags: input, code-review, debounce
---


title: Arduino relay power supply question

text:
# Question
Title: Arduino relay power supply question
Hello everyone i got 2 ssr's from here

(link)

Sorry about the long link. My question is what power supply should i use. I was thinking a 12v 2amp. On a side note do i look at the input or the output when choosing a power supply

Thank you

# Answer
In the product description it says "DC 12V 8-Channel Relay interface board, and each one needs 15-20mA Driver Current." So 8 times 0.020A is 0.160A per board. I think your 2 amp power supply should work just fine.
> 1 votes

---
Tags: relay
---


title: Serial uart communication issues

text:
# Question
Title: Serial uart communication issues
I know this isnt specific but could you suggest some causes for the following issue:

Mega2560 sends values to Raspi 3 and Raspi 3 receives prints them accordingly (arduino also prints out the values it sends). However, at every occasional instances, garbage data is printed on Raspi terminal while the right data is still printed on the serial monitor for Arduino for a baudrate of 115200 for both.

Any helpful suggestions would be appreciated

# Answer
> 1 votes
This answer will also be not so specific, but you can try:

* Check all wiring (use a multimeter/analyzer)
* Reduce the data rate
* Find out if there is a pattern whenever garbage is created (depending on values?)
* Check (if possible) for errors (overrun/parity)
* Play with the parity setting/stop bits to see if it makes a difference

# Answer
> 1 votes
I often have this issue with my data-loggers. They use Nano or Uno to send readings to the Pi3 Python programs. My Arduinos send data every 60 seconds. Then the Pi adds a date and time stamp and appends it to the day's data file

Invariably, in my case, it happens that I might get some garbage as I start the program, and then it runs fine after that. I solved the garbage part by flushing the input buffer. Then I also make sure my data is of the expected length, which depends on how many variables it is sending.

Once I applied a little Python Fu the issue has ceased to be a problem.

Here is a generic representation of my solution:

```
import serial
ser = serial.Serial("/dev/ttyUSB0",9600)
ser.flushinput()
while True :
    linein = ser(readlin)
    if len(linein<10) : continue
    if len(linein>50) : continue
    PROCESS THE INPUT

```

---
Tags: arduino-mega
---


title: 3-speed DC fan control with Uno

text:
# Question
Title: 3-speed DC fan control with Uno
I have built this MOSFET circuit, which is supposed to run 2 DC fans using an Arduino Uno.

I am trying to get the two DC fans running with four settings: OFF, LOW, MED and HIGH. I have been having issues with the MED option, because when its option is selected by the rotary switch (5 V pulse detected by the analog pin A2) the speed of the fan is not the constant 75% duty cycle (191) as defined on line 75 in the code below:

```
int motorPin1 = 3;
int motorPin2 = 9;
int DCfanSpeed = 0;
int voltageZero = 0;
int voltageOne = 1;
int voltageTwo = 2;
int voltageThree = 3;

void setup() {
  pinMode(motorPin1, OUTPUT);
  pinMode(motorPin2, OUTPUT);
  digitalWrite(voltageZero, INPUT_PULLUP);
  digitalWrite(voltageOne, INPUT_PULLUP);
  digitalWrite(voltageTwo, INPUT_PULLUP);
  digitalWrite(voltageThree, INPUT_PULLUP);
  Serial.begin(9600);
}

void loop() {
  int voltageReadingZero = analogRead(voltageZero); // OFF SWITCH
  int voltsZero = voltageReadingZero / 204.6;
  if (voltsZero == 5) {
    delay(300);
    if (voltsZero == 5) DCfanSpeed = 0;
    // else DCfanSpeed = DCfanSpeed;
    while (voltsZero == 5) {
      analogWrite(motorPin1, DCfanSpeed);
      analogWrite(motorPin2, DCfanSpeed);
      voltageReadingZero = analogRead(voltageZero);
      voltsZero = voltageReadingZero / 204.6;
    }
  }
  int voltageReadingOne = analogRead(voltageOne); // LOW SWITCH
  int voltsOne = voltageReadingOne / 204.6;
  if (voltsOne == 5) {
    delay(300);
    if (voltsOne == 5) DCfanSpeed = 128;
    //else DCfanSpeed = DCfanSpeed;
    while (voltsOne == 5) {
      analogWrite(motorPin1, DCfanSpeed);
      analogWrite(motorPin2, DCfanSpeed);
      voltageReadingOne = analogRead(voltageOne);
      voltsOne = voltageReadingOne / 204.6;
    }
  }
  int voltageReadingTwo = analogRead(voltageTwo); //  MED SWITCH
  int voltsTwo = voltageReadingTwo / 204.6;
  if (voltsTwo == 5) {
    delay(300);
    if (voltsTwo == 5) DCfanSpeed = 191;
    //else DCfanSpeed = DCfanSpeed;
    while (voltsTwo == 5) {
      analogWrite(motorPin1, DCfanSpeed);
      analogWrite(motorPin2, DCfanSpeed);
      voltageReadingTwo = analogRead(voltageTwo);
      voltsTwo = voltageReadingTwo / 204.6;
    }
  }
  int voltageReadingThree = analogRead(voltageThree);  //  HIGH SWITCH
  int voltsThree = voltageReadingThree / 204.6;
  if (voltsThree == 5) {
    delay(300);
    if (voltsThree == 5) DCfanSpeed = 255;
    //else DCfanSpeed = DCfanSpeed;
    while (voltsThree == 5) {
      analogWrite(motorPin1, DCfanSpeed);
      analogWrite(motorPin2, DCfanSpeed);
      voltageReadingThree = analogRead(voltageThree);
      voltsThree = voltageReadingThree / 204.6;
    }
  }
}

```

Excuse the poor formatting but the basic rundown of the medium option is such that the voltage across the analog pin 2 is measured and converted into volts and if it is 5 Volts (rotary turned to the medium position) then it enters a while loop where the voltage is monitored such that if there is any change then there must be a speed setting change. This is the only option for which I get this pulsating speed on the fans instead of smooth and continuos operation.

Any ideas about how I could improve this? I have taken away one fan to see if one was faulty but this didn't work.

# Answer
Solved simply by condensing code and getting rid of unnecessary variable declarations.

Corrected program:

```
    int motorPin1 = 3;
    int motorPin2 = 9;
    int DCfanSpeed = 0;

    void setup()
    {
      pinMode(motorPin1, OUTPUT);
      pinMode(motorPin2, OUTPUT);
      digitalWrite(A0, INPUT_PULLUP);
      digitalWrite(A1, INPUT_PULLUP);
      digitalWrite(A2, INPUT_PULLUP);
      digitalWrite(A3, INPUT_PULLUP);
      Serial.begin(9600);
    }

    void loop()
     {

       int voltsZero = analogRead(A0)/204.6; // OFF SWITCH
       if(voltsZero == 5)
        {
          delay(300);
          if(voltsZero == 5) DCfanSpeed = 0;

           while(voltsZero == 5)
            {
              analogWrite(motorPin1, DCfanSpeed);
              analogWrite(motorPin2, DCfanSpeed);
              voltsZero = analogRead(A0)/204.6;

            }
         }

      int voltsOne = analogRead(A1)/204.6;    // LOW SWITCH
      if(voltsOne == 5)
        {
          delay(300);
          if(voltsOne == 5) DCfanSpeed = 128;
          while(voltsOne == 5)
           {
             analogWrite(motorPin1, DCfanSpeed);
             analogWrite(motorPin2, DCfanSpeed);
             voltsOne = analogRead(A1)/204.6;
           }
        }

       int voltsTwo = analogRead(A2)/204.6;  //  MED SWITCH
       if(voltsTwo == 5)
        {
          delay(300);
          if(voltsTwo == 5) DCfanSpeed = 191;
          while(voltsTwo == 5)
           {
             analogWrite(motorPin1, DCfanSpeed);
             analogWrite(motorPin2, DCfanSpeed);
             voltsTwo = analogRead(A2)/204.6;

           }
        }

      int voltsThree = analogRead(A3)/204.6;  //  HIGH SWITCH
      if(voltsThree == 5)
        {
          delay(300);
          if(voltsThree == 5) DCfanSpeed = 255;
          while(voltsThree == 5)
           {
             analogWrite(motorPin1, DCfanSpeed);
             analogWrite(motorPin2, DCfanSpeed);
             voltsThree = analogRead(A3)/204.6;
           }
         }

    }

```
> 0 votes

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


title: Arduino: Camera streaming

text:
# Question
Title: Arduino: Camera streaming
I want to make Arduino to stream video by camera thru bluetooth to android.

1. Is Arduino powerfull enough to stream it without lag(Sorry if the question is stupid)
2. Are there any good cameras, I have been searching before, but only found one 0.3 mp camera, so are there other cameras with better quality?
3. What is better, to use Arduino or Rasberry Pi for that job?

# Answer
> 3 votes
1. Not even close
2. In light of 1 it doesn't matter
3. Get a Pi if you want to do video

# Answer
> 1 votes
Assuming a 0.3 MP camera, that means 300,000 pixels. The Arduino (Uno) has a few KB of SRAM, so you need much more. External SRAM might be an option, but even 300.000 pixels need a lot (like multiple 23LC1024 SRAMs).

Also the Arduino is 16 MHz. This means 16.000.000 cycli/s. That means for every pixel processing only 53 cycli are available. And using those external SRAMs will probably need much more.

A Raspberry is much more suitable for this task.

---
Tags: bluetooth, android
---


title: Arduino Due's clock frequency

text:
# Question
Title: Arduino Due's clock frequency
I want to change the clock frequency of the Arduino Due. The default value of the main clock, according to the SAM micro-controller, is 4 Mhz. But I found in some forums that it is 84 Mhz. But I need to work with it at 16 Mhz. Hence, I need to access to the low-level clocks of the Due and **change its operating clock frequency**.

1. How can I find the low-level registers of the Due in the Arduino IDE? Any header files for the Due to change its clocking?
2. Is it possible to write code for the Arduino Due via Atmel Studio 7? When I tried compiling code in AS7, Chip.h was not found. How to avoid this? Is it possible with "micro" IDE in AS7? Can I access registers of the Due via AS7 and change its clocking?
3. I cannot find the "sam" library in the Arduino IDE. Only avr is present. How can I find this sam library?

# Answer
> 1 votes
> How can I find the low-level registers of the Due in the Arduino IDE? Any header files for the Due to change its clocking?

Read the datasheet / programming manuals for the chip. The Arduino Due is arranged to run at 84MHz.

> I cannot find the "sam" library in the Arduino IDE. Only avr is present. How can I find this sam library?

Install it. The IDE is (fairly) modular these days.

But I have to ask... why do you want to run at 16MHz?

---
Tags: arduino-ide, arduino-due, frequency, oscillator-clock, atmel-studio
---


# Question
Title: Power Arduino with 12V while using Serial Communication over USB
I'm going to build a **8x8x8 Led RGB Cube**, therefore I will need a **lot of Power** which the **arduino can't handle**, so I'm using a **12V** 20A (I know 20A isn't necessary but I had one laying around).

So the question is, is it possible to power the arduino over the Vin Pin with the 12V and program / communicate over serial connection in the same time? Like a real time programmed RGB LED Cube.

simulate this circuit – Schematic created using CircuitLab

# Answer
**How to power an Arduino**

Arduino can manage multiple power inputs at the same time while fully operational (incluide Serial - USB connection to the PC).

**JAPAN JACK socket:** an external source (a power supply, usually) must be connected to this socket, with the positive pole going to the central part of the jack, and the value must be ranging between 6 V and 20 V, even though the range recommended by the manufacturer is 7÷12 V, thus it is not advisable to use voltages that are lower than 7 V or greater than 12 V, if not in the case of a real need; 6 V may not guarantee a proper stabilization on the part of the regulator, it is in fact needed to consider the voltage fall of the protection diode, placed in series at the regulator’s input (whose purpose is to preserve the board from destruction in the case of polarity inversion on the jack); while values above 12 V would create an excessively high drop-out (an electric potential difference between the regulator’s input and output) that would cause a pointless overheating of the regulator, even with low levels of current draw.
> 2 votes

# Answer
I'm now starting to doubt what I though about Arduinos. If you are using a 12V PSU to power the Arduino, you are only going to get 5V out of the vOut pin. The 20Amps you are supplying isn't going to come out either, all you'll get is ~300mA from the vOut or ~20mA from the digital pins. This is because of all the regulators.

If you want to get the Arduino to switch LEDs on and off from another source you are going to need **transistors**. This will let you switch different voltages and higher currents.
> 0 votes

---
Tags: serial, power, communication, voltage
---


# Question
Title: Controlling two AC devices, device turning on incorrectly
I am making use of the code below to control the speed of an AC fan and the intensity of an AC Lamp with an Uno.

The problem I am having is that, when I set the lamp intensity to low or medium, the fan turns on at a very low speed as well, and I cannot turn it off even when setting the fan to off.

Also if I turn the lamp on and then off, the fan (which is still set as off), will spin slowly for a second or two in random intervals.

For troubleshooting purposes, I did separate this program into two programs, controlling each device and its circuit separately, and it works perfectly, but when I combine them, I get the above problem.

Any assistance in troubleshooting or ideas to solve this would be appreciated. Haven't attempted AC control before.

```
int PWM = 3;
int FAN = 4;
int dimming;

void setup()
{
  Serial.begin(9600);
  Serial.println("Serial connection started, waiting for instructions…n0 =     Offn1 = 25%n2 =50%n3 = 75%n4 = 100%");
  pinMode(PWM, OUTPUT);
  pinMode(FAN, OUTPUT);

  attachInterrupt(0, zero_crosss_int, RISING);
}

void zero_crosss_int()
// function to be fired at the zero crossing to dim the light
{
  int dimtime = (75 * dimming);  // For 60Hz =>65
  delayMicroseconds(dimtime);    // Off cycle
  digitalWrite(FAN, HIGH);   // triac firing
  delayMicroseconds(10);         // triac On propogation delay
  //(for 60Hz use 8.33)
  digitalWrite(FAN, LOW);    // triac Off
}

void loop ()
{
  if (Serial.available()) {
    char ser = Serial.read(); //read serial as a character

    switch (ser)
{

  /* Lamp Control  */

  case '0':
    analogWrite(PWM, 0);  //lamp Off
    break;
  case '1':
    analogWrite(PWM, 50);  //lamp low
    break;

  case '2':
    analogWrite(PWM, 130); //lamp medium
    break;

  case '3':
    analogWrite(PWM, 255); //lamp high
    break;

  /* Fan Control  */

  case '4':
    dimming = 128;  //fan off
    break;

  case '5':
    dimming = 90; //fan low
    break;

  case '6':
    dimming = 65; //fan medium
    break;

  case '7':
    dimming = 35; //fan high
    break;

  default:
    Serial.println("Invalid entry");

    }
  }
}

```

The circuits it controls is based on these :

Lamp

Fan

Also, these circuits and code are based on these post, if it may interest you:

Lamp PWM AC Lamp

Fan Dimmer AC Fan

# Answer
The design of the zero\_crosss\_int() ISR is unreliable. After each interrupt it unconditionally turns on the triac, even in the OFF position. Since the `dimming` value in that case is close to the AC cycle duration, it may miss the current cycle and turn on early in the next cycle. This may happen e.g. due to noise in zero crossing input.

75 us * 128 = 9.6 ms. Assuming 50 Hz AC, cycle duration is 1000 ms / 100 = 10 ms. You only have 4% margin.

You need to avoid turning on the triac close to the end of the AC cycle. Limit the maximum value of `dimming` variable to, say, 75% of the AC cycle. This will impose a lower limit on the output power. However, you want to do this anyway because motors need a minimum power to start rotating. Adjust the ISR so that in the OFF position it does not send a positive pulse at all.

ADDED: so you just need to add an `if` statement to you ISR code:

```
void zero_crosss_int()
// function to be fired at the zero crossing to dim the light
{
  if (dimming > 96) // choose this value experimentally, adding some margin
    return;
  ... everything else goes here ...
}

```

ADDED2: Blocking for extended duration in the ISR is not a good idea in general. If you happen to need to do anything else in addition to 'dimming' a fan, you will almost certainly need to get rid of this. You could start a timer in the ISR and send the output pulse in the timer ISR, making sure that the timer ISR does not get executed after the next zero-crossing ISR...
> 1 votes

# Answer
Imraan, you have most definitely NOT build your circuit safely as to do so is impossible on a 'breadboard' when using 220 VAC. The contacts on these boards are extremely poor not to mention that the separation between the metal contacts is inadequate. Please read up on track separation for mains voltages on PCB's to get an idea of what is required. The commonly used 0.1" pitch strip board is also unsuitable for mains voltages.
> 2 votes

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


# Question
Title: Trying to connect a 1.3" IIC OLED display to an Arduino M0 board (not Uno)
I'm trying to connect an OLED display to the Arduino M0. I got the code example (ssd1306\_128x64\_i2c) from the Adafruit SSD1306 library I downloaded.

Video showing at 8:14 how it should look

However, when I upload the code to the board most of the display just lights up with no motion. It's only in the bottom that you can see the program is running, showing part of the different shapes.

After I uploaded it the first time I didn't change anything but now the compiler gives an error message saying that one display setting must be specified in SSD1306.h

I've tried setting the display size in the library header file which looks like this:

```
Displays
-----------------------------------------------------------------------
The driver is used in multiple displays (128x64, 128x32, etc.).
Select the appropriate display below to create an appropriately
sized framebuffer, etc.

    SSD1306_128_64  128x64 pixel display
    SSD1306_128_32  128x32 pixel display
    SSD1306_96_16

#define SSD1306_128_64
//#define SSD1306_128_32
//#define SSD1306_96_16

```

But the same error message appears in the compiler.

Does anybody know how I can fix this?

Thank you.

# Answer
That header part should look like this (notice the comment starts and ends):

```
    /*=========================================================================
    SSD1306 Displays
    -----------------------------------------------------------------------
    The driver is used in multiple displays (128x64, 128x32, etc.).
    Select the appropriate display below to create an appropriately
    sized framebuffer, etc.
    SSD1306_128_64  128x64 pixel display
    SSD1306_128_32  128x32 pixel display
    SSD1306_96_16
    -----------------------------------------------------------------------*/
#define SSD1306_128_64
//   #define SSD1306_128_32
//   #define SSD1306_96_16
/*=========================================================================*/

```

If it compiles but doesn't work try to replace the I2C address of Adafruits 128x64 module (0x3D) by the address often used in Chinese modules (0x3C):

```
display.begin(SSD1306_SWITCHCAPVCC, 0x3D);

```

to

```
display.begin(SSD1306_SWITCHCAPVCC, 0x3C);

```

If that doesn't work, use an I2C scanner to find the address of the connected module.
> 0 votes

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


# Question
Title: How do I make the HC-05 bluetooth module take data from the HC-SRO4, and then send it to my Android app?
Currently, I have an Arduino Uno set up, with a HC-SRO4 ultrasonic sensor printing distances of objects in front of it on a scale from 1-15 to the serial monitor. I want to attach the HC-05 bluetooth module and do the following: First, it will read the values from the serial monitor. Then, I would like the HC-05 module to take these numbers and continuously send it to my Android app, which will then process what to do with the numbers.

I understand the Android part may be out of scope of this forum, but please try to help me with taking data from the serial monitor and have it transmit the data.

Here is the code I have for the ultrasonic sensor:

```
const int trigPin = 9;
const int echoPin = 10;
// defines variables
long duration;
int distance;
void setup() {
  pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
  pinMode(echoPin, INPUT); // Sets the echoPin as an Input
  Serial.begin(9600); // Starts the serial communication
}
void loop() {
  // Clears the trigPin
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  // Sets the trigPin on HIGH state for 10 micro seconds
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  // Reads the echoPin, returns the sound wave travel time in microseconds
  duration = pulseIn(echoPin, HIGH);
  // Calculating the distance
  distance = duration * 0.034 / 2;
  // Prints the distance on the Serial Monitor
  Serial.print("Distance: ");
  Serial.println(distance);
}

```

# Answer
> First, it will read the values from the serial monitor. Then, I would like the HC-05 module to take these numbers and continuously send it to my Android app, which will then process what to do with the numbers.

No. What you do is you connect your Bluetooth module to two digital pins, which you'll use, along with the `SoftwareSerial` library, just the way you are using currently the `Serial` object. Look at the `SoftwareSerial` examples in the IDE.

Before you use the HC-05 module, and transmit data, you'll have to make sure it is set up properly (baud rate, name, PIN code, etc). Plenty of code and tutorials on Google about that.
> 1 votes

# Answer
Use software serial library and connect your HC-05 TX RX pins accordingly, to transmit/recieve the ultrasonic data using bluetooth. From playstore you will get bluetooth terminal software. Install it in your smart phone. Now connect your phone's bluetooth to HC-05 using that software. Now you can see in that app, all data you are receiving via bluetooth. you can also transmit data using that app. If you want to develop your own app, maybe you can check out MIT app inventor. Simple and fast.
> 0 votes

---
Tags: arduino-uno, hc-05, android, code-review, hc-sr04
---


# Question
Title: Where is random defined with no arguments?
I can't seem to find `void random()` (with no arguments) defined in the library and yet my sketches seem to compile just fine when calling `random()` with no arguments.

I've found random with 1 argument and random with 2 arguments but no cases of random with no arguments.

Is `random()` defined in the library with no arguments?

If so, where is it defined?

If it isn't, what could explain how my code compiles despite me not providing any arguments?

# Answer
> 1 votes
It's defined in the libc, in `stdlib.h`.

---
Tags: library
---


title: Const data optimisation for Arduino

text:
# Question
Title: Const data optimisation for Arduino
I'm taking a course on Arduino Uno programming and on today's talk I heard that the const data is optimized by Arduino, so that it occupies less space than the actual data type (namely, a const int occupies less than an int).

If instead of int I use const uint8\_t, const uint16\_t etc. is the optimization still applied, or does using the 8 and 16 bit ints represent bad practice?

# Answer
> 4 votes
This question is not really about the Arduino. It is about GNU C/C++ compiler optimizations.

By adding the keyword `const` the compiler can do a lot of optimization. One is that the value does not need to be stored in SRAM. The value can end up as part of an instruction, become part of an expression that is evaluated at compile-time, etc.

In the Arduino-GPIO library `static const` member data is used to allow the compiler to optimize to a single instruction `digitalRead()` with almost X100 performance improvement (on Arduino Mega).

Check GCC and AVR optimizations for further details.

1. http://www.nongnu.org/avr-libc/user-manual/using\_tools.html
2. https://gcc.gnu.org/wiki/avr-gcc
3. http://www.linuxjournal.com/article/7269

Cheers!

# Answer
> 1 votes
Const memory will still store ts value both in Flash and in SRAM. For arrays PROGMEM can be used and for strings F() to remove the copy to SRAM.

Normal (non const) memory will be stored in SRAM. And if it is initialized with a value, that value is stored in Flash.

However, uint8\_t will always occupy 1 byte, and uint16\_t always two bytes.

You can read more about the different types of memory and F here.

You can read more about program here.

Update:

Test with const:

```
const uint8_t  Amount1 = 4;
const uint8_t  Amount2 = 4;
const uint8_t  Amount3 = 4;
const uint8_t  Amount4 = 4;
const uint8_t  Amount5 = 4;
const uint8_t  Amount6 = 4;
const uint8_t  Amount7 = 4;

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

void loop() {
  // put your main code here, to run repeatedly:
  Serial.print(Amount1);
  Serial.print(Amount2);
  Serial.print(Amount3);
  Serial.print(Amount4);
  Serial.print(Amount5);
  Serial.print(Amount6);
  Serial.print(Amount7);
}

```

Result: 1758 bytes of program storage space, 184 bytes of dynamic memory.

Same without word 'const:

Result: 1758 bytes of program storage space, 184 bytes of dynamic memory. No difference

using #define Amount1..7 4

Result: 1702 bytes of program storage space, 184 bytes of dynamic memory.

Conclusion: to save Flash space, use #define instead of (const) uint8\_t. However, also see Jot's experiment, it seems that code optimalization is smarter than my conclusion.

---
Tags: arduino-uno, code-optimization, memory-usage, data-type, memory
---


# Question
Title: Problem with simple coding for PLDuino: trying to turn relay on and off
I am writing the following, simple code to try to turn a relay in the PLDuino on and off, and it is giving me warnings and not compiling/uploading. Any help would be greatly appreciated. Here is my code:

```
#include <PLDuino.h>
using namespace PLDuino;

void setup()
{
  // A necessary call.
  // It sets pin modes according to their function.
  PLDuino::init();
}

void loop()
{
  // Simple switch RELAY3 on and off with 2 second timeout.
  digitalWrite(PLDuino::RELAY3, HIGH);
  delay(2000);
  digitalWrite(PLDuino::RELAY3, LOW);
  delay(2000);
}

```

I have installed the proper libraries. Here are the warnings I am getting:

```
WARNING: Category 'Graphics' in library PLDTouch is not valid. Setting to 'Uncategorized'
WARNING: Category 'General' in library PLDuino-Library is not valid. Setting to 'Uncategorized'
WARNING: Category 'Graphics' in library PLDuinoGUI is not valid. Setting to 'Uncategorized'
Sketch uses 1702 bytes (0%) of program storage space. Maximum is 253952 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 8183 bytes for local variables. Maximum is 8192 bytes.
avrdude: ser_open(): can't open device "\\.\COM4": The system cannot find the file specified.

avrdude: ser_drain(): read error: The handle is invalid.

avrdude: ser_send(): write error: sorry no info avail
avrdude: stk500_send(): failed to send command to serial port
avrdude: ser_recv(): read error: The handle is invalid.

avrdude: ser_recv(): read error: The handle is invalid.

avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: ser_send(): write error: sorry no info avail
avrdude: stk500_send(): failed to send command to serial port
avrdude: ser_recv(): read error: The handle is invalid.

avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: ser_send(): write error: sorry no info avail
avrdude: stk500_send(): failed to send command to serial port
avrdude: ser_recv(): read error: The handle is invalid.

avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: ser_send(): write error: sorry no info avail
avrdude: stk500_send(): failed to send command to serial port
avrdude: ser_recv(): read error: The handle is invalid.

avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: ser_send(): write error: sorry no info avail
avrdude: stk500_send(): failed to send command to serial port
avrdude: ser_recv(): read error: The handle is invalid.

avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: ser_send(): write error: sorry no info avail
avrdude: stk500_send(): failed to send command to serial port
avrdude: ser_recv(): read error: The handle is invalid.

avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_getsync(): timeout communicating with programmer

```

# Answer
For the library warning, you'll need to add / edit library.properties to those folders to specify a valid category.

This is an example library.properties to give you a feel for the structure (I found this particular one here).

```
name=TMRpcm_PLDuino
version=1.0
author=TMRh20
maintainer=digitalloggers
sentence=PCM/WAV Audio playback (USE_TIMER2 enabled)
paragraph=Play WAV audio files from SD card using AVR (UNO,Nano,etc) based devices.
category=Communication
url=https://github.com/digitalloggers/TMRpcm_PLDuino
architectures=avr

```

However, these are just warnings, and don't seem to be the cause of your problem.

---

Your actual problem in this case seems to be that it's trying to upload the sketch via COM4 and it can't find the PLDuino on that port.
> 1 votes

---
Tags: programming, uploading, relay, compilation-errors
---


# Question
Title: can arduino on output mode sink current?
I have a arduino set below:

```
pinMode(1,OUTPUT);
digitalWrite(1,LOW);

```

Now, I am expecting 1.2mA current flow through the pin that is set as output. Is that accepted? If so, what it the max current a pin can sink?

The current comes from a pul up resistor on the line

note: I can't protect it with a diode.

# Answer
Ok, I just found it.

from the arduno docs:

Atmega pins set aa output can source (provide positive current) or sink (provide negative current) up to 40 mA (milliamps) of current to other devices/circuits.
> 6 votes

# Answer
Yes it can. This blog post of mine will help to explain it.

In short:

> It’s all so simple now, isn’t it? The output pin is just like a switch that either connects it to 5V or to ground.
> 2 votes

# Answer
> can arduino on output mode sink current?

yes.

> from the arduno docs:

the datasheet for the particular device is the best place for that answer.
> 1 votes

---
Tags: arduino-uno, pins
---


# Question
Title: How to use arduino IDE to compile .s files
Hi I'm new to arduino and im using it to learn assembly for my computer hardware 101 class, I read online that I can make the IDE accept .s files and compile them to the board but I dont know how to do this (something about editing the source code and recompiling the IDE?).

Could I get a step by step walk through? Assuming it's relatively simple, or just a link to some relevant documentation that's not a literal reference manual :-).

**EDIT** As terrible as it is,I'm working from a macbook pro

# Answer
The IDE should be able to accept `.S` files (not `.s` \- the difference is very important: `.S` will be preprocessed, `.s` won't).

Just create a new sketch, and create a new tab called `whatever.S` (obviously rename the `whatever` to whatever you want to call it.

Then in the main sketch `.ino` file put something like:

```
extern "C" void myAssemblyMain();

void setup() {
    myAssemblyMain();
}
void loop() {
}

```

That will then call the function `myAssemblyMain:` in your assembly file and not much else.

(Note: I haven't tested this since I don't use the Arduino IDE).
> 3 votes

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


# Question
Title: Arduino Mega + SIM808 GSM + GPS Module + Program Switch ON without pressing Push Button?
I am new to IOT and tried out integration and a small test code with an Arduino Mega + SIM808 + GSM + GPS Module. It works fine with the SIM808 Library.

My requirement is to put it in an enclosure, but when the power restarts, for some reason we have to manually start the SIM 808 + GPS + GSM Module. Can we control it from code? Can we do a software trigger from Arduino code?

Maybe if we have some pins to connect and trigger the power on. Kindly provide inputs/suggestion for this module.

If you are aware of some module that can be started through code kindly suggest.

Here's one reference I found for a different module with Software Trigger.

# Answer
> 6 votes
There is a simple way of power the module without pressing the button. There is pin call D9 at the bottom right corner of the module. Just power the pin by Arduino digital pin or 5v pin around 3, 4 seconds. Then it will power the whole module. No need to press the press switch. Make sure you connect power(9V-12V) to the board and provide 5V and GND to the sim808 module. below figure shows the pin D9

# Answer
> 0 votes
I can't get a great view of the board, but if you are pressing the button just below "GSM" and "Made" then I would suggest soldering some leads onto the button and connecting them to a digital output and Gnd on the Arduino. (You might need resistors and stuff) Then when you wanted to press the button you could pulse the line high.

---
Tags: arduino-mega, gsm, gps
---


title: Creating a queue in Arduino?

text:
# Question
Title: Creating a queue in Arduino?
Does anyone know if there is a way to create a queue of some sort for arduino?

My project consists of simulating multiple traffic lights with crossing pedestrians on an Arduino breadboard. Since I need to assume the situation where on all sides are cars waiting + pedestrians having pressed the button, I needed to figure out a way to store these inputs into an array of some sort.

However, the problem with array I believe is that it doesn't allow me to shift the data to the left, so that the next one will be selected in the queue. Deleting the data inside an array would only merely make it null, which doesn't work.

Greatly appreciated if someone can help me by pointing to the right direction.

# Answer
I wrote a simple queue library some weeks ago, you can find it in the arduino library manager, or here: Queue

I think you need FIFO implementation, but LIFO is also implemented in the lib & possibility to overwrite previous records when full.
It can handle any structure or data type (as long as it's size is fixed for memory allocation), defining a number of records in the queue, then you're good to go.

2 methods are implemented to interact with the queue, push() & pull(). I'll probably add a peek() later on if needed.

I also noticed this other FIFO only queue lib in the library manager when I commited mine: MD\_CirQueue

Hope this can help!
> 3 votes

# Answer
Regarding how to “create a queue of some sort for Arduino”, about the first thing to settle is how many items may need to be queued. On a typical personal computer with gigabytes of RAM, queue size often is not much of an issue ... one just allocates a few more megabytes whenever necessary. On an typical Arduino, however, with a few kilobytes or few tens of kilobytes of RAM, use of dynamic (heap) allocation is risky unless you carefully analyze possible execution paths.

If you are ok with a fixed queue size, the next issue is what kind of queue, eg FIFO, LIFO, priority, etc. The question's concern about a “shift the data to the left, so that the next one will be selected in the queue” issue suggests a FIFO (first in first out) queue is desired. For this, a circular buffer or circular queue is a relatively-low-overhead method often used. Using terms from the wikipedia article, Start and End pointers are maintained, marking next-data-out and last-data-in positions. Via modular arithmetic or `if` tests, each of these pointers wraps to array front whenever it goes past the array end. The queue is empty if `Start == End` (modulo N, if queue size is N) and full if `Start == End+1`.

If an interrupt-driven process can modify pointers asynchronously to the main thread of execution, then synchronization methods need to be used to ensure atomic updates of pointers. (This is true for all kinds of queues, not just circular ones.)

If instead of a FIFO queue you need a priority queue, a binary heap is easy to implement. Usually Fibonacci heaps and binomial heaps are not worth the extra trouble of implementing, except when you need efficient heap merging or secondary operations like decreasing keys of elements. The Summary of running times section of wikipedia's binomial heap article shows the complexity of different operations across different heap structures. Note that with Arduino RAM being so limited, a complexity difference like Θ(log n) vs Θ(1) is negligible; simplicity of code, leading to a compact implementation, is more important.

Note, also see *QueueList Library For Arduino* at arduino.cc. This library apparently uses dynamic allocation. It provides methods `push(), pop(), peek()` et al. Also see *QueueArray Library For Arduino* at arduino.cc, which provides the same methods as *QueueList*, plus `enqueue` and `dequeue()` as synonyms for `push()` and `pop()`. Where *QueueList* uses lists to build its data structures, *QueueArray* uses arrays.

*OsWrap* at arduino.cc is a heavy package (eg 15KB flash, 1.5KB RAM) that supports various message and priority queue structures.

Depending on your rationale for using a queue, *Task Scheduler Library* may also be of interest.

As noted in Mikael Patel's comments above, Cosa platform software includes a Queue class, which is a “Template class for ring-buffer for queueing data elements”, with usage of the class illustrated in an Event class, which in turn is used in a Job class.
> 2 votes

# Answer
I had an arduino project that I needed to build a queue for.

You can download the source code and copy into a file called `Queue.h` next to your arduino `project.ino` file.

Here is a simple interactive example (with the Serial monitor) to see how its used, make sure you set the `baud rate` to 115200 and `No new line`.

```
#include "Queue.h":

Queue<char> queue(10);

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

void loop() {
  while(Serial.available()) {
    queue.push(Serial.read());
  }

  Serial.print(millis() / 1000);
  Serial.print(": ");
  int count = queue.count();
  if (count > 0) {
    Serial.print("Found ");
    Serial.print(count);
    Serial.print(" items.. '");
    Serial.print(queue.pop());
    Serial.print("' is the oldest. Next is.. '");
    Serial.print(queue.peek());
    Serial.println("'.");
  } else {
    Serial.println("Nothing to process...");
  }
  delay(2000);
}

```
> 0 votes

---
Tags: programming
---


# Question
Title: Arduino IDE not compile .S program to board
After answering my previous question correctly I'm getting all sorts of errors when trying to compile the following program:

I'm completely new to both assembly and the arduino IDE so I apologise in advance for any basic errors.

sketch.ino:

```
#include "blink.S"
extern void blink();
void setup() {
  // put your setup code here, to run once:
blink();
}

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

}

```

blink.S file:

```
#define __SFR_OFFSET 0
#include <avr/io.h>

  .section .text

  ldi r18, 0x20   ; loading 0x20 = 00100000 into register r18
  out DDRB, r18   ; making pin 5 of port B an output

  mov r16, r18    ; copy mask 00100000 also to r16

loop: out PORTB, r16    ; switch on or off the pins of port B
        ; according to bit pattern in r16

  ldi r17, 82   ; 1000ms delay, see below

outer_delay:
  clr r1
middle_delay:
  clr r2
inner_delay:
  dec r2      ; 1 clock tick
  brne inner_delay  ; 2 clock ticks when z!=0, 1 tick when z=0.

  dec r1      ; when this line is reached, about
        ; 256*3 = 768 ticks have been consumed since inner_delay.
  brne middle_delay ;

  dec r17                 ; when this line is reached, about
        ; 256*256*3 = 196608 ticks have been
        ; consumed since middle delay.
  brne outer_delay

  eor r16,r18   ; invert bit 5 in r16 using exclusive or.
  rjmp loop   ; jump back to loop.

```

# Answer
> 0 votes
A couple of things you can try.

First, make sure your assembly code makes the `blink()` function visible to the linker. blink.S should start like this:

```
#define __SFR_OFFSET 0
#include <avr/io.h>

.section .text
.global blink
blink:
  ; Your assembly code goes below the above label.

```

Next, your sketch file should not try to include the assembly source. It should only reference it as an external symbol. And note that the symbol should be declared `extern "C"`.

If your program is a mix of assembly and Arduino code, you could start with this sketch.ino:

```
extern "C" void blink();

void setup() {
    blink();
}

void loop() {}

```

If you are not using the Arduino core library, you could instead write:

```
extern "C" void blink();

int main(void)
{
    blink();
    return 0;
}

```

And if you don't want to use C++ at all, you could try to use a dummy or empty sketch.ino, and rename “blink” to “main” in blink.S.

# Answer
> 1 votes
There's four things I can see wrong (one of which is my fault, actually - I should have mentioned it in the previous question - nevermind).

Firstly you cannot include a .S file in a .INO file. A .S file is assembly, a .INO file is C++. You can't mix the two in one file (and including a file does just that - includes the file verbatim at that point). So remove that `#include`. Otherwise it would be like opening a book written in English only to find the preface is written in Klingon.

Secondly you need to give your function a name. It doesn't have one at the moment. Naming the file is *not* naming the function.

So you need to provide a label at the entry point:

```
  .section .text

blink:    ; << This is the name of the function
  ldi r18, 0x20   ; loading 0x20 = 00100000 into register r18
  out DDRB, r18   ; making pin 5 of port B an output

```

Third you need to export that name as a global symbol:

```
  .section .text
  .global blink ; << This exports the function name

blink:    ; << This is the name of the function
  ldi r18, 0x20   ; loading 0x20 = 00100000 into register r18
  out DDRB, r18   ; making pin 5 of port B an output

```

And finally you have the problem of linkage name munging. You're linking a C++ file with (ostensibly) a C file - and C++ munges names. So you have to tell your C++ file that the function is not a C++ function, but a C function (which is what I should have mentioned previously):

```
extern "C" void blink(); // << Add the "C" to tell it not to munge the name

void setup() {
  // put your setup code here, to run once:
  blink();
}

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

```

---
Tags: arduino-ide, java, assembly
---


# Question
Title: Voltage divider for 6 non intrusive current sensors
I have an Arduino project where I intend to use 6 non intrusive current sensor model SCT013 (100A/50mA) manufactured by yhdc.com

As reference voltage on examples I find at the internet it is suggested the use of 2 10K resistor connected in series from 5V to ground, the reference voltage is extracted from the middle connection between the resistors (2.5v).

Question:

In the case of six sensors will I have to use 6 independent voltage dividers or can I use a single divider as reference for all sensors?

I am concerned the interference between sensors may cause reading imprecision.

Thanks in advance Paulo

# Answer
I assume you refer to a circuit like this:

simulate this circuit – Schematic created using CircuitLab

The "reference" you speak of is not a reference - it is a *virtual ground*. A ground reference that is at a different potential to the Arduino - in this case 2.5V higher.

Since it is just the ground for the circuit you can use the same one for all the current transformers without problems.

If the offset voltage were applied to the output (as is often done for active devices that create an AC waveform, such as audio signals) then you would require a separate offset voltage for each one, since otherwise you would be connecting all the outputs together, which would be bad.

You can also "reverse" your thinking. The "offset" voltage you apply is ground, and the Arduino's "ground" is 2.5V *below* that. It's all relative.
> 1 votes

---
Tags: arduino-mega, sensors, voltage-level, current, analogreference
---


# Question
Title: How can configuration values be stored on an ESP8266?
I have a project that uses an MQTT service, and I'm wondering how to best store the configuration settings (server, user, password, port) for the service as right now they are just hard-coded into some constants.

I saw that EEPROM can be used for this but I'm not sure it is the best way. I went to look at the code for WifiManager to see how it accomplishes this task for the SSID and password since it works so well and it removed its EEPROM dependency back in 2015: https://github.com/tzapu/WiFiManager/commit/659df9cb277c5f93946d9d8795e39a5ae5863ab1

I can't figure out how those settings are persisted.

If EEPROM *is* the best way for storing something like this, I'd like to write my values without overwriting/corrupting existing values, is that possible? How can I set the initial values of the EEPROM to the constants that I need?

**Edit:** well after digging into the esp8266/Arduino repository I found that the `WiFi.SSID()` and `WiFi.psk()` settings come from `wifi_station_get_config` and stored with `wifi_station_set_config` although I haven't found how *those* work so I think EEPROM might be the way to go here, I just need a bit of guidance and clarification on the right way to use it.

# Answer
Thanks to Jaromanda X and Juraj for the SPIFFS recommendation. I was able to use this block of SPIFFS code as an example and safely store settings in my project outside of the compiled source.

To upload files to my ESP8266, I followed the installation and usage instructions for the ESP8266 filesystem plugin for the standard Arduino IDE.

First, I created a `.gitignore` file and added this so that none of the actual values would get added to the repository:

```
# MQTT config info
data/config.json

```

Then I created a `data` folder and added a `config.json` file that had all the configuration properties that I need to reference:

```
{
  "cloudmqtt_server": "***.cloudmqtt.com",
  "cloudmqtt_user": "********",
  "cloudmqtt_pass": "************",
  "cloudmqtt_port": 10000
}

```

Following the example above, I added `#include <FS.h>` at line #1 (as well as `#include <ArduinoJson.h>` for parsing the JSON) and have this block to instantiate the variables with dummy values that will be replaced by the actual values from the JSON file:

```
// MQTT pub/sub for the servo functions
#define CLOUDMQTT_CONFIG  "/config.json"
// these values are loaded from a config.json file in the data directory
char cloudmqtt_server[18] = "***.cloudmqtt.com";
int  cloudmqtt_port       = 0;
char cloudmqtt_user[9]    = "********";
char cloudmqtt_pass[13]   = "************";

```

Then in the setup I have this block to load the values from the config:

```
if (SPIFFS.begin()) {
  Serial.println("mounted file system");

  // parse json config file
  File jsonFile = GetFile(CLOUDMQTT_CONFIG);
  if (jsonFile) {
    // Allocate a buffer to store contents of the file.
    size_t size = jsonFile.size();
    std::unique_ptr<char[]> jsonBuf(new char[size]);
    jsonFile.readBytes(jsonBuf.get(), size);

    DynamicJsonBuffer jsonBuffer;
    JsonObject& json = jsonBuffer.parseObject(jsonBuf.get());
    if (json.success()) {
      strcpy(cloudmqtt_server, json["cloudmqtt_server"]);
      cloudmqtt_port = json["cloudmqtt_port"];
      strcpy(cloudmqtt_user, json["cloudmqtt_user"]);
      strcpy(cloudmqtt_pass, json["cloudmqtt_pass"]);
    } else {
      Serial.println("failed to load json config");
    }
    jsonFile.close();
  }
}

```

I'm not sure if there's a better way, but this way works for me: https://github.com/dieseltravis/esp8266-projects/tree/master/servo-demo
> 6 votes

---
Tags: esp8266, eeprom
---


# Question
Title: Can't flash ESP8266-01 with Sparkfun FTDI basic - wrong direction/command
```
Connections:
RX -> TX
TX -> RX
GND -> GND
VCC -> 3.3v
CH_PD -> 3.3v
GPIO0 -> GND (flash mode)

```

**Click the picture to make it larger/more readable.**

I am trying to flash an ESP8266-01 using a Sparkfun FTDI Basic. Above is my diagram. I am using a 16v max in to 3.3v out to handle the drop from my FTDI (5v) to the ESP8266 (3.3v). I am using a logic converter to change the 5v to 3.3v for the Rx/Tx. I have done this successfully (but with spotty results), flashing the ESP8266 with an Arduino Uno. Then I tried to reprogram the ESP8266 with my Arduino Uno and it kept giving me an error that ends with:

```
warning: espcomm_sync failed
error: espcomm_open failed
error: espcomm_upload_mem failed
error: espcomm_upload_mem failed

```

So I decided to troubleshoot by seeing if the problem was with my Uno, because it is fairly old - and I got an FTDI Basic - with the basic I get a little further - the whole output when I try to upload is:

```
Archiving built core (caching) in: /var/folders/lv/lj7d61jn61x_8knqdhghk_pc0000gn/T/arduino_cache_244685/core/core_esp8266_esp8266_generic_CpuFrequency_80,FlashFreq_40,FlashMode_dio,UploadSpeed_115200,FlashSize_1M64,ResetMethod_ck,Debug_Disabled,DebugLevel_None_____4d67f8743716b2ecc4b09162f2cdb6e3.a
Sketch uses 241193 bytes (25%) of program storage space. Maximum is 958448 bytes.
Global variables use 35476 bytes (43%) of dynamic memory, leaving 46444 bytes for local variables. Maximum is 81920 bytes.
/Users/eamonwhite/Library/Arduino15/packages/esp8266/tools/esptool/0.4.9/esptool -vv -cd ck -cb 115200 -cp /dev/cu.usbserial-AL034FJS -ca 0x00000 -cf /var/folders/lv/lj7d61jn61x_8knqdhghk_pc0000gn/T/arduino_build_545013/esp8266arest.ino.bin
esptool v0.4.9 - (c) 2014 Ch. Klippel <ck@atelier-klippel.de>
    setting board to ck
    setting baudrate from 115200 to 115200
    setting port from /dev/tty.usbserial to /dev/cu.usbserial-AL034FJS
    setting address from 0x00000000 to 0x00000000
    espcomm_upload_file
    espcomm_upload_mem
opening port /dev/cu.usbserial-AL034FJS at 115200
    tcgetattr
    tcsetattr
    serial open
opening bootloader
resetting board
trying to connect
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
trying to connect
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
An error occurred while uploading the sketch
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
Uploading 245344 bytes from /var/folders/lv/lj7d61jn61x_8knqdhghk_pc0000gn/T/arduino_build_545013/esp8266arest.ino.bin to flash at 0x00000000
    erasing flash
    size: 03be60 address: 000000
    first_sector_index: 0
    total_sector_count: 60
    head_sector_count: 16
    adjusted_sector_count: 44
    erase_size: 02c000
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    setting timeout 15000
    setting timeout 100
    espcomm_send_command: receiving 2 bytes of data
    writing flash
warning: espcomm_send_command: didn't receive command response
warning: espcomm_send_command(FLASH_DOWNLOAD_DATA) failed
warning: espcomm_send_command: wrong direction/command: 0x01 0x03, expected 0x01 0x04
closing bootloader
error: espcomm_upload_mem failed

```

Can anyone explain this line in detail?

```
warning: espcomm_send_command: wrong direction/command: 0x01 0x03, expected 0x01 0x04

```

Before, when flashing it with my Uno, it would work well enough. This used to happen, and then I would unplug it and plug it in (reset) and try again, until it eventually worked. However, now it happens every time. I have 4 different ESP8266 that are functional and they all respond the same way, with the error above. This leads me to believe that is something with the circuit, or with my settings, which are:

```
Board - Generic ESP8266
Flash mode - DIO
Flash freq. - 40hz
CPU freq. - 80hz
Flash size - 1M(64k SPIFFS)
Debug Level - none
Upload Speed - 115200

```

I have tried messing with the SPIFFS (what are those? packet size?) as well as changing the CPU frequency to 160 Hz, and I tried 80 Hz for the flash frequency.

I used this same system to program the ESP before with an Arduino Uno and I was successful. Why is it so finicky, and what does the response with the `0x01 0x03 instead of 0x01 0x04` trying to say?

# Answer
> 0 votes
Instead of using `Arduino IDE` to upload (I compiled with it), I used `esptool` standalone. After messing with it for a few minutes...this worked without a hitch:

```
esptool.py -c esp8266 --port /dev/cu.usbserial-AL034FJS -b 115200 write_flash --flash_freq 40m --flash_size 1MB 0x00000 /var/folders/lv/lj7d61jn61x_8knqdhghk_pc0000gn/T/arduino_build_545013/esp8266arest.ino.bin

```

I decided to try this after seeing that maybe the `esptool` that `Arduino IDE` uses is outdated - it has `0.4.9` where as the latest version is `2.1`.

---
Tags: programming, esp8266, arduino-ide, usb, voltage-level
---


# Question
Title: Porting code from Arduino IDE to other IDEs - expected code size reduction
Could I realistically be expecting some 25% - 50% code size reduction if I abandoned Arduino IDE's framework and moved to something more rudimentary such as AVR Studio ? I am using the EEPROM, Timer1 and Wire libraries whereas my own code is about 700 lines of code.

# Answer
> 5 votes
You don't need to abandon the Arduino IDE.

Let me quote from my forum post about sketch sizes.

---

# Introduction

Every now and again this subject pops up on the Arduino forum. Why does it take 1000 bytes to blink an LED? Why, oh why? It is obviously very bloated, eh?

---

# Example: blink

Let's check that claim first.

The "blink" sketch, as shipped with the IDE (and stripped of comments) is:

```
int led = 13;
void setup()
{
  pinMode(led, OUTPUT);
}

void loop()
{
  digitalWrite(led, HIGH);
  delay(1000);
  digitalWrite(led, LOW);
  delay(1000);
}

```

Compiled:

```
Binary sketch size: 1,084 bytes (of a 32,256 byte maximum)

```

OK, over 1000 bytes to "blink an LED".

Well first, as someone on the Arduino forum humorously pointed out, it doesn't take 2000 bytes to blink **two** LEDs!

```
int led1 = 13;
int led2 = 12;
void setup()
{
  pinMode(led1, OUTPUT);
  pinMode(led2, OUTPUT);
}

void loop()
{
  digitalWrite(led1, HIGH);
  delay(1000);
  digitalWrite(led1, LOW);
  delay(1000);

  digitalWrite(led2, HIGH);
  delay(1000);
  digitalWrite(led2, LOW);
  delay(1000);
}

```

That takes:

```
Binary sketch size: 1,140 bytes (of a 32,256 byte maximum)

```

So the overhead for the second LED is only:

```
1140 - 1084 = 56

```

So you could argue that it only takes **56 bytes** to blink an LED (providing you are already blinking another one).

---

# It does more than blink

The first relevant rejoinder here is that the example sketch does more than blink an LED. Rather importantly, it also waits for a second between turning the LED on and off (the "delay" function call).

If we remove that, the sketch is somewhat smaller:

```
int led = 13;
void setup()
{
  pinMode(led, OUTPUT);
}

void loop()
{
  digitalWrite(led, HIGH);
  digitalWrite(led, LOW);
}

```

Code size:

```
Binary sketch size: 882 bytes (of a 32,256 byte maximum)

```

So we saved 202 bytes by not doing a delay. This isn't totally unreasonable, as doing delays requires the library to configure a timer, and have code to check that timer.

---

# The pins numbers are variables

The code in the Blink example uses (wrongly in my opinion) a **variable** to hold the pin number (13) when a **constant** would do. And if you use a constant there is a library called digitalWriteFast that generates more efficient code.

```
#include <digitalWriteFast.h>

const int led = 13;
void setup()
{
  pinModeFast(led, OUTPUT);
}

void loop()
{
  digitalWriteFast(led, HIGH);
  digitalWriteFast(led, LOW);
}

```

Code size:

```
Binary sketch size: 470 bytes (of a 32,256 byte maximum)

```

Now we are down to 470 bytes to "blink an LED".

---

# We can use port manipulation

If all we want to do is blink the LED, we can omit using setup and loop, and go straight into using the processor registers. For example:

```
int main ()
  {
  DDRB = bit (5);
  while (true)
    PINB = bit (5);
  }

```

That blinks pin 13, believe it or not\*. And now it only takes 178 bytes:

```
Binary sketch size: 178 bytes (of a 32,256 byte maximum)

```

* very rapidly indeed

---

# Interrupt vectors

Well, you may be thinking "Pfft! Still 178 bytes. Why not 10 bytes?"

The answer to that lies in the way the hardware works. The Atmega328P has 26 interrupt vectors, at the start of program memory. Each one is 4 bytes (it jumps to a handler for each interrupt). So 26 * 4 = 104 bytes.

Thus there is an unavoidable overhead of 104 bytes in any piece of code. (Unless you know in advance you aren't going to use all those interrupt vectors, but this is rather specialized).

You can see these vectors if you add handlers for them:

```
EMPTY_INTERRUPT (INT0_vect)
EMPTY_INTERRUPT (INT1_vect)
EMPTY_INTERRUPT (PCINT0_vect)
EMPTY_INTERRUPT (PCINT1_vect)
EMPTY_INTERRUPT (PCINT2_vect)
EMPTY_INTERRUPT (WDT_vect)
EMPTY_INTERRUPT (TIMER2_COMPA_vect)
EMPTY_INTERRUPT (TIMER2_COMPB_vect)
EMPTY_INTERRUPT (TIMER2_OVF_vect)
EMPTY_INTERRUPT (TIMER1_CAPT_vect)
EMPTY_INTERRUPT (TIMER1_COMPA_vect)
EMPTY_INTERRUPT (TIMER1_COMPB_vect)
EMPTY_INTERRUPT (TIMER1_OVF_vect)
EMPTY_INTERRUPT (TIMER0_COMPA_vect)
EMPTY_INTERRUPT (TIMER0_COMPB_vect)
EMPTY_INTERRUPT (TIMER0_OVF_vect)
EMPTY_INTERRUPT (SPI_STC_vect)
EMPTY_INTERRUPT (USART_RX_vect)
EMPTY_INTERRUPT (USART_UDRE_vect)
EMPTY_INTERRUPT (USART_TX_vect)
EMPTY_INTERRUPT (ADC_vect)
EMPTY_INTERRUPT (EE_READY_vect)
EMPTY_INTERRUPT (ANALOG_COMP_vect)
EMPTY_INTERRUPT (TWI_vect)
EMPTY_INTERRUPT (SPM_READY_vect)

```

Now the start of the object code is:

```
00000000 <__vectors>:
   0:   0c 94 34 00     jmp 0x68    ; 0x68 <__ctors_end>
   4:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__vector_1>
   8:   0c 94 52 00     jmp 0xa4    ; 0xa4 <__vector_2>
   c:   0c 94 53 00     jmp 0xa6    ; 0xa6 <__vector_3>
  10:   0c 94 54 00     jmp 0xa8    ; 0xa8 <__vector_4>
  14:   0c 94 55 00     jmp 0xaa    ; 0xaa <__vector_5>
  18:   0c 94 56 00     jmp 0xac    ; 0xac <__vector_6>
  1c:   0c 94 57 00     jmp 0xae    ; 0xae <__vector_7>
  20:   0c 94 58 00     jmp 0xb0    ; 0xb0 <__vector_8>
  24:   0c 94 59 00     jmp 0xb2    ; 0xb2 <__vector_9>
  28:   0c 94 5a 00     jmp 0xb4    ; 0xb4 <__vector_10>
  2c:   0c 94 5b 00     jmp 0xb6    ; 0xb6 <__vector_11>
  30:   0c 94 5c 00     jmp 0xb8    ; 0xb8 <__vector_12>
  34:   0c 94 5d 00     jmp 0xba    ; 0xba <__vector_13>
  38:   0c 94 5e 00     jmp 0xbc    ; 0xbc <__vector_14>
  3c:   0c 94 5f 00     jmp 0xbe    ; 0xbe <__vector_15>
  40:   0c 94 60 00     jmp 0xc0    ; 0xc0 <__vector_16>
  44:   0c 94 61 00     jmp 0xc2    ; 0xc2 <__vector_17>
  48:   0c 94 62 00     jmp 0xc4    ; 0xc4 <__vector_18>
  4c:   0c 94 63 00     jmp 0xc6    ; 0xc6 <__vector_19>
  50:   0c 94 64 00     jmp 0xc8    ; 0xc8 <__vector_20>
  54:   0c 94 65 00     jmp 0xca    ; 0xca <__vector_21>
  58:   0c 94 66 00     jmp 0xcc    ; 0xcc <__vector_22>
  5c:   0c 94 67 00     jmp 0xce    ; 0xce <__vector_23>
  60:   0c 94 68 00     jmp 0xd0    ; 0xd0 <__vector_24>
  64:   0c 94 69 00     jmp 0xd2    ; 0xd2 <__vector_25>

```

The "real" code has to start at 0x68 (decimal 104) which is where the reset vector takes us (the first vector).

So now, our code is really 178 - 104 bytes of useful code. That's 74 bytes to blink an LED.

However even some (most) of that is overhead, generated by the C compiler to initialize global variables, call class constructors, etc. Let's test that by blinking **two** LEDs.

```
int main ()
  {
  DDRB = bit (5);  // pin 13
  DDRB |= bit (4);  // pin 12

  while (true)
    {
    PINB = bit (5); // pin 13
    PINB = bit (4); // pin 12
    }
  }

```

Code size:

```
Binary sketch size: 186 bytes (of a 32,256 byte maximum)

```

Eight bytes difference. So really, you can **blink an LED in 8 bytes**. That is the bottom line. And you can do it in the Arduino IDE.

---

# The libraries are designed to make things easy

The fact is that the default behaviour of the Arduino libraries is to simplify things for beginners. Thus they do some things which take up a bit of memory;

* You can pass **variables** to pinMode and digitalWrite. Not just constants. Thus, at runtime, code has to convert the variable value to an actual processor port.
* You get an automatic set-up of Timer 0, so you can use millis(), micros(), and delay() function calls.
* You get Timer 1 and Timer 2 set-up, so you can do PWM output easily.

So you are trading off program space, to an extent, for ease of use. But if you want to code around it, as I did above, you can trim that program space right down.

---

Tests on an Arduino Uno board type, IDE 1.0.5.

# Answer
> 2 votes
If you like the Arduino IDE, you also can do the following:

* Do not use the library functions, but use registers directly. The compiler is smart enough that it does not link functions you do not use with your executable/binary.
* Optimize your code by
    + Checking if you can simplify algorithms
    + Remove unnecessary statements
    + Remove global variables (maybe move them to locals if you can)
    + Reduce or remove text strings.
    + For globals (but also to reduce SRAM) minimize memory sizes of variables, e.g. use uint8\_t instead of integers, especially when using arrays of them.
* If you use library functions, optimize them:
    + Simplify library functions if you use them (by 'paying' less portability for example)
    + By removing functionality that you do not need

Other tips (not necessarily answering your answer but things to keep in mind);

* Use another Arduino which has more memory (Mega/Due)
* Switch to another type of microControllers with more memory/flash

# Answer
> 1 votes
I have managed some 33% downsizing, hurrah!

Adding to the current answers: the biggest reduction came by ridding the floating points. I have come across the answer here and put `avr-objdump` to good use. That's how I have had the shock of my life (no hardware FPU built into these $1 MCUs :-o) and also that is how you can see other offenders sneaking into your binary image.

HTH

# Answer
> 0 votes
> Could I realistically be expecting some 25% - 50% code size reduction ...

code size has nothing to do with the ide, but compiler, compilers used, and libraries / routines used.

in general (which means that there are lots of exceptions) you will see a size increase when porting to an non-arduino environment.

with that said, many of the arduino functionalities are not that well implemented so you can save code size if you roll your own functionally equivalent code.

---
Tags: arduino-ide, ide, code-optimization, avr-toolchain, sketch-size
---