# Question
Title: Changing the order of blinking LEDs with the push of a button
I am new to Arduino and I have written code that makes 3 LEDs blink while the push button is off, so the lights are blinking from left to right (1,0,0)(0,1,0)(0,0,1) and then repeat from left to right.

Now I am trying to modify this code so that whenever the system receives a High from the switch it reverses the order, so it should start blinking from right to left and keep blinking that way until I press the push button and then return to left to right.

I hope my issue is clear. I only know how to use the if & else.

Here is my code:

```
int switchState;
int switchst = LOW;
int d=LOW;

void setup() {
  pinMode(3,OUTPUT);
  pinMode(4,OUTPUT);
  pinMode(5,OUTPUT);
  pinMode(2,INPUT);
}

void loop() {
  switchState = digitalRead(2);
  if (switchState == HIGH) {
    d= ~d;
    if(d==LOW) {
    digitalWrite(3,~switchst);
    digitalWrite(4,switchst);
    digitalWrite(5,switchst);
    delay(200);
    digitalWrite(3,switchst);
    digitalWrite(4,~switchst);
    digitalWrite(5,switchst);
    delay(200);
    digitalWrite(3,switchst);
    digitalWrite(4,switchst);
    digitalWrite(5,~switchst);
    delay(200);
  }  else {
    digitalWrite(3,switchst);
    digitalWrite(4,switchst);
    digitalWrite(5,~switchst);
    delay(200);
    digitalWrite(3,switchst);
    digitalWrite(4,~switchst);
    digitalWrite(5,switchst);
    delay(200);
    digitalWrite(3,~switchst);
    digitalWrite(4,switchst);
    digitalWrite(5,switchst);
    delay(200);
  }
}

```

The problem with this code is that it doesn't keep blinking if I release the push button.

This is the old code. It only goes from left to right and keeps repeating.

```
int switchState = 0;
int switchst = LOW;

void setup() {
  pinMode(3,OUTPUT);
  pinMode(4,OUTPUT);
  pinMode(5,OUTPUT);
  pinMode(2,INPUT);
}

void loop() {
  switchState = digitalRead(2);
  if (switchState == switchst) {
    digitalWrite(3,~switchst);
    digitalWrite(4,switchst);
    digitalWrite(5,switchst);
    delay(200);
    digitalWrite(3,switchst);
    digitalWrite(4,~switchst);
    digitalWrite(5,switchst);
    delay(200);
    digitalWrite(3,switchst);
    digitalWrite(4,switchst);
    digitalWrite(5,~switchst);
    delay(200);
  } else {
    digitalWrite(3,switchst);
    digitalWrite(4,switchst);
    digitalWrite(5,switchst);
  }
}

```

# Answer
The easiest is to use a 'mode', which is a boolean that keeps the state if it is blinking right, let's call it blinkToRight. Initially this is true.

An if statement will be used to change the order.

So the program will be something like (not tested):

global:

```
bool blinkToRight = true;

```

in Setup:

```
pinMode(3,OUTPUT);
pinMode(4,OUTPUT);
pinMode(5,OUTPUT);
pinMode(2,INPUT);

```

In Loop:

```
// Check if loop is reversed
blinkToRight = checkReverse();

if (blinkToRight)
{
   show(true, false, false);
   show(false, true, false);
   show(false, false, true);
}
else
{
   show(false, false, true);
   show(false, true, false);
   show(true, false, false);
}

void show(bool led1, bool led2, bool led3)
{
   digitalWrite(2, led1);
   digitalWrite(3, led2);
   digitalWrite(4, led3);
   delay(200);
}

```

checkReverse will check the input button and returns true if the mode should be reversed.

However, you cannot simply check for the button state. The problem is bouncing. But check in the Arduino examples to a debounce example for this problem and the program should work as expected.

See example: Debounce example

Since only one led will be on, you can also use the following functions for Loop and show:

In Loop:

```
// Check if loop is reversed
blinkToRight = checkReverse();

if (blinkToRight)
{
   show(3);
   show(4);
   show(5);
}
else
{
   show(5);
   show(4);
   show(3);
}

```

Show:

```
void show(int ledOn)
{
   digitalWrite(ledOn == 3);
   digitalWrite(ledOn == 4);
   digitalWrite(ledOn == 5);
   delay(200);
}

```

And it's even better to use constants:

```
const int LED1   = 3
const int LED2   = 4
const int LED3   = 5
const int BUTTON = 2

```

Setup:

```
pinMode(LED1  , OUTPUT);
pinMode(LED2  , OUTPUT);
pinMode(LED3  , OUTPUT);
pinMode(BUTTON, INPUT);

```

Loop

```
// Check if loop is reversed
blinkToRight = checkReverse();

if (blinkToRight)
{
   show(LED1);
   show(LED2);
   show(LED3);
}
else
{
   show(LED3);
   show(LED2);
   show(LED1);
}

```

Show:

```
void show(int ledOn)
{
   digitalWrite(ledOn == LED1);
   digitalWrite(ledOn == LED2);
   digitalWrite(ledOn == LED3);
   delay(200);
}

```
> 3 votes

# Answer
In my opinion, there are two things I'd change. The first one is that delay functions should be avoided whenever possible, the other is that the switch bounces.

In order to solve the bounces, you will have to wait some time to stabilize the signal:

```
if (debouncedValueOfButton != (digitalRead(button_pin) == HIGH))
{ // Is there a change?
    if (((byte)currMillis) - lastMillisForButton) >= millisButtonDebounce)
    { // Yes, without bounces
        debouncedValueOfButton = !debouncedValueOfButton;
        if (debouncedValueOfButton)
        { // Rising edge
            if (increment > 1)
                increment = 1; // Go in one direction
            else
                increment = 2; // Go in the other direction
        }
    }
}
else
    lastMillisForButton = (byte)currMillis;

```

So, if the value is different from the one I think it is I'll wait for some milliseconds; if it is stable then I change the value I think it is.

As for removing the delay, I think it is better to use an approach similar to the "blink without delay" sketch:

```
if ((((uint16_t)currMillis) - lastMillisForBlink) >= millisBetweenBlinks)
{
    lastMillisForBlink += millisBetweenBlinks;
    currentLed = (currentLed + increment) % 3;

    digitalWrite(led0_pin, currentLed == 0);
    digitalWrite(led1_pin, currentLed == 1);
    digitalWrite(led2_pin, currentLed == 2);
}

```

In this implementation, you use a variable increment to decide whether you have to go forward or backwards; when increment is 1 the led to be colored are `0 -> 1 -> 2 -> (3)0 -> 1 ...`; when it is 2 the led are `0 -> 2 -> (4)1 -> (3)0 -> 2 ...`.

The complete code is (DISCLAIMER: NOT TESTED)

```
const byte led0_pin = 3;
const byte led1_pin = 4;
const byte led2_pin = 5;
const byte button_pin = 2;

int8_t currentLed, increment;
unsigned int lastMillisForBlink;
const unsigned int millisBetweenBlinks = 200;

bool debouncedValueOfButton;
byte lastMillisForButton;
const byte millisButtonDebounce = 50;

void setup() {
    pinMode(led0_pin,OUTPUT);
    pinMode(led1_pin,OUTPUT);
    pinMode(led2_pin,OUTPUT);
    pinMode(button_pin,INPUT);

    increment = 1;
    currentLed = 2; // At first run, currentLed will be increased by 1, so it starts at 0
    lastMillisForBlink = millis() - millisBetweenBlinks; // trigger a refresh at first loop

    debouncedValueOfButton = (digitalRead(button_pin);
}

void loop() {
    unsigned long currMillis = millis();

    if ((((uint16_t)currMillis) - lastMillisForBlink) >= millisBetweenBlinks)
    {
        lastMillisForBlink += millisBetweenBlinks;
        currentLed = (currentLed + increment) % 3;

        digitalWrite(led0_pin, currentLed == 0);
        digitalWrite(led1_pin, currentLed == 1);
        digitalWrite(led2_pin, currentLed == 2);
    }

    if (debouncedValueOfButton != (digitalRead(button_pin) == HIGH))
    { // Is there a change?
        if (((byte)currMillis) - lastMillisForButton) >= millisButtonDebounce)
        { // Yes, without bounces
            debouncedValueOfButton = !debouncedValueOfButton;
            if (debouncedValueOfButton)
            { // Rising edge
                if (increment > 1)
                    increment = 1; // Go in one direction
                else
                    increment = 2; // Go in the other direction
            }
        }
    }
    else
        lastMillisForButton = (byte)currMillis;
}

```
> 1 votes

---
Tags: led
---


# Question
Title: How to make two WIR 1186 RF transceivers communicate over serial communication?
I want to have two RF transceivers communicate, one as transmitter and one as a receiver, for longer distances. For that I'm using WIR 1186 RF modules with Arduino.

Pin connections are as below:

* Arduino :5v,gnd,RX,TX,2,3
* WIR1186 :VCC,gnd,Tx,Rx,prg,cts

But Arduino is not serially communicating with the WIR1186 module.

Below is the code:

```
char ch;
int prog = 2;
int cts = 3;
int stat;
unsigned int output;

void setup() {
  Serial.begin(9600);
  pinMode(prog, OUTPUT);
  digitalWrite(prog, LOW);
  stat = digitalRead(prog);
  Serial.println(stat);
  Serial.write("B=9600\r\n");
  output = Serial.read();
  Serial.println(output);
  digitalWrite(cts, HIGH);
}

void loop() {
  Serial.write('a');
  delay(1000);
}

```

Here is the datasheet of WIR1186

Please help me out with this.

# Answer
If you use pin 2 and 3 for serial communication you have to use SoftSerial, because Serial is hardwired to pin 0 and 1.
> 1 votes

# Answer
Two things are wrong:

1. You aren't setting PROG to HIGH to enable transmit mode - you are stuck in programming mode.
2. CTS is an *output from the module to an input on the Arduino*. You don't set it high - you look to see what level it is to see if it is safe to send more data.

To quote from the datasheet you link to:

> The WIR-1186 offers data flow control hardware to allow for zero data over-run and loss when sending large files and data packets. The internal data buffer on the WIR-1186 module is 128bytes. When the data terminal1 sends a large file for wireless transmission the module2 will except 128bytes and then set the CTS pin LOW to alert the data terminal to wait for the CTS to back HIGH before sending more data over UART.

(footnotes mine)

Also you *cannot* use pins 0 and 1 for serial if you are at the same time using them for USB debugging. You will either have to move to another pair of pins and use `SoftwareSerial`, or invest in a better Arduino with more than one UART.

Another thing of importance: If your WIR-1186 isn't on some kind of carrier board with voltage regulator and logic level translation it's safe to say that you have killed it. Well done.

> # Warnings
>
> * **The maximum allowable voltage on any of the interface pins with respect to GND is 3.6V**
> * **The maximum input voltage VCC with respect to GND is 3.6V**
> * The baud rate setting in configure mode is fixed 9600bps
> * Do not leave the UART\_TX input pin of the module open. The module will send junk data on thewireless channel. It must be pulled up to VCC if not used.

---

1 Arduino 2 WIR-1186
> 1 votes

---
Tags: serial, rf
---


# Question
Title: Need a proper diagram to connect my multiple relays (more than 8) with only a few pins on Arduino Uno Board
Specifically, I want to add multiple relays (approximately 36 to 40) to an Arduino Uno board (using only a few pins). I found a solution using ShiftOut. You can take a look here. But here the example is for testing small LEDs bulbs.

I will control high-voltage electricity like fans, tube lights, washing machine with those relays, so what will be a proper graph or image diagram for that? And if you have any more suggestions for me then you can tell me :) And yes please tell me what I should use for it.

Right now am thinking to use an Arduino, relays, 74HC595 IC only. My diagram for controlling LED is like this:

You can edit it. I just need proper guidance for it and a few good suggestions.

# Answer
If you want to drive a normal magnetic relay you will need to add a transistor / resistor to the output of the 74HC595 as the current is too high across the magnet of the relay to be driven directly by the 74HC595. If you don't want to use a transistor for every relay, you could you an 8 channel driver chip like the ULN2803A. You should be able to connect your relay coil directly from 12v and to the ULN2803A.

