# Question
Title: How to pad an ascii number with leading zeros?
I need to include a 3 digit ascii representation of message length number in the message header, but I am having difficulty trying to pad the number with leading '0' zeros in order to keep the number of 'length' digits needing to be appended always 3 even when the message length is only one or two digits long.

Addendum: The problem, more specifically, is how to left-pad a char array containing the number representation. I got as far as defining what and where, but I couldn't figure out **how** to shift the char\[\] contents right in order to insert the "0" at msglength\[0\]. (I tried using strcat, but that didn't work).

```
char msglength[4]          //(3 digits + nul)
for (int pad=1; pad<=3-strlen(msglength); pad++)
{
    // add a leading zero char to msglength, but that involves
    // somehow shifting all its contents to the right
}

```

# Answer
> 5 votes
This is the kind of situation where `printf()` comes handy:

```
printf("%03d", number);

```

prints the number in the format you described. Alas, `printf()` is not part of the standard Arduino API. But you can have it, nonetheless, at least on AVR-based Arduinos, as it is provided by the avr-libc, which is always linked with all Arduino programs. Some setup is needed to tell avr-libc about where is its “standard output”. We can use the macro `fdev_setup_stream()` to tell it to just push the bytes through `Serial.write()`:

```
static int Serial_write(char c, FILE *) {
    if (c == '\n') Serial.write('\r');  // convert LF -> CRLF
    return Serial.write(c);
}

static FILE mystdout;

void setup() {
    Serial.begin(9600);
    stdout = &mystdout;
    fdev_setup_stream(stdout, Serial_write, NULL, _FDEV_SETUP_WRITE);
}

void loop() {
    static int count;
    printf("%03d and counting...\n", count++);
    delay(500);
}

```

C.f. the manual of avr-libc's stdio.h for details.

**Pros of this method**:

* `printf()` has plenty of options to control the formatting of your messages.
* It's very standard C, understood by anyone having programmed in that language.

**Cons**:

* This can make your compiled program bigger than it would be if sticking with the Arduino API.
* It's not the “Arduino way”.

# Answer
> 3 votes
One straightforward way to do this is to extract digits separately (using integer division and mod). For example, the hundreds digit of a positive or unsigned `int x` is `(x/100)%10`.

A sketch shown below uses the statement

```
  Serial << ' ' << b/100 << (b/10)%10 << b%10;

```

to print a space and three digits of a positive number, with leading zeroes. Here are the first 18 lines of output from the sketch:

```
 000 001 002 003 004 005 006 007 008 009 010 011 012 013 014 015
 016 017 018 019 020 021 022 023 024 025 026 027 028 029 030 031
 032 033 034 035 036 037 038 039 040 041 042 043 044 045 046 047
 048 049 050 051 052 053 054 055 056 057 058 059 060 061 062 063
 064 065 066 067 068 069 070 071 072 073 074 075 076 077 078 079
 080 081 082 083 084 085 086 087 088 089 090 091 092 093 094 095
 096 097 098 099 100 101 102 103 104 105 106 107 108 109 110 111
 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191
 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239
 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
 000 001 002 003 004 005 006 007 008 009 010 011 012 013 014 015
 016 017 018 019 020 021 022 023 024 025 026 027 028 029 030 031

```

Here is the sketch:

```
#include <Streaming.h>

//char b=0;    // char is signed; messy when hi bit is on
byte b=0;    // byte is unsigned, all ok
void setup() {
  Serial.begin(115200);
}

void loop() {
  // To emulate
  //    Serial << ' ' << setw(3) << setfill('0') << b;
  // or
  //    Serial << ' ' << b<100? '0': '' << b<10? '0': '' << b;
  // write (eg)
  Serial << ' ' << b/100 << (b/10)%10 << b%10;
  // or if b is an int instead of a byte, write
  //    Serial << ' ' << (b/100)%10 << (b/10)%10 << b%10;

  ++b;
  if (b%16 == 0) Serial.println();
  delay(17);
}

```

The code shown above uses `Streaming.h`, a contributed library that adds some “syntactic sugar” to Arduino C. That is, at compile time it converts C++-like `<<` Serial stream operators to `Serial.print` statements, without increasing code size. If you don't have `Streaming.h` installed, either install it via `Streaming5.zip` from arduiniana.org or manually translate the `Serial << ...` statement to `Serial.print` statements.

Note, if the `Streaming.h` library supported `setw()` and `setfill()`, they could be used to set field width and fill character. (See comments in sketch.) However, the current implementation merely translates the stream insertion operator `<<` form into `print()` form. It supports four base-conversion specifiers, \_HEX, \_DEC, \_OCT, and \_BIN; a \_FLOAT function with number of decimal places specified; and `endl`. Some \_FILL functions are suggested at the Arduiniana.org link.

# Answer
> 2 votes
There is always brute force.

```
char* itob(int val, char* buf, size_t n)
{
  char* bp = buf + n;
  do {
    *--bp = (val % 10) + '0';
    val = val / 10;
  } while (bp != buf);
  return (buf);
}

void setup()
{
  Serial.begin(9600);
  while (!Serial);

  const int BUF_MAX = 3;
  char buf[BUF_MAX];

  Serial.write(itob(42, buf, BUF_MAX));
  Serial.println();
}

void loop()
{
}

```

Please observe that the buffer is not null-terminated, therefore the Serial.write().

Several possible optimizations from the simple solution such as detect when the value is zero and short-cut.

Cheers!

# Answer
> 0 votes
Thank you all for your suggestions. This is what I came up with, which seems to work ok.

```
char lengthstr[4]="7";
Serial.print("lengthstr='"); Serial.print(lengthstr); Serial.println("'");
int maxsize=sizeof(lengthstr);  // size of lengthstr array
int steps=strlen(lengthstr)+1;  // number of chars to be moved
int hop=maxsize-steps;          // number of steps to be jumped over each move
if((steps>1)&&(maxsize>steps)) {
   for (int pos=steps; pos >= 0; pos--) {
      lengthstr[pos+hop] = lengthstr[pos];
      lengthstr[pos]='0';
   }
}
Serial.print("lengthstr='"); Serial.print(lengthstr); Serial.println("'");

```

---
Tags: serial, programming, communication
---


# Question
Title: Neopixel led strip stops responding after change in brightness
I have an arduino UNO hooked up to a neopixel LED strip with 148 lights. Most of the time it works fine, but when I upload a program that changes the brightness frequently, particularly when I increase brightness, only the first 8 LEDs continue responding. The rest get stuck.

Here's an example of the kind of code that sets this issue off. To fix it, I usually have to restart the lights and the arduino and sometimes upload a blank program to the arduino.

I'm pretty new to arduino programming so and help would be really appreciated. Thank you.

```
#include "FastLED.h"

FASTLED_USING_NAMESPACE

// FAST LED definitions
#define DATA_PIN    3
#define LED_TYPE    WS2812B
#define COLOR_ORDER GRB
#define NUM_LEDS    148

CRGB leds[NUM_LEDS];
#define DATA_PIN 3 // Output Pin to Data Line on Strip

int fadeAmount = 5;
int brightness = 0;

void setup()
{
   FastLED.addLeds<LED_TYPE,DATA_PIN,COLOR_ORDER>(leds, NUM_LEDS).setCorrection(TypicalLEDStrip);
}

void loop()
{
   for(int i = 0; i < NUM_LEDS; i++ )
   {
   leds[i].setRGB(0,255,0);
   leds[i].fadeLightBy(brightness);
  }
  FastLED.show();
  brightness = brightness + fadeAmount;
  // reverse the direction of the fading at the ends of the fade:
  if(brightness == 0 || brightness == 255)
  {
    fadeAmount = -fadeAmount ;
  }
  delay(20);
}

```

# Answer
> 1 votes
After doing more research and getting feedback on the Adafruit forum here, it appears that the problem was a cracked solder joint. I managed to get access to the strip and wiggled it a little and the problem has gone away. The recommendation is to reflow the joint by adding a little solder over the data connection between where the LEDs stop being responsive.

# Answer
> 1 votes
It is almost certainly a power issue. The Adafruit page about one of those types of Neopixels says:

> Don't forget, with 256 LEDs, you could use over 15A of current if you turn on all the LEDs on to white (which we really do not recommend because we don't think the flex PCB can handle that much current). Try to keep the current draw at under 5A ...

Increasing the brightness increases the current drawn. Do you have a heavy-duty power supply? Are the connecting leads sufficient for (say) 8 amps of current?

---

## New information based on comments made

Based on comments by Lorenz I now think it is more likely to be that they are overheating.

> I have the strip embedded in a picture frame with epoxy resin over it.

That makes it difficult for the ICs to cool down, and LEDs generate heat. If you search for "neopixels heat" you find quite a few matches. Some suggestions made are to use a heat sink or a fan. If this isn't practical for you, then running at a lower PWM rate (ie. not as bright) and not as saturated colour, could help keep the heat down.

You don't want to "cook" one of the early pixels, because each one has to pass the data on to the next one in sequence, so if you lose an early one, you lose everything after it, particularly if you can't get at it to replace one.

---

## Postscript regarding heat

I have been testing a NeoPixel with a temperature sensor. Displaying full white (255/255/255) it has reached about 44°C. So clearly it warms up. However this is in the open air with just some sticky-tape holding the sensor onto the LED. According to the spec the chip can operate at up to 80°C, so this is within range.

However if the whole thing was sealed in epoxy, then the heat being generated would have much less chance of escaping into the ambient air, and thus would be likely to get a lot hotter.

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


# Question
Title: Custom built Arduino is not working - double blinks
I've made a home-made Arduino based on this video. The problem is that I can't upload anything, it doesn't react, only the LED double blinks in every second. What does that mean? How to fix it? Thanks.

Update:

# Answer
> 1 votes
It's a reasonably clear photo (another couple would help) however I do see at least one major problem. Pin 8 (and pin 22) are Ground, but I don't see any wires running to that. Also the 22 pF (or similar) capacitors connected to the crystal should have their other sides grounded.

I suggest you look at my page Breadboard Arduino which has clear photos and wiring guides. In particular:

Notice the ground wire, and how the capacitors are connected.

I suggest you double-check all wiring, and make sure it is very similar to this:

---
Tags: atmega328
---


title: MPU 6050 stuck on same values

text:
# Question
Title: MPU 6050 stuck on same values
I'm having a problem with my MPU6050. I'm using PID to speed up a motor with the MPU values. What could the problem be?

Here is a link to a previous question that I asked concerning a problem with pid: PID not working correctly

These are the values that I'm getting, which repeat forever. The values are:

* motor speed;
* the value that changes the motor speed;
* the MPU value;
* the change that PID made.

---

```
0.00
0
10900
4800

0.00
0
10900
4800

```

---

Here is the code itself.

```
int16_t ax, ay, az;

double Setpoint, Input, Output;
//Specify the links and initial tuning parameters
double Kp=2, Ki=5, Kd=1;
PID myPID(&Input, &Output, &Setpoint, Kp,Ki,Kd, DIRECT);

void setup() {
 Input = analogRead(ax);
  Setpoint = 100;
  //turn the PID on
   myPID.SetMode(AUTOMATIC);
}

void loop() {
 accelgyro.getAcceleration(&ax, &ay, &az);
  int a=ax+10900;
//Here I set the used variable to around 0. ax is actually around -10900
//This is always true, this won't be in the final code. This is just making        it work.

if(1) {
 int val;
  val = map(a, -1300, 1300, 0, 1023);
   Input = val;
    myPID.Compute();
     Serial.println(Output);

digitalWrite(motorPin2, HIGH);
Serial.print("\t");
Serial.println(ax);
Serial.print("\t");
Serial.println(a);
Serial.print("\t");
Serial.println(val);
     }
}

```

# Answer
Let's deconstruct this down to a simple example which we can test without the MPU6050:

