title: digitalWrite queued signals?

text:
# Question
Title: digitalWrite queued signals?
I have this simple code who send a signal to a android phone when I press a button:

```
const int botonPinD = 8;
const int relayPin =  12;
int retardo = 100;
int finBoton=1000;

void setup() {
  pinMode(relayPin, OUTPUT);

  pinMode(botonPinA, INPUT);
  pinMode(botonPinB, INPUT);
  pinMode(botonPinC, INPUT);
  pinMode(botonPinD, INPUT);
}
void loop(){
    botonD = digitalRead(botonPinD);
    if (botonD == HIGH){
   // for simplicity remove botonA, botonB and botonC code, but it's the same with a few digitalWrite
        digitalWrite(relayPin, HIGH);
        delay(retardo);
        digitalWrite(relayPin, LOW);
        delay(retardo);
        digitalWrite(relayPin, HIGH);
        delay(retardo);
        digitalWrite(relayPin, LOW);
        delay(retardo);
        digitalWrite(relayPin, HIGH);
        delay(retardo);
        digitalWrite(relayPin, LOW);
        delay(retardo);
        digitalWrite(relayPin, HIGH);
        delay(retardo);
        digitalWrite(relayPin, LOW);
        delay(retardo);
        delay(finBoton);
      }
      else{
        digitalWrite(relayPin, LOW);
      }
}

```

But if I press the button fast (maybe a half a second between clicks) I only receive once the signal.

I'm not very sure about what's happened here (I'm an Arduino newbie). The first signal, has it locked the channel? Can signals be queued? Can I control the way that they are queued?

# Answer
The code below is closer to what you seem to be asking about:

```
// For Mega2560

const int BUTTONS = 4;
const int FIRST_SWITCH = 18;
const int FIRST_RELAY =  41;
const int CLICKS = 5;
const unsigned long DEBOUNCE_TIME = 20;  // ms

int retardo  = 300;
int finBoton = 1000;

volatile byte counts [BUTTONS];
unsigned long lastPress [BUTTONS];

void doInterrupts (const int which)
 {
 // debounce
 if (millis () - lastPress [which] < DEBOUNCE_TIME)
   return;

 lastPress [which] = millis ();
 counts [which]++;
 }  // end of doInterrupts

void pin18Pressed ()
  {
  doInterrupts (0);
  }  // end of pin18Pressed

void pin19Pressed ()
  {
  doInterrupts (1);
  }  // end of pin19Pressed

void pin20Pressed ()
  {
  doInterrupts (2);
  }  // end of pin20Pressed

void pin21Pressed ()
  {
  doInterrupts (3);
  }  // end of pin21Pressed

void setup()
  {
  // configure inputs / outputs
  for (int i = 0; i < BUTTONS; i++)
    {
    pinMode (FIRST_SWITCH + i, INPUT_PULLUP);
    pinMode (FIRST_RELAY + i, OUTPUT);
    }

  attachInterrupt (5, pin18Pressed, FALLING);
  attachInterrupt (4, pin19Pressed, FALLING);
  attachInterrupt (3, pin20Pressed, FALLING);
  attachInterrupt (2, pin21Pressed, FALLING);

  } // end of setup

// turn relay on for a particular switch
void handleSwitchPress (const int which)
  {
  for (int i = 0; i < CLICKS; i++)
  {
    digitalWrite(FIRST_RELAY + which, HIGH);
    delay(retardo);
    digitalWrite(FIRST_RELAY + which, LOW);
    delay(retardo);
  }
  delay(finBoton);
  } // end of handleSwitchPress

// main loop
void loop()
  {
 for (int i = 0; i < BUTTONS; i++)
   if (counts [i] > 0)
     {
     handleSwitchPress (i);
     counts [i]--;
     }
  }  // end of loop

```

---

I'll explain parts of it from above:

### Interrupts

To queue up switch presses we can use an interrupt. The Mega has quite a few external interrupts (See: attachInterrupt()) so I'll use those. You can read about interrupts on my page about interrupts.

This code attaches four interrupts handlers:

```
  attachInterrupt (5, pin18Pressed, FALLING);
  attachInterrupt (4, pin19Pressed, FALLING);
  attachInterrupt (3, pin20Pressed, FALLING);
  attachInterrupt (2, pin21Pressed, FALLING);

```

Because of the way the hardware works we have to use pins 18, 19, 20 and 21 (there are a couple more but these are in sequence).

I set the switches to be INPUT\_PULLUP so that they are normally HIGH when not pressed, and go LOW when you press them. Hence the interrupts are looking for a FALLING edge.

---

### Handle one interrupt

An interrupt handler is like this:

```
void pin18Pressed ()
  {
  doInterrupts (0);
  }  // end of pin18Pressed

```

Since they all do much the same thing I put all of the switch management into one function and used an array of switches, like this:

```
volatile byte counts [BUTTONS];
unsigned long lastPress [BUTTONS];

void doInterrupts (const int which)
 {
 // debounce
 if (millis () - lastPress [which] < DEBOUNCE_TIME)
   return;

 lastPress [which] = millis ();
 counts [which]++;
 }  // end of doInterrupts

```

In order to "queue" presses the interrupt handler adds one to a counter, for that array item. (So, pin 18 is position 0, pin 19 is position 1 and so on).

---

### Debouncing

Debouncing of the switches is done by ignoring multiple presses in quick succession:

```
 // debounce
 if (millis () - lastPress [which] < DEBOUNCE_TIME)
   return;

 lastPress [which] = millis ();

```

---

### Handling a queued press

Now in the main loop we just check if the counter has gone up, for each switch:

```
 for (int i = 0; i < BUTTONS; i++)
   if (counts [i] > 0)
     {
     handleSwitchPress (i);
     counts [i]--;
     }

```

If so, we call `handleSwitchPress` which toggles the relay for the desired number of times.

---

### Code for Uno

If you are using a Uno instead of a Mega2560 you don't have four external interrupts. The alternative version below uses *pin change interrupts* instead of external interrupts.

Pin change interrupts work on all pins of the Uno, however they are in batches of three: Pins A0 to A5, pins D0 to D7 and pins D8 to D13. In the code below I use pins 2, 3, 4 and 5 which are in the batch D0 to D7.

With a pin-change interrupt you only get notification of a *change* to the pin, so the code has to detect whether the pin changed from high to low or low to high.

```
// For Atmega328 (eg. Uno)

const int BUTTONS = 4;
const int FIRST_BUTTON = 2;
const int FIRST_RELAY =  8;
const int CLICKS = 5;
const unsigned long DEBOUNCE_TIME = 20;  // ms

int retardo  = 300;
int finBoton = 1000;

volatile bool oldState [BUTTONS];
volatile byte counts [BUTTONS];
unsigned long lastPress;

// handle pin change interrupt for D0 to D7 here
ISR (PCINT2_vect)
 {

 // debounce
 if (millis () - lastPress < DEBOUNCE_TIME)
   return;

 lastPress = millis ();

 // check each switch
 for (int i = 0; i < BUTTONS; i++)
   {
   byte state = digitalRead (FIRST_BUTTON + i);
   if (state != oldState [i])
     {
     oldState [i] = state;  // detect state changes
     if (state == LOW)
       counts [i]++;
     }   // end of state change
   }  // end of for each button

 }  // end of PCINT2_vect

void setup()
  {

  // configure inputs / outputs
  for (int i = 0; i < BUTTONS; i++)
    {
    pinMode (FIRST_BUTTON + i, INPUT_PULLUP);
    oldState [i] = HIGH;
    pinMode (FIRST_RELAY + i, OUTPUT);
    }

  // pin change interrupt (example for D9)
  PCMSK2 |= bit (PCINT18) | bit (PCINT19) | bit (PCINT20) | bit (PCINT21);  // want pins 2, 3, 4, 5
  PCIFR  |= bit (PCIF2);   // clear any outstanding interrupts
  PCICR  |= bit (PCIE2);   // enable pin change interrupts for D0 to D7
  } // end of setup

// turn relay on for a particular switch
void handleSwitchPress (const int which)
  {
  for (int i = 0; i < CLICKS; i++)
  {
    digitalWrite(FIRST_RELAY + which, HIGH);
    delay(retardo);
    digitalWrite(FIRST_RELAY + which, LOW);
    delay(retardo);
  }
  delay(finBoton);
  } // end of handleSwitchPress

// main loop
void loop()
  {
 for (int i = 0; i < BUTTONS; i++)
   if (counts [i] > 0)
     {
     handleSwitchPress (i);
     counts [i]--;
     }
  }  // end of loop

```
> 1 votes

# Answer
The main problem I guess you are suffering from is the good old `delay()` blockage.

`delay()` is a terrible function and should be avoided at all costs. Nothing at all can happen while you are running `delay()` \- that means you can't be reading the state of your button - until all your `delay()` calls have finished.

If you want to queue the pressed of the button you will need to do three things:

1. You will need to recognise when the button changes from LOW to HIGH, not just "when it is HIGH" as you do now.
2. You will have to queue that button press somewhere. The simplest way is to maintain a count of how many times the button has been pressed.
3. You will have to process any pending button presses ("while the count \> 0") by triggering your output with the right timing without using `delay()`, which means using `millis()` and maintaining state information.
> 2 votes

---
Tags: programming, arduino-mega, c++, signal-processing
---


title: How to do a software reset on MAX7456?

text:
# Question
Title: How to do a software reset on MAX7456?
I messed around with the MAX7456 chip for a while, even the character set updating sketch seemed to work after a few modifications. But now it is not displaying anything with the Hello World sketch that worked before. No signal seems to pass through it, the screen is just black.

The datasheet says that one must write Video Mode 0 Register (VM0) at address 00H bit 1 to 1 via SPI to reset it, how would I do it? Also, how would one verify that the chip indeed did reset itself and responds to the commands given to it afterwards? (The board looks like this)

# Answer
The datasheet says:

> The SPI commands are 16 bits long with the 8 most significant bits (MSBs) representing the register address and the 8 least significant bits (LSBs) representing the data ...

Thus, you need to write address / data after selecting the chip.

```
digitalWrite (SS, LOW);  // select the chip
SPI.transfer (0x00);     // select address 0x00 (Video Mode 0)
SPI.transfer (bit (1));  // write bit 1 (Software Reset Bit)
digitalWrite (SS, HIGH); // done

```

According to the datasheet you need to wait around 20 µs for the operation to complete. You could, of course, just wait 20 µs but it might be nice to see if the bit gets cleared.

```
  byte result;

  do
    {
    digitalWrite (SS, LOW);      // select the chip
    SPI.transfer (0x80);         // select address 0x00 (Video Mode 0) - read mode
    result = SPI.transfer (0);   // read it
    digitalWrite (SS, HIGH);     // done
    } while (result & bit (1));  // loop while not reset yet

```

---

> Also, how would one verify that the chip indeed did reset itself and responds to the commands given to it afterwards?

I'm not sure, without the chip in hand, what other tests you can make, but if you added a counter into the above loop, you could probably verify that it was doing something. eg.

```
  // reset chip
  digitalWrite (SS, LOW);  // select the chip
  SPI.transfer (0x00);     // select address 0x00 (Video Mode 0) - write mode
  SPI.transfer (bit (1));  // write bit 1 (Software Reset Bit)
  digitalWrite (SS, HIGH); // done

  byte result;
  unsigned int counter = 0;

  // wait for it to become ready, or time-out
  do
    {
    digitalWrite (SS, LOW);      // select the chip
    SPI.transfer (0x80);         // select address 0x00 (Video Mode 0) - read mode
    result = SPI.transfer (0);   // read it
    digitalWrite (SS, HIGH);     // done
    if ((result & bit (1)) == 0)
      counter++;     // count times not ready
    } while ((result & bit (1)) && (counter < 1000) );  // loop while not reset yet

  if (counter == 0 || counter >= 1000)
    {
    // chip does not seem to be responding
    }
  else
    {
    // all OK!
    }

```
> 1 votes

---
Tags: atmega328
---


title: Does Anemometer consumes power?

text:
# Question
Title: Does Anemometer consumes power?
I planning to add an anemometer to my small solar weather station. I designed this system to run from a single 3.7v rechargeable battery and a solar panel so I have to calculate in more power drain.

What I don't really understand is do these anemometers consume any external power or just give out a voltage by themselves?

This one doesn't even have consumption specified:

https://www.adafruit.com/products/1733

For this Supply voltage : 5V - 24VDC:

http://www.ebay.com/itm/JL-FSX2-4-20MA-0-5V-Output-Wind-Speed-Sensor-Wind-Speed-Transmitter-Anemometer-/331521148973?hash=item4d3033482d

# Answer
> 1 votes
If it runs on electricity it definitely consumes power, its only how much the real question is.

Since you are working with electronics I am going to assume that you have a multimeter, if you dont have one. Its about time you did, doesnt cost much and will save you a ton of time debugging.

Nearly every multimeter has an onboard ammeter (the accuracy will be mentioned in the instructions manual). You can use this to determine the current consumed, have a look at a tutorial from sparkfun on how to do this

---
Tags: arduino-uno, power, solar
---


title: Optimizing an Arduino code

text:
# Question
Title: Optimizing an Arduino code
I am working on project and using Arduino Pro Mini (Atmega328p running on 2xAA) to measure the time to charge a capacitor (when the volt level is high). This is the code I used while testing:

```
int counter = 0;

// Charge the capacitor
digitalWrite(8,HIGH);

while (digitalRead(7) == LOW) {
    counter = counter +1;
    if (counter > 250) {
        break; // CHARGING FAILED!
    }
}

```

The code was working fine when the board was running at 16MHz since the loop was fast enough to give good result. ( counter =~ 28 when the test cap is charged).

However, the intention is to run the system on a battery with clock of 1MHz (to reduce power consumption) and when tested at that speed the counter only reaches 2~3 because the loop it too slow now that the cap will charge in about two to three cycles.

So I did two changes which are using byte instead of int for the counter, and reading the value of the pin directly from the PIND register:

```
byte counter = 0;

// Charge the capacitor
digitalWrite(8,HIGH);

while ((PIND & (1<<PD7)) == 0) {
    counter = counter +1;
    if (counter > 250) {
        break; // CHARGING FAILED!
    }
}

```

Both of these changes increased the speed and now counter reads ~20 which is much better and almost close to the 16MHz.

Is there any further optimizations?

Can I use one of the general registers instead of the counter, if yes then how? and will that improve the speed?

Is there a more clever and faster way to do this loop?

---

* Update:

I am going to follow the suggested answer and use the analog comparator, but I also wanted to add to my finding which might help others with general optimization.

Instead of incrementing the counter and comparing if it is larger than some value, it is faster to decrements and compare if it is equal to zero. The counter improved to ~23.

# Answer
> 3 votes
It looks like Ignacio Vazquez-Abrams and I have been doing similar things. :)