Have a look at this page for an example. http://www.mcmajan.com/mcmajanwpr/blog/2014/04/18/arduino-how-to-connect-many-12v-relays-en/
> 1 votes

# Answer
What about using an I2C I/O expander like MAX7328 or equal and a ULN28XX as relay driver. and you can connect several I/O expanders to the same I2C buss with different addresses.

This will use minimal amount of pins and minimal amount of components.
> 1 votes

---
Tags: arduino-uno, relay, shift-register
---


# Question
Title: Can Arduino Mega ADK charge connected smartphone?
I suppose Arduino Mega ADK acts as the USB host for the connected smartphone.

Is it capable of providing power to the smartphone?

# Answer
If you read the documentation, you will see this paragraph:

> NB: Because the MEGA ADK is a USB Host, the phone will attempt to draw power from it when it needs to charge. When the ADK is powered over USB, 500mA total is available for the phone and board.The external power regulator can supply up to 1500mA. 750mA is available for the phone and MEGA ADK board. An additional 750mA is allocated for any actuators and sensors attached to the board. A power supply must be capable of providing 1.5A to use this much current.

So yes (though slowly), if you connect it to a suitable power supply.
> 1 votes

---
Tags: arduino-mega
---


title: ESP8266-01 wrong flow control settings

text:
# Question
Title: ESP8266-01 wrong flow control settings
Changed ESP8266-01 to wrong settings by mistake. It was working ok at 115200 (its default settings). It was connected like this:

PC-\>(USB)-\>Arduino-\>ESP8266.

Using Arduino as bridge

* Pins 0 and 1 (RX/TX) connected directly to ESP8266 since I didnt have USB to TTL adapter.
* MCU removed so I could make that scenario work

It was just for testing AT commands. I did it like that because I realized that I was getting errors all the time trying to connect using SerialSoftware (and different pins in Arduino).

Found out later that SerialSoftware does not work correctly at 115200...

So I issued the following AT command:

```
         AT+UART_DEF=9600,8,1,0,3

```

Now I cannot connect to the ESP8266 to correct that setting. All I get is garbage characters. I understand it's because of the flow control settings. I set it to both RTS and CTS which I also read later ESP8266 does not support?

Have tried:

* Using Putty to change settings of COM port at connect. Have tried all speeps and flow control settings combinations I could think of. I get nothing or garbage characters.
* Changing COM port setting from Device Manager (Windows 7)
* Flashing ESP8266 using official tool (ESPFlashDownloadTool\_v3.6.1.0).It won't sync with the ESP8266. It does not allow me to adjust speed to 9600. Minimun speed that show is 115200
* Changing settings in ESPFlashDownloadTool\_v3.6.1.0 so it will sync at 9600 (file: spi\_download.conf)

I cannot think of anymore ideas. Have I completely messed up my ESP8266?

Is there a way that I'm not aware of that could fix this problem? How?

Thanks in advance!

Jorge

# Answer
```
AT+UART_DEF=9600,8,1,0,3

```

Are you aware that this configuration (3) as a rule would require both RTS and CTS extra physical signals to work ? That means, if you do not connect anything there, the level present at some pin configured anywhere would prevent ESP8266 from receiving further data from serial.

In general people use "no flow control" (0)

```
AT+UART_DEF=9600,8,1,0,0

```
> 1 votes

# Answer
andre,

As I stated in my post I did it by mistake. Nonetheless I was able to fix it by using a different flashing tool that used just one .bin file instead of many like the official ESP8266 tool does.

Can anyone please explain me why is that? Why are there different tools to flash the ESP8266? In concrete, why one requires just one file that will update the SDK and AT firmware in one pass, and the other requires many differente files? Or just a link to a site o post so I can better understand the differences?

The tool I ended up usign is "ESP8266 Flash Downloader"

The file I used: `AiThinker_ESP8266_DIO_8M_8M_20160615_V1.5.4.bin`

Thanks!
> 0 votes

---
Tags: arduino-uno, serial, esp8266, baud-rate, speed
---


# Question
Title: Grounding issues Arduino Ethernet Shield makes WS2811 LEDs flicker
I have an Arduino Due with an Arduino Ethernet Shield V2 that I use to control multiple daisy-chained WS2811 LED strips.

When I turn on most of the LEDs the Arduino and attached wires seem to become an antenna, picking up fluctuations that make the LEDs flicker, by messing with the data on the WS2811 data line. Touching the data cable, touching the ethernet plug on the shield, or simply hovering my hand over the Arduino adds noise that causes flickering in the lights.

When I pull out the ethernet plug, it stops. (The Arduino continues to update the WS2811 chips, even without network connection)

The flickering is especially strong when I set the first couple of LEDs in the chain to White (biggest draw of current), while having red or green colored LEDs at the beginning causes milder flickering (even if there are LEDs set to White further back in the chain).

Some more observations:

* The LED strips are powered from both sides. It doesn't seem to be a power issue.
* I tried with a different Arduino Due, a different Ethernet shield, a different router and Ethernet cable, and a different power supply.
* The router the Arduino is plugged into, is positioned on the same table, and powered from the same power bar as the LED/Arduino power supply.
* I tried running the Arduino and the LEDs from different power supplies but that didn't help. Rather the opposite (which makes sense)
* This happens no matter how long the equipment has already run or how hot it is.

Another mystery: You might notice the lose ground cable from the LED strip connector. When I plug that into the Arduino Due, the LEDs don't get turned on at all. When I plug that ground cable into the Ethernet shield sitting on the Due, then some lights turn on wrong. No matter if Ethernet is plugged in or not (though there's a difference in the 'wrongness' of the lights when Ethernet is plugged in). Note, that the Arduino and the LED strips already share ground 1 foot away as they are both fed by the same 12V power supply.

Where are all these grounding issues coming from and how do I get rid of them? What else could I try?

# Answer
> 1 votes
I suspect that the signal driving the LED strip does not have enough voltage swing. And that ground noise/resistance is what makes the system sometimes appear to work correctly.

With 12 volt LED strips, the data signal into the WS2811 should swing at least 0.3x to 0.7x 12 volts, or below 3.6 volts (low) to above 8.4 volts (high).

The Arduino Due has output signals from 0 volts to 3.3 volts.

Which would explain the observation that if ground is connected directly between Due and LED then the Due output is never high enough to signal the LEDs.

I would try using a logic level converter between the Arduino Due output and the LED strip data input.

---
Tags: ethernet
---


# Question
Title: How to send HTTP requests using wifi of Arduino Primo board?
I have bought an Arduino Primo board. I have configured it to connect to my wifi router and changed it to STA mode. Now, how do I program it to send HTTP requests to a server? Which library file I should use? Any tutorial?

# Answer
With Arduino Primo use the WiFi Link library. Look at WiFi Link Examples in IDE menu.

Arduino org web archive pages
> 1 votes

---
Tags: arduino-uno, programming, esp8266
---


# Question
Title: unexpected change of ADC value with multiple voltage dividers (thermistors and pot)
So this is my basic circuit. Three voltage dividers: one 10k pot, 2 thermistors. Fan driver circuit using TIP120 (currently just driving an LED from the 3.3v source). Board is a Leonardo clone, circuits.io only had the Uno in their library. Edit: circuit is now more simplified.

Schematic:

reality:

When I adjust the pot, the ADC value of `airPinValue` changes, regardless of which analog input it is connected to. `meatPinValue` does not change. Swapping the inputs that `airTempPin` and `meatTempPin` are assigned to has no effect, `airTempPin` changes the same. Physically swapping the thermistors has no effect, nor does switching which input they connect to.

Code:

```
#define potPin A0
#define airTempPin A5

int potValue = 0;
int airPinValue = 0;
int i = 0;

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

void loop() {
  i++;
  potValue = analogRead(potPin);
  airPinValue = analogRead(airTempPin);
  if (i == 2000) {
    Serial.print(potValue);
    Serial.print(",");
    Serial.println(airPinValue);
    i = 0;
  }
}

```

EDIT: much simplified code

EDIT v2.0 : I have now swapped out the board for an official Uno, as well as swapped everything to a different breadboard and a different Leonardo, with no change in behavior.

EDIT v3 : Corrected code sample. I have also dropped my DMM onto this, reading from the 5v rail to the voltage going to A2. With the pot set to 0 I see 2.401v from the divider, pot to max, same voltage, 2.401v.

EDIT v4: with only the pot and airTemp hooked up, still happens. Further DMM probing actually shows that this only happens when the pot and thermistor are both hooked up to the arduino. If either one is disconnected, the voltage being read by `airTempPin` is stable/correct. Once both are hooked up to the analog pins on the arduino, that's when the voltage at `airTempPin` goes off...

Also update diagram, pic, and code to match what I'm currently testing with.

EDIT v5 : This is some sort of analog bleed between the analog input ports. Not really sure how I can combat this :\

# Answer
Moral of the story, the multiplexer was not switching between inputs quickly enough causing the odd reading, looking very much like bleed between the pins. By simply reading each analog input twice and only storing the value of the second reading, I was able to get a valid, stable, reading as expected.

```
#define potPin A4
#define airTempPin A0

int potValue = 0;
int airPinValue = 0;
int i = 0;

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

void loop() {
  i++;
  analogRead(potPin);
  potValue = analogRead(potPin);
  analogRead(airTempPin);
  airPinValue = analogRead(airTempPin);
  delay(10);
  if (i == 50) {
    Serial.print(potValue);
    Serial.print(",");
    Serial.println(airPinValue);
    i = 0;
  }
}

```
> 2 votes

# Answer
```
#define meatTempPin A0
#define airTempPin A1

```

Your code says A0,A1 but the circuit and picture of the wires say A0,A2.

Since A1 doesn't appear to be connected, as you scan things, the ADC could be sampling and holding some voltage from the prior conversion of potPin.

Try this instead:

```
#define meatTempPin A0
#define airTempPin A2

```
> 2 votes

# Answer
https://www.arduino.cc/en/main/arduinoBoardUno

> Vin. The input voltage to the Arduino/Genuino board when it's using an external power source (as opposed to 5 volts from the USB connection or other regulated power source). You can supply voltage through this pin, or, if supplying voltage via the power jack, access it through this pin.

Thisi not to be used as powersource for motor/LED whatever, this is input.

Use 5V instead, maybe this would solve the problem.
> 0 votes

# Answer
You need to have a reference voltage for ADC the problem is that you are not setting the reference voltage for ADC.Change the code in setup where you add a analog reference voltage as internal or default according to your requirement.
> 0 votes

---
Tags: analogread
---


# Question
Title: How to expand program memory on an arduino?
Sometimes I run out of space of the program size for the embedded C program that I want to put on an arduino. So what chip do I need to expand the program memory of the arduino so that I can use bigger C programs with my arduino?

# Answer
> 12 votes
An ATmega2560 is the chip to add for more memory when you run out of program memory on an Uno. Referring to the Memory webpage at arduino.cc, you'll see that it has Flash=256KB, SRAM=8KB, EEPROM=4KB, where the ATmega328 chip on the Uno has Flash=32KB, SRAM=2KB, EEPROM=1KB.

When you run out of program memory on an Uno, you have about three choices that are practical: make the program smaller; remove the bootloader (to free up one or two KB); use a different board with a more-capable processor. The CPU on an Uno board doesn't have a way to access program bytes from places other than the on-chip 32KB flash. The CPU on a Mega2560 board starts out with 8 times as much flash, so it can hold bigger programs than an Uno can.

If you remove the bootloader, you could instead program using a USBASP board, as described in a “Program AVR chip using a USBASP with 10 pin cable” article at learningaboutelectronics.com.

# Answer
> 7 votes
Another way (other than MCU with more memory) is not using Arduino framework and its libraries. Such level of abstraction is expensive in both ways - memory usage and speed. But that's much harder way. If you need some library, you have to port it (if you haven't found native one) or at least provide required functions from Arduino.

For example in Arduino IDE 1.6.11 empty sketch is using up 444 Bytes of flash. Using one `pinMode` and `digitalWrite(13, ! digitalRead(13));` \+ `delay(500);` means 964 Bytes. Of course, these are most likely one-timers. If you use six more pins and toggle it, it uses much less program memory than using first one (1192B). But it still grows really fast.