```
#include <PID_v1.h>

double Setpoint, Input, Output;
//Specify the links and initial tuning parameters
double Kp = 2, Ki = 5, Kd = 1;
PID myPID(&Input, &Output, &Setpoint, Kp, Ki, Kd, DIRECT);

void setup() {
  Setpoint = 100;
  //turn the PID on
  myPID.SetMode(AUTOMATIC);
  Serial.begin (115200);
  Serial.println (F("\n\nStarting\n\n"));
}

void loop() {
  int a = 0;
  int val = map(a, -1300, 1300, 0, 1023);
  Input = val;
  myPID.Compute();
  Serial.print (F("Input = "));
  Serial.println(Input);
  Serial.print (F("Setpoint = "));
  Serial.println(Setpoint);
  Serial.print (F("Output = "));
  Serial.println(Output);
  Serial.println();
  delay (300);
}

```

Output:

```
Starting

Input = 511.00
Setpoint = 100.00
Output = 0.00

Input = 511.00
Setpoint = 100.00
Output = 0.00

Input = 511.00
Setpoint = 100.00
Output = 0.00

Input = 511.00
Setpoint = 100.00
Output = 0.00

```

Indeed it isn't changing. Let's analyze why:

* The input is 511
* The setpoint is 100
* Therefore the error is 100 - 511 = -411
* Disregarding (for the moment) the integral and differential terms, you have a proportional term of 2 (Kp) so the algorithm tries to output 2 * Error
* Output would be 2 * -411 = -822
* However the maximum and minimum limits default to 0 to 255, and thus the output is clamped to 0.
* The algorithm outputs 0.
* And the next time it does the same thing.

There is a function `SetOutputLimits` which can be used to change the default minimum and maximum output values.

The Ki and Kd values might eventually have an impact, but you won't notice anything with the output clamped to zero.

For example, adding this line in `setup` gives different results:

```
  myPID.SetOutputLimits (-5000, 5000);

```

Result:

```
Starting

Input = 511.00
Setpoint = 100.00
Output = -5000.00

Input = 511.00
Setpoint = 100.00
Output = -1233.00

Input = 511.00
Setpoint = 100.00
Output = -1438.50

Input = 511.00
Setpoint = 100.00
Output = -1644.00

Input = 511.00
Setpoint = 100.00
Output = -1849.50

Input = 511.00
Setpoint = 100.00
Output = -2055.00

Input = 511.00
Setpoint = 100.00
Output = -2260.50

Input = 511.00
Setpoint = 100.00
Output = -2466.00

```

Whether they are valid limits depend on what you are attempting to do exactly.
> 2 votes

# Answer
The problem was that I had the SCL and SDA pins connected to the wrong Arduino pins.

Sorry for bothering your time. Thanks for the tips.
> 1 votes

---
Tags: arduino-uno, motor, mpu6050, pid
---


title: SD card initialization fails randomly

text:
# Question
Title: SD card initialization fails randomly
I have a SD card reader that is working fine exept that sometimes SD.begin fails for no apparent reason. To work around this issue I have put the SD.begin in a while loop and then I display the error on my LCD. When the error happens I then remove and reinsert the card witch works usualy on the first or second try. I have never seen any problem ones the card is initilized. Does anyone has any idea what might be the problem?

# Answer
> 3 votes
I have seen SD cards that do not like this section of code:

```
  // command to go idle in SPI mode
  while (cardCommand(CMD0, 0) != R1_IDLE_STATE) {
    if (((uint16_t)millis() - t0) > SD_INIT_TIMEOUT) {
      error(SD_CARD_ERROR_CMD0);
      goto fail;
    }
  }

```

Some SD cards (mine, of course) seem to need a little quiet time to finish their INIT process. Adding a delay of \<something\> made the INIT process complete successfully, first time through the loop.

I'm *guessing* that the SD card spends so much time handling the repeated CMD0 commands (continuously sent by above loop) that they don't get to spend time on the INIT process. IIRC, the standard says the card is allowed to take up to 2 seconds to INIT (!). I can't recall, but I think I tried 150ms or so:

```
  // command to go idle in SPI mode
  while (cardCommand(CMD0, 0) != R1_IDLE_STATE) {
    delay( 150 ); // let SD get some time to work
    if (((uint16_t)millis() - t0) > SD_INIT_TIMEOUT) {
      error(SD_CARD_ERROR_CMD0);
      goto fail;
    }
  }

```

I do recall that reinserting the card would sometimes make it work. I have suggested this to at least one SD card library maintainer, but I think we're all reluctant to impose a delay on *all* cards. OTOH, it is just during `::begin`.

It might work for you, though. The above snippet is from SdSpiCard.cpp, but you may have to go looking for it in other places, depending on which library and version you're using.

---
Tags: sd-card
---


# Question
Title: Adding button which resets to top of void
I'm quite new to Arduino and the programming of the board, but I wanted to have a go at making a traffic light based on an example I found online.

The example supplied a simple layout which I roughly copied with the components I had.

I then created the following code to mimic the traffic lights of my local area.

```
int red = 13;   int yellow = 12;   int green = 11;

void setup(){
    pinMode(red,OUTPUT);
    pinMode(yellow,OUTPUT);
    pinMode(green,OUTPUT);
}

void loop(){
    changeLights();
}

void changeLights(){
    // red on, other off for 3 seconds
    digitalWrite(green,LOW);
    digitalWrite(yellow,LOW);
    digitalWrite(red,HIGH);
    delay(3000);

    // red on, amber on,green off for 3 seconds
    digitalWrite(green,LOW);
    digitalWrite(yellow,HIGH);
    digitalWrite(red,HIGH);
    delay(3000);

    // red off, amber off,green on for 3 seconds
    digitalWrite(green,HIGH);
    digitalWrite(yellow,LOW);
    digitalWrite(red,LOW);
    delay(3000);

    // red off, amber on,green on for 3 seconds
    digitalWrite(green,HIGH);
    digitalWrite(yellow,HIGH);
    digitalWrite(red,LOW);
    delay(3000);
}

```

What I'm wanting to achieve next is a button which resets the code back to the top of `void changeLights`. I assume I would be able to do this using a push-to-make switch, but I'm not sure how to incorporate it into my circuit or if it is even possible to reset using this.

# Answer
As currently written, your changeLights() function, which is repeatedly called over and over again by the Arduino loop() function, runs a timed sequence of lights.

* Red light is on for 3000 ms
* Amber is on for 3000 ms
* Green is on for 3000 ms

This sequence could also be implemented using a state machine, but as it is right now, it's just a simple sequence of operations.

So now you have a new feature request *(heh, this happens all the time in pro software development)*:

* hardware will include a momentary switch to ground
* when the switch is pressed, the changeLights() sequence will skip to the next Red light
* we might also want to do other kinds of sequence change, not just reset

The simplest way to code this would be to use digitalRead() to test whether the switch is pressed. You could test just after each of the delay(3000) calls. Technically this would work, but it would only sense the switch state just at the instant that digitalRead() is called. So for most of your 9-second sequence, it will ignore the switch, and only briefly test. The user will have to hold the button for 3 seconds to be sure the program senses the switch press.

There are some better ways to make this work. The delay(3000) actually makes the program do nothing else but watch the clock for the full delay interval, it doesn't do anything else during this time. So instead of delay(3000) you could use a for loop, and test whether the button has been pressed.

```
// Spend 3 seconds waiting; exit the function if BUTTON1 is pressed.
for(int count = 300; count > 0; count--) {
    delay(10); // test the button every 10 ms
    if (digitalRead(BUTTON1) == LOW) {
        return; // skip out of the changeLights() function
    }
}

```