I have a page about making a capacitor tester:

Turn your Arduino into a capacitor tester

However since link-only replies are frowned on (the link might go down) I'll summarize it here.

The simple approach is to charge the capacitor until it reaches 63.2% of the charging voltage.

That is because:

```
1 - e^(-1) = 0.63212

```

See RC Time constant - Wikipedia.

We can use the Analog Comparator to trigger an interrupt when the voltage reaches that level.

We need the capacitor to be on pin D6 on the Uno and a reference voltage on pin D7.

See Using the Arduino Analog Comparator for more details about the Analog Comparator.

This is much faster than using analogRead, because it triggers on an exact voltage.

Your basic objective is to find how long it takes to reach 63.2% of the supplied voltage (in the example being 1 volt):

In this particular example it took 47 µs for a 47 nF capacitor:

Instead of using an exact reference voltage (ie. 63.2% of 5 volts) you can do some fancy maths instead. Here is my test circuit:

*DUT = Device Under Test*

We plug the values of the resistors into the code like this:

```
const float Rc = 10000;    // charging resistor
const float R1 = 1000;     // between ground and D7
const float R2 = 1800;     // between +5V and D7
const float clockRate_us = 16;  // 16 MHz
const float k = 1000 / (clockRate_us * Rc * log ((R1 + R2) / R2));

```

**Note**: For high accuracy you should use the *measured* resistance values, not just the nominal ones.

---

Now with some fairly simple code we can use the constant **k** to work out the capacitance:

```
/*
Capacitance meter

Author: Nick Gammon
Date:   2 July 2013

Pulse pin (D2): Connect to capacitor via 10K resistor (Rc)

Reference voltage connected to D7 (AIN1) as per below.

Measure pin (D6 - AIN0) connected to first leg of capacitor, other leg connected to Gnd.

Like this:

Capacitor to test:

D2  ----> Rc ----> D6 ----> capacitor_under_test ----> Gnd

Reference voltage:

+5V ----> R2 ---> D7 ---> R1 ----> Gnd

*/

const byte pulsePin = 2;   // the pin used to pulse the capacitor
const float Rc = 10000;    // charging resistor
const float R1 = 1000;     // between ground and D7
const float R2 = 1800;     // between +5V and D7
const float clockRate_us = 16;  // 16 MHz

const float k = 1000 / (clockRate_us * Rc * log ((R1 + R2) / R2));

volatile boolean triggered;
volatile boolean active;

volatile unsigned long timerCounts;
volatile unsigned long overflowCount;

ISR (TIMER1_OVF_vect)
{
  ++overflowCount;               // count number of Counter 1 overflows
}  // end of TIMER1_OVF_vect

ISR (TIMER1_CAPT_vect)
  {
  // grab counter value before it changes any more
  unsigned int timer1CounterValue;
  timer1CounterValue = ICR1;  // see datasheet, page 117 (accessing 16-bit registers)
  unsigned long overflowCopy = overflowCount;

  if (active)
    {
    // if just missed an overflow
    if ((TIFR1 & bit (TOV1)) && timer1CounterValue < 0x7FFF)
      overflowCopy++;
    // calculate total count
    timerCounts = (overflowCopy << 16) + timer1CounterValue;  // each overflow is 65536 more
    triggered = true;
    digitalWrite (pulsePin, LOW);  // start discharging capacitor
    TCCR1B = 0;    // stop the timer
    }  // end if active
  }  // end of TIMER1_CAPT_vect

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

  Serial.begin (115200);
  Serial.println ("Started.");
  ADCSRB = 0;           // (Disable) ACME: Analog Comparator Multiplexer Enable
  ACSR = bit (ACIC);    // Analog Comparator Input Capture Enable
  DIDR1 |= bit (AIN1D) | bit (AIN0D); // Disable digital buffer on comparator inputs
  PRR = 0;
  }  // end of setup

void startTiming ()
  {
  active = true;
  triggered = false;
  noInterrupts ();

  // prepare timer
  overflowCount = 0;            // no overflows yet
  // reset Timer 1
  TCCR1A = 0;
  TCCR1B = 0;
  TCNT1 = 0;      // Counter to zero
  // Timer 1 - counts clock pulses
  TIMSK1 = bit (TOIE1) | bit (ICIE1);   // interrupt on Timer 1 overflow and input capture

  // get on with it
  digitalWrite (pulsePin, HIGH);  // start charging capacitor
  // start Timer 1, no prescaler
  TCCR1B =  bit (CS10) | bit (ICES1);  // plus Input Capture Edge Select
  interrupts ();

  } // end of startTiming

void finishTiming ()
  {
  active = false;
  Serial.print ("Capacitance = ");
  float capacitance = (float) timerCounts * k;
  Serial.print (capacitance);
  Serial.println (" nF");
  triggered = false;
  delay (3000);
  }  // end of finishTiming

void loop ()
  {
  // start another test?
  if (!active)
    startTiming ();

  // if the ISR noted the time interval is up, display results
  if (active && triggered)
    finishTiming ();

  }  // end of loop

```

---

For extra accuracy the code uses the Input Capture Unit, which is something that remembers the exact value in Timer 1 when the match occurs. This avoids the delay of 2 to 3 µs while the ISR kicks into action.

---

### Results

I measured a few values using a capacitance-substitution box. To check on the box I measured also with a high-precision multimeter. The value on the right is what the sketch gave (rounded).

*(All values in nF)*

```
Nominal    Meter     Sketch
Value      Measure   Measure

    40         42        42
   100         98       102
   200        202       201
   300        312       313
   400        389       391
  1000       1004      1010
  2000       2011      2012
  3000       2950      2953
  4000       4160      4170

```

The sketch output certainly seems to be close to the nominal and measured values.

---

> What about using the internal voltage reference (1.1v) instead of AIN0? which one will be better as the 2xAA batteries voltage drops over time?

The voltage doesn't matter as it is not in the equation. It is the **ratio** that matters, and that will scale with battery drop (ie. the ratio between the two resistors will always be the same).

You need to use Vcc because it is turned on and off at an output pin (to start charging the capacitor).

---

> Also what is the difference between TIMER1\_CAPT\_vect which you used here and ANALOG\_COMP\_vect which you used in the example in your site?

If you are **not** using the Input Capture Unit, then you need to get the Analog Comparator interrupt. However if you use the Input Capture Unit then you use the Timer1 Capture Event which is triggered when you get the capture.

# Answer
> 2 votes
Get rid of the loop altogether. Instead of twiddling and checking bits manually, use timer 1 to trigger the output and capture the input.

If you perform the output on pin 10 and the input on pin 8 then you can use timer 1's output compare to send the pulse out and its input capture to detect when the capacitor has charged.

Untested:

```
#include <avr/interrupt.h>

void setup(void)
{
  cli();
  DDRB |= _BV(PB2); // Configure OC1B as output
  TCCR1B &= ~(_BV(CS12) | _BV(CS11) | _BV(CS10)); // Stop timer 1
  TCNT1 = 0; // Initialize timer count
  OCR1A = 0xffff; // Reset the timer at this count
  OCR1B = 0xf000; // Upper limit of the timed value, plenty of time before timer reset
  ICR1 = 0xff00; // Set to an invalid initial value
  TCCR1A = _BV(COM1B1); // Trigger output at 0, clear at upper limit
  TCCR1B = _BV(ICES1); // Capture on leading edge
  TCCR1B |= _BV(WGM13) | _BV(WGM12); // High bits for 16-bit fast PWM
  TCCR1A |= _BV(WGM11) | _BV(WGM10); // Low bits for 16-bit fast PWM
  TIMSK = _BV(ICIE1) | _BV(OCIE1B); // Enable input capture and limit interrupts
  sei();
  TCCR1B |= _BV(CS10); // Start the timer at its highest clock speed
}

ISR(TIMER1_CAPT_vect)
{
  TIMSK &= ~(_BV(ICIE1) | _BV(OCIE1B)); // Disable input and limit interrupts
  TCCR1B &= ~(_BV(CS12) | _BV(CS11) | _BV(CS10)); // Stop the timer
  PORTB &= ~_BV(PB2); // Kill the charging output
  // Check ICR1 for the captured value
}

ISR(TIMER1_COMPB_vect)
{
  if (ICR1 == 0xff00)
  {
    // WELL CRAP, charging is taking too long
    // Maybe try with a slower clock?
  }
}

void loop()
{
  // Do other stuff
}

```

---
Tags: avr
---


# Question
Title: Issue with CD74HC4067 MUX on high values
I'm having a small issue with the CD74HC4067 multiplexer/demultiplexer: I am using it to receive data from an array of sensors (at the moment I have only 2, but in a near future they will grow). Specifically I have a light sensor and a sound sensor.