In pure C empty program is about 134 Bytes long. Same functionality (toggling one pin every 500ms) takes 158 Bytes (and it's way faster).

But for hobby project i would go for ATMega2560 or ATMega644/1284 instead.

And you can use direct access to hardware too. Toggle pin sketch with using registers directly and \_delay\_ms from avr libraries uses 468 Bytes instead of 964B. With delay from Arduino core libraries it's 602B.

# Answer
> 3 votes
When asking a broad question, it is helpful to include some details. Like how much memory you need and why you think you need it.

I once specified a processor at 2 KB program space, 64 bytes RAM and 1 KIPS. The engineer asked, "MIPS?", and I explained thousands per second. He replied, "They don't come that slow". At the end of the project, a huge UI was added and memory got tight... but it still fit with no problem.

So, consider being more thoughtful about the resources being used.

To answer the question:

1. The Arduino does not provide a convenient bus to fetch memory over. So, there is no way to plug in a chip to get more memory.
2. The Arduino has SPI, so an SD card can be accessed. Any code on the SD card would need to be loaded into executable memory. This is complicated and not for beginners...
3. As suggested, tighten up you code. This is probably a good way to learn.
4. Move to a larger Arduino.

There are different Arduino processors. Some in the ACR line, others in the ARM line. Going to a different device in the same family is a relatively modest change and can provide up to 368 Bytes of program FLASH. But these are not Arduino boards exactly.

The Arduino ARM based devices are very different and use different libraries.

Check out the Arduino Mega 2560 it is very similar to the Uno, has a similar footprint, code should port relatively easily and is inexpensive.

There are also larger devices in the AVR family.

Note, the AVR32 is a different processor and the peripherals are enough different that it is a different device.

If you want to get into very large programs (gigabytes of memory) check out the Beagleboard. It has a full linux, with virtual memory (see #2 above) and has more powerful I/O mechanisms.

# Answer
> 2 votes
What about a raspberry pi zero? I have a couple and use them quite often as arduinos.

# Answer
> 2 votes
You could also look into other platforms. For instance, a Teensy 3.2 is Arduino compatible and has a 2KB eeprom and 64KB of RAM.

---
Tags: arduino-uno
---


# Question
Title: Why is there a limitation in using Serial.println on ESP8266?
I'm trying to upload this code on ESP8266, and when I do, it just resets continuously. This also happens when you have memory bugs, but obviously, this code has no memory bugs! Here is the code:

```
#include "Arduino.h"

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

void loop()
{

}

void foo(){
    for(unsigned int i = 1; i <= 10000; i++){
        Serial.println("FOOBAR");
    }
}

```

Also, in the serial monitor, I get this (per reset):

```
Soft WDT reset

ctx: cont
sp: 3ffef130 end: 3ffef390 offset: 01b0

>>>stack>>>
3ffef2e0:  feefeffe feefeffe feefeffe 00002580
3ffef2f0:  0000001c 00000001 3ffe85b1 402023d4
3ffef300:  feefeffe 00000005 3ffe842d 3ffee364
3ffef310:  3fffdad0 00000006 3ffee340 40201fd1
3ffef320:  3ffe85b0 00000000 3ffee340 40201fd1
3ffef330:  3ffe8428 00000000 3ffee340 40201fec
3ffef340:  00000001 feefeffe 3ffee340 40202010
3ffef350:  feefeffe 00000000 00002580 40201c00
3ffef360:  3fffdad0 00000000 3ffee35c 40201c2e
3ffef370:  feefeffe feefeffe feefeffe 402021c8
3ffef380:  feefeffe feefeffe 3ffee370 40100718
<<<stack<<<
Õ®(ŽL‰Ì==   I5

```

So, why is this happening?

# Answer
It's happening because you're not giving the ESP8266 a chance to do its housekeeping activities and the watchdog (which is enabled by default) is timing out - as evidenced by the very first line of your output:

> Soft WDT reset

You need to allow the MCU to do other things at the same time as you are printing to serial:

```
void foo(){
    for(unsigned int i = 1; i <= 10000; i++){
        Serial.println("FOOBAR");
        yield();
    }
}

```
> 5 votes

# Answer
With Arduino/ESP8266 you have to break your tasks in little pieces so `setup` and `loop` takes as little time as possible.

Your elemental tasks is executing one `Serial.println`. We first reformulate `foo` to run a single elemental task in each invocation. Then, we move the call to `loop`, so `setup` ends quickly. In `loop` we use the variable `iterations` to controls calls to `foo`. When it reaches zero it signal the end of the "setup" part.

```
#include "Arduino.h"
int iterations = 10000;
void setup()
{
    Serial.begin(9600);
}
void loop()
{
  if (iterations > 0) {
    iterations--;
    foo();
  }
}
void foo(){
  Serial.println("FOOBAR");
}

```

It can be tricky to break some big code in small parts, but it's something you must learn to do, because there is no other way.
> 0 votes

---
Tags: serial, esp8266, reset
---


title: Current Draw for LED Projects

text:
# Question
Title: Current Draw for LED Projects
I am working on a project with LED strips that would consume 12V and 20A. The problem is that the household wall outlet limitation is 15A, and 20A current draw would potentially start a fire. I have been searching for tutorials of large current LED project, and none of them really addresses the current draw problem.

I found an adequate power supply. It is Meanwell RSP-320-12. http://www.mouser.com/ProductDetail/Mean-Well/RSP-320-12/?qs=Uzd%2Fwh%252bZzhBChmc2p7rgKQ%3D%3D.

How can I make it work with a 15A wall outlet limitation?

Thanks in advance!

# Answer
> 2 votes
Drawing 20A on 12V means 240W which on 110V is 1A and a bit (a bit more once you consider efficiency of the conversion).

The spec sheet of the power supply you linked says that it will draw 2.7A max on a 115V input.

The power supply will convert the high voltage low amps into low voltage high amps.

# Answer
> 0 votes
The power outlet is either 110V AC or 230/240V AC. Ignoring modern Switch-mode power supplies, to convert the power outlet voltage down to 12V, you first need to step down the voltage (using a transformer) and then rectify the AC voltage to DC voltage.

Working backwards, to get 12V DC you need: `12 x square_root(2) = 16.97 V AC`.

A transformer can step down AC voltage. For example it can step down 110V AC down to 16.97 V AC.

The formula for an ideal transformer is:

```
V x i (primary side) = V x i (secondary side)

```

And using this to find the current draw on the primary side:

```
110 x i (primary side) = 16.97 x 20 (secondary side)

i (primary side) = 16.97 x 20 / 110

i (primary side) = 3.08 A

```

So if you have an outlet that provides 110 V AC then an ideal AC-DC converter would draw 3.08 A.

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


# Question
Title: Posting data to ASP web service from GSM using AT commands - where am I going wrong
I'm using an Arduino uno with a SIM900 GSM shield. I'm trying to connect the Arduino to my (ASP MVC) website. I've written an API which i've successfully tested with postman, and whilst the GET Command works fine, I've had no success with POSTING data as yet. Using the arduino to echo serial monitor input, I've done the following...

So, some setup commands

```
    AT+CGATT?
    AT+SAPBR=3,1,"CONTYPE","GPRS"
    AT+SAPBR=3,1,"APN","internet"    (vodafone UK parameters
    AT+SAPBR=3,1,"USER","web"
    AT+SAPBR=3,1,"PWD","web"
    AT+SAPBR=1,1
    AT+SAPBR=2,1     (confirms i have an IP address)

```

i then do the following...

```
    AT+HTTPINIT
    AT+HTTPPARA="CID",1
    AT+HTTPPARA="PROIP","212.183.137.12"   (vodafone uk proxy settings)
    AT+HTTPPARA="PROPORT","8799"
    AT+HTTPPARA="CONTENT","application/json"
    AT+HTTPPARA="URL","http://mywebsite.co.uk/api/obs"
    AT+HTTPDATA=83, 10000    (gives the download command).
    {"SensorName": "TestSensor", "ObsValue": 31, "ObsDateTime": "2017-10-01T03:30:00"}
    AT+HTTPACTION=1

```

and I just get an "OK" back, no httpaction response, and no data stored on the database.

Is there anything I'm doing that is obviously wrong? Does HTTPACTION come before the data?

Are there commands I can use to check the status of my http session on the GSM board? to confirm that my settings are correct?

Finally, I keep getting messages like

```
    +CREG: 1,"002A","0F48"

```

Always the 1 (presumably the CID i'm using), and always the 002A, but the final part varies.

Any help would be hugely welcome. Thanks.

# Answer
> 1 votes
> ```
> +CREG: 1,"002A","0F48"
>
> ```

That's the registration status. "1" is "Registered on your 'home' network", "002A" is your LAC (Location Area Code) and "0F48" is the Cell ID (CI).

---
Tags: gsm, web-service
---


# Question
Title: Do I need a relay to control a monitor's power with an Arduino?
I'm trying to use an Arduino to switch a monitor's power on and off. I'm going to wire the Arduino to the monitor's power switch. I've tested the power switch with a multimeter, and when pressed, there is a 3.3V current running through it that triggers the power on and off. The monitor itself is takes 12VDC to power. I know that a relay is used when switching larger power sources from a low voltage source so as not to damage the lower voltage source, but since the switch in question only runs at 3.3V would it be safe to use the Arduino without a relay?

# Answer
It's always better to use MOSFET as a switch (or relay) like this:

It can handle loads up to 24V, 5A. The load is powered from an external supply. It is based on a IRF520 Mosfet and cost 0.55 a piece in Aliexpress. Search "Arduino IRF520 module"

You need one Arduino pin to switch on/off the load.

It's very handy and provide posts for power input/output.

*I understand that you will still power the monitor from the wall, replacing only the original switch with Arduino. Otherwise, you will need a bigger relay*
> 0 votes

---
Tags: relay, arduino-micro
---


# Question
Title: Writing a value to 7-segment max7219 displays
I am new to arduino and I am trying to build an interface for my flight simulator. I am using a plugin for the simulator software which returns a float variable to my arduino, which I then want to display on a series of 7-segment displays. I have connected three max7219 modules, each with 8 digits.

I found the LedControl library which I managed to get to display on my modules like this:

```
#include <LedControl.h>

// inputs: DIN pin, CLK pin, LOAD pin. number of chips
LedControl mydisplay = LedControl(48, 44, 46, 3);

void setup() {
  mydisplay.shutdown(0, false);  // turns on display
  mydisplay.shutdown(1, false);  // turns on display
  mydisplay.setIntensity(0, 7); // 15 = brightest
  mydisplay.setDigit(0, 0, 9, false);
  mydisplay.setDigit(0, 1, 8, false);
  mydisplay.setDigit(0, 2, 7, false);
  mydisplay.setDigit(0, 3, 6, false);
  mydisplay.setDigit(0, 4, 5, true);
  mydisplay.setDigit(0, 5, 4, false);
  mydisplay.setDigit(0, 6, 3, false);
  mydisplay.setDigit(0, 7, 2, false);

  mydisplay.setDigit(1, 0, 9, false);
  mydisplay.setDigit(1, 1, 8, false);
  mydisplay.setDigit(1, 2, 7, false);
  mydisplay.setDigit(1, 3, 6, false);
  mydisplay.setDigit(1, 4, 5, true);
  mydisplay.setDigit(1, 5, 4, false);
  mydisplay.setDigit(1, 6, 3, false);
  mydisplay.setDigit(1, 7, 2, false);

}

void loop() {
}

```

The arduino code however for the plugin I am using has this function:

```
void ProgOut(byte id, float val) {

  if (id == 1)
  {
       // print this to display
  }
}

```

So my question is, right now based on the LedControl test sketch, I have to display each individual character one by one, but I receive a float variable.. so how can I just do something like "mydisplay.set(floatvariable)" ?

# Answer
> 1 votes
> how can I just do something like "mydisplay.set(floatvariable)" ?

write your own code.

let's say that you want to display up to two decimal points. Multiply the float vary by 100, save it into an int variable, and utilize the existing code to display that integer variable + decimal point at the right digit.

---
Tags: arduino-uno, programming, lcd, display
---


# Question
Title: Code runs, then doesn't run after I add some routine code
I am programming an ESP8266-01.

I have this code which I am using to operate an on-off switch, which is being used as an override switch for when the relay is turned on and off over the internet:

```
void loop() {

  // Connect to the cloud
  rest.handle(client);

  // put your main code here, to run repeatedly:
  int read3 = digitalRead(0);

  Serial.print(read3);
  Serial.println(" input (1 is off)");

  if(read3 == 0) {
    if(pressed2) {
      Serial.println("in on");
      digitalWrite(2, 1);
      pressed = true;
      pressed2 = false;
    }
  }
  else {
    Serial.println("in off");
    if(pressed) {
      Serial.println("in off once");
      digitalWrite(2, 0);
      pressed = false;
      pressed2 = true;
    }
  }
}

```

The above code never starts to run (nothing gets output on the serial) and the relay turns on. The thing is, this code works:

```
void loop() {

  // Connect to the cloud
  rest.handle(client);

  // put your main code here, to run repeatedly:
  int read3 = digitalRead(0);

  Serial.print(read3);
  Serial.println(" input (1 is off)");

  if(read3 == 0) {
    Serial.println("in on");
    digitalWrite(2, 1);
    pressed = true;
  }
  else {
    Serial.println("in off");
    if(pressed) {
      Serial.println("in off once");
      digitalWrite(2, 0);
      pressed = false;
    }
  }
}

```

Basically the way the code is set up, it is handling things so that the pin doesn't get read after the instance first instance that it is read (this is what the `bool` `pressed` is helping to do).

Why doesn't the first version work?

**UPDATE**

Whole working sketch:

```
/*
  This a simple example of the aREST Library for the ESP8266 WiFi chip.
  This example illustrate the cloud part of aREST that makes the board accessible from anywhere
  See the README file for more details.

  Written in 2015 by Marco Schwartz under a GPL license.
*/

// Import required libraries
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <aREST.h>

// Clients
WiFiClient espClient;
PubSubClient client(espClient);

// Create aREST instance
aREST rest = aREST(client);

// Unique ID to identify the device for cloud.arest.io
char* device_id = "ew1zard";

// WiFi parameters
const char* ssid = "MaisonBlanche";
const char* password = "7932gLBw";

bool pressed = true;

// Functions
void callback(char* topic, byte* payload, unsigned int length);

void setup(void)
{
  // Set input / output pin
  pinMode(0, INPUT);
  pinMode(2, OUTPUT);

  // Start Serial
  Serial.begin(115200);

  // Set callback
  client.setCallback(callback);

  // Give name & ID to the device (ID should be 6 characters long)
  rest.set_id(device_id);
  rest.set_name("esp8266");

  // Connect to WiFi
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");

  // Set output topic
  char* out_topic = rest.get_topic();
}

void loop() {

  // Connect to the cloud
  rest.handle(client);

  // put your main code here, to run repeatedly:
  int read3 = digitalRead(0);

  Serial.print(read3);
  Serial.println(" input (1 is off)");

  if(read3 == 0) {
    Serial.println("in on");
    digitalWrite(2, 1);
    pressed = true;
  }
  else {
    Serial.println("in off");
    if(pressed) {
      Serial.println("in off once");
      digitalWrite(2, 0);
      pressed = false;
    }
  }
}

// Handles message arrived on subscribed topic(s)
void callback(char* topic, byte* payload, unsigned int length) {

  Serial.print("request from interwebs: ");
  Serial.println(topic);
  rest.handle_callback(client, topic, payload, length);

}

```

# Answer
> 1 votes
I used this - it does the same thing basically, just moved where the bool variables were.

```
if(read3 == 0) {
    if(pressed2) {
      Serial.println("in on");
      digitalWrite(2, 1);
      pressed2 = false;
    }
    pressed = true;
  }
  else {
    Serial.println("in off");
    if(pressed) {
      Serial.println("in off once");
      digitalWrite(2, 0);
      pressed = false;
    }
    pressed2 = true;
  }

```

---
Tags: arduino-uno, programming, esp8266, switch
---


# Question
Title: Software Interrupts in Arduino or nodeMCU
The code given below is an example code I found on the internet. This is to use my nodeMCU as a server. For my application, I believe that these lines of code...:

```
if (request.indexOf("/LED=ON") != -1)  {
            digitalWrite(ledPin, HIGH);
            value = HIGH;
          }
          if (request.indexOf("/LED=OFF") != -1)  {
            digitalWrite(ledPin, LOW);
            value = LOW;
          }

```

... from the below program should run thereby interrupting every processes.

```
 #include <ESP8266WiFi.h>

    const char* ssid = "Linux"; // SSID i.e. Service Set Identifier is the name of your WIFI
    const char* password = "0123456789"; // Your Wifi password, in case you have open network comment the whole statement.

    int ledPin = 13; // GPIO13 or for NodeMCU you can directly write D7
    WiFiServer server(80); // Creates a server that listens for incoming connections on the specified port, here in this case port is 80.

    void setup() {
      Serial.begin(115200);
      delay(10);

      pinMode(ledPin, OUTPUT);
      digitalWrite(ledPin, LOW);

      // Connect to WiFi network
      Serial.println();
      Serial.println();
      Serial.print("Connecting to ");
      Serial.println(ssid);

      WiFi.begin(ssid, password);

      while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
      }
      Serial.println("");
      Serial.println("WiFi connected");

      // Start the server
      server.begin();
      Serial.println("Server started");

      // Print the IP address
      Serial.print("Use this URL to connect: ");
      Serial.print("http://");
      Serial.print(WiFi.localIP()); //Gets the WiFi shield's IP address and Print the IP address of serial monitor
      Serial.println("/");

    }

    void loop() {
      // Check if a client has connected
      WiFiClient client = server.available();
      if (!client) {
        return;
      }

      // Wait until the client sends some data
      Serial.println("new client");
      while(!client.available()){
        delay(1);
      }

      // Read the first line of the request
      String request = client.readStringUntil('\r');
      Serial.println(request);
      client.flush();

      // Match the request

      int value = LOW;
      if (request.indexOf("/LED=ON") != -1)  {
        digitalWrite(ledPin, HIGH);
        value = HIGH;
      }
      if (request.indexOf("/LED=OFF") != -1)  {
        digitalWrite(ledPin, LOW);
        value = LOW;
      }

    // Set ledPin according to the request
    //digitalWrite(ledPin, value);

      // Return the response
      client.println("HTTP/1.1 200 OK");
      client.println("Content-Type: text/html");
      client.println(""); //  do not forget this one
      client.println("<!DOCTYPE HTML>");
      client.println("<html>");

      client.print("Led pin is now: ");

      if(value == HIGH) {
        client.print("On");
      } else {
        client.print("Off");
      }
      client.println("<br><br>");
      client.println("<a href=\"/LED=ON\"\"><button>Turn On </button></a>");
      client.println("<a href=\"/LED=OFF\"\"><button>Turn Off </button></a><br />");
      client.println("</html>");

      delay(1);
      Serial.println("Client disconnected");
      Serial.println("");

    }

```

How can we achieve this kind of software Interrupt(s)? PS: Timer Interrupt won't work -- I believe.

# Answer
> 0 votes
That doesn't need an interrupt. Think about it, just check it right after you read it from the client. So the response will be immediate. It's not like it can suddenly become true at some other point without being read from the client. You're already using a blocking read so if the first part of the message has arrived you'll stop right there and wait for it. The loop should turn over really fast, keep it fast and non-blocking anywhere else and you can count on even if the message starts coming in immediately after your read the loop will make it back around to read again before the end of the message gets there.

---
Tags: interrupt, nodemcu
---


# Question
Title: In a circuit with a switch and a pull-down resistor, why does the high impedance of the input not discourage current from flowing into pin?
I'm a beginner to Arduino and circuits. I've spent the last couple hours hung up on the concept of how current flows through switches and pull-down resistors, having read every thread and watched every YouTube video I could find on the subject.

I understand that pull-down (and pull-up) resistors are necessary in order to prevent pins from floating. What confuses me is that, if the input pins effectively have a built-in 100 megohm resistance (according to this page), then how is it that a 10k ohm pull-down resistor is enough to dissuade current from flowing directly into ground even when the switch is closed?

Here is a diagram of my circuit:

Am I conflating the high-impedance state of input pins with resistance more generally?

Would really appreciate any clarification on this. Thanks!

# Answer
> 0 votes
Yes, all of the current that flows goes through that resistor to ground. That way almost all the voltage drops across that one resistor and you are able to read the voltage with the pin on the high side of it. Only a very very small amount of current flows into the pin when you read a voltage. It just needs to charge up a very small capacitor.

---
Tags: current, resistor, pull-up
---


title: Mapping string values

text:
# Question
Title: Mapping string values
I have a bunch of thermometers (between 1 and 128). The thermometers have an internal OneWire ID such as "28edce1e500e5" and it is not readable by humans.

Normally I would make an associative array like this:

```
map["28edce1e500e5"] = "Temp1";
map["28ffd33b9116420"] = "Temp2";

Serial.print(map[printAddress(allDevices[i])]);
Serial.print(" : ");
Serial.print(sensors.getTempC(allDevices[i]));

```

But it looks like the only hashmap library for Arduino is no longer supported and appears to be quite expensive.

The solution does not have to involve associative array.

The values are populated from a JSON file, loaded from an SD card.

I'm looking for a solutiuon to the problem, not a way to implement an associative array. (Unless that's the best way to solve the problem)

# Answer
Make a struct containing the name and id.

```
struct device{char[MAX_ID_LENGTH] id; char[MAX_NAME_LENGTH] name; }

```

Then store the those pairs in an array which you can have sorted by one field or the other. That way you can binary search on that field.
> 3 votes

# Answer
Taking the device structure from rachet freak's post you could implement a map of your own using something like this:

```
template  <class K, class V> class MyMap
{
public:
    MyMap()
    {
    }

    void Add(K key, V value)
    {
    }

    void Remove(K key)
    {
    }

    V operator[](const& K)
    {
    }

private:
}

```

But I think templates are expensive under Arduino so you might want to manually instantiate it to drop the template.
> 0 votes

---
Tags: array
---


# Question
Title: Servo motor activation with pressure sensor
I need to run my servo motor within a specific pressure range, given by a pressure sensor. I don't understand how to code this. I have coded for servo motor movement but I need to activate that movement in a specific range. Please, help me.

This is my servo code:

```
#include <Servo.h>

Servo myservo;  // create servo object to control a servo
                // twelve servo objects can be created on most boards
int pos = 0;    // variable to store the servo position

void setup() {
  myservo.attach(9);
  // attaches the servo on pin 9 to the servo object
}

void loop() {
  for(pos = 0; pos <= 30; pos += 1) {
    // goes from 0 degrees to 180 degrees
    // in steps of 1 degree
    myservo.write(pos);
    // tell servo to go to position in variable 'pos'
    delay(5); // waits 15ms for the servo to reach the position
  }
  for(pos = 30; pos>=0; pos-=1) {
    // goes from 180 degrees to 0 degrees
    myservo.write(pos);
    // tell servo to go to position in variable 'pos'
    delay(5);
    // waits 15ms for the servo to reach the position
  }
  delay(1500);
}

```

I need to activate this servo within a 10-70 pressure range.

# Answer
> 1 votes
You don't tell what pressure sensor are you using, but suppose that a call to `readPressure()` will give as pressure as an `int`

```
#include <Servo.h>

Servo myservo;  // create servo object to control a servo
// twelve servo objects can be created on most boards

int pos = 0;    // variable to store the servo position

void setup()
{
    myservo.attach(9);  // attaches the servo on pin 9 to the servo object
}

void loop()
{
    int pressure = readPressure();

    if(pressure >= 10 && pressure <= 70) {
        //  Pressure is in range. Move the servo.
        for(pos = 0; pos <= 30; pos += 1) { // goes from 0 degrees to 180 degrees
            // in steps of 1 degree
            myservo.write(pos);              // tell servo to go to position in variable 'pos'
            delay(5);                       // waits 15ms for the servo to reach the position
        }

        for(pos = 30; pos>=0; pos-=1) {   // goes from 180 degrees to 0 degrees
            myservo.write(pos);              // tell servo to go to position in variable 'pos'
            delay(5);                       // waits 15ms for the servo to reach the position
        }
    }

    //  Wait for another 1.5 sec before next loop().
    delay(1500);
}

```

Of course, you have to complete the code with the actual sensor calls.

---
Tags: servo
---


# Question
Title: IR Remote code not activating ON/OFF states
The code below is for turning RGB lights on/off. The connections are as indicated in pin numbers. I found the resulting value of the buttons of the remote but when I used them in code it is not showing ON/OFF.

I assume there may be some practical errors. How to avoid such errors?

```
#include <IRremote.h>

int RECV_PIN = 3;
int red = 13;
int blue = 12;
int green = 11;

IRrecv irrecv(RECV_PIN);

decode_results results;

void setup() {
  Serial.begin(9600);
  irrecv.enableIRIn(); // Start the receiver
  pinMode(red, OUTPUT);
  pinMode(blue, OUTPUT);
  pinMode(green, OUTPUT);
}

void loop() {
  if (irrecv.decode(&results)) {
    long int getting = results.value;
    Serial.println(getting);
  }
  switch (results.value) {
    case 16582903:
      digitalWrite(red, HIGH);
      digitalWrite(blue, LOW);
      digitalWrite(green, LOW);
      break;
    case 16615543:
      digitalWrite(red, LOW);
      digitalWrite(blue, HIGH);
      digitalWrite(green, LOW);
      break;
    case 16599223:
      digitalWrite(red, LOW);
      digitalWrite(blue, LOW);
      digitalWrite(green, HIGH);
      break;
    default:
      Serial.println("Enter ;");
  }
  irrecv.resume(); // Receive the next value
  delay(100);
}

```

# Answer
> 3 votes
Assuming you wiring is correct, the only mistake I could see is that your variable named "getting" used in switch is inside the if, and it should be at least in the same level of switch. Also, your resume needs to be inside the if.

```
#include <IRremote.h>

int RECV_PIN = 3;
int green = 11;
int blue = 12;
int red = 13;

#define code1  16582903 // Must match exactly the code generated by the IR button, would be something like 0xFF906F
#define code2  16615543
#define code3  16599223

IRrecv irrecv(RECV_PIN);
decode_results results;

void setup() {
  Serial.begin(9600);
  irrecv.enableIRIn(); // Start the receiver
  pinMode(red, OUTPUT);
  pinMode(blue, OUTPUT);
  pinMode(green, OUTPUT);
}

void loop() {
  if(irrecv.decode(&results)) {
    //this checks to see if a code has been received
    Serial.println(results.value, HEX);
    unsigned int getting = results.value;
    Serial.println(getting);
    switch (getting) {
      case code1:
        digitalWrite(red, HIGH);
        digitalWrite(blue, LOW);
        digitalWrite(green, LOW);
        break;
      case code2:
        digitalWrite(red, LOW);
        digitalWrite(blue, HIGH);
        digitalWrite(green, LOW);
        break;
      case code3:
        digitalWrite(red, LOW);
        digitalWrite(blue, LOW);
        digitalWrite(green, HIGH);
        break;
      default:
        Serial.println("Enter ;");
    }
    irrecv.resume(); //receive the next value
  }
  delay(100);
}

```

# Answer
> 1 votes
I would change "unsigned int getting = results.value;" to "unsigned long getting = results.value;" in Andrew's sketch and use it. I don't know what "type" of Arduino you are using, but I know on the Uno and other ATMEGA based boards, unsigned ints yield a useful range of 0 to 65,535. Unsigned long will give you a range from 0 to 4,294,967,295.

If you press ANY button and hold it down for a while on some IR remotes, code 4294967295 will be sent. This is true for the "Car" remotes: https://www.amazon.ca/dp/B00SMI1GZA/ref=pe\_386430\_126088100\_TE\_item, Apple TV (2nd generation) remote, and LG 50" TV remote.

One minor issue I found with both sketches is I could not get them to compile. I had to remove the space between "#" and "include" and the spaces between "\<" and "\>" in "# include \< IRremote.h \>". I am using an older version of the IDE which may explain it. Arduino UNO. IDE Version 1.0.6.2, GCC 4.2.1 on OSX 10.6.8.

---
Tags: remote-control, code-review
---


# Question
Title: Why do GPS coordinates fail to save on MySQL database using SIM900?
My project is a vehicle tracking system. I'm using a NEO-6M for GPS and a SIM900 for GPRS. I want to send the GPS coordinates to a MySQL database. I've tested the GPS and it's working well. I've succeeded to send the data to the online MySQL database by manually typing the AT commands on the Arduino Serial Monitor. Now, I would like to put the sending of coordinates in a `loop` for Arduino to send the coordinates on the database every 3 seconds. But there's no data entering the database. What do you think is the problem here? Here's my code (by the way it has no errors reported):

sendlatlng.ino:

```
#include <SoftwareSerial.h>
#include "SIM900.h"
#include <TinyGPS.h>
#define pinPowerSIM900 14

TinyGPS gps;
SoftwareSerial ss(10, 11);

uint16_t startAddr = 0x0000;
uint16_t lastAddr;
uint16_t TimeIsSet = 0xaa55;
int currentDay = 0;
int currentMonth = 0;
int currentYear = 0;
int currentHour = 0;
int currentMinute = 0;
float flat, flon;
float previousFlat = 0.0;
float previousFlon = 0.0;
static void smartdelay(unsigned long ms);
static void print_float(float val, float invalid, int len, int prec);
static void print_int(unsigned long val, unsigned long invalid, int len);
static void print_date(TinyGPS &gps);
static void print_str(const char *str, int len);

void setup() {
  pinMode (pinPowerSIM900, OUTPUT); digitalWrite (pinPowerSIM900, LOW);
  powerUpOrDown();
  Serial.begin(115200);
  Serial.print("Testing TinyGPS library v. ");
  Serial.println(TinyGPS::library_version());
  Serial.println("");
  Serial.println();
  Serial.println("Stats HDOP Latitude  Longitude  Fix  Date       Time     Date Alt    Course Speed Card  Distance Course Card  Chars Sentences Checksum");
  Serial.println("          (deg)     (deg)      Age                      Age  (m)    --- from GPS ----  ---- to London  ----  RX    RX        Fail");
  Serial.println("-------------------------------------------------------------------------------------------------------------------------------------");
  ss.begin(9600);
}

void loop() {
  bool newData = false;
  for (unsigned long start = millis(); millis() - start < 1000;) {
    while (ss.available()) {
      char c = ss.read();
      //Serial.write(c);  /*uncomment this line if you want to see GPS data*/
      if (gps.encode(c)) newData = true;
    }
  }

  if (newData) {
    float flat, flon;
    unsigned long age, date, time, chars = 0;
    unsigned short sentences = 0, failed = 0;
    static const double LONDON_LAT = 51.508131, LONDON_LON = -0.128002;
    print_int(gps.satellites(), TinyGPS::GPS_INVALID_SATELLITES, 5);
    print_int(gps.hdop(), TinyGPS::GPS_INVALID_HDOP, 5);
    gps.f_get_position(&flat, &flon, &age);  /*latitude, longitude, age*/
    print_float(flat, TinyGPS::GPS_INVALID_F_ANGLE, 10, 6);  /*print lat */
    print_float(flon, TinyGPS::GPS_INVALID_F_ANGLE, 11, 6);  /*print long */
    print_int(age, TinyGPS::GPS_INVALID_AGE, 5);
    print_date(gps); /* print date */
    print_float(gps.f_altitude(), TinyGPS::GPS_INVALID_F_ALTITUDE, 7, 2); /* print altitude */
    print_float(gps.f_course(), TinyGPS::GPS_INVALID_F_ANGLE, 7, 2);
    print_float(gps.f_speed_kmph(), TinyGPS::GPS_INVALID_F_SPEED, 6, 2);
    print_str(gps.f_course() == TinyGPS::GPS_INVALID_F_ANGLE ? "*** " :
   TinyGPS::cardinal(gps.f_course()), 6);
    print_int(flat == TinyGPS::GPS_INVALID_F_ANGLE ? 0xFFFFFFFF : (unsigned long)TinyGPS::distance_between(flat, flon, LONDON_LAT, LONDON_LON) / 1000, 0xFFFFFFFF, 9);
    print_float(flat == TinyGPS::GPS_INVALID_F_ANGLE ?
   TinyGPS::GPS_INVALID_F_ANGLE : TinyGPS::course_to(flat, flon, LONDON_LAT, LONDON_LON), TinyGPS::GPS_INVALID_F_ANGLE, 7, 2);
    print_str(flat == TinyGPS::GPS_INVALID_F_ANGLE ? "*** " :
   TinyGPS::cardinal(TinyGPS::course_to(flat, flon, LONDON_LAT, LONDON_LON)), 6);
    gps.stats(&chars, &sentences, &failed);
    print_int(chars, 0xFFFFFFFF, 6);
    print_int(sentences, 0xFFFFFFFF, 10);
    print_int(failed, 0xFFFFFFFF, 9);
    Serial.println();
    smartdelay(3000);
    if ((flat != previousFlat) || (flon != previousFlon)) {
      previousFlat = flat;
      previousFlon = flon;
      SendSQL();  //Function to send the coordinates
    }
  }
}

static void smartdelay(unsigned long ms) {
  unsigned long start = millis();
  do {
    while (ss.available()) gps.encode(ss.read());
  } while (millis() - start < ms);
}

static void print_float(float val, float invalid, int len, int prec) {
  if (val == invalid) {
    while (len-- > 1) Serial.print('*');
    Serial.print(' ');
  } else {
    Serial.print(val, prec);
    int vi = abs((int)val);
    int flen = prec + (val < 0.0 ? 2 : 1); // . and -
    flen += vi >= 1000 ? 4 : vi >= 100 ? 3 : vi >= 10 ? 2 : 1;
    for (int i=flen; i<len; ++i) Serial.print(' ');
  }
  smartdelay(0);
}

static void print_int(unsigned long val, unsigned long invalid, int len) {
  char sz[32];
  if (val == invalid) strcpy(sz, "*******");
  else sprintf(sz, "%ld", val);
  sz[len] = 0;
  for (int i=strlen(sz); i<len; ++i) sz[i] = ' ';
  if (len > 0) sz[len-1] = ' ';
  Serial.print(sz);
  smartdelay(0);
}

static void print_date(TinyGPS &gps) {
  int year;
  byte month, day, hour, minute, second, hundredths;
  unsigned long age;
  gps.crack_datetime(&year, &month, &day, &hour, &minute, &second, &hundredths, &age);
  if (age == TinyGPS::GPS_INVALID_AGE) Serial.print("********** ******** ");
  else {
    char sz[32];
    sprintf(sz, "%02d/%02d/%02d %02d:%02d:%02d ", month, day, year, hour, minute, second);
    Serial.print(sz);
  }
  print_int(age, TinyGPS::GPS_INVALID_AGE, 5);
  smartdelay(0);
}

static void print_str(const char *str, int len) {
  int slen = strlen(str);
  for (int i=0; i<len; ++i) Serial.print(i<slen ? str[i] : ' ');
  smartdelay(0);
}

void powerUpOrDown() {
  digitalWrite(pinPowerSIM900, HIGH);
  delay(2000);
  digitalWrite(pinPowerSIM900, LOW);
  delay(3000);
}

void SendSQL() {
  Serial.println("Start Send");
  gsm.SimpleWriteln("AT+SAPBR=3,1,\"Contype\",\"GPRS\"");
  delay(500);
  gsm.SimpleWriteln("AT+SAPBR=3,1,\"APN\",\"my.apn.com\"");   //APN
  delay(500);
  gsm.SimpleWriteln("AT+SAPBR=1,1");
  delay(3000);
  gsm.SimpleWriteln("AT+SAPBR=2,1");
  delay(3000);
  gsm.SimpleWriteln("AT+HTTPINIT");
  delay(500);
  gsm.SimpleWriteln("AT+HTTPPARA=\"CID\",1 ");
  delay(500);
  gsm.SimpleWriteln("AT+HTTPPARA=\"URL\",\"http://crbphil-001-site1.1tempurl.com/adddata.php\""); //URL
  delay(500);
  gsm.SimpleWriteln("AT+HTTPPARA=\"CONTENT\",\"application/x-www-form-urlencoded\"");
  delay(500);
  gsm.SimpleWriteln("AT+HTTPDATA=38,10000");
  delay(500);
  gsm.SimpleWriteln("addlati=");
  Serial.print(previousFlat, 6);
  gsm.SimpleWriteln("&addlongti=");
  Serial.print(previousFlon, 6);
  gsm.SimpleWriteln("\"");
  delay(3000);
  gsm.SimpleWriteln("AT+HTTPACTION=1");
  delay(15000);
  gsm.SimpleWriteln("AT+HTTPTERM");
  delay(500);
  gsm.SimpleWriteln("AT+SAPBR=0,1");
  delay(500);
  Serial.println("Finish");
}

```

And this is my PHP script to save data in the MySQL database:

adddata.php:

```
<?php
//Connect to MySQL
include("config.php");

// Perform a query, check for error
if (!mysqli_query($connect,"INSERT INTO track (tr_date, tr_time, latitude, longitude) VALUES ('".$_POST["addday"]."','".$_POST["addhour"]."','".$_POST["addlati"]."','".$_POST["addlongti"]."')")) {
  echo("Error description: " . mysqli_error($connect));
}
?>

```

# Answer
Can you see a slight discrepancy in these lines?

```
gsm.SimpleWriteln("addlati=");
Serial.print(previousFlat, 6);
gsm.SimpleWriteln("&addlongti=");
Serial.print(previousFlon, 6);

```

I can.
> 1 votes

---
Tags: programming, gsm, gps, web-server, tinygps
---


# Question
Title: Including Arduino library in a Makefile for Due
I'm currently using a Makefile for the Arduino Due I've found on Github (with some modifications). It's useful to me cause it allows me to add a static library for cryptographic functions I need and I can't do it using the IDE. Now I need to include the WiFi library from Arduino but I don't know how. I've tried to put the path to the source (/usr/share/arduino/libraries/WiFi/src) but it gives me warnings saying that some classes are undefined. Does anyone know how to include that library?

# Answer
> 0 votes
Adding a library isn't as simple as just adding an include path.

You also have to identify each and every source file (or use wildcards as are used for the various sections of the core) and compile them into object files. It is then quite convenient to archive those into a library (.a) file which you can then link your sketch against (if you don't archive you will have to link all the objects files with your sketch in the linking phase).

---
Tags: wifi, arduino-due, makefile, arduino-makefile
---


title: Problem with my 2 motor system

text:
# Question
Title: Problem with my 2 motor system
I am trying to operate two DC motors at once using a L293D chip. I have managed to control them however, one of the motors has a slight problem. Whenever I start the program (attached below), one of the motor (I tried switching them, it isn't a problem due to the motor itself) has a counterclockwise spin for a second before starting to spin clockwise as it is suppose to. When it is spinning counterclockwise, the other motor is not doing any movements.

Is something wrong in the code or in the circuit? (I've also attached a hyperlink to my circuit which I found online, as well as my code)

Thank you

```
#define E1 11  // Enable Pin for motor 1
#define E2 10  // Enable Pin for motor 2
#define I1 12  // Control pin 1 for motor 1
#define I2 13  // Control pin 2 for motor 1
#define I3 8   // Control pin 1 for motor 2
#define I4 9   // Control pin 2 for motor 2

void setup() {
  pinMode(E1, OUTPUT);
  pinMode(E2, OUTPUT);
  pinMode(I1, OUTPUT);
  pinMode(I2, OUTPUT);
  pinMode(I3, OUTPUT);
  pinMode(I4, OUTPUT);
}

void loop() {
  analogWrite(E1, 255); // Run at full speed
  analogWrite(E2, 255); // Run at full speed
  digitalWrite(I1, HIGH);
  digitalWrite(I2, LOW);
  digitalWrite(I3, HIGH);
  digitalWrite(I4, LOW);
  delay(4500);
  // change direction
  digitalWrite(E1, LOW);
  digitalWrite(E2, LOW);
  delay(2000000000000);
  analogWrite(E1, 255);  // Run at full speed
  analogWrite(E2, 255);  // Run at full speed
  digitalWrite(I1, LOW);
  digitalWrite(I2, HIGH);
  digitalWrite(I3, LOW);
  digitalWrite(I4, HIGH);
  delay(000);
}

```

http://hw.sudarmuthu.com/wp-content/uploads/sites/2/2013/06/basic-bot1.png

# Answer
> 1 votes
I'm having trouble compiling your code Max. It's failing on this line: delay(2000000000000);

The last line of code: delay(000); doesn't seem to be doing anything useful and can be removed.

I do not have a L293D IC to test the following code with so I need you to test it for me please.

```
#define E1 11  // Enable Pin for motor 1
#define E2 10  // Enable Pin for motor 2

#define I1 12  // Control pin 1 for motor 1
#define I2 7   // Control pin 2 for motor 1 (change pin 13 to pin 7)
#define I3 8   // Control pin 1 for motor 2
#define I4 9   // Control pin 2 for motor 2

void setup() {
  pinMode(E1, OUTPUT);
  pinMode(E2, OUTPUT);
  pinMode(I1, OUTPUT);
  pinMode(I2, OUTPUT);
  pinMode(I3, OUTPUT);
  pinMode(I4, OUTPUT);

  // Disable motors
  digitalWrite(E1, LOW);
  digitalWrite(E2, LOW);
}

void loop() {

    // Set direction first
    digitalWrite(I1, HIGH);
    digitalWrite(I2, LOW);
    digitalWrite(I3, HIGH);
    digitalWrite(I4, LOW);

    // Enable motors
    analogWrite(E1, 255);
    analogWrite(E2, 255);

    // Motors run for 4.5 seconds
    delay(4500);

    // change direction

    // Disable motors
    digitalWrite(E1, LOW);
    digitalWrite(E2, LOW);

    // Give the motors time to stop if required
    delay(500);

    // Change motor direction
    digitalWrite(I1, LOW);
    digitalWrite(I2, HIGH);
    digitalWrite(I3, LOW);
    digitalWrite(I4, HIGH);

    // Enable motors
    analogWrite(E1, 255);
    analogWrite(E2, 255);

    // Motors run for 4.5 seconds
    delay(4500);

    // Disable motors
    digitalWrite(E1, LOW);
    digitalWrite(E2, LOW);

    // Give the motors time to stop if required
    delay(500);
}

```

# Answer
> 2 votes
```
#define I2 13  // Control pin 2 for motor 1

```

Pin 13 is the LED and is blinked by the bootloader. You will have to use a different pin for your motor.

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


# Question
Title: Adafruit RTC DS3231 Crashing Arduino Uno
I am having some issues with a new DS3231 Precision RTC module. I have made connections as in the guide linked, and when used, the serial output from the Arduino is garbled, and the arduino apparently crashes, endlessly flowing garbled messages (which appear to be bits of the beginning of the first serial output).

Sometimes I can get better output, but only up until I try to set the datetime, where it then crashes, with endless garble.

Code used to set datetime (all vars given are `int`s):

```
rtc.adjust(DateTime(year, month, day, hour, minute, second));

```

The way I have things wired is the same as on the guide listed. I am basing my code off of the example on the guide (which is the same as on the guide), yet the example code functions well.

Relevant excerpt(s) from my code:

```
//includes
#include <Servo.h> //for running the servo
#include <Wire.h> //required for RTClib
#include "RTClib.h" //to run the real time clock functionality. https://github.com/adafruit/RTClib

boolean timingEnabled = true;
RTC_DS3231 rtc;
void setup(){
  Serial.begin(9600);
  if(timingEnabled){
    //clock
    boolean rtcOn = rtc.begin();
    Serial.print(String(rtcOn) + "\n");
    if(! rtcOn){
      Serial.print("Couldn't find RTC. Timing Disabled\n");
      timingEnabled = false;
    }else{
      if(rtc.lostPower()){
        Serial.println("Clock lost power.\n");
        setTime();//set the clock
      }
    }
  }
}

```

Since it was asked for, full code (minus `loop()`):

```
/* Sketch for Arduino to run the automatic cat feeder.
 *
 *
 */

//includes
#include <Servo.h> //for running the servo
#include <Wire.h> //required for RTClib
#include "RTClib.h" //to run the real time clock functionality. https://github.com/adafruit/RTClib

//status indicator values
const int onboardLedPin = 13;

//buzzer values
const boolean buzz = true; //turns on and off the buzzer functionality
const int buzzerPin = 8;
const int buzzLength = 250;
const int buzzDefaultFreq = 1000;
const int buzzFeedStartFreq = 2000;
const int buzzFeedEndFreq = 500;
const int buzzBattWarnFreq = 2000;
const int buzzConfirmFreq = 100;

//Servo setup
Servo dispenserServo;
const int servoPin = 11;
const int feedServoSpinTime = 2000;
const int STOP = 90;
const int SPIN_CLOCKWISE = 180;
const int SPIN_COUNTER_CLOCKWISE = 0;

//clock
boolean timingEnabled = true;
RTC_DS3231 rtc;
String feedTimes[] = {"7:00"};

//button
const int buttonPin = 7;
int buttonVal = 0;

//other
const int mainWait = 5000;

/*
 * Does a buzz if it is set to.
 */
void doBuzz(int frequency, boolean wait){
  if(buzz){
    tone(buzzerPin, frequency, buzzLength);
    if(wait){
      delay(buzzLength);
    }
  }
}

/*
 * Default function to not wait for buzz to finish.
 */
void doBuzz(){
  doBuzz(buzzDefaultFreq, false);
}

void checkButton(){
  buttonVal = digitalRead(buttonPin);
}

/*
 * Determines if it is time to do the feeding.
 */
boolean isFoodTime(){
  if(!timingEnabled){
    return false;
  }
  DateTime curTime = rtc.now();

  String hr = String(curTime.hour());
  String mn = String(curTime.minute());

  String time = hr + ":" + mn;

  for(int i = 0; i < sizeof(feedTimes); i++){
    if(feedTimes[i] == time){
      return true;
    }
  }

  return false;
}

String formatDateTime(DateTime dtIn){
  return String(dtIn.month()) + "/" + String(dtIn.day()) + "/" + String(dtIn.year()) + " " + String(dtIn.hour()) + ":" + String(dtIn.minute()) + ":" + String(dtIn.second());
}

String formatDateTime(){
    formatDateTime(rtc.now());
}

int getNumFromButton(int startAt){
  doBuzz(buzzFeedEndFreq, true);
  int longPressLength = 500;
  int output = startAt;
  bool counting = true;
  do{
    checkButton();
    if(buttonVal == HIGH){
        delay(longPressLength);
        checkButton();
        if(buttonVal == HIGH){
          counting = false;
        }else{
          output++;
          doBuzz(buzzConfirmFreq, true);
          delay(longPressLength);
        }
    }
  }while(counting);
  doBuzz(buzzConfirmFreq, true);
  delay(buzzLength);
  doBuzz(buzzConfirmFreq, true);
  return output;
}

void setTime(){
  //rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
  //Serial.print("Setting the clock... ("+formatDateTime()+")\n");
  delay(buzzLength);
  delay(buzzLength);
  doBuzz(buzzConfirmFreq, true);
  delay(buzzLength);
  doBuzz(buzzConfirmFreq, true);
  delay(buzzLength);
  doBuzz(buzzConfirmFreq, true);
  Serial.print("Getting Year... (");
  int year = getNumFromButton(2000);
  Serial.print(String(year) + ")\nGetting Month... (");
  int month = getNumFromButton(1);
  Serial.print(String(month) + ")\nGetting Day... (");
  int day = getNumFromButton(1);
  Serial.print(String(day) + ")\nGetting Hour... (");
  int hour = getNumFromButton(0);
  Serial.print(String(hour) + ")\nGetting Minute... (");
  int minute = getNumFromButton(0);
  Serial.print(String(minute) + ")\nGetting Second... (");
  int second = getNumFromButton(0);
  Serial.print(String(second) + ")\n");
  delay(buzzLength);
  doBuzz(buzzConfirmFreq, true);

  Serial.print("Finished getting numbers.\n");
  rtc.adjust(DateTime(year, month, day, hour, minute, second));
  Serial.print("Clock set to: " + formatDateTime() + "\n");
}

/*
 * Setup of things:
 *  - status led
 *  - buzzer
 *  - servo
 */
void setup(){
  Serial.begin(9600);
  Serial.print("\nBeginning setup of the CatFeeder.\n");
  // status led
  pinMode(onboardLedPin, OUTPUT);
  // buzzer
  pinMode(buzzerPin, OUTPUT);
  doBuzz();
  //servo
  dispenserServo.attach(servoPin);
  pinMode(servoPin, OUTPUT);
  dispenserServo.write(STOP);

  if(timingEnabled){
    //clock
    boolean rtcOn = rtc.begin();
    Serial.print(String(rtcOn) + "\n");
    if(! rtcOn){
      Serial.print("Couldn't find RTC. Timing Disabled\n");
      timingEnabled = false;
      doBuzz(buzzConfirmFreq, true);
      delay(buzzLength);
      doBuzz(buzzConfirmFreq, true);
      delay(buzzLength);
      doBuzz(buzzConfirmFreq, true);
      delay(buzzLength);
      doBuzz(buzzConfirmFreq, true);
    }else{
      if(rtc.lostPower()){
        Serial.println("Clock lost power.\n");
        setTime();
      }
    }
  }
  if(!timingEnabled){
    Serial.print("Timing disabled. Will only actuate on button press.\n");
  }else{
    Serial.print("Current time: " + formatDateTime());
  }

  //button
  pinMode(buttonPin, INPUT);

  Serial.print("Finished setup.\n\n");
}

```

Full code size:

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

# Answer
Memory is never allocated for the result of formatDateTime().

Or more exactly there is a local variable inside formatDateTime() which has memory allocated as the string is built, then formatDateTime() returns a pointer to this memory, but as soon as the formatDateTime() exits this memory is freed, hence when Serial.print() is called and passed this pointer the memory at this pointer that used to hold the string may have already been reused.
> 0 votes

---
Tags: arduino-uno, rtc
---


# Question
Title: 3 AC current sensors using one Arduino Uno board measuring at 200Hz
I'm new to electronics and need some help please.

I'm planning to measure current of a 3-phase output using one sensor for each phase (thus 3 sensors would be required). The frequency of data recording should be 200 Hz.

Performance/data transfer wise: Is one Arduino Uno board enough to plug in the three sensors and get the data transferred using the USB cable onto a PC? Or should I get one board for each sensor?

I appreciate your help.

Cheers.

lorena

# Answer
> 1 votes
1. Is the sampling speed enough?

It takes about 100 microseconds (0.0001 s) to read an analog input, so the maximum reading rate is about 10,000 times a second.

Ref.: https://www.arduino.cc/en/Reference/AnalogRead

2. Is the USB port fast enough?

The serial speed over USB is maximum 2Mbps and a fast calculation (200 samples/s x 3 sensors x 10 bit) 18kbps, so 2Mbps should be enough.

---
Tags: arduino-uno, sensors, datalogging
---


# Question
Title: Recording of sensor results but only retain the last 3 sets of data
I'm doing a radiation-seeking robot, which will find the source of the radiation autonomously. But in this case, my robot will spin 180 degrees to detect the nearest source of radiation and 1 set of data recorded is considered for every 180 degree turn. However I think it is not possible to store all of the data in the Arduino due to a storage problem.

Therefore is there any function in Arduino that can only record the last 3 sets of data from the sensor? For example, after it has recorded 3 sets of data, the fourth set data could be recorded by overwriting the first set of data. I would be really grateful if anyone could help me with this.

PS if possible I don't want to install an SD card in my Arduino.

# Answer
> 2 votes
It depends how big the data is... if one data set is 100 bytes, you can spend 300 bytes of internal SRAM memory.

What you also can do if the memory usage is too big, is to add external SRAM, like the 32K256 which has 32 kb (kilobyte) SRAM or the 23LC1024 which has 128 kb SRAM.

To loop through the data sets you can easily use a so called 'ring buffer'.

You allocate 3 sets of data (like 3 arrays of a byte array), and an index. the index you increase after every use like:

```
index = (index + 1) % 3

```

External SRAM normally uses SPI to communicate with, and you can read/write it by a single byte, multiple bytes or page (typically 128 to 512 bytes). You cannot directly store variables in it, but you have to manually keep track where you store what ... for 3 data sets this will be relatively easy. You can even calculate (beforehand) the number of data sets that can be stored and cycle through them as needed.

---
Tags: robotics, memory
---


# Question
Title: ESP8266WiFi library severely slowed down my embedded system project
I am trying to incorporate IoT to my embedded system project. I would call it soft real-time embedded system project. But because of these '*LAZY*' lines,

```
while (WiFi.status() != WL_CONNECTED) {
  delay(500);
  Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
// Start the server
server.begin();
Serial.println("Server started");
if (!client) {
  return;  // Wait until the client sends some data
}
Serial.println("new client");
while (!client.available()) {
  delay(1);
}

```

The rest of the embedded system project has become so slow. If I don't put any of those lines, there will be obnoxious side-effects. How can I run this code along my actual embedded system project and still get done the soft real-time job?

\[Edited\] Full code:

```
#include <ESP8266WiFi.h>

const char* ssid = "Linux"; // SSID i.e. Service Set Identifier is the name of your WIFI
const char* password = "0123456789"; // Your Wifi password, in case you have open network comment the whole statement.

int ledPin = 13; // GPIO13 or for NodeMCU you can directly write D7
WiFiServer server(80); // Creates a server that listens for incoming connections on the specified port, here in this case port is 80.

void setup() {
  Serial.begin(115200);
  delay(10);

  pinMode(ledPin, OUTPUT);
  digitalWrite(ledPin, LOW);

  // Connect to WiFi network
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");

  // Start the server
  server.begin();
  Serial.println("Server started");

  // Print the IP address
  Serial.print("Use this URL to connect: ");
  Serial.print("http://");
  Serial.print(WiFi.localIP()); //Gets the WiFi shield's IP address and Print the IP address of serial monitor
  Serial.println("/");

}

void loop() {
  // Check if a client has connected
  WiFiClient client = server.available();
  if (!client) {
    return;
  }

  // Wait until the client sends some data
  Serial.println("new client");
  while(!client.available()){
    delay(1);
  }

  // Read the first line of the request
  String request = client.readStringUntil('\r');
  Serial.println(request);
  client.flush();

  // Match the request

  int value = LOW;
  if (request.indexOf("/LED=ON") != -1)  {
    digitalWrite(ledPin, HIGH);
    value = HIGH;
  }
  if (request.indexOf("/LED=OFF") != -1)  {
    digitalWrite(ledPin, LOW);
    value = LOW;
  }

// Set ledPin according to the request
//digitalWrite(ledPin, value);

  // Return the response
  client.println("HTTP/1.1 200 OK");
  client.println("Content-Type: text/html");
  client.println(""); //  do not forget this one
  client.println("<!DOCTYPE HTML>");
  client.println("<html>");

  client.print("Led pin is now: ");

  if(value == HIGH) {
    client.print("On");
  } else {
    client.print("Off");
  }
  client.println("<br><br>");
  client.println("<a href=\"/LED=ON\"\"><button>Turn On </button></a>");
  client.println("<a href=\"/LED=OFF\"\"><button>Turn Off </button></a><br />");
  client.println("</html>");

  delay(1);
  Serial.println("Client disconnected");
  Serial.println("");

}

```

# Answer
> 1 votes
I tested your sketch on a NodeMCU 0.9 and it works fine. Response times is sub-second. I'm using Firefox on a Linux Mint as a client.

I added code to timed each `loop` execution. The average time is 20-30 ms per loop. It looks fine to me or is it to long for you?

I think using a ESP8266WebServer is overkill and probably will take more resources to run. Having used ESP8266WebServer, for a project with one or two pages, using your approach is just fine.

# Answer
> -1 votes
Try ESP8266WebServer instead. The following is an example included with the ESP8266 board package.

```
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>

const char* ssid = "........";
const char* password = "........";

ESP8266WebServer server(80);

const int led = 13;

void handleRoot() {
  digitalWrite(led, 1);
  server.send(200, "text/plain", "hello from esp8266!");
  digitalWrite(led, 0);
}

void handleNotFound(){
  digitalWrite(led, 1);
  String message = "File Not Found\n\n";
  message += "URI: ";
  message += server.uri();
  message += "\nMethod: ";
  message += (server.method() == HTTP_GET)?"GET":"POST";
  message += "\nArguments: ";
  message += server.args();
  message += "\n";
  for (uint8_t i=0; i<server.args(); i++){
    message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
  }
  server.send(404, "text/plain", message);
  digitalWrite(led, 0);
}

void setup(void){
  pinMode(led, OUTPUT);
  digitalWrite(led, 0);
  Serial.begin(115200);
  WiFi.begin(ssid, password);
  Serial.println("");

  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("Connected to ");
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());

  if (MDNS.begin("esp8266")) {
    Serial.println("MDNS responder started");
  }

  server.on("/", handleRoot);

  server.on("/inline", [](){
    server.send(200, "text/plain", "this works as well");
  });

  server.onNotFound(handleNotFound);

  server.begin();
  Serial.println("HTTP server started");
}

void loop(void){
  server.handleClient();
}

```

---
Tags: esp8266, wifi
---


title: Arduino with sensor

text:
# Question
Title: Arduino with sensor
I am new to arduino and sensor. I am going to do a project related to E-nose to detect children breath odor. I wanted to use few sensors including Figaro TGS2602, TGS2600, TGS825, TGS2620 and TGS2180 together with arduino. May I ask is it possible for an Arduino Uno or Mega to support all these 5 sensors at one time?

# Answer
They are all analog sensors, so yes - you have 6 analog inputs on an Uno and 5 analog sensors, so you have one spare analog pin to do something else with if you want.
> 1 votes

---
Tags: arduino-uno, arduino-mega, sensors
---


# Question
Title: MAX7219 7-segment 8-digit display in wrong order
I have daisy-chained three MAX7219 7-segment 8-digit displays and wired it according to this diagram:

but no matter what library I use, the middle segment is in the wrong order when I display it.

So the numbers "123456789123456789"

would display as"12345678 76543219 89"

What could be wrong?

# Answer
If you had three separate boards that you had chained together I would be surprised if one of them was wrong, but looking at the picture it looks like one board and I would think it was more likely that one display was incorrect.

I can't see your code, so I can't say if there is a bug in it or not. It is possible that you have done something unusual, you might want to post a MINIMAL example to let people give it the once over.

As far as I know there aren't any "configuration settings" on a Max7219 to cause the affect you are seeing. The fact that the 3rd display is correct implies that the tracks on the PCB are correct and its the IC that's got its wiring backwards, but that's a daft idea.

You might be able to work out if a track is wrong, or such like, but it would be so much easier to fix in software. When you write to the display add an extra function that traps calls to the middle segment and flips the digits round (so `tmp == digit[7]; digit[8] == digit[0]; digit[0] = tmp; // You know what I mean`).
> 0 votes

---
Tags: led, lcd, display, max7219
---


# Question
Title: SdFat library Change output style of sd.ls(LS_R)
I'm using the SdFat Library's `sd.ls(LS_R)` function to give me a serial output stream of all files on an SD card. My issue is that I would like to have it use a different character than '\n' at the end of each line as I'm using it as a termchar for my overall comms protocol. How can I get it to print a `:` or (another symbol that doesn't appear in file names) instead of a `\ln`

# Answer
> 1 votes
I am currently trying to have fun Modding my own sd.ls().

Worst way, modifying the library:

Go into FatFilePrint.cpp

(Suggestion: Create yourself a new 'flag' like LS\_COMMA)

Find the line

```
void FatFile::ls(print_t* pr, uint8_t flags, uint8_t indent) { ...

```

add your flag

```
if (flag & !LS_COMMA) {
   pr-->write(':');
} else {
    //original library set of
    // pr->write(stuff);
}

```

# --\> SuperClass version # (prefered )

this will override the original ls() method by creating a new Class inheriting from the original one.

rather then invoking it from "volume", sd.ls( **your params**);

invoke it from a directory file instead.

```
superFatFile rootDir;
rootDir.open("/");
rootDir.ls( __your_params__);

```

Place this superClass declaration in your .h don't hesitate to remove any of the "flags" related code if YOUR requirement never calls for them.

```
class superFatFile : public FatFile {
    public:
    void ls(print_t* pr, uint8_t flags /* = 0 */, uint8_t indent /* = 0 */){
        superFile file;
        rewind();
        while (file.openNext(this, O_READ)) {
            if (!file.isHidden() || (flags & LS_A)) {
                // adds 'spaces' indent for dir level
                for (uint8_t i = 0; i < indent; i++) {
                    pr->write(' ');
                }

                if (flags & LS_DATE) {
                    file.printModifyDateTime(pr);
                    pr->write(' ');
                }

                if (flags & LS_SIZE) {
                    file.printFileSize(pr);
                    pr->write(' ');
                }

                // prints filename
                if (!file.isDir()) {
                    file.printName(pr);
                    pr->write('\r');
                    pr->write('\n');    // HERE IS YOUR SEPARATOR CARACTERS !!!
                }

                // execute recursivly if LS_R flag was set
                if ((flags & LS_R) && file.isDir()) file.ls(pr, flags, indent + 2);

            }

        }
        file.close();
    } // end of new LS method
}; // end of superClass

```

---
Tags: arduino-mega, communication, sd-card
---


# Question
Title: Can I control two coreless DC motors using L293DD SMD IC?
I wish to control two 3.7V 6x12mm Coreless DC motors (both direction and speed individually). The only constraint is that the motor driver (circuit) has to be as small as possible.

I've seen couple of driver circuits used in quadcopters where a single FET (such as IRLML2502) is used to control the speed of coreless motors. However, the direction control is not possible with such a circuit.

It requires at least 6 MOSFETs and maybe Schottky diodes to prevent back EMF (similar to half H-bridge like here). Even after this, opposite direction control for two motors at once cannot be achieved. Then I figured all of this will increase the area required and decided to replace it with L293DD IC. Now my question is:

1. Can the L293DD SMD IC be used to control these motors?
2. Is there an alternate solution/circuit/IC which can minimize the size and area?
3. Are ESCs required for these small coreless motors? Can they be controlled directly via the L293DD (like normal motors)?

PS: The controller will be ESP8266 and the entire system will powered by a 3.7V 300mAh LiPo battery.

# Answer
> 0 votes
> Can the L293DD SMD IC be used to control these motors?

Yes

> Is there an alternate solution/circuit/IC which can minimize the size and area?

Any of the more modern MOSFET based H-Bridge drivers that exhibit far less loss than the antiquated l293d

> Are ESCs required for these small coreless motors?

No

> Can they be controlled directly via the L293DD (like normal motors)?

Yes

The L293 is old and, well, basically crap. For efficient battery based operation you realy need to be looking for something a little more modern and efficient. There's length to choose from - take a look on your favourite electronics supplier (which means *not Amazon*...)

---
Tags: motor, pwm
---


# Question
Title: Arduino analogWrite source code explanation
The source code for the `analogWrite` function looks like this:

```
void analogWrite(uint8_t pin, int val) {
    ...
    sbi(TCCRnA, COM0x);
    OCRnx = val;
    ...
}

```

Where n is which timer (0, 1, 2...) and x is which pin is controlled by that timer (A, B).

This doesn't make sense to me, because the ATmega328P datasheet says that the bits `TCCRnA.WGM0[1:0]`, and `TCCRnB.WGM0` need to be set up as well.

Datasheet

Obviously the above code works, but how, with the missing bit settings?

# Answer
Look at the init() function in wiring.c. All of the timers get set up there depending on which chip is selected. I don't know if some might also be done by initVariant(). But all it leaves for analogWrite to do is set the bit in the COM register to enable the PWM.
> 1 votes

# Answer
> because the ATmega328P datasheet says that the bits TCCRnA.WGM0\[1:0\], TCCRnB.WGM02, and TIMSKn.OCIEx all need to be set as well.

they use different meanings for the word "set".

1. the datasheet is saying that you need to SET UP those bits for the appropriate mode. "SET" here means both set or clear, as appropriate.
2. the code, poorly written actually, sets those bits that need to be set, and let the rest is in their default / reset state, presumably cleared. a more robust way would have been to explicitly clear those bits.
> 0 votes

---
Tags: arduino-uno, atmega328, avr
---


title: Program hangs when correcting CO2

text:
# Question
Title: Program hangs when correcting CO2
I am building a special chamber, where I'm dealing with humidity, temperature and co2 contamination, but I'm having difficulties with software. If I separate it by parts, everything works as it should, but when I combine everything together, the CO2 measuring stops and the CO2 is being added to the chamber continuosly.

Here are my requests: -The temperature has to be between 36 and 37°C, -It has to be known the exact humidity, -The amount of CO2 (carbon dioxide) has to be around 5% (50.000 ppm), around +/- 0.2% is allowed, -Everything should be shown on 1602 LCD display.

To measure temperature, I have a LM335, for measuring humidity a HIH-4004-001 humidity sensor and for measuring CO2 contamination I have a MH-Z16 sensor. If there is lack of CO2 in the chamber, I'm adding it with a electromagnetic gas valve, which is driven by a relay. To heat up the chamber, I'm also using a relay, to turn on the heater.

Here's the code. Does anyone has any kind of clue, what could possibly go wrong here?

```
#include <SoftwareSerial.h>           //lib for serial communication for co2
#include <NDIR_SoftwareSerial.h>      //lib for co2

#include <LiquidCrystal.h>
LiquidCrystal lcd(8, 9, 4, 5, 6, 7);  //(RS, EN, D4, D5, D6, D7)

//LM335 sensor TEMP
int outputPin = 3;

//heater
const int rele = 2;  //relay output for HEATER
int flag = 0;       //flag for hysteresis at 37°C

//humidity
int HIH4000_Pin = A2; //analog pin 2, humidity sensor

//co2
NDIR_SoftwareSerial mySensor(11, 12); //green= 11; yellow= 12.
float percentage = 0.00; //co2 in percentage

//co2 gas valve
const int ventil = 3;  //relay output for CO2 GAS VALVE

void setup() {
  lcd.begin(16, 2);
  pinMode(rele, OUTPUT);      //relay for HEATER
  pinMode(ventil, OUTPUT);    //relay for CO2 GAS VALVE
  Serial.begin(9600);

  digitalWrite(rele, HIGH);   //heater off
  digitalWrite(ventil, HIGH);   //co2 gas valve off

  if (mySensor.begin()) {
    Serial.println("Wait 10 seconds for sensor initialization...");

    lcd.setCursor(0, 0);
    lcd.print("Wait_10_seconds");
    lcd.setCursor(2, 1);
    lcd.print("CALIBRATION");
    delay(1000);
    lcd.clear();
    lcd.print("Wait_9_seconds");
    lcd.setCursor(2, 1);
    lcd.print("CALIBRATION");
    delay(1000);
    lcd.clear();
    lcd.print("Wait_8_seconds");
    lcd.setCursor(2, 1);
    lcd.print("CALIBRATION");
    delay(1000);
    lcd.clear();
    lcd.print("Wait_7_seconds");
    lcd.setCursor(2, 1);
    lcd.print("CALIBRATION");
    delay(1000);
    lcd.clear();
    lcd.print("Wait_6_seconds");
    lcd.setCursor(2, 1);
    lcd.print("CALIBRATION");
    delay(1000);
    lcd.clear();
    lcd.print("Wait_5_seconds");
    lcd.setCursor(2, 1);
    lcd.print("CALIBRATION");
    delay(1000);
    lcd.clear();
    lcd.print("Wait_4_seconds");
    lcd.setCursor(2, 1);
    lcd.print("CALIBRATION");
    delay(1000);
    lcd.clear();
    lcd.print("Wait_3_seconds");
    lcd.setCursor(2, 1);
    lcd.print("CALIBRATION");
    delay(1000);
    lcd.clear();
    lcd.print("Wait_2_seconds");
    lcd.setCursor(2, 1);
    lcd.print("CALIBRATION");
    delay(1000);
    lcd.clear();
    lcd.print("Wait_1_second");
    lcd.setCursor(2, 1);
    lcd.print("CALIBRATION");
    delay(1000);
    lcd.clear();
  }
  else {
    Serial.println("ERROR: Failed to connect to the sensor.");
    lcd.setCursor(0, 0);
    lcd.print("Press RST button");
    while (1);
  }

  lcd.setCursor(0, 0);
  lcd.print("T= ");
  lcd.setCursor(7, 0);
  lcd.print((char)223);
  lcd.setCursor(8, 0);
  lcd.print("C");

  lcd.setCursor(10, 0);
  lcd.print("H=");
  lcd.setCursor(15, 0);
  lcd.print("%");

  lcd.setCursor(0, 1);
  lcd.print("CO2=");
  //lcd.setCursor(8,1);
  //lcd.print("%");
}

void loop() {
  delay(100);

  //beggining of measuring and displaying CO2
  if (mySensor.measure()) {
    Serial.print("CO2 Concentration is ");
    Serial.print(mySensor.ppm);
    Serial.println("ppm");
    lcd.setCursor(4, 1);
    lcd.print("        ");
    lcd.setCursor(4, 1);
    lcd.print(mySensor.ppm);
    percentage = mySensor.ppm;
  } else {
    Serial.println("Sensor communication error.");
  }
  //end of measuring and displaying CO2

  //beggining of CO2 gas valve
  if (percentage < 1000) {
    digitalWrite(ventil, LOW);
    delay(1000);
    digitalWrite(ventil, HIGH);
    /*lcd.setCursor(2,0);
      lcd.print(celsius);  */
  }
  else {
    digitalWrite(ventil, HIGH);
  }
  //end of CO2 gas valve

  //start measuring temperature
  int rawvoltage = analogRead(outputPin);
  float millivolts = (rawvoltage / 1024.0) * 5000;
  float celsius = (millivolts / 10) - 276.20;
  lcd.setCursor(2, 0);
  lcd.print(celsius);
  //stop measuring temperature

  //start humidity sensor
  float relativeHumidity  = analogRead(HIH4000_Pin);
  float av = 0.0048875 * relativeHumidity;
  float vlaga = (av - 0.86) / 0.03;
  int humi = vlaga;
  if (humi < 100) {
    lcd.setCursor(12, 0);
    lcd.print(" ");
    lcd.setCursor(13, 0);
    lcd.print(humi);
  }
  else {
    lcd.setCursor(12, 0);
    lcd.print(humi);
  }
  //end humidity sensor

  //start of relay for heater
  lcd.setCursor(12, 1);
  if (celsius < 37 && flag == 0) {    //upper treshold of hysteresis 37
    digitalWrite(rele, LOW);
    //lcd.print("WARM");
  }

  if (celsius < 36 && flag == 1) {    //lower treshold of hysteresis 36
    digitalWrite(rele, LOW);
    //lcd.print("WARM");
  }

  if (celsius > 37) {               // treshold of first heating up
    digitalWrite(rele, HIGH);
    //lcd.print("COOL");
    flag = 1;
  }
  //end of relay for heater

  delay(650);
}

```

# Answer
> 0 votes
Okay, I figured it out, what was wrong. It's completely unlogical and strange, but it solved me a problem. First off, I tried to disconnect the valve relay from arduino, while arduino was still giving logical 0 and 1 on the output. And the strange thing was, it worked. So I took a step further and back connected the relay, but disconnected the burden (valve). It worked fine aswell. So I figured it out, that here's some sort of a problem, that the valve SHOULDN'T be opened with relay, so I just added a 2N2222 transistor and a 12k resistor to the base, and the whole thing is working now perfectly. I just connected the output of the arduino (which was on relay for valve before) and put it on base resistor of 2N2222.

But thanks everyone for help!

# Answer
> 0 votes
If the CO2 sensor stops working that means you should be getting a message out of the Serial console, you didn't mention it so I presume you aren't which means it is still reading a value.

If you are still reading a value and the CO2 is still being added this means the 'percentage' CO2 has to be less than 1000.

So, either the CO2 sensor is faulty (which because it works on its own it looks like it isn't) or there is a "wiring fault" and you aren't actually reading the CO2 sensor when you think you are.

Is it possible that you are misreading the result from the serial connection? Is it possible that the library is misreading the data?

Try a simple program that reads the value from the CO2 sensor, prints it to the serial console and then opens the value for a second.

(Oh and in the setup function have a look at using a loop :) )

---
Tags: arduino-uno
---