(Just saw Edgar Bonet's comment about the blink without delay Ardino example, which is another valid way to do the same thing. You could also use the millis() function and calculate the time when the next state transition should happen.)

Since this is an educational example, it's worth looking into how you would implement this as a **state machine**. (The traffic lights controller is often used as an introduction to state machines.) There's two types of state machines, Mealy and Moore, the difference is that one kind the outputs are determined only by the internal state, and the other kind, the outputs are a function of the internal state and the inputs.

A simple traffic light controller state machine might look like this:

* state 0: initialize; next state=1
* state 1: Red light on, timer=5 seconds, next state=2
* state 2: Green light on, timer=3 seconds, next state=3
* state 3: Amber light on, timer=1 seconds, next state=1

Use a timing countdown like in the example above, and when the countdown reaches 0, advance to the next state.

```
const int S0_INIT = 0; // state 0: initialize
const int S1_RED = 1; // state 1: Red light on
const int S2_GREEN = 2; // state 2: Green light on
const int S3_AMBER = 3; // state 3: Amber light on
int state = S0_INIT;
int stateTimer = 0;
// void setup() not shown; configures input and output pins by pinMode(...)
void loop()
{
    if (stateTimer < 0) { stateTimer = 0; state = S0_INIT; return; }
    if (stateTimer > 0) {
        stateTimer = stateTimer - 1;
        delay(10); // 10 ms interval
        return;
    }
    switch(state) {
    case S0_INIT: // state 0: initialize; next state=1
        stateTimer = 0;
        state = S1_RED;
        break;
    case S1_RED: // state 1: Red light on, timer=5 seconds, next state=2
        // digitalWrite(... etc.) Red light on
        stateTimer = 500;
        state = S2_GREEN;
        break;
    case S2_GREEN: // state 2: Green light on, timer=3 seconds, next state=3
        // digitalWrite(... etc.) Green light on
        stateTimer = 300;
        state = S3_AMBER;
        break;
    case S3_AMBER: // state 3: Amber light on, timer=1 seconds, next state=1
        // digitalWrite(... etc.) Amber light on
        stateTimer = 100;
        state = S1_RED;
        break;
    }
}

```

A more advanced traffic light controller (that responds to input) might look like this:

* state 0: initialize; next state=1
* state 1: Red light on, next state=2 (unless SWITCH1=HIGH, next state=4)
* state 2: Green light on, next state=3 (unless SWITCH1=HIGH, next state=4)
* state 3: Amber light on, next state=1 (unless SWITCH1=HIGH, next state=4)
* state 4: Red light on, next state=5 (unless SWITCH1=LOW, next state=2)
* state 5: no lights on, next state=4 (unless SWITCH1=LOW, next state=2)

An external input SWITCH1 switches this traffic controller between Red-Amber-Green sequence (states 1-2-3) and flashing-Red sequence (states 4-5). Adding constants for S4\_BLINKING\_RED=4 and S5\_BLINKING\_RED=5 and replacing the switch(state):

```
    switch(state) {
    case S0_INIT:
        stateTimer = 0;
        state = S1_RED;
        break;
    case S1_RED:
        // digitalWrite(... etc.) Red light on
        stateTimer = 500;
        state = S2_GREEN;
        if (digitalRead(SWITCH1) == HIGH) {
            state = S4_BLINKING_RED;
        }
        break;
    case S2_GREEN:
        // digitalWrite(... etc.) Green light on
        stateTimer = 300;
        state = S3_AMBER;
        if (digitalRead(SWITCH1) == HIGH) {
            state = S4_BLINKING_RED;
        }
        break;
    case S3_AMBER:
        // digitalWrite(... etc.) Amber light on
        stateTimer = 100;
        state = S1_RED;
        if (digitalRead(SWITCH1) == HIGH) {
            state = S4_BLINKING_RED;
        }
        break;
    case S4_BLINKING_RED:
        // digitalWrite(... etc.) Red light on
        stateTimer = 50;
        state = S5_BLINKING_RED;
        if (digitalRead(SWITCH1) == LOW) {
            state = S2_GREEN;
        }
        break;
    case S5_BLINKING_RED:
        // digitalWrite(... etc.) no lights on
        stateTimer = 50;
        state = S4_BLINKING_RED;
        if (digitalRead(SWITCH1) == LOW) {
            state = S2_GREEN;
        }
        break;
    }

```

(Remember to define the SWITCH1 pin, and configure pinMode(SWITCH1 ) in setup().)

Of course a *real* traffic light controller has more lights, say Northbound-Red, Northbound-Amber, Northbound-Green, Westbound-Red, Westbound-Amber, Westbound-Green, etc. Not to mention left turn arrows and maybe even "vehicle present" sensors. For a smart traffic light controller like that, the state is named by what traffic flow is authorized during that state:

* state 1: northbound-southbound traffic green, 5 seconds, next state 2
* state 2: northbound-southbound traffic amber, 2 seconds, next state 3
* state 3: all lights red, 0.5 second, next state 4 (unless no vehicles waiting west-east lanes, then next state 6)
* state 4: westbound-eastbound traffic green, 5 seconds, next state 5
* state 5: westbound-eastbound traffic amber, 2 seconds, next state 6
* state 6: all lights red, 0.5 second, next state 7 (unless no vehicles waiting N-W nor S-E left turn bays, then next state 9)
* state 7: north-to-west left turn and south-to-east left turn green, 3 seconds, next state 8
* state 8: north-to-west left turn and south-to-east left turn amber, 2 seconds, next state 9
* state 9: all lights red, 0.5 second, next state 10 (unless no vehicles waiting W-S nor E-N left turn bays, then next state 12)
* state 10: west-to-south left turn and east-to-north left turn green, 3 seconds, next state 11
* state 11: west-to-south left turn and east-to-north left turn amber, 2 seconds, next state 1
* state 12: all lights red, 0.5 second, next state 1 (unless no vehicles waiting north-south lanes, then next state 3)

The power of using state machines is that they all use the same basic "engine", just with more states, more outputs, more inputs. If the traffic engineer wants to adjust the timing to improve the flow of traffic, that only requires adjusting some of the data, which is much lower risk than rewriting code. ... and of course state machines apply to more than just traffic lights, it's a very generally useful design technique.
> 4 votes

# Answer
MarkU provided a pretty thorough answer with all the whys and hows of state machines. This is definitely the way to go, and I encourage you to read that answer very carefully.

I wrote a comment to your question where I suggest dropping `delay()` in order for your loop to never block and your program to be responsive to user input. Now I am writing this answer only to show you how to combine both ideas, i.e. implement a state machine without delays. I do not think this code needs any explanation besides those in MarkU's answer and in the Blink without delay Arduino example.

```
// Pinout.
const int red = 13, yellow = 12, green = 11, reset = 10;

void setup() {
    pinMode(red,    OUTPUT);
    pinMode(yellow, OUTPUT);
    pinMode(green,  OUTPUT);
    pinMode(reset,  INPUT_PULLUP);  // use internal pull-up
}

void loop() {
    static enum { INIT, RED, RED_AMBER, GREEN, GREEN_AMBER } state = INIT;
    static uint32_t duration;
    static uint32_t last_change;
    uint32_t now = millis();

    // Sense the reset button.
    if (digitalRead(reset) == LOW)
        state = INIT;

    // Wait at this state for the specified duration.
    if (state != INIT && now - last_change < duration)
        return;

    // Switch to next state.
    switch (state) {
        case INIT:
        case GREEN_AMBER:
            state = RED;
            duration = 3000;
            digitalWrite(green,  LOW);
            digitalWrite(yellow, LOW);
            digitalWrite(red,    HIGH);
            break;
        case RED:
            state = RED_AMBER;
            duration = 3000;
            digitalWrite(green,  LOW);
            digitalWrite(yellow, HIGH);
            digitalWrite(red,    HIGH);
            break;
        case RED_AMBER:
            state = GREEN;
            duration = 3000;
            digitalWrite(green,  HIGH);
            digitalWrite(yellow, LOW);
            digitalWrite(red,    LOW);
            break;
        case GREEN:
            state = GREEN_AMBER;
            duration = 3000;
            digitalWrite(green,  HIGH);
            digitalWrite(yellow, HIGH);
            digitalWrite(red,    LOW);
            break;
    }
    last_change = now;
}

```

I would normally have declared `duration` as a `static const`. I kept it non-const only to follow MarkU's steps and make it easy to have different durations for different states (really, the green light should last longer...).
> 2 votes

# Answer
The best way to handle this problem is using a state machine, as shown in all the other answers. In fact, this IS the classical problem to learn how to use and implement state machines.

I just wanted to add the "fast" solution to your problem, which will enable you to do what you want without changing your code too much:

```
void changeLights(){
    unsigned long startTime;

    // red on, other off for 3 seconds
    digitalWrite(green,LOW);
    digitalWrite(yellow,LOW);
    digitalWrite(red,HIGH);
    startTime = millis();
    while ((millis() - startTime) < 3000)
    { // Wait for 3 seconds while checking for the button
        if (digitalRead(buttonPin) == HIGH)
            return; // Just exit this function; the loop will start again
    }

    [ repeat for the other colors ]
}

```
> 0 votes

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


# Question
Title: Help with a rather specific implementation of FFT Library?
So, I guess what I'm trying to do here is properly understand the FFT library posted here by Open Music Labs, done in C++. I believe I understand the Fourier transform, but the FFT has some nuance that I'm not quite familiar with. From what I understand, the FFT takes a amplitude vs. time signal and transforms it into its constituent frequencies like a normal Fourier transform, but it only does so at given points that break down the signal into the Arduino's clock speed divided by the number of bins decided on, for the sake of efficiency. Thus each bin actually accounts for a number of frequencies that is also equal to the clock speed divided by bin number. I'm correct so far, right?

So here's my question. I have a very specific application of the FFT that requires reading only frequencies at roughly 0-100 Hz. Everything else I don't need, and I want to know how to achieve such high resolution. I imagine that because the number of bins seems to be capped at around 512, that there must be some sort of way to decrease the clock speed to an exorbitantly low number in order to read these frequencies. How might I go about doing that? Or maybe there is a better way to apply the transform to the data at such low frequencies through some other method outside of FFT?

Second, I'm wondering how performing multiple FFTs simultaneously will affect performance, and if there is some way I can export this data to another program in order to do the heavy lifting regarding data storage, seeing as I imagine performing many FFTs all at once will decimate the available memory on the Arduino itself if all of those values aren't being kept on my computer.

Thanks in advance for any insight you guys might be able to provide

# Answer
As Edgar has mentioned you are confusing things slightly.

First there is your sampling frequency. According to the Shannon-Nyquist theorem that is at a minimum of 2x the maximum frequency in your signal. So that is 2x100 = 200Hz. That's the number of samples per second in your sample set.

Secondly is your sample size, which is directly related to the FFT bucket size. For every two samples you can get one bucket. The more samples you have the more buckets you have, and the higher the resolution each bucket is. But for FFT to work you need a power-of-two sized sample set. That means 2, 4, 8, 16 etc samples. So 256 samples would give you 128 buckets. That would be a little under 1Hz per bucket.

To make things cleaner though you can back-apply the last calculation to the first and get them to match. 256 samples at 256 samples per second will give you 128 buckets covering 0-128Hz so 1Hz per bucket. Double that to 512 samples and you get 256 buckets at 0.5Hz per bucket. Double it again and you get double the resolution again.

The main speed issue that you will come across is not the time taken to do the FFT, but the time taken to capture your sample set. 256 samples at 256 samples per secod will, of course, take 1 second to capture. 512 samples will be 2 seconds, etc. Far longer than a decent FFT takes to calculate.
> 2 votes

---
Tags: programming, c++, library, sound, analog-sampling
---


# Question
Title: How to know if my Bluetooth HC-05 is connected through serial monitor
I want to connect a Bluetooth module to arduino and check if my module is connected or not.. Through serial monitor. Is there and particular code to connect with that?

# Answer
> 1 votes
If your board is actually a HC-05, you can

1. Pull the KEY pin to Vcc (see note)
2. Write the serial command `AT` on the serial interface
3. Look at the output: if you receive `AT` or `OK` then the module is connected, otherwise it is not

Note: The key pin is the number 34 on the SMT module (with the antenna pointing upwards, its the pin in the top-right corner). If you have a THT module (so the one with about 6 pins) MAYBE this pin is connected to one of the pins you don't usually use (they are named EN, STATE, ...). Check with a multimeter if it is connected to one of these. If it is not, then you'll have to solder a wire from it to an arduino pin.

If, on the other hand, your board is a HC-06 (almost identical to HC-05, but with a different firmware - it is a slave-only bt device), then keep it disconnected from the master and perform steps 2 and 3: when not connected, in fact, the HC-06 is already in AT mode.

More information on this webpage

---
Tags: bluetooth
---


title: Breadboard for kids

text:
# Question
Title: Breadboard for kids
I am interested in teaching young kids how to build arduino projects. I was thinking that using a breadboard may be difficult for them, as the holes are all very close together. It is easy to put the pins in the wrong hole.

Are there any breadboards with larger hole spacings that could make it easier to use for kids?

# Answer
> 4 votes
The problem (probably) isn't only because it's too small, wiring can be hard to understand.

I think this might be a solution:

It'll cost you some work. But it will get difficult for them to wire it wrongly. Also, I believe coloring them, will make the kids understand it much better. This way they would also be less likely to short out pins etc. Saving you some rangers/arduinos.

Be sure that the power-connectors are not reversible. And you should use a separated supply (with overcurrent protection and what not) and tie the GND to the arduino GND. This way you could even use the supply power for heavier devices.

I'm not a 100% sure on the resistors though, they might interfere with some things you want to make/show.

Maybe even add blue color for inputs and yellow for outputs (or whatever the standard is). Or you might even make generic connectors, like on the Lego NXT robots, that's some really easy wiring! http://www.philohome.com/nxtldraw/NXTkitLDview.jpg

Or check out projects like: "LittleBits Arduino". https://s3.amazonaws.com/lb-spree/spree/products/2003/large/ArduinoDetail4.png?1423167488

And, check http://www.rugged-circuits.com/ruggeduino/ on 10-ways to destroy your arduino. If you take these things into mind, you can make a pretty solid Arduino, so that wrong wiring won't lead to any damaged Arduino's etc.

# Answer
> 6 votes
Breadboards are made to work with components of a standard size - a breadboard with larger hole spacing would not be able to fit standard through-hole chips. I have never seen such an item.

Having said that, I have had a lot of success using alligator clips. You can clip them directly on to wires for LEDs, resistors, capacitors, so long as you make sure they legs/clips don't touch.

Then there are made-for-children systems, snap-together, like http://www.vk3bq.com/2013/08/17/snap-circuits-electronics-kits/ or http://mashable.com/2013/05/21/lightup-magnetic-building-blocks/#t5Kq\_yIDpaqr

# Answer
> 4 votes
or

or

Maybe use something like Littlebits, which uses magnets, but is kind of expensive.

# Answer
> 3 votes
Build your own breadboard!

Literally, a wooden board with a grid of small woodscrews screwed into it, each screw holding down a cup washer.

Connections are made by trapping component leads and wires under the edge of the cup washer before screwing it down.

You need components with reasonably long leads, and it might still be necessary to solder longer wires to the leads in some cases.

I am told that in the olde days, this is how hobbyists used to do it...

Here's a link to an example (I read a copy of this book as a kid): http://www.mds975.co.uk/Content/george\_dobbs\_trf\_radio.html

---
Tags: hardware, mechanical
---


# Question
Title: How to use strtok() and strstr() with arduino?
Can anyone explain how things like strtok() and strstr() can be used to provide a numeric value for a substring location position within the mainstring array.

I've tried to understand from the C++ examples, but their 'position' locations of the substring within the mainstring (which I need) are returned in C++ as %d variables, whereas all I can get returned by the arduino 'char * pointer=' is the actual substring chars if they exist, rather than a number for their start position locations within the mainstring.

The C++ examples show that it is possible to discover the position values from %d, but how can I get that equivalent position value in arduino?

I want to be able to parse a char header\[30\] array for occurances of things like "s=123" and "d=789" in order to extract and assign the specified values to any appropriate variables (source or destination etc).

# Answer
> 1 votes
You have to define a format for the header you will be parsing and stick to that format. Say this is a sample `header` terminated by null:

```
s=123 d=789 e=463

```

A common property of each assignment in the string is the '=' symbol. You can use that to locate each variable and the value assigned to it. `strchr` is the function to use to locate a single character. Once you locate the = character, you move back and then forward along the array to obtain the variable and its value.

I will make some assumptions here: that your variable names will be single character, that numbers assigned will be no bigger than ints, and a space character is used to separate assignments.

```
char header[] = "s=123 d=789 e=463";

int d, s, e;   //your variables to be assigned to
char * ptr = header;
char * eq = NULL; //locate assmts
int * num = NULL; //just for starters
while (1){
  eq = strchr(ptr, '=');
  ptr = eq; // update the pointer
  if (ptr == NULL) // found no = chars
    break;
  switch (*(ptr - 1)){
    case 'd':    //all the possible variables
      num = &d; break;
    case 's':
      num = &s; break;
    case 'e':
      num = &e; break;
    default:   //unknown variable
      num = NULL;
  }
  ptr++;
  if (num == NULL) //unrecognized var
    continue;   // locate next = char
  *num = 0;
  while (*ptr && (*ptr != ' ')){  // while space or end of string not yet reached
    *num *= 10;  // extract each int
    *num += *ptr - '0';
    ptr++;
  }
}

Serial.println(d);  //now contains the numbers in the header
Serial.println(s);
Serial.println(e);

```

Untested but it should work for the header sample I gave.

---
Tags: programming
---


title: Power Arduino Nano with OTG cable

text:
# Question
Title: Power Arduino Nano with OTG cable
I have a project that I am putting an Arduino Nano in an enclosed box that will light LEDs in a pattern. I am planning to power it with a 5 V power brick but I would like to build a way a update the code to the Arduino without needing to disassemble the box.

Could I use an OTG cable with power (OTG Y cable) to accomplish this? or is there a better way to do this?

# Answer
It is possible to use a OTG Y cable just plug it into your phone, power cable into the power source and use the third connector to connect to your PC. (Assuming the PC only gets GND, D+ and D- and battery bank GND, 5V)

It is also possible to reprogram an Arduino with an Android device that has OTG support. Would save you a bit of hassle.

My Android phone (LG D605) with ArduinoDroid can easily upload code to my Nano and Uno.
> 0 votes

---
Tags: power, usb, arduino-nano
---


# Question
Title: See compiled assembly output (Visual Micro)
I'm curious about what some of my code is being compiled into, is there a way to have the compiler save the intermediate assembly files, ideally somewhere in the project folder? I read some forum posts about holding down shift when compiling from the Arduino IDE, but even that seems pretty hackish.

# Answer
> 2 votes
Turn on Verbose Compiling in the Arduino IDE and you will see all the intermediate file names (they are done in a temporary folder).

For example:

```
/home/nick/Development/arduino-1.6.7/arduino-builder -dump-prefs -logger=machine -hardware "/home/nick/Development/arduino-1.6.7/hardware" -hardware "/home/nick/.arduino15/packages" -hardware "/home/nick/Arduino/hardware" -tools "/home/nick/Development/arduino-1.6.7/tools-builder" -tools "/home/nick/Development/arduino-1.6.7/hardware/tools/avr" -tools "/home/nick/.arduino15/packages" -built-in-libraries "/home/nick/Development/arduino-1.6.7/libraries" -libraries "/home/nick/Arduino/libraries" -fqbn=arduino:avr:uno -ide-version=10607 -build-path "/tmp/build1cdca0d02fcf3112936d1438c170697d.tmp" -warnings=default -prefs=build.warn_data_percentage=75 -verbose "/tmp/arduino_1cdca0d02fcf3112936d1438c170697d/sketch_mar03b.ino"
/home/nick/Development/arduino-1.6.7/arduino-builder -compile -logger=machine -hardware "/home/nick/Development/arduino-1.6.7/hardware" -hardware "/home/nick/.arduino15/packages" -hardware "/home/nick/Arduino/hardware" -tools "/home/nick/Development/arduino-1.6.7/tools-builder" -tools "/home/nick/Development/arduino-1.6.7/hardware/tools/avr" -tools "/home/nick/.arduino15/packages" -built-in-libraries "/home/nick/Development/arduino-1.6.7/libraries" -libraries "/home/nick/Arduino/libraries" -fqbn=arduino:avr:uno -ide-version=10607 -build-path "/tmp/build1cdca0d02fcf3112936d1438c170697d.tmp" -warnings=default -prefs=build.warn_data_percentage=75 -verbose "/tmp/arduino_1cdca0d02fcf3112936d1438c170697d/sketch_mar03b.ino"
"/home/nick/Development/arduino-1.6.7/hardware/tools/avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10607 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-I/home/nick/Development/arduino-1.6.7/hardware/arduino/avr/cores/arduino" "-I/home/nick/Development/arduino-1.6.7/hardware/arduino/avr/variants/standard" "/tmp/build1cdca0d02fcf3112936d1438c170697d.tmp/sketch/sketch_mar03b.ino.cpp" -o "/dev/null"
"/home/nick/Development/arduino-1.6.7/hardware/tools/avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10607 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-I/home/nick/Development/arduino-1.6.7/hardware/arduino/avr/cores/arduino" "-I/home/nick/Development/arduino-1.6.7/hardware/arduino/avr/variants/standard" "-I/home/nick/Arduino/libraries/PID_v1" "/tmp/build1cdca0d02fcf3112936d1438c170697d.tmp/sketch/sketch_mar03b.ino.cpp" -o "/dev/null"
"/home/nick/Development/arduino-1.6.7/hardware/tools/avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10607 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-I/home/nick/Development/arduino-1.6.7/hardware/arduino/avr/cores/arduino" "-I/home/nick/Development/arduino-1.6.7/hardware/arduino/avr/variants/standard" "-I/home/nick/Arduino/libraries/PID_v1" "/home/nick/Arduino/libraries/PID_v1/PID_v1.cpp" -o "/dev/null"
"/home/nick/Development/arduino-1.6.7/hardware/tools/avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10607 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-I/home/nick/Development/arduino-1.6.7/hardware/arduino/avr/cores/arduino" "-I/home/nick/Development/arduino-1.6.7/hardware/arduino/avr/variants/standard" "-I/home/nick/Arduino/libraries/PID_v1" "/tmp/build1cdca0d02fcf3112936d1438c170697d.tmp/sketch/sketch_mar03b.ino.cpp" -o "/dev/null"
...
"/home/nick/Development/arduino-1.6.7/hardware/tools/avr/bin/avr-ar" rcs  "/tmp/build1cdca0d02fcf3112936d1438c170697d.tmp/core/core.a" "/tmp/build1cdca0d02fcf3112936d1438c170697d.tmp/core/main.cpp.o"
"/home/nick/Development/arduino-1.6.7/hardware/tools/avr/bin/avr-ar" rcs  "/tmp/build1cdca0d02fcf3112936d1438c170697d.tmp/core/core.a" "/tmp/build1cdca0d02fcf3112936d1438c170697d.tmp/core/new.cpp.o"
"/home/nick/Development/arduino-1.6.7/hardware/tools/avr/bin/avr-gcc"  -Os -Wl,--gc-sections -mmcu=atmega328p  -o "/tmp/build1cdca0d02fcf3112936d1438c170697d.tmp/sketch_mar03b.ino.elf" "/tmp/build1cdca0d02fcf3112936d1438c170697d.tmp/sketch/sketch_mar03b.ino.cpp.o" "/tmp/build1cdca0d02fcf3112936d1438c170697d.tmp/libraries/PID_v1/PID_v1.cpp.o" "/tmp/build1cdca0d02fcf3112936d1438c170697d.tmp/core/core.a" "-L/tmp/build1cdca0d02fcf3112936d1438c170697d.tmp" -lm
"/home/nick/Development/arduino-1.6.7/hardware/tools/avr/bin/avr-objcopy" -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0  "/tmp/build1cdca0d02fcf3112936d1438c170697d.tmp/sketch_mar03b.ino.elf" "/tmp/build1cdca0d02fcf3112936d1438c170697d.tmp/sketch_mar03b.ino.eep"
"/home/nick/Development/arduino-1.6.7/hardware/tools/avr/bin/avr-objcopy" -O ihex -R .eeprom  "/tmp/build1cdca0d02fcf3112936d1438c170697d.tmp/sketch_mar03b.ino.elf" "/tmp/build1cdca0d02fcf3112936d1438c170697d.tmp/sketch_mar03b.ino.hex"
Using library PID_v1 in folder: /home/nick/Arduino/libraries/PID_v1 (legacy)

Sketch uses 6,484 bytes (20%) of program storage space. Maximum is 32,256 bytes.
Global variables use 285 bytes (13%) of dynamic memory, leaving 1,763 bytes for local variables. Maximum is 2,048 bytes.

```

---

Of interest are the last couple - the `xxx.elf` file and the `xxx.hex` file (where xxx is your sketch name).

The `xxx.hex` file is what is uploaded to your Arduino (well, it is decoded by Avrdude).

The `xxx.elf` file can be used to get assembly output, like this:

```
avr-objdump -Sz xxx.elf

```

That outputs to the screen. I usually output to a file:

```
avr-objdump -Sz xxx.elf > /tmp/avr_dump.txt

```

---

Example output:

```
void setup() {
      ec:   0f 93           push    r16
      ee:   1f 93           push    r17
  Setpoint = 100;
      f0:   80 e0           ldi r24, 0x00   ; 0
      f2:   90 e0           ldi r25, 0x00   ; 0
      f4:   a8 ec           ldi r26, 0xC8   ; 200
      f6:   b2 e4           ldi r27, 0x42   ; 66
      f8:   80 93 73 01     sts 0x0173, r24
      fc:   90 93 74 01     sts 0x0174, r25
     100:   a0 93 75 01     sts 0x0175, r26
     104:   b0 93 76 01     sts 0x0176, r27
  //turn the PID on
  myPID.SetMode(AUTOMATIC);
     108:   61 e0           ldi r22, 0x01   ; 1
     10a:   70 e0           ldi r23, 0x00   ; 0
     10c:   82 e3           ldi r24, 0x32   ; 50
     10e:   91 e0           ldi r25, 0x01   ; 1
     110:   0e 94 04 04     call    0x808   ; 0x808 <_ZN3PID7SetModeEi>

```

In this particular case `Setpoint` was a double so it took 8 instructions to load a literal into it.

---
Tags: build, visualstudio
---


title: Arduino serial hex decimal values code

text:
# Question
Title: Arduino serial hex decimal values code
I'm trying to send heximal values from arduino to PZEM-04 power module (it shows voltage, current and ect.) over serial communication in heximal format and get values in decimal format for further actions with them. Any help with the code please? One of the commands: Send command: B4 C0 A8 01 01 00 1E Reply data: A4 00 00 00 00 00 A4

Edit: I am connecting wires from PZEM module TTL to arduino "serial port": TX-RX, RX-TX, VCC-VCC, GND-GND, so it's serial communication.. PZEM module: http://www.aliexpress.com/store/product/PEACEFAIR-AC-100A-Electric-power-monitoring-and-communication-module-power-meter-power-energy-Volt-Ammeter/1773456\_32373508101.html

# Answer
A possible implementation of the protocol using serial read/write of binary data (command and response).

```
void send(Stream& ios, uint8_t cmd[6])
{
  uint8_t sum = 0;
  for (int i = 0; i < 6; i++) {
    uint8_t c = cmd[i];
    sum += c;
    ios.print((char) c);
  }
  ios.print((char) sum);
}

bool recv(Stream& ios, uint8_t res[6])
{
  uint8_t sum = 0;
  uint8_t c;
  for (int i = 0; i < 6; i++) {
    while (!ios.available());
    c = ios.read();
    sum += c;
    res[i] = c;
  }
  while (!ios.available());
  c = ios.read();
  return (sum == c);
}

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

  uint8_t cmd[] = { 0xB4, 0xC0, 0xA8, 0x01, 0x01, 0x00 };
  uint8_t res[6];
  send(Serial, cmd);
  recv(Serial, res);
}

void loop()
{
}

```

Cheers!
> 2 votes

---
Tags: serial, uart
---


# Question
Title: Why is the result of this product operation wrong?
I had a problem in a program where the result of product is not what it's supposed to be. For example: 775\*775 gives 10801 instead of 6006025.

To try to isolate and resolve the problem, I made a simple sketch to test the result of different products. What I found is that if I do the same product in this way: 775/100.00\*775/100.00 then multiply the result by 10000 I get the right value: 600625.00

The attached pictures illustrate what I said.

While I can use this solution in my initial program by I still want to do the multiplication directly as more operations means more time.

I would appreciate any help. Thank you.

# Answer
Integer overflow. You're multiplying an `int` by an `int` then assigning it to a `long`. Instead if you multiply a `long` by a `long`, or an `int` by a `long`, or a `long` by an `int`, it should work.

```
unsigned long res = 775L * 775;

```

The `L` suffix tells the compiler to treat it as a long, not an int.
> 6 votes

---
Tags: arduino-uno
---


# Question
Title: Arduino serial port eats data for 3 seconds before it sends?
With the source code below, I'm getting what I think to be strange behaviour with the serial port output.

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

int c = 0;
void loop() {
  Serial.println(c++);
}

```

Presumably what this will do is starting printing incrementing numbers, one on each line, starting from 0. However, my serial monitor only starts printing these numbers after the 3000 mark. I found this behaviour only after discovered in another sketch that I was losing data at the beginning.

Is this normal Arduino behaviour? Or a serial monitor problem? Or something else?

# Answer
> 2 votes
Is this a Leonardo or Yun? If it is, you have to wait until the `Serial` object says the USB connection is really ready:

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

```

Read this.

Because you did't wait, your `loop` is able to execute 3000 times before `Serial` actually sends something back to the PC.

---
Tags: serial
---


# Question
Title: Possible to use the hardware serial port for peripheral on ATmega32u4 when using USB for programming?
I have a Arduino Pro Micro and use the USB port for programming. Is it possible to use the hardware serial port for connecting with a peripheral while I'm using the USB port (and hence the hardware serial port) for programming? Or must I disconnect the USB cable or otherwise reconfigure the hardware?

# Answer
I have a Teensy 2.0 with a ATmega32u4 and I can use both, with the USB as Serial.\* and the hardware UART as Serial1.\*

For the Arduino Pro Micro it is the same. See Arduino Pro Micro, get data out of Tx pin?

For Teensy, see https://www.pjrc.com/teensy/td\_uart.html
> 3 votes

---
Tags: serial, hardware
---


title: A question about chars and Serial

text:
# Question
Title: A question about chars and Serial
I have the following code:

```
int count = 0;
char serial_char;
char serial_message[96];

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

void loop(){
  while(Serial.available() > 0){

    serial_char = Serial.read();
    if (serial_char == '\n' || serial_char == '\r'){

      serial_message[count] = 0; // <<-- What does this line do?
      count = 0;
      Serial.println(serial_message);

    }
    else{
      serial_message[count++] = serial_char;
    }

  }

}

```

With this code, I can type a message into the serial monitor, and it will print the message back at me. So if I type 'Goodbye', it returns:

```
Goodbye

```

If I send it another message 'Word', it returns:

```
Word

```

However, my questions is when I comment out the line:

```
serial_message[count] = 0;

```

And then I repeat the same sequence of actions before, 'Goodbye' returns 'Goodbye', but when next I enter 'Word', it returns:

```
Wordbye

```

Could anyone explain this to me? I am really curious to know why this occurs. What does adding that 0 in the char array accomplish? Thank you.

# Answer
There is a difference between char\[\] and String.
You are using char\[\] which is the best way to work on a small processor like the Arduino. However; it is also a bit more difficult.

Char array is just a piece of memory that can contain any data. Because we want to put a variable length string in there we need a convention to know what is the last character of the string. By convention this is a value 0.
This is why we speak about "null terminated strings".

This explains why after sending word (without adding the 0 at the end" you get "Wordbye" because the memory contains 'W' 'o' 'r' 'd' 'b' 'y' 'e' and 0.

The reason why it works OK with 'Goodbye' is because all memory gets set to 0 at startup of the processor.
So as long as the last send word is longer than the previous it works fine.

A last thing. The memory does not actually contain 'W' 'o' 'r' 'd' 'b' 'y' 'e'. The memory contains the ASCII values of the letters 'W' 'o' 'r' 'd' 'b' 'y' 'e'
> 1 votes

# Answer
The zero-value, the "null character", indicates the end of the string. For strings, you allocate some maximum space, in your case 96 bytes:

```
char serial_message[96];

```

When storing variable-length strings in that, you need to indicate where the string ends. That's what the zero value does in a null-terminated string. (Note that `0` is really binary `0x00` here; it's not the ASCII *character* 48, `0x30`.) So, the 96 bytes allow for a string of at most 95 characters, followed by the terminator. When printing, it prints the memory contents until it finds that null character.
> 4 votes

---
Tags: serial, string
---


title: Digital Vs. Analog Sensor

text:
# Question
Title: Digital Vs. Analog Sensor
Background: I'm using an Atmega1284P to add sensors to an off road racing truck onto a CANBUS network. The standard automotive sensors are thermistors, but the Dallas 1 wire temp sensors (DS18B20) with an integrated ADC caught my eye. They don't, however, come in a package that would work for my purposes so I would have to build one. I haven't been able to find one waterproofed in an NPT fitting with only a 1" probe length.

My question: how much more accurate would the 1 wire be over a thermistor? How much of a difference would it make for processor efficiency to not have to do the math involved with thermistors and just read the value from the 1 wire? I don't mind building them, I just want to make sure they're worth it first.

# Answer
> 2 votes
To make an informed decision you first need to understand a few basic concepts and some pros and cons of each system.

Firstly there are the concepts of *precision* and *accuracy*. These are two very different properties and each is important in their own way. On the face of it they may sound the same, but they aren't.

**Precision**

This is how close to the real value your measurements are. This is the "±" value that datasheets list. It's how close a match to the actual temperature the measured temperature is. So a ±0.5° measurement could be anywhere within half a degree of the actual temperature.

**Accuracy**

This can also be considered as the *resolution* of the measurement. It is how fine a difference in temperatures the device is able to measure. For instance you may be able to detect 0.0125° differences. This is mostly defined by the resolution of the ADC in the device.

And now the pros and cons:

**Digital**

**Pros**

These devices can be factory calibrated for a more precise reading. The accuracy is usually pretty good too, but is fixed by the design of the device. Communication is generally reliable and wire length doesn't generally affect the values reported.

**Cons**

Communication protocols can have some large overheads limiting the number of samples you can take per second (not just on one sensor but across the whole array of sensors). Excess EMI noise (especially from engines) can corrupt the communication signals over long connections unless extra care is taken (such as implementing a balanced line communication medium).

**Analog**

**Pros**

Very simple to connect up and samples can be read very rapidly. Accuracy is determined by the ADC you choose to use.

**Cons**

Wire length can have a detrimental affect on the values read unless special wiring and sensor schemes are used to cancel out the resistance of the wires. Noise induced into the wires is very hard to detect or cancel out and can give spurious results. Requires more complex mathematics to calculate a resistance.

**Summary**

So in short: Digital can give you more reliable communication of your sampled values over longer distances but at the cost of reduced sampling speeds.

# Answer
> 0 votes
I fully agree with Majenko except for the cons for analog.
Basically it is not easy to get a (very) accurate ADC reading with an arduino. The main problem is the reference voltage that fluctuates.

This is the main reason why I prefer digital to analog when it needs to be "correct"

---
Tags: sensors, code-optimization
---


# Question
Title: How does Arduino distinguish between SPI programming data and regular data?
The Arduino can be programmed using SPI without a boot loader. Without a boot loader, the Arduino starts running its sketch right away. So, how does the Arduino know that it is being programmed via SPI vs regular SPI traffic already present on the SPI bus? Was is the pin-level, electrical signal that let's the Arduino know the difference?

# Answer
> 10 votes
In-system programmer is activated with RESET line. During normal operation reset line is not active and ISP module is disabled.

You can find detailed description of AVR ISP in this document:

http://www.atmel.com/images/doc0943.pdf

---
Tags: icsp
---


# Question
Title: Interfacing with desktop computer console software
Recently I bought the following USB to Serial cable: https://www.adafruit.com/products/954

This cable has grd, vcc, rx and tx lines.

I am looking to use this cable to interface with my desktop computer with a program like Tera Term or Hyperterminal so i can output messages for debugging purposes.

Also, I am trying to stay from using the Arduino IDE. I would prefer using C and flashing in the hex manually.

So, can anyone point me to a tutorial or explain how to make this happen?

thanks people.

# Answer
> 1 votes
**For debugging:**

Configure the UART on the ATmega to output TTL serial. If you are using the Arduino libraries, then `Serial` is what you want. Connect the TX pin of the ATmega to the RX of the USB/Serial cable, and vice versa.

Open the serial device on your computer in the program of your choice. When you write to the UART on the ATmega, you should see the messages in your terminal.

Pretty straightforward.

**For programming:**

If you're going to be using C and flashing things manually, you'd best go and buy an AVR programmer so you can program the ATmega directly without messing about with a bootloader. A programmer is ~15USD, so you might as well buy one. Then you can use the GNU AVR toolchain, which is very easy to use. Compile code with `avr-gcc`, and program the device with `avrdude`.

If you really want to use programming over serial, you'll have to manually hit the reset button each time you program the chip, because (as Mikael pointed out), that serial cable lacks the lines necessary to automatically reset the chip (and drop to the bootloader).

---
Tags: usb
---


# Question
Title: Not seeing frames returned from client when using ESP8266 Wifi Shield
I'm trying to make a web server using an Arduino R3 and Sparkfun ESP8266 Wifi Shield. I've built a webpage that has a form I would like to control the Arduino with.

Currently my sketch can successfully send the webpage, but when I use the form, 9 / 10 times I see no output on the serial monitor, and the 1/10 times I see the frame from the client the sketch seems to hang and the client keeps waiting for more data.

I'm using the Sparkfun ESP8266 libraries for the product I bought.

I don't think this is a hardware problem, I've visually inspected the Arduino and ESP pins and they seem ok. I don't think it's a memory problem.

I've put the salient part of the sketch below:

```
void serverDemo()
{
  // available() is an ESP8266Server function which will
  // return an ESP8266Client object for printing and reading.
  // available() has one parameter -- a timeout value. This
  // is the number of milliseconds the function waits,
  // checking for a connection.
  ESP8266Client client = server.available(1000);
  char clientline[BUFSIZ];
  int index = 0;

  if (client)
  {
    Serial.println(F("Client Connected!"));
    // an http request ends with a blank line
    boolean currentLineIsBlank = true;

    while (client.connected())
    {
      if (client.available())
      {
        char c = client.read();

        if( index < BUFSIZ ) {
          clientline[index++] = c;
        } // end of if

        if (c == '\n' && currentLineIsBlank)
        {
          clientPrintProgmemArray(htmlHeaderTable, htmlHeaderTableSize, client);
          clientPrintProgmemArray(webpageTable, webpageTableSize, client);
          Serial.println(F("Page sent"));
          break;
        } // end of if

        if (c == '\n')
        {
          currentLineIsBlank = true;
        } // end of if

        else if (c != '\r')
        {
          // you've gotten a character on the current line
          currentLineIsBlank = false;
        } // end of if
      } // end of if( client.available() )
    } // end of while ( client.connected() )
    delay(10);
    client.stop();
    Serial.println(F("Client disconnected"));
    Serial.print(F("Index: "));
    Serial.println(index);
    Serial.print(F("Clientline: \""));
    for( int i = 0; i <= index; i++)
    {
      Serial.print(clientline[i]);
    }
    Serial.print(F("\"\r\n"));
    if( strstr(clientline, "e=1") != 0) {
      Serial.println("hooray!");
    }
  }
}

```

The header and webpage the Arduino sends to the client is:

```
HTTP/1.1 200 OK
Content-Type: text/html
Connection: close
<!DOCTYPE HTML>
<html>
<body>
<form action="/?" method="get">
    <input name="e" type="submit" value="0">
    <input name="e" type="submit" value="1">
</form>
</body>
</html>

```

The output I get on the serial monitor is:

```
ESP8266 Shield Present
Mode set to station
Connected to: XXXXX
My IP: 192.168.0.13
Server started! Go to 192.168.0.13

Client Connected!
Page sent
Client disconnected
Index: 2
Clientline: "
 "
Client Connected!
Page sent
Client disconnected
Index: 2
Clientline: "
 "

```

I'd be very grateful if anybody has any advice on where the problem lies.

Thanks in advance

# Answer
> 1 votes
So I figured out the answer to my own question.

It turns out there must be a mistake in the example sketches that come with the ESP8266 shield I bought, as the function to begin Arduino/ESP8266 communications didn't have any arguments when the function expected parameters. So it appeared to be trying to set their baud rate to 0!!

I edited the library to have a hard value of 57600 and now it seems to work far more reliably.

---
Tags: arduino-uno, esp8266, web
---


# Question
Title: Arduino is not responding to a Tiny RTC I2C modules, How to fix?
We have an arduino due with a Tiny RTC I2C module and we're trying to print the current time to the serial monitor. However its not working, currently its printing the time as 2165/165/165 (Monday) 165:165:85 (it should read something like 2016/3/3 (Thursday) 4:15:00). Interestingly it continues to read the same thing, it doesn't change, even if I remove the module from the breadboard completely. I have tried this with two of the modules and both have the same exact results. Does anyone know how to fix this?

My schematics are the same as shown here: http://www.hobbyist.co.nz/?q=real\_time\_clock

This is my code, it's just the example code from the imported library for the clock.

```
// Date and time functions using a DS1307 RTC connected via I2C and Wire lib
#include <Wire.h>
#include "RTClib.h"

#if defined(ARDUINO_ARCH_SAMD)
// for Zero, output on USB Serial console, remove line below if using programming port to program the Zero!
   #define Serial SerialUSB
#endif

RTC_DS1307 rtc;

char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};

void setup () {

#ifndef ESP8266
  while (!Serial); // for Leonardo/Micro/Zero
#endif

  Serial.begin(57600);
  if (! rtc.begin()) {
    Serial.println("Couldn't find RTC");
    while (1);
  }

  if (! rtc.isrunning()) {
    Serial.println("RTC is NOT running!");
    // following line sets the RTC to the date & time this sketch was compiled
    rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
    // This line sets the RTC with an explicit date & time, for example to set
    // January 21, 2014 at 3am you would call:
    // rtc.adjust(DateTime(2014, 1, 21, 3, 0, 0));
  }
}

void loop () {
    DateTime now = rtc.now();

    Serial.print(now.year(), DEC);
    Serial.print('/');
    Serial.print(now.month(), DEC);
    Serial.print('/');
    Serial.print(now.day(), DEC);
    Serial.print(" (");
    Serial.print(daysOfTheWeek[now.dayOfTheWeek()]);
    Serial.print(") ");
    Serial.print(now.hour(), DEC);
    Serial.print(':');
    Serial.print(now.minute(), DEC);
    Serial.print(':');
    Serial.print(now.second(), DEC);
    Serial.println();

    Serial.print(" since midnight 1/1/1970 = ");
    Serial.print(now.unixtime());
    Serial.print("s = ");
    Serial.print(now.unixtime() / 86400L);
    Serial.println("d");

    // calculate a date which is 7 days and 30 seconds into the future
    DateTime future (now + TimeSpan(7,12,30,6));

    Serial.print(" now + 7d + 30s: ");
    Serial.print(future.year(), DEC);
    Serial.print('/');
    Serial.print(future.month(), DEC);
    Serial.print('/');
    Serial.print(future.day(), DEC);
    Serial.print(' ');
    Serial.print(future.hour(), DEC);
    Serial.print(':');
    Serial.print(future.minute(), DEC);
    Serial.print(':');
    Serial.print(future.second(), DEC);
    Serial.println();

    Serial.println();
    delay(3000);
}

```

# Answer
You have a couple of problems (although the lack of pull-up resistors is not one of them, because the board you linked has pull-up resistors on it).

* The DS1307 needs to operate at a minimum of 4.5 volts, so you can't connect it to the 3.3V pin on the Due. (You need to supply it with 5V).
* However the Due is a 3.3V device on its data pins, and thus you can't connect the DS1307 directly to SDA/SDL or you will damage the Due.

Thus you need to supply the clock board with 5V, and use a bi-directional logic-level converter, such as this (using two logic-level MOSFETs):

You can buy level-converter boards, but as you can see, one is easy enough to make up.

Now the clock chip runs at 5V, but the logic levels are converted to 3.3V for the Due.

I tested this with mine, and it worked OK.

---

```
#include <Wire.h>
#include "RTClib.h"

RTC_DS1307 myclock;

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

void loop () {
    DateTime now = myclock.now();

    Serial.print(now.year(), DEC);
    Serial.print('/');
    Serial.print(now.month(), DEC);
    Serial.print('/');
    Serial.print(now.day(), DEC);
    Serial.print(' ');
    Serial.print(now.hour(), DEC);
    Serial.print(':');
    Serial.print(now.minute(), DEC);
    Serial.print(':');
    Serial.print(now.second(), DEC);
    Serial.println();

    Serial.print(" since midnight 1/1/1970 = ");
    Serial.print(now.unixtime());
    Serial.print("s = ");
    Serial.print(now.unixtime() / 86400L);
    Serial.println("d");

    Serial.println();
    delay(3000);
}

```

---

Output:

```
2016/3/6 12:0:20
 since midnight 1/1/1970 = 1457265620s = 16866d

2016/3/6 12:0:23
 since midnight 1/1/1970 = 1457265623s = 16866d

2016/3/6 12:0:26
 since midnight 1/1/1970 = 1457265626s = 16866d

```

---

A useful technique for debugging is to run the "I2C scanner" I have on my I2C page. The code is:

```
// I2C Scanner<!-- language-all: lang-none -->
// Written by Nick Gammon
// Date: 20th April 2011

#include <Wire.h>

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

  // Leonardo: wait for serial port to connect
  while (!Serial)
    {
    }

  Serial.println ();
  Serial.println ("I2C scanner. Scanning ...");
  byte count = 0;

  Wire.begin();
  for (byte i = 8; i < 120; i++)
  {
    Wire.beginTransmission (i);
    if (Wire.endTransmission () == 0)
      {
      Serial.print ("Found address: ");
      Serial.print (i, DEC);
      Serial.print (" (0x");
      Serial.print (i, HEX);
      Serial.println (")");
      count++;
      delay (1);  // maybe unneeded?
      } // end of good response
  } // end of for loop
  Serial.println ("Done.");
  Serial.print ("Found ");
  Serial.print (count, DEC);
  Serial.println (" device(s).");
}  // end of setup

void loop() {}

```

If you don't see your device appear in the Serial Monitor, there is no point wondering why the date doesn't change, because it hasn't found the clock at all. You should see something like this:

```
I2C scanner. Scanning ...
Found address: 104 (0x68)
Done.
Found 1 device(s).

```

---

## How the level converter works

For more information, read the Philips Application Note AN97055

In brief (taking SDA as an example):

* If neither side is driving SDA low, then VGS is zero (they are both 3.3V) and the MOSFET does not conduct. Hence each side is "pulled-up" to their respective voltages. The low side is pulled up to 3.3V and the high side is pulled up to 5V.
* If the low side drives SDA low, then VGS is 3.3V which is high enough for the MOSFET to conduct. Since it conducts it also drags the high side low as well (overpowering the 10k pull-up resistor).
* If the high side drives SDA low, current initially flows through the drain substrate diode of the MOSFET (it will be a diode drop above 0V, namely 0.7V), lowering the voltage at the source, until VGS is high enough for the MOSFET to conduct. Once it starts conducting then the low side is pulled further lower.

---

> Do you have an actual photograph of this?

I've pulled it all apart days ago, however thankfully I took a snapshot before I did.

To be honest, the schematic is easier to follow. When looking at photos it can be hard to see exactly what is plugged into where.
> 5 votes

---
Tags: arduino-due, rtc
---


# Question
Title: How to burn Arduino Bootloader on ATmega168PA-PU?
How can I burn the Arduino Bootloader on an ATmega168PA-PU with an Arduino Uno?

# Answer
> 2 votes
I have a bootloader-programmer sketch here:

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

Basically you connect up the boards like this:

```
Arduino Uno         Target ATmega168PA

D10 (SS)            Reset (pin 1)
D11 (MOSI)          MOSI  (pin 17)
D12 (MISO)          MISO  (pin 18)
D13 (SCK)           SCK   (pin 19)

Gnd                 Gnd   (pins 8 & 22)
+5V                 +5V   (pins 7 & 20)

```

Then download the sketch from GitHub \- the one you want is in the **Atmega\_Board\_Programmer** folder. Run that and follow the instructions in the Serial Monitor.

For more information see the link above.

# Answer
> 1 votes
The official Arduino documentation has detailed instructions on how to transform Arduino board into an ISP.

https://www.arduino.cc/en/Tutorial/ArduinoISP

---
Tags: arduino-uno
---


title: Controlling arduino over webserver

text:
# Question
Title: Controlling arduino over webserver
I want to control arduino through Internet without using Ethernet shield. I know there is a way. So can you help me what things I'll be needing for that

# Answer
> 3 votes
This is incredibly broad: you could use an Arduino Ethernet, which has built in Ethernet, or you could use an ENC28J60 Ethernet module, or any of the many, many WiFi peripherals.

Also, consider using the ESP8266, instead of an Arduino with an Ethernet/WiFi peripheral. The ESP8266 can be programmed directly from the Arduino IDE with Arduino-style syntax, and can also run the NodeMCU firmware (programmed in Lua).

---
Tags: ethernet
---


# Question
Title: Arduino serial communication input string checking
I am trying to check whether the input string in my serial is inside my string array, but it seems like that the condition if(array\[i\]==inputString) does not print true.

So here is my code:

```
String array[4]={"hey","jude","jane"},inputString,test;
boolean stringComplete=false;
void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
  //int store=0;
  serialEvent();
  if(stringComplete){
    Serial.println(inputString);
    for(int i=0;i<4;i++){
      Serial.println("..");
      //test=array[i];
      Serial.println(array[i]);
      if(inputString==array[i]){
        Serial.println("true");
        break;
      }
    }
  inputString="";
  stringComplete=false;
  }
   //Serial.println(store);
}

void serialEvent() {
  while (Serial.available()) {
    char inChar = (char)Serial.read();
    inputString += inChar;
    if (inChar == '\n') {
      stringComplete = true;
    }
  }
}

```

# Answer
> 1 votes
First, you declare an array of 4 items and provide an initializer for 3. Don't know how it can even compile, maybe it is tolerated but in doubt

```
String [] array = {"hey","jude","jane","foo"};

```

Also, your serialEvent function appends `\n` to the string. Even if you receive string jane, you will compare `jane` from array with `jane\n` from serial

```
char inChar = (char)Serial.read();
if( inChar == '\n')
   stringComplete = true;
else
   inputString += inChar

```

---
Tags: arduino-uno, serial, c++
---


# Question
Title: Picking the time a led on an arduino should turn on, via android
I have created an app which is connencted to my arduino via bluetoth. The user of the app can turn on and off a led which is connented to the arduino. But I want to take it a step further... I want the user to be able to give the time and the date when the light should turn on and additionally the time that sould pass until the led turns off again. Is it significantly harder? I have thought of using an already existing alarm app but I am pretty stuck, so could anyone give me some suggestions?

# Answer
Make the Bluetooth message send how many seconds it is until the light should be on, and how many seconds it should stay on.

Then the arduino code can just handle everything with millis(). You know the millis() you were asked to start, add the delay, and wait for that time.

Delays less than 50 days (wrap around of millis ()) take no effort to handle it you embrace the overflow.

Handling delays greater than 50 days can be achieved by watching for millis() overflows and counting them. You could also make your own timer based counter.

*If* you care about recovery after power loss / reset you could use an RTC module. Depending on its complexity, it could interrupt you or you poll it to check for a date you saved to Arduino eeprom. You would have to consider what the system should do it the alarm would have happened during the power loss...
> 1 votes

---
Tags: timers, time, android, arduino-mini
---


# Question
Title: Arduino LiquidCrystal_I2C fast overwritting
I have an arduino board connected to 2 temperature sensors, 2 switch buttons and 1 lcd display.

When the switch button changes to off, "off" is printed on the lcd display. When the button state is on, the temperature is printed on the lcd display.

The problem is when it shows "off" its still possible to see the temperature value for "1 millisecond" each second. I don't know what is causing the "off" message to change for a millisecond.

Source code:

```
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#include <Streaming.h>

#define DS18B20_SENSOR1 2               // pino de dados do DS18D20
#define DS18B20_SENSOR2 4               // pino de dados do DS18D20

int buttonState1 = 0;
int lastButtonState1 = 0;
int buttonState2 = 0;
int lastButtonState2 = 0;

float Temp1, Temp2;

OneWire oneWire1(DS18B20_SENSOR1);       // Objeto do baramento One-wire
DallasTemperature sensor1(&oneWire1);     // Objeto do sensor DS18D20

OneWire oneWire2(DS18B20_SENSOR2);       // Objeto do baramento One-wire
DallasTemperature sensor2(&oneWire2);     // Objeto do sensor DS18D20

// Set the LCD address to 0x27 for a 16 chars and 2 line display
LiquidCrystal_I2C lcd(0x27, 16, 2);

void setup(void)
{
  Serial.begin(3000);
  Serial << F("Teste do Sensor 1") << endl << endl;
  Serial << F("Teste do Sensor 2") << endl << endl;
  sensor1.begin();
  sensor2.begin();
  lcd.begin();
  lcd.setBacklight(HIGH);

  /*
   * Control Variables
   */

  pinMode(5, INPUT);
  pinMode(7, INPUT);
  pinMode(8, OUTPUT);
  pinMode(9, OUTPUT);
  pinMode(10, OUTPUT);
  pinMode(11, OUTPUT);
  pinMode(12, OUTPUT);
  pinMode(13, OUTPUT);
}

void turnAllOff1(){
  digitalWrite(11, LOW);
  digitalWrite(12, LOW);
  digitalWrite(13, LOW);
}

void turnAllOff2(){
  digitalWrite(8, LOW);
  digitalWrite(9, LOW);
  digitalWrite(10, LOW);
}

void printTemp1(){
  lcd.setCursor (0,0);
  lcd.print("Sensor1: ");
  lcd.print(Temp1);
  lcd.print("C");
}

void printOff1(){
  lcd.setCursor (0,0);
  lcd.print("Sensor1: ");
  lcd.print(" off   ");
}

void printTemp2(){
  lcd.setCursor (0,1);
  lcd.print("Sensor2: ");
  lcd.print(Temp2);
  lcd.print("C");
}

void printOff2(){
  lcd.clear();
  lcd.setCursor (0,1);
  lcd.print("Sensor2: ");
  lcd.print(" off   ");
}

void loop(){
  buttonState1 = digitalRead(5);
  buttonState2 = digitalRead(7);

  if(buttonState1 != lastButtonState1){
    if(buttonState1 == HIGH){
      sensor1.requestTemperatures();
      Temp1 = sensor1.getTempCByIndex(0);
      turnAllOff1();
      if(Temp1 < 36){
        digitalWrite(13, HIGH);
      }
      else if(Temp1 > 38){
        digitalWrite(11, HIGH);
      }
      else{
        digitalWrite(12, HIGH);
      }
      printTemp1();
    }
    else{
      printOff1();
    }
  }
  lastButtonState1 = buttonState1;

  if(buttonState2 != lastButtonState2){
    if(buttonState2 == HIGH){
      sensor2.requestTemperatures();
      Temp2 = sensor2.getTempCByIndex(0);
      turnAllOff2();
      if(Temp2 < 0){
        digitalWrite(10, HIGH);
      }
      else if(Temp2 > 2){
        digitalWrite(8, HIGH);
      }
      else{
        digitalWrite(9, HIGH);
      }
      printTemp2();
    }
    else{
      printOff2();
    }
  }
  lastButtonState2 = buttonState2;
}

```

# Answer
> 0 votes
You need to use INPUT\_PULLUP pin mode and connect the buttons between the pins and ground.

```
pinMode(5, INPUT_PULLUP);
pinMode(7, INPUT_PULLUP);

```

Later on you will also have to debounce the button but that is another question (where you can find plenty of answers already).

Cheers!

---
Tags: arduino-uno, lcd, button
---


title: Low-Pulse Occupancy and Voltage Divider

text:
# Question
Title: Low-Pulse Occupancy and Voltage Divider
I have a PPD42NS dust sensor I'd like to hook up to an ESP8266-01 microcontroller. The ESP8266 uses 3.3v logic, but the PPD42NS uses 5v. The PPD42NS uses low pulse occupancy as output.

I'd like to use parts I have on hand, and I was wondering if a simple voltage divider built from 2 resistors can reliably shift the voltage without distorting the signal.

If not, could an NPN transistor do the job instead?

# Answer
> 0 votes
While the PPD42NS has a 5-pin connector, it is shown at seeedstudio.com and howmuchsnow.com connected up with three wires: +5V, Ground, and an LPO or “Low Occupancy Output” signal, which goes low when a particle occludes an LED beam path. LPO is used as an input to let sketches measure the fraction of time the beam's occluded, which correlates with number of dust particles.

Yes, a resistive voltage divider will let you use the 0-to-5V occupancy signal as an input to your 3.3V-tolerant ESP8266.

What values of resistors should be used? Because input pin capacitance is small (eg under 10 pF), signal "crispness" should be about the same over a broad range of resistances – say from a 100Ω+200Ω divider up past 1KΩ+2KΩ; even 10KΩ+20KΩ might be ok.

The Grove\_-\_Dust\_sensor.pdf data sheet at seeedstudio.com says:

> Output Method Negative Logic, Digital output,
> Hi : over 4.0V(Rev.2) Lo : under 0.7V
> (As Input impedance : 200kΩ) OP-Amp output, Pull-up resistor : 10kΩ

This suggests (but doesn't clearly indicate) that some sort of open-drain output might be used. If so, instead of using a voltage divider one could remove the 10kΩ pull-up on the sensor, and pull the output to 3.3 V instead of 5 V, via either an external resistor or using an INPUT\_PULLUP pinmode setting (if available on the ESP8266).

*Edit:* Regarding the comment, “I'm considering use it in conjunction with an MCP23017 I/O expander IC. The GPIO pins on the chip appear to be rated at a max capacitance of 50 pF. Will that affect the range of resistors available? How does resistor choice affect the crispness of the signal, and how can I determine it for myself?”:

The “max capacitance of 50 pF” spec, which is parameter D101 in table 2.1 of the MCP23017 spec sheet, refers to “Capacitive Loading Specs on Output Pins”, ie, how much capacitance MCP23017 outputs can drive. It doesn't refer to input pin capacitance, so isn't relevant here.

In general, when a signal edge (a rise or fall) arrives at an input pin, the input pin's voltage doesn't change instantaneously. The input pin's capacitance needs to charge or discharge. (It charges for a rising edge, discharges for a falling edge.) The speed of change depends on the RC time constant of the circuit. A delay occurs, probably 1–3 time constants long, before the pin starts to switch. (The switch may take a few tens or hundreds of nanoseconds.)

For example, if input circuit capacitance is 10 pF and its effective resistance is 100kΩ, RC = 10 pF · 100kΩ = 10⁻¹¹·10⁵ = 10⁻⁶ seconds = 1 microsecond. Whether that's large enough to matter for your measurements depends on how many time constants have to occur before the pin starts switching, and on how narrow the LPO signals are.

In short, compute RC, and if it's more than a few microseconds, use a smaller value of R. Alternately, if you have access to an oscilloscope, attach it to the input and try various resistance values in the voltage divider, to get a feel for how the signals degrade as the resistors in the divider get bigger.

Note, using a voltage divider causes different RC values for falling edges than for rising edges. For example, suppose an actively driven 0-5V signal enters a divider with 10KΩ in series with 20KΩ, and the 0-3.3 V signal is taken from the resistors' junction. Then R is 10KΩ for a rising edge, and 20KΩ for a falling edge. If the 0-5V signal weren't actively driven high, but instead pulled up via a pullup resistor R' when a transistor turns off, then the rising edge R value would be R'+10KΩ for this example.

---
Tags: esp8266, voltage-level
---


# Question
Title: Unable to upload sketches after little oopsie (reversed input polarity)
So playing around with an arduino uno, I was powering it with a 12volt battery (putting power between Vin and Gnd) and I fat fingered the battery terminals, putting them in reverse (oops)

I see smoke coming out of the 5 volt regulator (the little 3 pin IC). I immediately pull out the battery thinking I've just bricked this thing.

After a minute or two I plug the battery in again (taking care to plug it in straight this time) and to my surprise it works, works pretty well. The last sketch I uploaded works perfectly fine.

I've been using the same thing for an hour or so. But now I wanted to upload another sketch and it doesn't upload. The voltages seem to be fine, I'm putting in 11.8 volts on Vin, there is 5.12 volts on 5v and 3.34 volts on 3v3

I thought there may be some problem with the voltage regulator, so I tried connecting it directly to the USB (powering it from USB) but still the same thing.

I find it intriguing that it works perfectly for everything except uploading new sketches, especially after such an explosive oopsie. Can any of you chaps deduce what the problem might be? I have a USBasp module so I can reburn the bootloader, but I doubt that's the problem.

# Answer
> 2 votes
The atmega328 that runs the sketch is fine, but the communication is broken somehow. See the steps in https://arduino.stackexchange.com/a/13293/6628

---
Tags: arduino-uno, power, uploading
---


# Question
Title: Digital Input with long cable - flickering values
I have an Arduino Nano with two attached Motion sensors **"PIXNOR HC-SR501"**. This sensor puts 5V on its middle Pin, when it detects motion. I have connected this Pin to my Arduino and read the value with `digitalRead`

Here is the simplified code of my loop:

```
void loop() {
    motion1 = digitalRead(motion_pin1);
    motion2 = digitalRead(motion_pin2);

    if(motion1== HIGH) {
      if(debug){
        Serial.println("Motion 1");
      }
    }
    if(motion2== HIGH) {
      if(debug){
        Serial.println("Motion 2");
      }
    }

    // Wait 1,0 Second
    Sleepy::loseSomeTime(1000);
  }

```

Problem is... This used to work fine, but I had to extend the cable to the motion sensors from ~10 cm to 500 cm. Now I have the problem, that the Arduino sometimes (quite often) detects voltage on the motion pins, although there is no motion. I guess the Input-pins are is too sensitive? **What can I do to prevent this flickering?**

# Answer
That device (datasheet) puts out 3.3V on the OUT pin, not 5V:

> ◦ TTL output: 3.3V, 0V

The excess cable is most likely picking up EMI and creating spurious pulses on the input. There are two basic ways of combating this:

1. Increase the drive strength (especially the sink capacity) of the output
2. Implement a balanced line communication system

You can combine both those quite easily, whilst at the same time boosting the output voltage to 5V using a 74HCT04 hex inverter chip (make sure it's the HCT variant). Powered from 5V it will boost the logic level from 3.3V to 5V, and it will have a greater drive strength than the PIR chip alone.

Then the trick is to use multiple gates in the right way to make a crude balanced line system:

Basically you're double-inverting the signal so it remains the same logic level (high = high, low = low) but has higher drive strength, and you're also single-inverting the signal so it has inverted logic (high = low, low = high). You then connect those to two different IO pins on the Arduino. Read both pins (instead of just one) and as long as the signal are opposite (Q = HIGH and !Q == LOW) then you have a valid signal. If both signals are HIGH then you have noise and you can ignore it.

You also need to ensure you select the right kind of cable. Ideally you need a cable with at least one twisted pair in it so that the Q and !Q signals are twined around each other. This ensures that if EMI is induced into the wire it's induced into both signals equally. CAT5 Ethernet cable is often quite a good choice.
> 3 votes

---
Tags: sensors, arduino-nano, input
---


# Question
Title: Why doesn't interrupt TIMER0_COMPA work with loops?
I need have two stepping motors working at the same time each with a different number of steps. But loops (`for`, `while`) don't work with this task using type of interrupt above. What is wrong?

My code:

```
class Driver {
    int pinStep;
    long times;
    int state;
    unsigned long previousTime;

  public:
    Driver(int pin, long interval) {
      pinStep = pin;
      pinMode(pinStep, OUTPUT);
      times = interval;
      state = LOW;
      previousTime = 0;
    }

    void update(unsigned long currentTime) {
      int iteration;
      while ((iteration < 5) & (currentTime - previousTime >= times)) {
        previousTime = currentTime;
        if (state == LOW) {
          state = HIGH;
        } else {
          state = LOW;
        }
        digitalWrite(pinStep, state);
        iteration++;
      }
    }
};

Driver drv1(5, 2);
Driver drv2(7, 50);

// set timer behavior
void setup() {
  OCR0A = 0x80; // 128
  TIMSK0 |= _BV(OCIE0A);
}

// interrupt handler
SIGNAL(TIMER0_COMPA_vect) {
  unsigned long currentTime = millis();
  drv1.update(currentTime);
  drv2.update(currentTime);
}

void loop() {
}

```

# Answer
> 1 votes
```
void update(unsigned long currentTime) {
      int iteration;
      while ((iteration < 5)

```

Your code take a variable with an undefined value (`iteration`) and loops while it is less than 5. How is this useful? Perhaps set iteration to zero:

```
      int iteration = 0;

```

---

> But cycles (for, while) don't work with this task using type of interrupt above.

Please define what "don't work" means here. It does too much? Too little? Nothing at all?

---

> And Serial.print prints out iteration value as "111111"

The only way that could happen is if `currentTime - previousTime >= times` is false. Which it would be.

```
  while ((iteration < 5) & (currentTime - previousTime >= times)) {

```

Do you mean: `currentTime - previousTime < times`?

---
Tags: c++, interrupt
---


# Question
Title: Aurduino Mega prototype board connectors
Might someone shed some light on the 52 pin connectors on the end of the prototype board? Both boards have no 52 pin female connectors, the board that doesn't include the breadboard wire has a male connector that is not 52 pins. The female connectors are hard to find. I've only looked on Ebay.

Thanks

\]

# Answer
I presume the pictured board has pins underneath (like an Arduino shield). It would be designed so you can stack more than one on top of each other.
> 1 votes

---
Tags: arduino-mega
---


title: Piezo not making sound

text:
# Question
Title: Piezo not making sound
I've used the piezo on other projects with no problem, but for some reason this project isn't working out so hot.

Here's a photo of my current set up.

Here's the basic code that I presumed would make a sound, but no such luck.

```
void setup() {}

void loop() {
  tone(12,260);
  delay(10);
}

```

Not sure where to begin debugging this...

# Answer
> 4 votes
As Majenko pointed out, the wires are not connected to the piezo. By moving the piezo to the correct rails on the other side of the board, the circuit would be completed and the piezo should work.

**Edit:** Building on Nick Gammon's comment, the rows of each side of a breadboard are not connected (to allow DIP packages).

---
Tags: arduino-uno, piezo
---


title: LCD not working with Arduino Uno

text:
# Question
Title: LCD not working with Arduino Uno
I am a new learner on Arduino. I am trying to learn how to control the LCD. I looked in the article, "Hello World!", and followed the instructions but it did not work (I checked it many times). The result I got is shown below (the text is not showing).

Please help me. Any help is appreciated.

Here is my code:

```
    #include <LiquidCrystal.h>
    LiquidCrystal lcd(12, 11, 5,4,3,2);

    void setup() {
      // set up the LCD's number of columns and rows:
     lcd.begin(16, 2);

    lcd.print("hello, world!");
    }

    void loop() {
      // set the cursor to column 0, line 1
      // (note: line 1 is the second row, since counting begins with 0):
      lcd.setCursor(0, 1);
      // print the number of seconds since reset:
      lcd.print(millis() / 1000);
    }

```

# Answer
There are 3 things you can try.

**1.** If you have any male pins, solder those to the lcd screen, then stick it in the breadboard. After that you can stick the wires in the breadboard appropriately. The first time I tried this the wires were either touching or not connected enough to the lcd screen.

**2.** Double check all the connections made. This also happened to me, just make sure all the wires are in their right places.

**3.** Have you tried adjusting the potentiometer? Thats what its there for. Try turning it **slowly** both directions to adjust the background and letter brightness.

From the looks of the picture, number 3 may be your problem. Try that step first, and if it doesn't work you can try the other two. Hope this helps!
> 0 votes

---
Tags: arduino-uno, lcd
---


title: A simple login page on Arduino Uno

text:
# Question
Title: A simple login page on Arduino Uno
I'm trying to setup home automation system controlled with webpage stored in SD card of Arduino, I was thinking if it was possible to set a login page, only combination of correct user id & password will be able to access the control page.

# Answer
I have a page about a tiny web server for the Arduino Uno or similar boards. It simply isn't true that you can't make one, or that a much more powerful processor would be better. There are *some* limitations imposed by small amounts of RAM, but the library described there decodes incoming HTTP information "on the fly" so it can handle a reasonably large page.

You could put the data to be display into PROGMEM (more information here) or onto an SD card as someone suggested.

The login and password could be stored in EEPROM.
> 3 votes

# Answer
~~Arduino cannot run a web server so it is not possible to do what you want with just using an Arduino board?.~~ It seems we can run a web server, look at the answer by @Nick Gammon below.

By using a wifi shield and connecting to a local or public web server where your page is hosted you should be able to to do it.

Don't expect to load a full fledged page on an Arduino you have to try posting a few post and get requests to get this working. It will look like a terminal based login.

What is the control page you are trying to do?

If you are ok with spending more money try using a Raspberry pi + Arduino combination.
> 2 votes

# Answer
Have you tried to change Arduino Uno board to Arduino Yun board? Yun has a Linux distribution onboard and you can easy configure a web page to control physical objects.

**Here some examples:** http://scuola.arduino.cc/lesson/b4EoRkV/Arduino\_Yn\_Intro\_to\_web\_server https://github.com/mat-lo/yun-examples
> 1 votes

# Answer
I guess you could do it with Javascript and HTML, and put the pages in the micro SD card.

But it will make it harder (if not impossible) to make the automation.
> -1 votes

# Answer
Make simple webpage and put it in sd card. If it's just one page with few buttons and bit js even flash memory of controller would suffice.

In arduino code add lines that can detect click on particular button of webpage and control relay/motor etc.

Knowledge of basic post request using js can help. You can't implement php page in arduino as it needs complex processing at arduino side
> -1 votes

---
Tags: arduino-uno, ethernet, web-server
---


title: int not declared in this scope

text:
# Question
Title: int not declared in this scope
This posting contains 2 sketches. the analogmux1 compiles successfully. Concerning analogmuvvolts sketch an error stating updateMux1 was not declared in this scope results. The int Mux1\_State \[8\] = 0: is defined exactly the same in both however the error results.

I'm learning Arduino programming so there are other errors in the sketch. What I'm trying to accomplish is to display the actual voltage of each channel, not numbers which appear in the analogMux.

It would be appreciated if the community could provide me with some guidance.

Analogmux:

```
int pin_Out_S0 = 8;
int pin_Out_S1 = 9;
int pin_Out_S2 = 10;
int pin_In_Mux1 = A0;
int Mux1_State[8] = {0};

void setup() {
  pinMode(pin_Out_S0, OUTPUT);
  pinMode(pin_Out_S1, OUTPUT);
  pinMode(pin_Out_S2, OUTPUT);
  //pinMode(pin_In_Mux1, INPUT);
  Serial.begin(9600);
}

void loop() {
  updateMux1();
  for(int i = 0; i < 8; i ++) {
    if(i == 7) {
      Serial.println(Mux1_State[i]);
    } else {
      Serial.print(Mux1_State[i]);
      Serial.print(",");
    }
  }
}

void updateMux1 () {
  for (int i = 0; i < 8; i++){
    digitalWrite(pin_Out_S0, HIGH && (i & B00000001));
    digitalWrite(pin_Out_S1, HIGH && (i & B00000010));
    digitalWrite(pin_Out_S2, HIGH && (i & B00000100));
    Mux1_State[i] = analogRead(pin_In_Mux1);
  }
}

```

And analogmuxvolts

```
int pin_Out_S0 = 8;
int pin_Out_S1 = 9;
int pin_Out_S2 = 10;
int pin_In_Mux1 = A0;
int Mux1_State[8] = {0};
//float Mux1_State[i] =0;
int RawValue=0;
float Voltage = 0;
void setup() {
  pinMode(pin_Out_S0, OUTPUT);
  pinMode(pin_Out_S1, OUTPUT);
  pinMode(pin_Out_S2, OUTPUT);
  pinMode(pin_In_Mux1, INPUT);
  Serial.begin(9600);
}

void loop() {
 RawValue = analogRead(pin_In_Mux1);
 Voltage = (RawValue * 5.0) / 1024; //scale the ADC
  updateMux1();
  Serial.println(Mux1_State);
  for(int i = 0; i < 8; i ++) {
    if(i == 7) {
      Serial.println(Mux1_State[i]);
    } else {
      Serial.print(Mux1_State[i]);
      Serial.print(",");
      //vout = (value * 5.0) / 1024.0;
    }
  }
  Serial.print("Raw  Value = " );
  Serial.print(RawValue);
}

```

# Answer
Declare the updateMux() function by copying it from your first sketch into your second sketch:

```
void updateMux1 () {
  for (int i = 0; i < 8; i++){
    digitalWrite(pin_Out_S0, HIGH && (i & B00000001));
    digitalWrite(pin_Out_S1, HIGH && (i & B00000010));
    digitalWrite(pin_Out_S2, HIGH && (i & B00000100));
    Mux1_State[i] = analogRead(pin_In_Mux1);
  }
}

```

And do the conversions on the stored Mux1\_State\[\] values during printing like:

```
  for(int i = 0; i < 8; i ++) {
    Serial.println(Mux1_State[i]*5.0/1024.0);
    if(i == 7) {
       Serial.println();
    } else {
       Serial.print(",");
    }
  }

```
> 1 votes

---
Tags: programming
---