Mux output is connected to A0 since the readings I do are analog. The pins I use to switch the channels are A3 and A2 (when the other sensors will arrive also A1 will be dedicated to that).

My problem is that when switching between one channel and another, my readings highly fluctuate, but only when the reading value is \> 500 or so, and I don't understand why. In a simple sketch I've tried adding some delay (40 msec) and the issue goes away. But in my project which is far more complex and uses also other analog channels I need a delay of ~1 second to get a correct reading, which is absolutely unacceptable since I need it to run in real-time(ish). I also tried using the digital pins to control the mux but to no avail. The only thing that seems to stabilize everything is connecting a capacitor between the MUX out and ground, and using a 20msec delay, but it only works for a bit.

I hope I've been clear enough and that someone can point me the right way!

EDIT:

Here is the schematic

(Error in the drawing: "temp" is actually a "light sensor" as in the bottom of the post...)

And my code:

```
#define MUX A0
#define S0 A2
#define S1 A3

void setup() {
  Serial.begin(9600);
  pinMode(S0, OUTPUT);
  pinMode(S1, OUTPUT);

  selectMux(1);
}

void loop() {

  //selectMux(0);
  //Serial.println(analogRead(MUX));
  //selectMux(1);
  Serial.println(analogRead(MUX));

}

void selectMux(byte port) {
//  pinMode(MUX, mode);
  int r0 = bitRead(port, 0);
  int r1 = bitRead(port, 1);

  digitalWrite(S0, r0);
  digitalWrite(S1, r1);
  analogRead(MUX);
}

```

the `analogRead(MUX)` in the selectMux function was added because I read in a post that they suggested to do that in order to get a more accurate reading. With this code only the results already fluctuate:

```
Output:
76
41
77
76
76
75
36
75
74
76
77
106
76
76
76
76

```

but it goes crazy when the input is higher, close to 5V:

```
Output:
948
780
340
948
948
635
437
949
948
499
551
949
950
396
684
950

```

If you enable the commented code that starts to switch the outputs it is even worse. As I said, adding delays helps, but in my final application I cannot afford to have 1s delays.

I also show that in the circuit there is a timer that uses other Analog pins, but in the code I didn't include that part. If you need I'll add that too.

Sound Sensor, Light Sensor

# Answer
> 2 votes
I don't think you should leave s2 and s3 floating. A floating pin does not mean nor 0 nor 1.

Connect them both to ground.

---
Tags: arduino-uno, analogread, multiplexer
---


# Question
Title: Computer not detecting my Arduino MEGA 2560 R3
I've tried different USB cables, computers, ports and none of them can detect my possibly bricked Mega 2560 R3. Nothing shows up at all in the Device Manager, not even "Unknown Device".

When the board is plugged in via USB, the "L" LED is constantly lit as well as the "ON" LED next the reset button.

I came up on this article here and I gave it a try, which I believe is putting it in DFU mode. However I'm not having any luck with this. http://www.wayneandlayne.com/blog/2011/02/16/fixing-linux-firmware-issues-on-arduino-mega-2560/

Any one have any ideas on where to go from here? I'm very new with Arduino.

# Answer
> 1 votes
If your Mega has an ICSP header for the USB chip (circled below) then you can test that chip.

You can use another Arduino (eg. a Uno) to detect the signature on that chip, as per my sketch on Sketch to detect Atmega chip types.

All you need is 6 hookup wires to connect your testing board (the known good one with the sketch on it) to the ICSP header on the Mega. Note the pin orientation. I have circled the correct header pins, and pointed to pin 1. On the board pin 1, has a small white dot.

Below are the ICSP pin names, seen from above (component side).

---

Wire the Uno to the chip being tested as follows:

```
Arduino Uno      Target chip

D10 (SS)            /RESET
D11 (MOSI)          MOSI
D12 (MISO)          MISO
D13 (SCK)           SCK

Gnd                 GND
+5V                 VCC

```

Check your wiring! If you wire things around the wrong way you can turn a good chip into a bad one.

---

**Important!** Only attempt this process if you can see that you have an ATmega8U2 or ATmega16U2 chip on your board (see below). If you have something totally different this will not work. In that case you probably have a cheap clone board.

---

Using the Serial Monitor on your Uno, you should then see something like this:

```
Atmega chip detector.
Written by Nick Gammon.
Version 1.17
Compiled on Jul  7 2015 at 10:47:47 with Arduino IDE 106.
Attempting to enter ICSP programming mode ...
Entered programming mode OK.
Signature = 0x1E 0x93 0x89
Processor = ATmega8U2
Flash memory size = 8192 bytes.
LFuse = 0xEF
HFuse = 0xD9
EFuse = 0xF4
Lock byte = 0xFF
Clock calibration = 0xAB
Bootloader in use: No
EEPROM preserved through erase: No
Watchdog timer always on: No
Bootloader is 4096 bytes starting at 1000

Bootloader:

1000: 0x4B 0xC0 0x00 0x00 0x64 0xC0 0x00 0x00 0x62 0xC0 0x00 0x00 0x60 0xC0 0x00 0x00
1010: 0x5E 0xC0 0x00 0x00 0x5C 0xC0 0x00 0x00 0x5A 0xC0 0x00 0x00 0x58 0xC0 0x00 0x00
1020: 0x56 0xC0 0x00 0x00 0x54 0xC0 0x00 0x00 0x52 0xC0 0x00 0x00 0xCB 0xC4 0x00 0x00
1030: 0x4E 0xC0 0x00 0x00 0x4C 0xC0 0x00 0x00 0x4A 0xC0 0x00 0x00 0x48 0xC0 0x00 0x00
...

```

My board had a ATmega8U2 on it, yours might have a ATmega16U2. However the concept is the same. If you see something like that, the chip is (probably) good. At least it responds to programming commands.

---

If you see something like

```
Atmega chip detector.
Written by Nick Gammon.
Version 1.17
Compiled on Jul  7 2015 at 10:47:47 with Arduino IDE 106.
Attempting to enter ICSP programming mode ......................................................
Failed to enter programming mode. Double-check wiring!
Programming mode off.

```

Then either you made a wiring error, or the chip is bad.

# Answer
> 0 votes
I have had the same symptom with a Arduino Decimilia.

In that case had the USB to Serial chip failed. I used a USB to Serial device to verify the problem

# Answer
> 0 votes
It sounds like the USB to serial chip has failed. You could test this by using another arduino or a programmer like the AVRISP mkII to load a program that way and see if it's your whole board or just the serial chip.

If the board and main chip are still good, you could just get used to uploading with this new method, or you could try to reprogram the other chip used for serial. I know it I'd possible but ever time I've burned one this hadn't help so YMMV.

# Answer
> 0 votes
Check the Chips for any solder mistake, I found that my serial chip had two pins soldered together, probably cause i bought it for cheap :D

---
Tags: arduino-mega, led
---


# Question
Title: How can I configure Arduino after programming it (for post upload wifi configuration)?
I would like to make a device that can take a photo, and send it to a website over wifi. I'm using an Arduino Uno, a ArduCam OV2640 module, and ESP8266 Serial WIFI module. Eventually I'd like to take it off the board as a stand alone project for permanent use.

The wifi works fine, but requires a serial communication to configure. I would like to make it so that I can plug the device into a computer (via something like micro usb), change the WIFI settings, and save those settings for future reboots.

If there anyway I can do this with an Arduino interface? If not, what could I use instead?

# Answer
> 0 votes
I like Gerben's suggestion about putting the ESP8266 into Wireless Access Point mode and then providing access to your configuration settings via a web interface. I've been dealing with the same question myself and this might be a workable solution. The only downside is the amount of code required to get an ESP8266 to function as a WAP, provide a web-based UI, switch between configuration and running mode, etc.

Another idea that isn't as elegant, but would require a lot less code: Just store your configuration on an SD card, and add an SD card to your project using a separate board or shield. You could edit the configuration by plugging it into a PC and editing the configuration file, then plug the card into your project which would read its configuration from the SD Card.

---
Tags: wifi, communication
---


title: problem with using String()

text:
# Question
Title: problem with using String()
I'm new to arduino and currently trying to build a small program with multiple screens and buttons and a counter. when I try to convert a int to a chararray it messes up the world. with out it what I have so far works any suggestions on what I'm doing wrong? with the code to convert the int to chararray it seems to lock up the program when I switch from main screen to options screen then back. I put some serial outs to narrow down where the flaw is.

My results are it is between

```
   test1++;  Serial.println("oops check");
   str = String(test1); Serial.println("sanity check");

```

Something hangs it up after it outputs "oops check" so I figure it is `str = String(test1);` I have been searching and trying every thing I can find. if someone can give me a kick in the right direction. I'm usin the tft seedstudio v2 display with the modified tft library for text direction.

```
   /*
  Title: TouchScreenButton Tutorial
  About: Example/tutorial file for how to create buttons with the TouchScreenButtons library
  Author: Richard Kirkpatrick
  Date: 20 July 2014
*/

// Libraries
#include <stdint.h>
#include <SeeedTouchScreen.h>  // Library for the Seeed Studio TFT Touch Shield
#include <TFTv2.h>      // Library for the Seeed Studio TFT Touch Shield
#include <TouchScreenGeometry.h> // Library for drawing geometric shapes for the touch screen
#include <TouchScreenStrings.h> // Library for drawing strings for the touch screen
#include <TouchScreenButtons.h> // Library for creating buttons for the keypad
#include <SPI.h>

//Measured ADC values for (0,0) and (210-1,320-1)
//TS_MINX corresponds to ADC value when X = 0
//TS_MINY corresponds to ADC value when Y = 0
//TS_MAXX corresponds to ADC value when X = 240 -1
//TS_MAXY corresponds to ADC value when Y = 320 -1
#define TS_MINX 890*2
#define TS_MAXX 116*2
#define TS_MINY 913*2
#define TS_MAXY 83*2

TouchScreen ts = TouchScreen(XP, YP, XM, YM);

// Global variables
String str;
Button bigButton;
Button buttons[12];
Button reset;
Button back;
int screen = 1;
int test;
int test1 = 0;
char b[5];

void setup()
{
  // Initializes the TFT library
   Tft.TFTinit();

  // Start the Serial port. Used to determine which button was pressed.
  Serial.begin(9600);
 screen = 1;

}

void loop()
{ test1++;  Serial.println("oops check");
  str = String(test1); Serial.println("sanity check");
  str.toCharArray(b,5);

  Serial.print("screen = "); Serial.print(screen );
  // A point objects holds x, y, and z coordinates
  Point p = ts.getPoint();
  p.x = map(p.x, TS_MINX, TS_MAXX, 240, 0);
  p.y = map(p.y, TS_MINY, TS_MAXY, 320, 0);

  // Determine which button was pressed
  int userInput = -1; // -1 means no button is pressed
  if (p.z > __PRESURE){
    userInput = getButtonNumber(p.x, p.y);
     Serial.print("X = "); Serial.print(p.x);
     Serial.print("\tY = "); Serial.print(p.y);
     Serial.print("\tPressure = "); Serial.println(p.z);
  }

   // Show which button was pressed on the Serial monitor

   if (userInput == 13) {
    Serial.println("Options button was pressed!");
    bigButton.buttonDisplay();
  }
   if (userInput == 15) {
    Serial.println("back button was pressed!");
    back.buttonDisplay();
  }
  else if (userInput == 14) {
    Serial.println("reset button was pressed!");
    reset.buttonDisplay();
  }

  delay(10);

if (screen == 1)  {

if (test == 1) {

    Tft.fillScreen();    }

  Serial.print("test1 =  "); Serial.println(b);      // prints "Hello String"

    // Draw reset button
   reset.setValues(75, 215, 35, 100);
  reset.draw();

 // Draw the big button
  bigButton.setValues(15, 185, 35, 130);
  bigButton.draw();
Tft.drawRectangle(40, 15, 70, 120,BLUE);

Tft.setDisplayDirect(UP2DOWN);

  Tft.drawString("Frays",100,20,2,RED);

   Tft.drawString(b,65,20, 2, BLUE);

  //Draw reset buttons text
  TouchScreenString resetText("RESET", 100, 230, 2, RED);
  resetText.drawText();
 Serial.println("a");      // prints "Hello String"

  // Draw the big button's text
  TouchScreenString bigButtonText("OPTIONS", 40, 197, 2, WHITE);
  bigButtonText.drawText();
test = 0;

}

if (screen == 2)  {

  if (test == 0) {Tft.fillScreen();}
 // draw back button
  back.setValues(15, 15, 35, 85);
  back.draw();

Tft.setDisplayDirect(UP2DOWN);

   // Draw the back button's text
  TouchScreenString backText("BACK", 40, 30, 2, WHITE);
  backText.drawText();
test = 1;
}}

// Gets which button was pressed.  If no button is pressed, -1 is returned.
int getButtonNumber(int xInput, int yInput)
{

if (screen == 1) {
  if (bigButton.isPressed(xInput, yInput)) {
    screen = 2;
    return 13; // Signifies big button was pressed
  } }
  if (screen ==2) {
  if (back.isPressed(xInput, yInput)) {
    screen = 1;
    return 15; // Signifies big button was pressed
  }}
  if (screen == 1) {
  if (reset.isPressed(xInput, yInput)) {
    test1 = 0;
    return 14; // Signifies reset button was pressed
  }}
  else {
  return -1; // Signifies no button was pressed
  }
}

```

# Answer
> 1 votes
My guess is you are running out of RAM. Your various string constants alone take up 202 bytes. Then there is this:

```
  test1++;
  str = String(test1);
  str.toCharArray(b,5);

```

That is very likely to fragment memory, as `test1` gets larger and larger. So you are fragmenting RAM, of which you don't have much to start with.

Why are you even converting test1 into a String object? And then converting it back into an array?

The array `b` can only hold 4 digits as it needs one byte for the trailing null-terminator.

I suggest you stop doing that String stuff, and also use the `F()` macro like this ...

Change:

```
    Serial.println("Options button was pressed!");

```

to:

```
    Serial.println(F("Options button was pressed!"));

```

Ditto for all the other places you are displaying stuff.

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


# Question
Title: Modify the call stack of interrupts on Arduino
I'm working with Arduino's libraries. And my interest in the possibility to change the call stack of the SPI interrupt, this because I want: after the interrupt happen, the program could jump to other function and not to the interrupted address.

I mean: This is the Main code.

```
void loop ()
{
    func();
}

void func()
{
   // code
   // here happens the ISR interrupt
}

```

ISR happens inside `func()`

```
ISR(SPI_STC_vect)
{
    // code
    // SPDR = 0x00; // MY ANSWER to SPI
    // MODIFY CALL STACK TO GO TO LOOP()
}

```

**Now, after answering the SPI, I want to go back to `loop()` instead of continue `func()`.**

**How can I do this?**

Thanks for your help.

# Answer
> 1 votes
Arduino is open source, so just modify the ISR to set a global flag when ran. Within func() just check for this flag and return when the condition is met. Little can be offered as little contextual information is given. To modify the stack you would have to work with avr assembly, but either way you must modify the ISR

Something like the following would work, but performance depends heavily on your application.

```
#define SPI_ISR_RAN 0x00
static volatile uint8_t flagByte;

void loop(){
    func();
}

void func(){
    uint8_t indicator;
    do {
        // Do something

        //Check for SPI condition
        ATOMIC_BLOCK(ATOMIC_RESTORESTATE){ //Atomic access is required
            indicator = flagByte;
        }
    }while( !(indicator & 1<<SPI_ISR_RAN) );

    ATOMIC_BLOCK(ATOMIC_RESTORESTATE){
        flagByte &= ~(1<<SPI_ISR_RAN); //Don't forget to clear the flag!
    }
}

ISR(SPI_STC_vect){
    // Do ISR necessities

    // Set flag when appropriate
    flagByte & 1<<SPI_ISR_RAN;
}

```

# Answer
> 0 votes
You can achieve almost what you are describing with the `setjmp()` and `longjmp()` functions. Here is an example, using INT0 to interrupt a function calling `delay()`:

```
/*
 * Test non local return from ISR:
 *   - wire a pushbutton between digital 2 and GND
 *   - monitor the serial port at 9600/8N1
 *   - pressing the button should skip "func() ending" and immediately
 *     write "func() returned"
 */

#include <setjmp.h>

jmp_buf saved_context;

/*
 * ISR triggered by low level of INT0 = PD2 = Arduino digital 2.
 * Should only be allowed to trigger while inside loop().
 */
ISR(INT0_vect) {
    EIMSK &= ~_BV(INT0);        // disable further interrupts
    longjmp(saved_context, 1);  // return to loop()
}

void func() {
    Serial.println("  func() beginning");
    EIMSK |= _BV(INT0);   // enable INT0 interrupt
    delay(3e3);           // wait 3 s for an interrupt
    EIMSK &= ~_BV(INT0);  // disable INT0 interrupt
    Serial.println("  func() ending");
}

void setup() {
    pinMode(2, INPUT_PULLUP);  // pin 2 is INT0
    Serial.begin(9600);
}

void loop() {
    Serial.println("Calling func()");
    if (setjmp(saved_context) == 0) func();
    Serial.println("func() returned");
    Serial.println();
    delay(2e3);
}

```

# Answer
> 0 votes
> Now, after answering the SPI, I want to go back to loop() instead of continue func().

This is an extremely bad idea, and not what ISRs are for.

It is all very well wanting to go back to loop, but you would also have to discard whatever is on the stack, since loop started. The suggested method of using `setjmp` / `longjmp` may possibly achieve that, but almost certainly you are doing this for the wrong reason.

Jumping back to `loop` is like saying:

* I don't care what was happening when the interrupt occurred
* I don't care if it is half-way through sending some message
* I don't care if it is half-way through turning on or off some device

In addition to this memory which was allocated (eg. by String objects) might not be freed. In fact the interrupt might occur during memory allocation in which case variables used by the memory allocation routine could be in an indeterminate state.

I strongly disagree with any suggested work-arounds. You simply should not be "jumping out of" an ISR and going somewhere else. Re-think the design.

---
Tags: avr
---


# Question
Title: How to store IR data needed for AC controll in less space?
I'm trying to controll an AC unit but the issue is space - right now, I store the data like this:

```
consts PROGMEM unsigned int Signal_Heat_Fan0_Temp30[] = {233,636,17884,3032,8944,500,496,492,1496,524,472,548,452,544,448,552,444,552,444,548,444,552,444,552,1436,556,444,552,444,548,1440,552,472,524,472,520,1472,492,1496,520,1468,556,1436,552,1440,552,444,548,448,548,444,552,448,548,448,548,448,548,472,524,468,524,472,524,476,520,472,520,476,520,476,520,472,524,472,552,444,548,452,548,444,552,444,548,448,548,444,552,448,544,452,544,448,552,472,524,468,524,472,524,472,524,472,520,476,520,476,520,472,524,1468,552,1436,556,1436,556,1436,552,2944,3028,8920,548,1440,552,448,548,472,524,468,524,472,524,472,472,524,516,476,552,444,548,1444,552,444,548,448,552,440,556,440,556,1432,556,1440,548,452,544,1444,552,1464,524,1464,472,1520,524,1464,556,1436,552,1440,552,1436,556,440,552,448,548,444,552,1440,552,1440,552,1464,524,472,496,496,472,524,520,476,548,444,552,448,552,1440,548,1440,556,1432,556,1440,548,448,548,444,552,448,548,472,524,472,524,1464,472,524,472,524,516,476,552,444,552,444,552,1440,552,1440,552,1436,556,1436,552};
consts PROGMEM unsigned int Signal_Heat_Fan0_Temp29[] = {233,636,17896,3032,8916,552,468,524,1468,524,468,500,496,472,528,520,476,544,448,552,444,552,444,548,1440,556,440,552,448,548,1440,552,444,548,452,544,1444,548,1468,524,1464,472,1520,520,1468,552,444,552,448,548,444,552,444,548,448,548,444,552,444,556,444,548,448,548,444,552,448,544,472,524,472,524,472,524,472,468,528,520,476,544,448,552,444,552,444,548,444,556,440,556,444,548,448,548,444,552,444,552,444,548,452,544,476,524,472,524,468,524,472,492,1496,520,1472,548,1440,556,1440,548,2944,3032,8916,552,1436,552,444,552,444,548,452,544,448,548,476,524,468,524,472,524,472,492,1496,520,476,524,472,548,448,552,444,552,1440,548,1440,548,448,548,1440,556,1440,548,1440,552,1464,524,1464,500,1496,520,1468,552,1440,548,444,556,444,552,444,548,1440,552,1440,548,1444,544,476,524,472,524,472,524,468,524,472,492,1496,524,476,548,1444,548,1440,548,1444,552,444,552,444,548,448,548,444,552,448,544,1448,544,476,524,468,524,472,524,472,492,504,516,1472,548,1444,552,1440,548,1440,548};
consts PROGMEM unsigned int Signal_Heat_Fan0_Temp28[] = {233,636,17880,3056,8912,524,476,544,1444,552,444,548,448,552,440,556,440,556,444,552,444,548,444,552,1440,552,444,552,468,524,1468,524,468,472,524,520,1476,544,1444,548,1440,556,1432,556,1440,548,448,548,444,552,448,548,448,548,472,524,472,520,472,524,472,496,500,472,524,492,504,544,452,548,444,552,444,552,444,548,448,552,440,556,444,548,448,548,444,552,448,544,452,544,476,524,472,524,468,524,472,524,472,492,500,520,476,548,452,544,448,552,444,552,1440,548,1440,552,1440,552,1440,548,2944,3028,8924,544,1444,552,468,524,472,496,500,492,504,516,476,552,444,548,452,548,444,552,1440,548,444,552,444,552,1444,548,444,552,1440,548,1444,544,476,520,1472,492,1496,520,1468,552,1444,548,1440,552,1436,552,1440,552,1440,552,444,548,452,544,476,520,1468,524,1468,492,1496,520,480,544,448,548,448,552,444,548,444,552,444,548,452,548,1440,552,1436,552,1444,544,476,520,476,524,468,524,472,496,500,492,1496,524,476,544,452,548,444,552,444,548,448,548,1444,548,1440,552,1440,548,1444,520};
consts PROGMEM unsigned int Signal_Heat_Fan0_Temp27[] = {233,640,17892,3032,8916,552,448,548,1464,528,468,528,468,468,528,468,528,520,472,552,444,552,444,552,1440,548,448,548,444,556,1436,552,444,552,444,552,1436,552,1444,548,1468,492,1496,472,1516,552,448,548,448,548,448,548,444,552,444,552,444,552,440,556,444,552,444,548,444,552,448,548,448,548,472,524,472,524,468,468,528,472,524,520,472,524,472,552,448,548,448,548,444,552,444,548,448,548,444,556,440,552,448,548,444,552,444,552,448,544,472,524,472,528,1464,468,1520,520,1472,552,1436,556,2944,3028,8912,556,1440,548,448,548,444,552,448,548,448,548,444,552,472,520,472,524,472,524,1464,472,528,488,508,544,448,552,444,552,1436,556,1436,552,448,548,1440,548,1440,556,1440,548,1440,552,1464,524,1464,472,1524,544,1444,552,444,552,448,548,444,552,1440,548,1440,552,1444,548,444,552,448,544,472,524,472,524,468,500,1492,492,1500,548,452,544,1440,556,1436,552,444,552,444,552,444,548,448,548,448,548,1444,548,472,524,468,524,472,524,472,472,528,468,1520,520,1468,552,1440,552,1436,552};
consts PROGMEM unsigned int Signal_Heat_Fan0_Temp26[] = {233,640,17884,2980,8992,528,472,524,1464,472,524,520,476,548,444,556,440,556,444,548,444,552,444,552,1440,552,440,556,444,548,1440,552,444,552,468,524,1468,528,1460,472,1520,548,1444,548,1440,556,444,548,448,548,444,552,444,552,444,552,444,552,444,552,444,548,448,548,472,524,468,524,472,472,528,468,528,488,504,548,448,552,444,548,444,556,440,556,444,548,444,552,444,552,444,548,448,548,448,552,444,548,448,548,472,524,472,520,472,524,472,472,524,520,1468,548,1444,552,1440,552,1436,556,2944,3024,8920,552,1440,552,444,548,444,552,448,548,468,524,472,528,472,468,524,468,528,520,1472,548,444,556,444,548,1440,552,444,548,1440,556,1440,548,444,552,1440,548,1444,552,1464,492,1496,520,1472,548,1440,556,1440,548,1440,552,444,552,444,552,444,548,1440,552,1444,548,1440,548,472,524,472,472,524,472,520,520,480,544,452,548,1440,548,448,548,1440,552,1440,552,444,548,448,548,448,552,444,552,468,524,1464,524,472,472,528,468,524,468,528,544,452,548,1440,556,1436,552,1440,548,1440,556};
consts PROGMEM unsigned int Signal_Heat_Fan0_Temp25[] = {233,644,17892,3028,8916,552,444,548,1440,556,440,552,448,548,444,552,444,548,448,548,448,548,472,528,1464,468,528,520,472,548,1448,544,444,556,440,556,1440,548,1440,548,1440,556,1440,548,1440,552,448,544,472,528,472,524,468,468,528,468,528,544,448,552,444,552,444,552,444,552,444,552,444,552,444,548,444,552,444,552,444,552,448,548,444,552,468,524,472,524,472,524,468,472,524,472,528,520,476,544,448,552,444,548,448,548,444,556,440,556,444,548,444,552,1440,548,1440,556,1440,548,1468,548,2920,3052,8920,472,1516,548,452,548,444,552,444,548,448,548,444,556,440,556,444,548,448,548,1440,548,452,544,448,552,1440,548,472,524,1464,472,1516,552,448,544,1444,552,1444,548,1440,552,1436,552,1440,552,1440,552,1440,548,1464,528,472,496,500,468,524,520,1472,548,1440,556,1436,552,444,552,444,556,440,552,444,552,444,552,1436,552,448,544,452,548,1468,524,1464,468,528,520,472,552,448,548,448,548,448,548,1440,548,448,548,444,552,444,556,444,548,444,552,1440,548,1440,552,1464,500,1496,548};

```

The first item is the length of the array and the rest is data I can send with IRemote library with the raw send libray. I've mapped most of the buttons and now I'm at

```
Sketch uses 95.286 bytes of program storage space

```

Is there a better encoding that could take less space? I'd like to add at least 3 times more commands to the Sketch, but I'm already at 37% on an Arduino Mega.

I know ideally I should generate the array, not store it, but I haven't gotten that far (yet, I'm working on it) and for me this is an interesting issue.

Thank you!

---

Edit 1: Code uploaded on GitHub - https://github.com/vladbabii/SamsungACIrControll/tree/master/AC\_IrControll

# Answer
> 2 votes
I have analysed your codes with a small Lua script:

```
function pairsByKeys (t, f)
  local a = {}
  -- build temporary table of the keys
  for n in pairs (t) do
    table.insert (a, n)
  end
  table.sort (a, f)  -- sort using supplied function, if any
  local i = 0        -- iterator variable
  return function () -- iterator function
    i = i + 1
    return a[i], t[a[i]]
  end  -- iterator function
end -- pairsByKeys

nums = {233,636,17884,3032,8944,
-- and so on ...
548,444,552,444,556,444,548,444,552,1440,548,1440,552,1464,500,1496,548}

uniq = { }

for k, v in ipairs (nums) do
  if uniq [v] then
    uniq [v] = uniq [v] + 1
  else
    uniq [v] = 1
  end -- else
end -- for

count = 0

for k, v in pairsByKeys (uniq) do
  print (string.format ("%8i = %3i", k, v))
  count = count + 1
end

print ("count = ", count)

```

---

Results:

```
     233 =   6
     440 =  18
     444 = 154
     448 =  86
     452 =  20
     468 =  42
     472 = 103
     476 =  27
     480 =   2
     488 =   2
     492 =  15
     496 =   8
     500 =  10
     504 =   4
     508 =   1
     516 =   4
     520 =  41
     524 =  97
     528 =  26
     544 =  39
     548 = 189
     552 = 196
     556 =  56
     636 =   3
     640 =   2
     644 =   1
    1432 =   3
    1436 =  24
    1440 =  91
    1444 =  26
    1448 =   2
    1460 =   1
    1464 =  21
    1468 =  16
    1472 =   8
    1476 =   1
    1492 =   1
    1496 =  12
    1500 =   1
    1516 =   3
    1520 =   5
    1524 =   1
    2920 =   1
    2944 =   5
    2980 =   1
    3024 =   1
    3028 =   4
    3032 =   4
    3052 =   1
    3056 =   1
    8912 =   2
    8916 =   4
    8920 =   3
    8924 =   1
    8944 =   1
    8992 =   1
   17880 =   1
   17884 =   2
   17892 =   2
   17896 =   1
count =     60

```

---

Assuming there is some jitter I rounded them to the nearest 50:

```
for k, v in ipairs (nums) do

  v = math.floor (v / 50)    -- <--- add this
  v = v * 50                 -- <--- add this
  if uniq [v] then
    uniq [v] = uniq [v] + 1
  else
    uniq [v] = 1
  end -- else
end -- for

```

---

Results:

```
     200 =   6
     400 = 258
     450 = 219
     500 = 411
     550 = 252
     600 =   6
    1400 = 146
    1450 =  60
    1500 =  10
    2900 =   6
    2950 =   1
    3000 =   9
    3050 =   2
    8900 =  11
    8950 =   1
   17850 =   6
count =     16

```

So, 16 different lengths.

---

So now you can use 4 bits per code (and a lookup table) rather than 16 bits.

Also see TV-B-Gone design notes for how they compressed the IR codes for lots of TV brands into a small table in an ATtiny85.

# Answer
> 1 votes
Do you need all of the data accessible at once? How about storing it on a file device or external memory? SDcards are slow but huge. FRAM devices a fast but not as huge and typically aren't formatted for a file system. They act more like an independent memory space accessed by a function. (The Adafruit product is one example; I'm sure there are more).

# Answer
> 1 votes
Another form of storage is the EEPROM. There are between 512 bytes and 4K of EEPROM per Arduino, depending on the model of Arduino - see https://www.arduino.cc/en/Reference/EEPROM

EEPROM is persistent when the power gets cut, and MAY or may not be overwritten when the program is changed - I have not tried. If it is not overwritten, you can write a sketch just to set it, then overwrite it with your IR sketch; otherwise, you may have to set up some way to "upload" the data into your sketch (e.g. if you press a special button, it will listen on the serial port, any bytes it reads it will write to the EEPROM.

If you have an ISP (aka ICSP) programmer such as the USBasp (see google), which are very inexpensive, then you can read/write the EEPROM directly - all you need is 6 pins exposed. You can also use the USBasp to reprogram an AtMega/AtTiny which is not on an Arduino board (this also gives you a little extra program space, since it no longer requires a bootloader).

---
Tags: arduino-mega, code-optimization, progmem
---


# Question
Title: Burning Arduino Leonardo Bootloader to ATmega32U4 with 8MHz internal clock
Burning question:

So, I'm trying to burn the Arduino Leo bootloader onto a ATmega32U4 that's on 3.3V and the internal 8MHz clock. Do I have to modify and rebuild the bootloader to set the fuses correctly, and can this be done with AVR Studio?

All of the references on doing this are dated. The folder structure for the Arduino IDE has changed. I've done it in the past with 5V 16MHz 32U4s using an Arduino as ISP, but never with the AVRISP mkII on the Arduino IDE.

On the good side, I do have it up and running with Atmel Studio.

Thanks!

# Answer
> 2 votes
If you have an appropriate crystal attached then you can do this in the Arduino IDE. Select your board and programmer in the IDE menu, connect the programmer to the board, and choose `Burn Bootloader` from the menu. This will both burn the prebuilt bootloader image and set the fuses in a single operation.

Note that you cannot use USB on the '32U4 if you are running off either a ceramic resonator or the internal oscillator, and so you should not attempt to use the Leonardo bootloader in either case.

---
Tags: arduino-leonardo, bootloader, atmega32u4
---


# Question
Title: Light communication from pc/app to arduino
I will like to implement a serial communication protocol, using javascript in a mobile browser to make the browser background blink (alternating the color from black to white) according to the bits, to communicate a few bytes to an Arduino using some kind of light sensor (photo diode or resistor) to parse. Electric Imp did something with https://electricimp.com/platform/blinkup/ .

Is there any library or implementation or where to start guide?, if not, how would you implement it?

I fear one of the problems of using a mobile browser with javascript to light-encode the bits will be timing issues, since setTimeInterval is not perfect, I could split the screen, one half blinking continuously (clock) and the other half the data, but that will require two light sensors.

# Answer
Doing bit stuffing can prevent timing problems when you are sending a lot of `0`s or `1`s in an row. Alternatively use Manchester encoding (slower).

On the browser side, I'd suggest using `<Canvas>`. Combine this with `requestAnimationFrame` which gives you a very accurate timestamp as an argument. Though you have to check for support as older browsers don't support that.
> 1 votes

# Answer
You should investigate communication protocols and encoding techniques that embed the clock signal into the same data stream as the data signal.

One common method is called *Manchester Coding*. This entails splitting each bit into two halves. A 1 sends light followed by dark, and a 0 sends a dark followed by a light. It's then up to you to work out which transitions are which and where in a bit they occur (is a high transition the start of a 1 or mid-way through a 0?)

Another popular method (used in things like Ethernet) is called 8b/10b. That involves sending 10 bits to represent every 8 - more efficient than manchester coding (that could be considered 8b/16b) and can be read about here: https://en.wikipedia.org/wiki/8b/10b\_encoding It's somewhat harder to implement than Manchester Code, so although it's less efficient I'd recommend the simplicity of Manchester Code.
> 0 votes

---
Tags: serial
---


# Question
Title: Student Project Inquiry(Building a Self Balancing robot)
I am currently building a self balancing robot using an L298N motors driver,and MPU6050 using an arduino microcontroller.

I managed to control my motors movements with no issues. After I extracted the data from my MPU6050 which was easy by using MPU6050 library I faced a problem: When linking the motors movement according to MPU6050 readings, the sensor freezes and stops showing its data on the serial monitor after giving couple of readings, the motors keep moving. I even have capacitors soldered into my motors to filter the noise. I am definitely sure my sensor works perfectly because it was tested before implemented into the motors drivers circuit and code.

If anyone can give me any hints why does the MPU sensor stop giving readings please.

Thanks.

# Answer
The MPU6050 is an I2C device. By default the Arduino uses the internal pullup resistors in the IO pins for the pullups on the I2C bus.

This is bad - it makes the I2C bus *very* susceptible to noise, and motors are *very* noisy devices.

You need to make sure you have appropriate pullup resistors on the I2C bus (3.3KΩ is good) and keep the I2C wires as short as you reasonably can.

Also keeping power sources as separate as possible is essential. Don't be tempted to use the 5V power from the Arduino to power your motors - you must use an external power source, or the motors will cause havoc with the microcontroller circuitry and communications.
> 1 votes

# Answer
This answer addresses the additional questions in Salah's comment:

> I am using a 12V battery to power my motors and the ground of the battery is linked to the ground of my motor driver then mounted onto the arduino. So you mean i must use 3.3K resistors and connect them to the SDA and SCL pins on the MPU6050??to prevent any oscillations affecting the sensor is that right ?

The MPU-6050 will work ok with Vdd = 3.3 V. More specifically, page 14 of the 1788002.pdf datasheet for MPU-6000/MPU-6050 products shows

> VDD = 2.375V-3.46V, VLOGIC (MPU-6050 only) = 1.8V±5% or VDD, TA = 25°C

The wiring diagram on page 39 shows SDA and SCL being pulled up to VLOGIC (which is either 1.8 V or VDD, say 3.3 V).

One suitable choice would be to operate an 8 MHz Mega and the 6050 at 3.3 V and pull SDA and SCL up to 3.3 V via 3.3 KΩ resistors.

Another choice would be to operate a 16 MHz Mega at 5 V, operate the 6050 at 3.3 V, pull SDA and SCL up to 3.3 V via 3.3 KΩ resistors, and use 3.3V/5V level translations on SDA and SCL into the Mega.

Built-in pullups for I/O pins on Mega2560 and similar devices are spec'd at 20 KΩ min, 50 KΩ max, so will provide less restoring current when a device releases a pin, than will a 3.3 KΩ resistor, and thus may be less noise-resistant or operate less speedily.

The important issues for your power wiring are these:

1, Isolate the motor drive and logic drives. They can use the same ground point but motor current should not be running through the ground lead or leads that connect to the Arduino and the MPU-6050. And use decoupling capacitors as necessary.

2, Power the MPU-6050 with 3.3 V or less; pull up SDA and SCL to that level via 3.3 KΩ resistors; use level translators if the Mega operates at a different voltage than the MPU-6050.

*Edit: About Grounding –* For a detailed discussion, see Staying Well Grounded, an analog.com article. For overviews, see Star Grounding at lh-electric.net, or at wikipedia, Ground Noise, Ground Bounce, and Ground (electricity) Electronics. By “motor current should not be running through the ground lead or leads that connect to the Arduino and the MPU-6050” I refer to the use of separate wires for conducting ground current. Typically, this will matter only if your motor current is high or noisy. The idea is to have a heavy wire from the ground post of the battery to the motors, and a separate wire from the ground post of the battery to the Arduino and the MPU-6050. Voltage across a wire changes as current in the wire changes. Using separate ground wires, the Arduino and the MPU-6050 are less affected by ground wire voltage changes caused by motor current.
> 0 votes

---
Tags: sensors, arduino-motor-shield
---


# Question
Title: Can anyone identify why this incrementer is losing count?
I am working on a project where the end result is to count the number of cycles of a moving piece of metal using an inductive sensor.

For now I am using an Arduino Uno and have created a breadboard version for testing. The sensor has been replaced by a momentary push button. To check the count data I am viewing the number using Serial Monitor

All the elements of this set-up are working, apart from one major issue. When pressing the button the incrementer (++) occasionally adds 2 instead of 1 from only one button press. As a rough guide to the error frequency, it seems to count 11 for every 10 button presses. The error has never presented as not counting enough.

I am new to software, as such I cannot seem to see the error

Any help and guidance would be greatly appreciated

Here is the code I have written so far:

```
//Libraries
#include <EEPROM.h>

//Constants
const int counterPin = 2;   //Input from counter (looking for HIGH as external pulldown resistor is used)
const int EEPROMadress = 3; //holds the EEPROM address

//Variables
int counterState = 0;       //current button state
int counterStatePrv = 0;    //previous button state
int storedValue;
int presetCount = 100;

unsigned long countNumber;      //unsigned 32bit variable

void setup() {

    for (int i = 0; i < 255; i++) {
        // this performs as EEPROM.write(i, i)
        EEPROM.update(i, i);
    }
    for (int i = 0; i < 255; i++) {
        // write "presetCount" value to cell "EEPROMaddress" only the first time
        // will not write the cell the remaining 254 times
        EEPROM.update(EEPROMadress, presetCount);
    }

    pinMode(counterState, INPUT);
    Serial.begin(9600);

    countNumber = EEPROM.read(3);   //Start the counter at the presetCount value
}

void loop() {

    counterState = digitalRead(counterPin);   //Read the status of the counter input
    storedValue = EEPROM.read(EEPROMadress);

    if (counterState != counterStatePrv) {      //check that pulse went off
        if (counterState == HIGH) {             //check for pulse
            countNumber++;                      //increment (add 1) to the stored count value
            delay(10);
            Serial.print("Count  Value: ");
            Serial.println(countNumber);

            Serial.print("Stored Value: ");
            Serial.println(storedValue);
            Serial.println();

        }
    }
    counterStatePrv = counterState;

}

```

# Answer
Buttons bounce (at least they appear to, electrically), meaning that if you're fast enough, you can detect multiple pulses per button-press. Usually we don't count the button as being pressed until we read the same value {n} times in a row or for {m} mSec, or some similar technique.

Because you call `EEPROM.read()` immediately after testing the button, perhaps most times the bouncing will have ceased when the call returns, but once in a while one last bounce slips through.

Nick Gammon, a regular contributer here, has a good discussion of de-bouncing on his web site. Have a look at that and pick a technique that's compatible with what you're trying to do.
> 0 votes

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


# Question
Title: How to measure nitrogen flow through a tube?
I am looking for a simple way to detect nitrogen gas flow through a tube. I don't even need any sort of precision, just really need to know if flow exists or not.

What are some options I could pursue to easily measure this with the arduino?

# Answer
You can use a pressure sensor for gas and measure the pressure differential between two points and if there is a large pressure differential then you know a flow exists.
> 1 votes

# Answer
What you are looking for is a mass flow sensor(MAF), or something along those lines as you mention wanting to know if there is flow, this gives you the *'speed'* of the flow. There are various types available according to size, flow rate, type of element, and accuracy. Just search for mass flow sensor, you can even hack them off cars.

If you just want to detect only the presence of the N2 as you say then you can split your pipe somewhere,and then add a T-piece to that. You then put a gas sensor in the T part, and seal it off so there is no leaks. You would then hook that up to the Arduino board and interpret the signal.

Can't recommend any specific sensors though.

Here is an image for the idea:
> 1 votes

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


# Question
Title: Assigning value inside structure array outside setup and loop functions
I'm having some difficulty assigning a value to a variable in a struct array outside the loop and setup functions. Assigning a value to an int or char array works completely fine but this doesn't.

The example code and error message returned after trying to compile are below. Any help is greatly appriciated. Thanks

```
void setup()
{
}

struct trap_game_detail {
    byte flush_quantity;
    byte flush_interval;
    byte random_min;
    byte random_max;
    byte random_quantity;
} trap_game_details[2];

trap_game_details[0].random_min = 1;

void loop()
{

}

```

src/sketch.ino:13:5: error: ‘trap\_game\_details’ does not name a type trap\_game\_details\[0\].random\_min = 1; ^ .build/uno/Makefile:166: recipe for target '.build/uno/src/sketch.o' failed

# Answer
> 1 votes
> Assigning a value to an int or char array works completely fine but this doesn't.

It only works fine if you do it on the declaration.

eg.

This works:

```
int foo = 42;  < ---- declare and define with initial value

```

This doesn't:

```
int foo;   // < ---- declare and define

foo = 42;  // < ---- assignment statement

```

Your code was like the second example.

---

Majenko has shown one way. He split the declaration into two parts. The first part declared the **type** trap\_game\_detail, and the second part is an **instance** of that type, like this:

```
struct trap_game_detail {
    byte flush_quantity;
    byte flush_interval;
    byte random_min;
    byte random_max;
    byte random_quantity;
};

struct trap_game_details trap_game_details[2] = {
    { 10, 5, 1, 100, 4 },
    { 8, 23, 5, 95, 8 }
};

```

---

Alternatively, and a bit closer to what you were doing, just keep going with the initialization values after you define the structure, like this:

```
struct trap_game_detail {
    byte flush_quantity;
    byte flush_interval;
    byte random_min;
    byte random_max;
    byte random_quantity;
} trap_game_details[2] =
  {
    { 10, 5, 1, 100, 4 },
    { 8, 23, 5, 95, 8 }
  };

```

# Answer
> 1 votes
You can't access array contents in the global scope like that. You have to assign the entire block of data in one go:

```
struct trap_game_detail {
    byte flush_quantity;
    byte flush_interval;
    byte random_min;
    byte random_max;
    byte random_quantity;
};

struct trap_game_details trap_game_details[2] = {
    { 10, 5, 1, 100, 4 },
    { 8, 23, 5, 95, 8 }
};

```

Items in the *global scope* aren't executed - only things in functions are executed. Accessing individual parts of an array or struct like you are trying to is a programatic operation, so can't be executed since it's not in a function.

---
Tags: c++, struct
---


title: 'Simple' problem. Delay not working?

text:
# Question
Title: 'Simple' problem. Delay not working?
Servo goes to one end, and immediately travels back without a 2s delay inbetween. After it travels back there is a 2s delay before it loops. Why isn't there a 2s delay before the travel back?

```
Servo testservo;

void setup() {
    testservo.attach(9);
}

void loop() {
    testservo.writeMicroseconds(700);
    delay(2000);
    testservo.writeMicroseconds(2300);
    delay(2000);
}

```

# Answer
Your description (“Servo goes to one end, and immediately travels back without a 2s delay... After it travels back there is a 2s delay before it loops”) implies an overall cycle time of 2 seconds, which appears to be inconsistent with the overall 4-second cycle implied by the code shown.

Here are things you can do to debug the problem:

1. Turn on an LED before one `writeMicroseconds()` call, and turn it off before the other. For example, add `pinMode(13, OUTPUT);` in `setup()`, and revise `loop()` as follows:

```
void loop() {
    testservo.writeMicroseconds(700);
    digitalWrite(13, HIGH);
    delay(2000);
    testservo.writeMicroseconds(2300);
    digitalWrite(13, LOW);
    delay(2000);
}
```

This may allow you to find out which end the servo is going to.

2. Besides adding LED signals, try slightly-less extreme times in the `writeMicroseconds()` calls; eg 1000 and 2000 microseconds rather than 700 and 2300.
3. See if a neutral servo setting works, eg via code like the following.

```
enum { LEDpin=13, dtime=2000}
void stest(angletime, tHi, tLo) {
    testservo.writeMicroseconds(angletime);
    digitalWrite(LEDpin, HIGH);
    delay(tHi);
    digitalWrite(LEDpin, LOW);
    delay(tLo);
}
void loop() {
    stest(1000, dtime-50, 50); // Go CCW
    stest(1500, 50, dtime-50); // Middle
    stest(2000, 50, dtime-50); // Go CW
}

```

When this code runs, the LED should stay on about 2 seconds with the servo fully (or nearly so) counterclockwise. Then the LED should blip and the servo should move to center position and stay there about 2 seconds. Then the LED should blip and the servo should stay fully clockwise about 2 seconds. This three-part cycle should repeat every six seconds. If it works ok, then try modifying it, eg by changing 1000 us to 700, 2000 to 2300, etc, or by decreasing the `dtime` value to see how quickly the servo can respond, etc.
> 2 votes

---
Tags: servo
---


# Question
Title: Level tracking using optical or capacitance sensors
I am looking to devise a level tracking system using arduino and some sensors. My particular situation is I have solute that is coming out of solution and I want to track the formation rate of the solid phase as the salts settle at the bottom and build a bed of particulates.

I am looking for precision at about 0.5mm and over a range of like 6 inches. My initial idea was to get a sensor bar that could detect when and where light is hitting the sensor and post processes that signal. I have to design this device to sit outside the cylindrical vessel. The solvent is transparent so any form of light would work. I am stuck on finding the parts that could pull this off and I was hoping the more experienced community could point in the right direction.

*** UPDATE ***

a little cartoon for a clearer picture of the idea I am leaning towards capacitance since using light seems like a rabbit hole. I was playing with some foil and it may work but I need a much more sensitive tool on the order of pico-Farads to work.

# Answer
What about measuring this with two resistive probes - the electricity will go through down one probe to the top of the water, across the water, and up the other probe. You can measure how much of the probe it went down, by measuring the resistance. You would need the probes to be a specific, very consistent distance apart, and be made of resistance wire.

Another option is to use a float of some kind, and measure it this way. This is a lot easier if all you need to know is full/not full.
> 1 votes

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


# Question
Title: Can't get values of max232 with loopback
I didn't find answers which solves my problem with the max232 yet. I connected it like this to my Arduino uno, so my Arduino provides the +5V VCC and the ground: max232 connection

The only thing what is differences are that I do a loopback at the RS232 side and I use 1µF for every capacitor even for the bypass one. I did a loopback so I can see if the max232 works. I don't get anything out of it when I send some data to it. I measure +8.7V on pin2 and -8.15V on pin 6.

My Arduino code:

```
/*
  Software serial multiple serial test

 Receives from the hardware serial, sends to software serial.
 Receives from software serial, sends to hardware serial.

 The circuit:
 * RX is digital pin 10 (connect to TX of other device)
 * TX is digital pin 11 (connect to RX of other device)

 created back in the mists of time
 modified 25 May 2012
 by Tom Igoe
 based on Mikal Hart's example

 This example code is in the public domain.

 */
#include <SoftwareSerial.h>

SoftwareSerial mySerial(10, 11); // RX, TX

void setup()
{
  // Open serial communications and wait for port to open:
  Serial.begin(9600);

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

void loop() // run over and over
{
  if (mySerial.available())
    Serial.print(mySerial.read());
  if (Serial.available())
    mySerial.write(Serial.read());
}

```

What did I do wrong or is my max232 broken?

**EDIT**

I think the serial monitor (same baudrate) doesn't write to the ports so I rewrite some code.

loop code:

```
int i = 0;
void loop() // run over and over
{
  if(i == 10)
    i = 0;

  mySerial.write(i);
  Serial.print(mySerial.read());
  i++;
  delay(3000);
}

```

In serial monitor I get strange values back for a cascade counter.

Values: -1 45 49 52 53 52 57 53 ...

These numbers aren't ascii code for ectual numbers I think.

**EDIT 2**

Now the loopback works thanks to the answer below. Now I replaced the loopback with the module FUM DCF-U. The loop code has changed to this:

```
void loop() // run over and over
{
  if(Serial.available())
    Serial.println(Serial.read());
}

```

The problem is that the result is '000000000000000000000000000000000...' in a fast rate and not every second.

The module gets its 3.3V and is connected to the same GND as the MAX232.

Pin connections:

Arduino - MAX232

11 - 11

0 - 12

MAX232 - FUM DCF-U

14 - 3

13 - 4

Thanks in advance

# Answer
> 1 votes
SoftwareSerial cannot both send and receive at the same time, as it does receiving inside an ISR, and turns interrupts off when sending. Thus this will never work properly.

I suggest you switch to HardwareSerial. Or, if you want to see the results, send using SoftwareSerial and receive using HardwareSerial. For example:

```
#include <SoftwareSerial.h>
SoftwareSerial mySerial (10, 11); // RX, TX

void setup ()
  {
  Serial.begin (115200);
  mySerial.begin (115200);
  }  // end of setup

unsigned long lastSend;
char c = ' ';
void loop ()
  {
  // time for another test send?
  if (millis () - lastSend >= 500)
    {
    mySerial.print (c++);
    if (c > 'z')
      {
      c = ' ';
      Serial.println ();
      }
    lastSend = millis ();
    }

  // check for response
  if (Serial.available ())
    Serial.print (char (Serial.read ()));
  }  // end of loop

```

I tested that as a simple loopback and it worked fine. Connect pin 11 (Tx) to pin 0 (Rx). Disconnect the wire to pin 0 whilst uploading.

---
Tags: max232
---


# Question
Title: Arduino Mega read of serial encoder read at 1,024,000 baudrate?
Reading a 1.024m baud rate 77 bit stream from a serial encoder- `begin.serial1(1024000);` is accepted - but no idea if UART can actually run there.

In the screen grab, channel 7 is a 8 microsecond clock pulse generated by the Arduino, channel 6 is the encoder response - always begins 13 microseconds after rising edge of clock pulse, first part is always 10101101, after that it's pretty random as encoder rotates.

I tried unsuccessfully to read the pins at that speed, no way, then tried reading the repeating data at synchronous microseconds +1 to try reading one bit at a time through sequential 77 bit words while not rotating - but clocking varies in Arduino program by up to 8 microseconds over the 2 millisecond repeating patterns though.

I tried the serial read through serial1 port, getting some data, but random... with no terminator to rely on, wondering if anyone has a suggestion as to how to clear/load serial buffer after a long pause (long being almost two milliseconds) followed by the 10101101 that always starts the next read (but could possibly repeat inside of it).

I'm a newbie to these things, just tinkering around thought decoding a serial encoder would be fun... many many many hours later, have learned a bit about them and more so learned how little I know about them :)

# Answer
> 1 votes
I think the problem is that there is more to serial I/O than just bits coming in. Otherwise, if nothing was sending, you would always read 0 from the serial port. Serial has a start and stop bit, for example. I doubt you could use the hardware serial to read in random bits.

If you are going to do this in software, you will have less than 16 clock cycles per bit - enough time to run about 15 instructions. It is not impossible, but very difficult.

There are two ways to read the data in code.

Option 1: Disable interrupts, and hand-write assembler that takes exactly the right amount of time. If you branch, make sure all branches take the same amount of time. I think all assembler instructions on Atmel take 1 cycle. You will need to pad out your loop to a predictable size. At 1.024mhz, the clock will drift by 2.4%, which means you'll either have to supersample (e.g. take one sample every 12 instructions, then throw away the samples closest to the clock interval) or you'll have to make some loops longer than others. If you store 8 bits per byte (as opposed to having an array of 77 bytes, storing 1 bit in each, which would be quicker), then you might get away with making "move to next byte" a different length. Try to measure each sample in the MIDDLE of the allowed period, or as close to it as you can. You may have to unroll your loops (i.e. instead of "repeat this 77 times", do "do it, do it again, do it again....).

Or you might be able to write an ISR - Your ISR would have to be very short, basically "write the current time to a pre-defined array". Now you have 15 instructions to get the data out, but padding it OUT isn't so critical. With this method, you will get one datapoint per CHANGE (rising or falling signal). I don't know if micros() would be quick enough. Then, once the read is complete, you can post-process the data at your leisure. The ISR will be called at the start of the clock cycle following the change in signal, so this is likely to be easier.

UPDATE:

Micros only has a resolution of 4 microseconds, so you will have to make your own "clock". The easiest way to do this, is to set a counter with about how long you think it will take (, then hand-code a loop to decrement this, until zero. As far as I can make out, the decrement loop should take 2 cycle (decrement the counter, if-not-zero jump back to decrement). So if you start it at 800, it should take 100ms to reach zero. Remember that the ISR will stop the counter for the duration, you will need to compensate. Make sure that this loop isn't optimized out! Your ISR will be: copy the (above) counter into an array, increment your array pointer by 1 (so next time you put it in a different slot in your array). After the counter reaches zero, disable your ISR, and find the difference between each number and the next; add a constant (worked out by trial and error), round to the nearest 8 (which should be pretty close). Divide by 8. The first result should be the delay to the start of the data (first 1); the second will be the number of consecutive 1's, then the number of consecutive 0's, etc.

---
Tags: serial, hardware, servo
---


# Question
Title: Arduino Command Line Interface - How to change boardsmanager.additional.urls
I am building a Travis CI job to test my Arduino Library and it needs to install external board definitions.

Is there a way that I can set the boardsmanager.additional.urls from the command prompt like it would have been done in the Preferences window?

Or should I create preferences.txt file? (If so where does that live in a Linux environment)

# Answer
Found the solution:

```
arduino --pref "boardsmanager.additional.urls=http://arduino.esp8266.com/stable/package_esp8266com_index.json"

```
> 5 votes

---
Tags: arduino-ide
---


title: Cheap LCD with Few Pins

text:
# Question
Title: Cheap LCD with Few Pins
I am working on a project with an Arduino Nano that includes a keypad, screen, and the NRF4001 transceiver. The keypad requires 7 digital pins to operate, the wireless transceiver uses pins D9 - D13 with the RF24 library I am using. Now, that leaves me with 1 Digital Pin left for a screen unless there is an I2C screen I could use.

That would be easy enough to find except that I have some limitations. If at all possible I would like the screen to be under 5 dollars and about the size of a Nokia 5110. The Nokia uses to many pins and does not tolerate 5v logic levels I've heard. An OLED 0.96 inch is only a 4 bucks and is I2C, but it is too small. I could make a board for the keypad that used different values of resistors and one analog pin to detect different buttons but would rather not go that route if there is any easier way to get around this.

Are there any options out there that would suffice my pin, cost and size conditions or am I being too picky?

# Answer
You can use a single analog pin to read an entire keypad.

First, read up on voltage dividers - they let you convert a resistance into a voltage. You will need to know this later on.

A keypad typically has 4 inputs, and 3 outputs (or vice-versa). Label the 4 pins A,B,C,D and the 3 pins E, F, G. You will be wiring A up to a voltage supply, and G up to an analog pin, and via a suitable resistor to ground. This becomes your voltage divider.

Then, put a resistor between A+B, B+C, C+D, and between E+F, F+G. So, if you press the button that connects A to G, there will be no resistance (=+5V). If you press the button that connects A to F, then the resistance will be that of the resistance F-\>G. If you press the button that connect D and E, the circuit goes: VCC-A-resistor-B-resistor-C-resistor-D-pushbutton-E-resistor-F-resistor-G - Arduino analog pin. With no button pressed, the voltage will be 0.

You will need to work out different resistors in advance, to give you as even a range as possible between 0 and 5 volts (the critical thing being the smallest difference). You can calculate the resistance of any combination here: http://www.calculator.net/resistor-calculator.html and you can use Ohm's law to calculate the final voltage. This depends on what you have in your kit. I ended up making a spreadsheet, and then trying random resistor values until I got a good spread.

DO NOT use any resistors under 1kOhm.

Once you have the right spread, make it up on a solderless breadboard. Measure the voltage with your arduino (use the "readanalogvoltage" sketch, take out `* (5.0 / 1023.0)` , and make up a table - press button 1, you get a reading if A, press button 2, get a reading of B. Include the reading when no button is pressed, which should be 0.

Then find the numbers exactly in between.

For example, if the lowest three readings are 0,20,37 for no button, A, and B pressed, respectively, then in your code, you will say: if the pin measures less than (half way between 0 and 20=) 10, then no button is pressed; else if the pin measures less than (half way between 20 and 37=) 29, then button A is pressed... and so forth.
> 2 votes

---
Tags: lcd, hardware
---


# Question
Title: what is the importance of the resistors that connect to push buttons ? can i replace them by wires?
Please, iam a junior in arduino and i want to know what is the importance of the resistors that connect to push buttons? can i replace them by wires? thanks in advance.

# Answer
They are what is known as Pull-Up resistors. The circuit will not work if you replace them with wires. Not only that but you will short circuit the power supply when you press a button.

Why don't you want to use resistors?

The value is not important - you could use the same value as you are using for the LED if you don't have the 10k resistors shown in the drawing.

Having said that an alternative is to leave them out and instead activate the internal pull-ups within the processor on the Arduino:

```
pinMode(pin, INPUT);           // set pin to input
digitalWrite(pin, HIGH);       // turn on pullup resistors

```
> 6 votes

---
Tags: led, wires, electronics, resistor
---


# Question
Title: Burning Arduino Leonardo Bootloader to ATmega32U4 with 8MHz internal clock
Burning question:

So, I'm trying to burn the Arduino Leo bootloader onto a ATmega32U4 that's on 3.3V and the internal 8MHz clock. Do I have to modify and rebuild the bootloader to set the fuses correctly, and can this be done with AVR Studio?

All of the references on doing this are dated. The folder structure for the Arduino IDE has changed. I've done it in the past with 5V 16MHz 32U4s using an Arduino as ISP, but never with the AVRISP mkII on the Arduino IDE.

On the good side, I do have it up and running Atmel Studio.

Thanks!

EDIT: Sorry for double posting, I posted in electronics before I noticed there was an Arduino specific section.

# Answer
If you have an appropriate crystal attached then you can do this in the Arduino IDE. Select your board and programmer in the IDE menu, connect the programmer to the board, and choose `Burn Bootloader` from the menu. This will both burn the prebuilt bootloader image and set the fuses in a single operation.

Note that you cannot use USB on the '32U4 if you are running off either a ceramic resonator or the internal oscillator, and so you should not attempt to use the Leonardo bootloader in either case.
> 1 votes

---
Tags: bootloader
---


# Question
Title: Replacing atmega8 with atmega328 on Arduino Single-Sided Serial Board
i want to know that if i use atmega328-pu instead of atmega8 on this design provided by "https://www.arduino.cc/en/Main/ArduinoBoardSerialSingleSided3", will it works fine on this design or i have to use only atmega8 ?

# Answer
Yes and no. It will work on this board, but won't get programmed by arduino IDE directly.

ATmega328 and ATmega8 are fully pin compatible. ATmega328 is like bigger and powerful in terms of onchip resources. However, if you want to program ATmega328 on the arduino board, you must install bootloader. Otherwise you will have to program it everytime using ISP programmers such as USBASP. This will connect to the ICSP socket shown on the above board.

Refer to: http://tutorial.cytron.com.my/2011/09/30/how-to-program-arduino-by-using-avr-usbasp-programmer/
> 2 votes

---
Tags: hardware
---


# Question
Title: I'm looking for a way to serially communicate with a multi mesh Arduino slave network
I have one PC running Visual Studio and a program that will be sending commands to Arduinos via serial COM Ports. So, in 11 Nano MCUs, I will have motor drivers L293D/L298N ICs, while in other Nanos I will have sensors.

What I would like to do is have a program in Visual Studio which sends commands via serial to actuate motors to each and every MCU on board. This is a robotic application and everything I mentioned above will be enclosed within the Humanoid.

Here are some examples of what I'm thinking of doing:

```
char data = Serial.read();
if (data == 'A')
{
  digitalWrite(13, HIGH);
}

```

Or something like this:

```
servodata = Serial.read();
if (servodata == '1') // Single Quote! This is a character.
{
  SERVO.write(pos);
}

```

As you can see, Arduinos will have something like this running and waiting for Visual Studio to send commands via serial to one or multiple MCUs simultaneously. I'm thinking 30 char dividing/spiting that number across each Rx Arduino.

# Answer
> 6 votes
It's not obvious what the exact query is but answering the subject line question:

You can easily multidrop connect multiple serial / RS232 COM ports by having all slave RX inputs and the master TX output on one line, and all slave TX outputs connected by an OR network to a single line to the master's RX input. The master 'talks' to all slaves at once. Each slave talks to only the master. Only one slave can usefully talk at once. Message destination assignment and slave-talking arbitration is carried out in software.

As shown below, the OR network at each slave can be as simple as a diode with cathode (bar side) to TX line and anode to common line to master RX. A single pullup resistor (or an internal pullup in the master on the RX line) pulls the line high when all slave TX lines are high.

This diagram shows how simple multidrop communications can be.
**NB - As shown the diodes polarity is for true RS232 with logical 1 = low = negative.**
**When connecting directly between UART TTL lvel (5V/0V) outputs reverse the diodes.**

Also, add a pullup from +5V to the Blue RX line to the master - 10k to 5V is probably OK.

From here - **Multidrop network for RS232**.

When a slave TX pin is high its diode is "blocked" and it does not affect the common slave to master level. When any slave TX line goes low the common line is pulled low via its diode and the master sees the low. Normal RS232 COMs can occur between slave and master.

When the master sends all slaves see the transmission at once. A basic protocol must be established to allow messages to be handled by the intended recipient. This could consist of, e.g. sending an address word + command word or words. You can have a single slave act on a message or all slaves or a sunset, based on your addressing system.

The slave to master direction allows only one slave to send at one and you must ensure either that only one slave ever sends at a time and/or that collisions are able to be resolved.

Despite the obvious limitations of such a system it can work very well and is cheap and simple to implement. If there are many slaves the loadings should be checked so that e.g. the master TX is able to drive all slave RXs at once. As the circuit is unidirectional it is easy to add a basic buffer.

# Answer
> 2 votes
RS-485 or RS-422 are the normal industrial ways of having one serial port talk to many devices, especially in noisy environments with lots of motors. It requires a driver chip for each device to get the right electrical interface.

RS-485 provides bi-directional communication if you want to receive data back from your remote nodes, and RS-422 provides "simplex" or uni-directional communication if you just want to blindly send commands with no feedback.

As for software, my ICSC library would probably be the easiest route to take - it allows you to address individual devices on an RS422 or RS485 bus and send commands to them.

---
Tags: serial, softwareserial
---


# Question
Title: Arduino time keeping using millis() is not accurate or correct?
I have been using the Arduino to record some data. In my Arduino sketch I also used the `millis()` function so I can keep track of the time at which each value I am measuring is taken. However, I noticed that the timing isn't correct. For example 30 seconds in real life only comes out as 10 seconds (made up example).

Am I correct in saying that the Arduino delay function affects the time keeping using `millis()`? In other words suppose I have a delay of 50ms, does that mean the `millis()` function stops for that duration as well and then continues and so on for the duration of the connection? I noticed this when I tried plotting some data and finding that the frequency of the peaks in my data was too frequent given the time which had passed by. So I want to know if that is the reasoning for this mismatch of timing and if so, how do I fix this so that I can keep the time each sample occurs?

To give some context here is my sketch:

```
#include <eHealth.h>

unsigned long time;
// The setup routine runs once when you press reset:
void setup() {
  Serial.begin(9600);
}

// The loop routine runs over and over again forever:
void loop() {

  float ECG = eHealth.getECG();
  time = millis();
  Serial.print(time);
  Serial.print(" ");
  Serial.print(ECG, 5);
  Serial.println("");

  delay(50);
}

```

# Answer
> 10 votes
`millis()` is interrupt driven so `delay()` won't impact it, at least not on an ATmega based board.

That isn't to say that `millis()` is totally accurate either. Each tick of the timer is not exactly 1ms, but is 1.024ms. This error gradually accumulates until a correction is made. This can be seen in the implementation of the TIMER0\_OVF (timer 0 overflow) interrupt handler.

Another source of inaccuracy is the oscillator/crystal itself, which is not exactly 16MHz. It is pretty close though, and as long as temperature doesn't change too much, is relatively stable.

The above means that you might be about 1ms out when using `millis()`. This doesn't sound like your problem.

Another potential issue would be what `getECG()` is doing - it might be very slow.

```
float eHealthClass::getECG(void)
    {
        float analog0;
        // Read from analogic in.
        analog0=analogRead(0);
        // binary to voltage conversion
        return analog0 = (float)analog0 * 5 / 1023.0;
    }

```

`analogRead()` is slow, but not so slow as to impact a loop like this.

Another problem I have seen people have is when they change the clock speed but don't correctly change boards.txt. This means that the constants used in the `millis()` implementation are wrong and the times are wrong.

If you actually want to read values every 50ms, a much better way of implementing this is to do the following

```
static long lastUpdate;

if (millis() - lastUpdate > 50)
{
    lastUpdate = millis();
    //Do stuff
}

```

We'd really need to see the timestamps you are getting. If you actually seeing 30s showing as 10s, then there is something else at work.

# Answer
> 2 votes
If interrupts are turned off for any significant fraction `eHealth.getECG()` call duration, `millis()`'s count could fall behind. Otherwise, `millis()` should return much more accurate time than the 3x errors you described.

You said your sampled signal appears higher in frequency than what you expected, which could happen if your sample rate is lower than you intended. Are you a assuming a 20Hz sample rate? Your loop could be taking a fair bit longer than 50ms, which you would see in the printed times, but those should still track the clock time. If you didn't account for that but assumed 50ms/sample, you'd see an apparent speed up of of the data.

If this is not the issue, then the next step would be to toggle an output while you're in `loop()`, and measure the frequency of the resulting square wave with a frequency meter (some inexpensive DVMs can do this) or a 'scope. Do the same thing with an empty `loop()`. The first experiment will your real sampling rate or interval; the second will tell you whether `millis()` (ie., the timer0 frequency) is what you expected.

# Answer
> 0 votes
Same here. I can add that if interruptions are turned off, the time measured is "real time". Anyway, I dont understand why this delay, because if the loop take too long, anyway the millis() should return real time values (only with more distance between each value)

---
Tags: arduino-uno, programming, time
---


# Question
Title: How can I stop my Arduino UNO rev 3 from briefly turning on digital output pins on startup or reset?
I am using my Arduino UNO rev 3 to control other devices via the digital output pins. On startup or reset, I find that these pins are all briefly turned on (perhaps as part of a self test). This interferes with my application. How can I suppress this?

# Answer
> 1 votes
Digital pin 13 will be turned on briefly as part of the bootloading process (it flashes a few times). Thus this is not a good choice of pin for a device like a motor to be connected to. Also if you are uploading a new sketch the Tx pin (digital pin 1) will be turned on and off.

You can change the processor fuses to not use the bootloader, which would avoid these issues, however then you have to change them back to upload a new sketch - unless you upload using ICSP instead of the bootloader.

As Gerben and Majenko have pointed out, any other issues could be from "floating" pins which some devices might interpret as having a HIGH on them, possibly. Pull-down resistors could help there (or pull-up if that is more appropriate).

The ideal thing could be to structure your system in such a way that the two pins (1 and 13) which come on during the bootloading process are connected to something "harmless" (eg. an LED) rather than "harmful" (eg. a motor).

---
Tags: arduino-uno, digital
---


# Question
Title: Are there any Analog pins on the mega that can not be used as Digital?
I am using both Arduino nano and Arduino mega boards in my projects. I got a nasty surprise the other day when I learned that, on the nano, Analog pins 6 and 7 can not be used as digital pins.

Are there any Analog pins on the mega that can not be used as Digital?

# Answer
No, the ATmegaXXX0 has no analog pins without GPIO capability.

Additionally, the ATmegaXX8P**B** *adds* GPIO capability to the other analog pins plus a couple of the supply pins, so if you can convince someone to slip one of those on instead then you will gain two GPIOs (a respin will be required to access the ones on supply pins). Note that the core will also need to be modified, but it's only a couple of quick changes.
> 3 votes

# Answer
On https://www.arduino.cc/en/Main/ArduinoBoardNano it says:

> Analog pins 6 and 7 cannot be used as digital pins.

There is no such corresponding statement on https://www.arduino.cc/en/Main/ArduinoBoardMega2560 and judging by the datasheet all of the analog pins can be used as digital pins.
> 2 votes

---
Tags: arduino-mega, pins, analogread, digital-in
---