# Question
Title: What are the implications of running an ATmega328P at 8 MHz and 3.3 V with the Arduino system?
I'm working on a custom arduino that will run at 3.3 V with no regulators or USB chips (for power consumption). I've heard that overclocking the chip at 16 MHz/3.3 V is generally fine, but I'd like to stay within spec anyway.

First: to run at 8 MHz, do I just need to replace the crystal? Or is there anything else I have to do?

Second: Do I need to make any code changes to reflect the new speed? I'm using serial, SPI, and I2C connections in this project, along with the NilRTOS operating system and millis/delay functions. Will any of these be broken? Will the code run noticeably slower?

Third: How can I program the chip? Is it ok to program it in an Arduino Uno at 16 MHz, then transplant it to the custom arduino?

Fourth: Will power consumption change at 8 MHz?

Thanks!

# Answer
> 7 votes
The formula seems to be volt\*5.9-6.6=mhz (valid between 1.8v and 4.5v), so at 3.3v, this would give 12.8mhz. Be aware that, if you are running at 12.8mhz, ANY drop below 3.3v MAY cause problems (and very hard to diagnose, too!) or you MAY get away with it.

However, Arduino Atmega328p chips have a "brown-out" detection set at 4.3v - any drop below that, the chip shuts down. You can get an ISP (AKA ICSP) to change the fuses - go to http://www.engbedded.com/fusecalc/ to work out what to set fuses to. You can also use the ISP to read the current fuses, or indeed reprogram the chip without an Arduino board - all my projects have a 6-pin header. If you do this, before reprogramming using the Arduino board, you will have to "Burn Bootloader" (in the tools menu). Note that programming can still be done via Arduino IDE.

Alternatively, if you want to go "light" (and have an ISP), you can change the fuses to use the internal 8mhz clock - this frees up 2 extra pins, too! Be aware, however, that the internal clock may drift 1.2 hours per day (=5%), compared to 1.7 seconds per day (=20 parts per million) on a typical quartz crystal. If you don't use it for timekeeping, this probably doesn't matter.

You will need to make changes to the timing, for your code - you need to add a boards.txt with correct settings for your chip/clockspeed etc - you can copy the settings from the entry for the board, change the name, and change the setting "build.f\_cpu"; restart (or start) your Arduino IDE, go to "Tools-\>Board" and select the board you added.

You can move the chip on/off the board, and reprogram it there (note that the board selected in Tools-\>Board is the FINAL board, not the programming board). Be careful plugging/unplugging it - eventually, you WILL bend the pins! Alternatively, you can use ISP (ICSP), as mentioned above - much recommended. ISP programming will also work if the chip is factory default, so long as it has a working clock.

How much power is used by the chip depends hugely on what you do with it - not just clock speeds, clock source, etc but also sleep modes. If you are sleeping a lot, it may draw less when running faster than running slower - if almost all your time is asleep, then the power consumption should be counted per clock cycle, not per second - if your clock is half the speed, and half current, then you draw the same current per instruction. Since the rest of your time is spent asleep, you get no benefit. See http://www.gammon.com.au/power for a very good breakdown of power usage, tips on how to save power, etc.

If you slow your clock down too much, serial and i2c may become unreliable (unless you slow down the speed), but I would expect to be able to go down to 1mhz before this to be a problem - a 1mhz chip trying to do 9600bps has 104 instructions per bit of data transferred. i2c runs at 100khz, so you get 10 instructions per bit (at 1mhz) - possibly pushing it. 8mhz should be fine. Test, test, test.

UPDATE: There are 3 possible settings for the brown-out detection - there are 3 possible values for the AtMega328p: disabled, 1.8v, 2.7v, and 4.3v. I was under the impression (above) that Arduinos were normally set to 4.3v; apparently that is not the case (see comment below). I recall seeing somewhere that there was brownout detection. This is something to keep in mind, if your arduino resets, especially when putting larger loads on the battery (running motors, multiple leds etc).

# Answer
> 4 votes
> First: to run at 8 MHz, do I just need to replace the crystal? Or is there anything else I have to do?

No, run on the internal oscillator as suggested by AMADANON Inc.

Alternatively, set the "divide clock by 8" fuse (which would run it at 2 MHz from a 16 MHz crystal) and then in code change the division back up to 2. ie.

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

void setup ()
  {
  // slow clock to divide by 2
  clock_prescale_set (clock_div_2);
  } // end of setup

```

Or for programming in another Uno leave the fuse alone, program at 16 MHz and then drop the clock down in the target chip, hoping it works long enough at 3.3V to execute that first instruction. The safest thing would be to just install an 8 MHz crystal or resonator on the target board. However if timing is not critical run with the internal oscillator.

> Second: Do I need to make any code changes to reflect the new speed? I'm using serial, SPI, and I2C connections in this project, along with the NilRTOS operating system and millis/delay functions.

If you tell the IDE you have an 8 MHz processor (eg. a Lilypad) then it should adjust delays, baud rate calculations etc. appropriately.

> Will any of these be broken?

I2C and SPI are self-clocked. They can run at a variety of rates. I doubt there will be any problems with them. As for serial, providing the calculations are done right a wide range of baud rates should still be available.

> Will the code run noticeably slower?

Well yes, it will run at half speed compared to 16 MHz.

> Third: How can I program the chip? Is it ok to program it in an Arduino Uno at 16 MHz, then transplant it to the custom arduino?

You can do that. Or you could connect up an ICSP header or an FTDI header and program it in situ.

Examples here: http://www.gammon.com.au/breadboard

> Fourth: Will power consumption change at 8 MHz?

Yes, it is reduced somewhat.

You can reduce it considerably more by using other techniques as described at http://www.gammon.com.au/power, and referred to by AMADANON Inc.

---
Tags: atmega328
---


title: Data at Serial Port Avaliable

text:
# Question
Title: Data at Serial Port Avaliable
I am interfacing a GSM modem via Arduino at Serial port 2.

I have seen that responses fron GSM modem are subject to time. Sometime its response are fast and sometime it are slow. I have a code like below which checks for response from GSM modem based upon a user configurable timeout value:

```
sendATcommand(str_at_cmd, str_ok, 500);

int8_t sendATcommand(char* ATcommand, char* expected_answer, unsigned int timeout)
{
    uint8_t x=0;
    char response[100];
    unsigned long previous;
    int answer = 0;
    memset(response, '\0', 100);
    answer = 0;;
    delay(100);
    ClearSerialData(); // read and flush all data
    debug_println(ATcommand);
    Serial2.println(ATcommand);
    delay(200);
    x = 0;
    previous = millis();
    do {
       if(Serial2.available() > 0){
       response[x] = Serial2.read();
       delay(100);
       debug_print(response[x]);
       response[++x] = '\0';
       if (strstr(response, expected_answer) != NULL)
       {
           debug_print("\nAnswer Mathced");
           answer = 1;
       }
       }
    }while((answer == 0) && ((millis() - previous) < timeout));
    debug_println("\nReturning from AT Command");
    return answer;
}

```

I was never able to set the correct timeout value - as at random test it failed once or twice and not received 100% success.

My question if I change the code like below

```
while(Serial2.available() > 0){
   response[x] = Serial2.read();
   delay(100);
   debug_print(response[x]);
   response[++x] = '\0';
   if (strstr(response, expected_answer) != NULL)
   {
       debug_print("\nAnswer Mathced");
       answer = 1;
   }
}

```

So when does Serial2.available() method returns \<= 0 value. Is my above code correct - this way I overcome the timeout issue and all my GSM responses are being read - are there scenarios that I will end up in infinite loop?

# Answer
Your code is flawed in that you are waiting a fixed time, and then hoping that the entire response will arrive quickly. Personally I would send the query, and then exit the function. Test for incoming data in your main loop, and process it when it is all received. Techniques described here: http://www.gammon.com.au/serial

The whole thing should be able to be written without delay().
> 1 votes

---
Tags: serial, arduino-mega, gsm
---


# Question
Title: Using shiftin() and shiftout() with the same circuit - what to consider?
I am designing a smart (or at least I hope so) onboard bicycle light system. The system will have an Arduino (currently prototyping with UNO) and a subsystem composed of a "panel" of buttons and leds.

This panel should stay at the handlebar, connected by multi-wire cable to the Arduino located elsewhere on the bicycle.

In order to read an arbitrary number of push-buttons, I plan to use CD4021 IC with `shiftIn()` function. And, in order to turn an arbitrary number of leds on and off, I plan to use 74HC595 IC and the `shiftOut()` function.

My doubts are: what should I consider in order to do so?

1. How many wires should I need to connect an arduino to the panel circuit containing the ICs? I believe it is 8 wires (two for the power, three for shifting in \[latch, clock, data\], and three for shifting out), right?
2. Can I use any pin I want? Or is it required to use specific pins?
3. Is that the "right way" of doing this? Any suggestion or improvement is welcome!

# Answer
I have a post here about using an I2C 16-port port-expander: http://www.gammon.com.au/forum/?id=10945

That would use 4 wires for I2C (power, ground, SDA, SCL) or there is an SPI version which would require an extra wire (power, ground, SCK, MOSI, MISO).

I'm not sure about noise over your cable runs, on a bicycle presumably electrical noise is low, so either one might suit. This is the chip that Ignacio Vazquez-Abrams mentioned in his comments. Any of the 16 ports can be configured as inputs or outputs as you desire, plus it can raise an interrupt on a change on an input pin.

You might find that the maximum current limits for output may not be adequate for your LEDs (the datasheet says maximum of 25 mA per output pin, plus a maximum of 125 mA for the whole chip). You could work around this with driver transistors on the chip output, but this is more complexity.

There are higher-powered shift registers (eg. TPIC6B595) which can handle more per pin than the 74HC595.

> Can I use any pin I want? Or is it required to use specific pins?

If you want to use I2C there are two specific pins dedicated to the I2C hardware. If you want to use SPI there are dedicated hardware pins as well (different ones) but you can also "bit-bang" SPI if you want.

See:

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

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

> Is there a through-hole version of that?

All the chips I mention here have through-hole versions.
> 1 votes

---
Tags: button, digital, shift-register
---


title: Simple question about && vs ||

text:
# Question
Title: Simple question about && vs ||
I want to skip all `'\r'` and `'\n'` chars and I have IF statment:

```
char c = Serial.read();
if (c != '\r' || c != '\n') { // <- This line interesting
   mAnswer[mAnswerLength] = c;
   mAnswerLength++;
}

```

VS

```
char c = Serial.read();
if (c != '\r' && c != '\n') { // <- This line interesting
   mAnswer[mAnswerLength] = c;
   mAnswerLength++;
}

```

What is better and what is the difference?

# Answer
> 4 votes
Think about it "logically" (pun intended...):

You read a character. Say it's "A". You then compare it to both '\r' and '\n'.

```
char c = Serial.read();
if (c != '\r' || c != '\n') { // <- This line interesting
    mAnswer[mAnswerLength] = c;
    mAnswerLength++;
}

```

That is saying "If A is not CR or A is not LF then add it". Since it's A and not LF or CR then it's going to add it. Now imagine it's CR. "If CR is not CR or CR is not LF then add it". CR is CR, so the first part will be false. But CR isn't LF, so the second part is true. If it's OR, then if either part is true then it will be true. So since CR is not LF it will add it.

Now:

```
char c = Serial.read();
if (c != '\r' && c != '\n') { // <- This line interesting
    mAnswer[mAnswerLength] = c;
    mAnswerLength++;
}

```

That is saying "If A is not CR and A is not LF then add it". Since it's A and not LF or CR then it's going to add it. Now imagine it's CR. "If CR is not CR and CR is not LF then add it". CR is CR, so the first part will be false. But CR isn't LF, so the second part is true. Just as before. However, if it's AMD, then if BOTH parts are true then it will be true. So since CR is CR it won't add it.

In summary, the first one will ALWAYS be true since one half is always going to be true. The second one will ONLY be true if BOTH parts are true. So the first one just plain isn't going to do what you want.

# Answer
> 1 votes
You can rewrite first condition to be more obvious

```
if (c != '\r' || c != '\n') {

```

as

```
if (!(c == '\r' && c == '\n')) {

```

Which is always true (`c` have only one value), i.e. it makes no sense.

# Answer
> 0 votes
|| means logical OR

&& means logical AND

---
Tags: code-optimization
---


# Question
Title: Unable to alter SPI speed on Arduino Micro
I am using SPI to communicate with a IMU device which is working perfectly, except the SPISpeed which is not being altered as it should:

```
unsigned int m_SPISpeed = 400000;
SPI.begin();
pinMode(m_SPISelect, OUTPUT);
m_SPISettings = SPISettings(m_SPISpeed, MSBFIRST, SPI_MODE0);
...
SPI.beginTransaction(m_SPISettings);
digitalWrite(m_SPISelect, LOW);
SPI.transfer(regAddr | 0x80);

```

Where `m_SPISpeed` is 400000. No matter what i set this value to it is always operating at `125000Hz`.

# Answer
> 1 votes
As was pointed out in the question comments, your use of **unsigned int** is the problem. The prototype for SPISettings is:

```
SPISettings(uint32_t clock, uint8_t bitOrder, uint8_t dataMode) {

```

The comments in spi.h say:

```
// We find the fastest clock that is less than or equal to the
// given clock rate. The clock divider that results in clock_setting
// is 2 ^^ (clock_div + 1). If nothing is slow enough, we'll use the
// slowest (128 == 2 ^^ 7, so clock_div = 6).

```

So your SPI speed will be the processor speed divided by 128, which is 16 MHz divided by 128, being 125000 Hz, which is your observed result (since unsigned int cannot possibly hold more than 65535 on this platform).

---
Tags: arduino-ide, spi, arduino-micro
---


title: Slaving multiple Arduinos via SPI

text:
# Question
Title: Slaving multiple Arduinos via SPI
I am attempting to use SPI communication between a Master Arduino Mega 2560, and standalone Slave Arduino Unos (4, to be exact).

**The intention** is for the Unos to do some trivial work and produce one byte of data that the Master will take from it, whenever needed. They produce this byte very quickly, and the SPDR is updated with a holding variable (a byte) when the slave is interrupted. The Slaves do not take data from the Master.

The standalone platforms are working 100% (doing the work without problem), and using a single Slave to perform the work, create the byte of data, and have a Master take that data from it, is also working 100%.

**The issue** When all four slaves are connected (all being powered from the Master), all sharing the MISO, MOSI, and SCK lines, each with its own unique SS line, I am getting xFF for my data byte (garbage data) from the primary slave. I am using the default Mode 0, and the SCK lines are tied to ground via a 0.1uF capacitor (to smooth the clock signal)... All other SPI lines are wired directly.

The other three slaves are floating their MISO lines (third state), and the Master has all four SS lines as outputs, and all are pulled HIGH in the Master setup. The primary slave I am attempting to communicate with is SS connected to the main SS on the Master (pin 53 on a Mega). I pull the pin LOW, grab the byte from the Slave, and then pull the line HIGH... still garbage.. but only when all four slaves are 'hooked up', like I said, it works fine with one Master, one Slave.

Anyone have thoughts as to what I could be neglecting, missing, etc??

---

Here is the slave schematic. What you can't see is that VCC and AVCC are tied to the 5V line from the 10-pin header (the connection to the master).

The external power supply I am currently using is added in parallel to the 5V/Grnd you see in the schematic. The power supply has a max current draw at 5V of 10A, so I'm pretty confident that power is not my issue now, unless I have missed something.

I just realized that the imgur image is hard to see, here is a cut-away that should be clearer.

# Answer
> 2 votes
> the SCK lines are tied to ground via a 0.1uF capacitor (to smooth the clock signal)

Get rid of that for a start.

> The other three slaves are floating their MISO lines (third state)

That's your problem. They should all be outputs. From the datasheet:

> When the SPI is configured as a Slave, the Slave Select (SS) pin is always input. When SS is held low, the SPI is activated, and MISO becomes an output if configured so by the user. All other pins are inputs. When SS is driven high, all pins are inputs, and the SPI is passive, which means that it will not receive incoming data. Note that the SPI logic will be reset once the SS pin is driven high.

As you can see from that, you should configure all the MISO pins as outputs. However the SPI hardware will turn them into inputs if SS is high. Thus only one slave (the one you set MISO as an output) is capable of responding at present.

You should probably set them as outputs **after** turning on SPI slave mode. eg.

```
  // turn on SPI in slave mode
  SPCR |= bit (SPE);

  // have to send on master in, *slave out*
  pinMode (MISO, OUTPUT);

```

---
Tags: spi
---


# Question
Title: Can do I make an Arduino program that can decipher telephone touch tones?
I have an old land line phone that I want to connect to my Arduino. Then I would like to write a program that can decipher the touch-tone button presses (which are a combination of two tones) so that the Arduino can react to specific key presses and numeric sequences. My final goal is to make the Arduino play specific messages when the user enters in codes. I am really not sure even where to begin.

Thanks for the hardwares fixes for this problem, but if possible, I am looking for a softwares solution.

This will be used to make a telephone (with an attached Arduino) that will play a series of conversations when specific codes are dialed.

# Answer
> 3 votes
As John Taylor said, DTMF is not a single tone but two tones transmitted simultaneously, which select the digit from a two-dimensional grid. (*Dual* tone multi-frequency). This allow 16 possible combinations from only 8 distinct tones.

There are chips available specifically for the task of decoding DTMF, but it's always nice to try and find a one-chip solution.

There are two solutions that I can think of:

* ArduinoFFT \- a **Fourier transform** is an operation that splits a time-based signal into its frequency components. If you control the ADC directly instead of via the Arduino library, it is easily fast enough to sample a DTMF signal. Once you've done the FFT you just need to find the peaks in the output, which will tell you the tones that are present.
* If you put the signal through the analog comparator and **count the rate of zero-crossings** (use an interrupt with a routine that increments a number, you may miss some if you just poll the pin), the rate of crossings should be **unique for each tone combination**. Counting for e.g. 10 ms and looking up the closest match from a table you've pre-measured should give reliable decoding, and is a slightly less brute-force approach than an FFT.

That said, you won't be able to beat a dedicated chip (although I personally think this way is much more fun.)

Happy hacking!

# Answer
> 3 votes
It is possible to decode DTMF tones with only a few common external components. The trick is to turn the analog audio into a digital signal, and then check the timing between the leading and trailing edges in order to figure out which tone is present.

First, create a 1.1V bias using a voltage divider. This bias will connect to both a capacitor that is coupling the audio, as well as one of the analog inputs. **Note that phone lines have high voltages on them at times, and you must have both isolation and voltage clamping in place before connecting a device to one.**

Second, enable the analog comparator in the MCU. See the "Analog Comparator" section of the MCU datasheet for details. Configure the non-inverting input to connect to the internal bandgap reference, the inverting input to connect to the analog input chosen earlier, and the output to connect to the input capture facility.

Third, configure the input capture facility in the MCU. See the "16-bit Timer/Counter1 with PWM" section of the datasheet, with particular emphasis on the "Input Capture Unit" subsection. Note that there is no way to trigger the input capture on "any" edge, therefore you will need to either flip the capture edge select bit each time, or you will need to detect the tone from only one set of edges. Also note that you will need to use the overflow interrupt to increment your explicit "high bytes" counter in case the edges to be detected appear on opposite sides of the overflow.

Now that all that is done, all that remains is to compare the timing detected by the input capture with your internal table of timings and select the appropriate tone from that. But that's the easy part.

# Answer
> 2 votes
DTMF is actually two non-harmonically related frequencies transmitted at the same time as opposed to a single frequency tone that can be measured with the above process, hence Dual-Tone-Multi-Frequency:

You can use the Rohm BU8872 series devices which decodes the 4 x 4 multi tone combinations directly into a 4 bit digital result per the grid above. This also works the same way in the Mitel MT8870 series devices (I think they were bought by Microsemi). These have digital filtering which pick out the two signals and some devices can even do single tone detection.

---
Tags: programming, arduino-mega, analogread, sound, analog-sampling
---


# Question
Title: Is it possible to control the speed of DC motors with Arduino's analogWrite() using analog pins?
I'm trying to control the speed of two DC motors that are connected to a dual H bridge. I always used digital PWM pins with `analogWrite()` to change the speed, but since I'm making a project that will be using most of the digital pins, I wonder if I can use analog pins instead.

P.S. I know I can use analog pins as digital pins to free the digital PWM pins, but I'm not interested in doing that.

# Answer
No, you can't. As it says in the Arduiuno reference page for analogWrite(): "The analogWrite function has nothing to do with the analog pins or the analogRead function."

You can use the "analog input pins" (A0..A5) of Arduino for analog input, or as digital inputs or outputs. They cannot be used for PWM(digital)-output. Only digital pins, and only those specifically stated for PWM-output, can actually be used for PWM output (unless you go down the path of software-PWM, though I would hesitate to do that for an H-bridge).
> 1 votes

# Answer
You can't do it with the analogWrite function as that is reliant on physical binding beween certain pins and hardware timers inside the AVR. But you can always use SoftPWM because the the analog pins can generally be used as digital pins just as well.
> 1 votes

# Answer
You can use multiplexers if you are running out of digital pins or SPI PWM drivers for the motors. There are many multichannel drivers out there like TLC5940, put a power stage after them and you're done.

\*Use Soft SPI on the analog pins to control the driver.
> 0 votes

---
Tags: pwm
---


title: Shift registers. What, how and why?

text:
# Question
Title: Shift registers. What, how and why?
I'm making a project and I'm using multiple 1 digit 7 segment displays. I haven't plugged them all on my arduino because currently I'm just testing. The problem is on the I/O ports. Obviously I need to use shift registers and since it's my first time ever using them I need to know more about them. After googling, I found that the specific model I bought outputs 8 pins and you can stack up to 8 in series. So lets do the math. `8 shift register` x `8 pins each SR` = `64 new pins` It seems cool but assuming I'm using 28 displays let's do the math again. 28 displays, each display has 8 pins (8 for segments and 2 as common cathode) `28` x `8` = `224` required pins. Is is possible to expand the I/O pins by 224 pins? How many shift registers can I stack together? Also which is better, the single digit display or the 4 digit display?

# Answer
You can chain as many shift registers as you want.

Most commonly, these displays are multiplexed. Only one digit is lit at a time, cycling though all the digits fast enough, so the eye can't tell. This is however not very good practice for 28 digits, as the brightness will become 1/28th (though you could create groups of digits, and multiplex those groups separately).

There are specialized chips that do this multiplexing for you. E.g. the Max7219. This chip can multiplex 8 digits, with 8 segments. So you'd need 4 of these to light up 28 digits.
> 4 votes

# Answer
You can buy these displays on eBay for a few dollars. A bit of soldering and you are done (although also pre-assembled ones are available). They can be daisy-chained. Example:

You only need 5 wires to the Arduino: Gnd/5V/MOSI/SCK/SCK.

Also, 64-dot displays for displaying arbitrary text:

Again, only 5 wires.

I have Arduino libraries for driving both sorts of display on Interfacing LED displays with the MAX7219 driver.
> 1 votes

---
Tags: arduino-uno, pins, communication, display, shift-register
---


# Question
Title: Why all blink tutorials use 330 ohm resistor
When I do the led calculation I found 150 ohm resistor is enough for 3mm red led. If so why all arduino tutorials, like this one, are suggesting 330 ohm resistor?

I assume V = 5 Volt, diode forward voltage = 2V and diode forward current 20mA

# Answer
> 4 votes
150 Ohms may be "enough", but it's often still far too bright, so many tutorials keep a lower limit of around 10mA to help the LED live longer without affecting the application.

You'll probably find that red LEDs are still visible at 1mA and a 330 Ohm resistor with a 5V supply will give about 8.5mA (assuming a 2.2V drop), which is plenty.

It's really a "lazy" choice that will work well in "most" situations.

# Answer
> 3 votes
An important consideration is that the chip cannot necessarily source 20 mA on all output pins at once. In fact pins D5 to D13 on the Uno (PD5 to PD7, and PB0 to PB5) cannot source more than 150 mA combined. Thus the maximum you could source on those pins, if you are driving them all at once, is 150 / 9 = 16 mA.

So, designing for 10 mA per LED is allowing a safety margin, possibly to save tutorials the complexity of explaining that 20 mA is OK for one pin, but not for all the pins at once.

---
Tags: led, resistor
---


# Question
Title: How many interrupt pins can an Uno handle?
I am looking at using a 7 channel RC receiver with the Arduino Uno R3. In the documentation, there are mentions of a maximum of 2 interrupt pins, whereas on certain other blogs I have seen mentions of using upto 20 pins as interrupts, with PinChangeInt library. So, how many interrupts can the Arduino handle natively? And is this different from how many can be handled with software support such as PinChangeInt?

# Answer
> 18 votes
There are two types of "pin change" type interrupts. The external interrupts, of which there are two on the Uno. They are called 0 and 1, however they refer to digital pins 2 and 3 on the board. These can be configured to detect rising, falling, change (rising **or** falling) or LOW.

In addition to that are "pin change" interrupts, which detect a change to the pin state in any of the 20 pins (A0 to A5, and D0 to D13). These pin change interrupts are also **hardware based** so, in themselves, will be as fast as the external interrupts.

Both types are slightly fiddly to use at the register level, but the standard IDE includes attachInterrupt(n) and detachInterrupt(n) which simplifies the interface to external interrupts. You can also use the Pin Change Library to simplify the pin change interrupts.

However, steering clear of the library for a minute, we can establish that pin change interrupts can be as fast, or faster, than external interrupts. For one thing, although pin change interrupts work on batches of pins, you don't have to enable the whole batch. For example, if you want to detect changes on pin D4, this will suffice:

Example sketch:

```
ISR (PCINT2_vect)
 {
 // handle pin change interrupt for D0 to D7 here
 if (PIND & bit (4))  // if it was high
   PORTD |= bit (5);  // turn on D5
 else
   PORTD &= ~bit (5); // turn off D5
 }  // end of PCINT2_vect

void setup ()
  {
  // pin change interrupt (example for D4)
  PCMSK2 |= bit (PCINT20);  // want pin 4
  PCIFR  |= bit (PCIF2);    // clear any outstanding interrupts
  PCICR  |= bit (PCIE2);    // enable pin change interrupts for D0 to D7
  pinMode (4, INPUT_PULLUP);
  pinMode (5, OUTPUT);
  }  // end of setup

void loop ()
  {
  }

```

My testing indicates that it took 1.6 µs for the "test" pin (pin 5) to react to a change on the interrupt pin (pin 4).

---

Now if you take the simple (lazy?) approach and use attachInterrupt() you will find the results are slower, not faster.

Example code:

```
void myInterrupt ()
 {
 if (PIND & bit (2))  // if it was high
   PORTD |= bit (5);  // turn on D5
 else
   PORTD &= ~bit (5); // turn off D5
 }  // end of myInterrupt

void setup ()
  {
  attachInterrupt (0, myInterrupt, CHANGE);
  pinMode (2, INPUT_PULLUP);
  pinMode (5, OUTPUT);
  }  // end of setup

void loop ()
  {
  }

```

This takes 3.7 µs to change the test pin, a lot more than the 1.6 µs above. Why? Because the code the compiler has to generate for the "generic" interrupt handler has to save every conceivable register (push them) on entry to the ISR, and then restore them (pop them) before returning. Plus there is the overhead of another function call.

---

Now we can work around that by avoiding attachInterrupt() and doing it ourselves:

```
ISR (INT0_vect)
 {
 if (PIND & bit (2))  // if it was high
   PORTD |= bit (5);  // turn on D5
 else
   PORTD &= ~bit (5); // turn off D5
 }  // end of INT0_vect

void setup ()
  {
  // activate external interrupt 0

  EICRA &= ~(bit(ISC00) | bit (ISC01));  // clear existing flags
  EICRA |=  bit (ISC00);    // set wanted flags (any change interrupt)
  EIFR   =  bit (INTF0);    // clear flag for interrupt 0
  EIMSK |=  bit (INT0);     // enable it

  pinMode (2, INPUT_PULLUP);
  pinMode (5, OUTPUT);
  }  // end of setup

void loop ()
  {
  }

```

That is the fastest of them all at 1.52 µs - it looks like one clock cycle got saved somewhere.

---

There is one caveat though, for pin-change interrupts. They are batched, so if you want to have interrupts on lots of pins, you need to test inside the interrupt **which** one changed. You could do that by saving the previous pin status, and comparing it to the new pin status. This is not necessarily particularly slow, but the more pins you need to check, the slower it would be.

The batches are:

* A0 to A5
* D0 to D7
* D8 to D13

If you just want a couple more interrupt pins, you could avoid any testing by just choosing to use pins from different batches (eg. D4 and D8).

---

More details at http://www.gammon.com.au/interrupts

# Answer
> 8 votes
There are two types of interrupts. What the **Arduino Playground** said:

> The processor at the heart of any Arduino has two different kinds of interrupts: “external”, and “pin change”. There are only two external interrupt pins on the ATmega168/328 (ie, in the Arduino Uno/Nano/Duemilanove), INT0 and INT1, and they are mapped to Arduino pins 2 and 3. These interrupts can be set to trigger on RISING or FALLING signal edges, or on low level. The triggers are interpreted by hardware, and the interrupt is very fast. The Arduino Mega has a few more external interrupt pins available.
>
> On the other hand the pin change interrupts can be enabled on many more pins. For ATmega168/328-based Arduinos, they can be enabled on any or all 20 of the Arduino's signal pins; on the ATmega-based Arduinos they can be enabled on 24 pins. They are triggered equally on RISING or FALLING signal edges, so it is up to the interrupt code to set the proper pins to receive interrupts, to determine what happened (which pin? ...did the signal rise, or fall?), and to handle it properly. Furthermore, the pin change interrupts are grouped into 3 “port”s on the MCU, so there are only 3 interrupt vectors (subroutines) for the entire body of pins. This makes the job of resolving the action on a single interrupt even more complicated.

Basically, the external interrupts are extremely fast since they're all hardware based. However, there is also the pin change interrupts, but those seem to be much slower because they are mostly software based.

**tl;dr:** the 20 interrupt pins together are much slower. The 2 interrupt pins are the fastest and most efficient.

---

**EDIT:** I just looked at the datasheet and it says that a pin change interrupt is triggered for *any* of the pins selected with no indication of which pin has changed (although it is split into three interrupt vectors).

* For external interrupts, it'll tell you *pin 3 just changed*
* For pin change it'll tell you *a pin changed that you were monitoring!*

As you can see, a pin change interrupt adds a lot of overhead into the ISR that you have to handle by storing previous states and seeing if it's the pin you're worried about. It might be fine for a sleep state, but it's better to use the external interrupts.

---
Tags: arduino-uno, interrupt
---


# Question
Title: Can't drive long NeoPixel strips with Due or Duemilanove?
I spent a significant part of today developing a sprite movement library for a 30-pixel NeoPixel strip using my Arduino Duemilanove (ATmega 168). It works like a charm. However, if I change `N_LEDS` to a significantly higher value, the program seems not to run. I can't get it to run on the Duemilanove for a strip of longer than 50.

In fact, (see the below code) a relatively high `N_LEDS` value won't even allow the test patterns to run as defined in `setup()`. This leads me to believe that inexplicably the constructor for `Adafruit_Neopixel` is failing.

A friend of mine (who has the ultimate application for this) is hoping to drive a strand of 750 LEDs using this code on an Arduino Due. I can't imagine memory would be an issue with the Due, so what's going on here?

Headers:

```
#include <Adafruit_NeoPixel.h>

#define PIN    6
#define N_LEDS 30      // <-- If this number is > ~50, nothing happens
#define MAXSPRITES 5
#define MIN_UPDATE_INTERVAL_IN_MS  15
#define MAX_UPDATE_INTERVAL_IN_MS  40
#define SENSOR_TIMEOUT_IN_MS  2000
#define SCANNER_WIDTH  9

```

Strip declaration:

```
Adafruit_NeoPixel strip = Adafruit_NeoPixel(N_LEDS, PIN, NEO_GRB + NEO_KHZ800);

```

`setup()` and `loop()`:

```
void setup() {
    randomSeed(analogRead(0));

    strip.begin();

    darkenStrip();

    manager = new SpriteManager();
    manager->Add(new TestPatternSprite(0, 0xff0000));
    manager->Add(new TestPatternSprite(5, 0x00ff00));
    manager->Add(new TestPatternSprite(10, 0x0000ff));
}

loop() {
    ...
}

```

Are there any coding mistakes in the above that wouldn't allow us to run this code on the Due? Or is this a known limitation?

# Answer
Your Duemilanove only has 1k of RAM. That's not much. Each pixel takes 3 bytes of RAM (R/G/B). So (say) 60 pixels would be 180 bytes. That's less than 1k, but there would be other uses of RAM in your sketch.

750 LEDs sounds like pushing it for the low-RAM Arduinos.

You might want to look at NeoPixels Revealed: How to (not need to) generate precisely timed signals The author managed to drive over 1000 NeoPixels with a Duemilanove.

I'm not sure if that applies to your exact type of NeoPixels, but it is worth considering.
> 4 votes

---
Tags: arduino-due, adafruit, arduino-duemilanove
---


# Question
Title: Where is documentation on Arduino's Internal Interrupts?
First time arduino programmer here...however I have programmed the TI MSP430 in the past...

I am trying to figure out how to configure internal Interrupt Vectors on this Arduino Uno.

In the Arduino IDE, I am skeptical about writing lines of code like

```
ISR(TIMER1_CAPT_vect) {
    Serial.Print("Entered Capture Vector");
}

```

Because it doesn't appear to matter what I type inside ISR(), for instance I can write ISR(GibERisH) { }

And it still compiles and uploads to the arduino. What?! Also how could Arduino IDE know what the heck TIMER1\_CAPT\_vect is without having the library?

I found a list of interrupt vector names here: http://www.nongnu.org/avr-libc/user-manual/group\__avr\__interrupts.html

But I can not find documentation ANYWHERE ELSE on what to call these interrupt vectors.

Should I abandon the Arduino IDE and go with the Atmel Studio 6.2 (There is a juicy looking arduino plug-in...)? I need advanced control of the guts of this processor, and there is zero documentation about how to do this anywhere on the internet.

---

EDIT: I realized my problem was I was looking for documentation for the atmega16U2 (that does something else on the board), not the atmega328P.

# Answer
> 6 votes
The vector names are all defined within the header files for the main chip in the compiler. The IDE doesn't need to know anything about that kind of thing - that's all up to the compiler.

Look for the files "lib/avr/include/avr/io\*.h within the compiler in your chosen IDE. In there are all the chips and all their definitions.

For instance, the ATMega328P definition (iom328p.h) has this list:

```
#define INT0_vect         _VECTOR(1)   /* External Interrupt Request 0 */
#define INT1_vect         _VECTOR(2)   /* External Interrupt Request 1 */
#define PCINT0_vect       _VECTOR(3)   /* Pin Change Interrupt Request 0 */
#define PCINT1_vect       _VECTOR(4)   /* Pin Change Interrupt Request 0 */
#define PCINT2_vect       _VECTOR(5)   /* Pin Change Interrupt Request 1 */
#define WDT_vect          _VECTOR(6)   /* Watchdog Time-out Interrupt */
#define TIMER2_COMPA_vect _VECTOR(7)   /* Timer/Counter2 Compare Match A */
#define TIMER2_COMPB_vect _VECTOR(8)   /* Timer/Counter2 Compare Match A */
#define TIMER2_OVF_vect   _VECTOR(9)   /* Timer/Counter2 Overflow */
#define TIMER1_CAPT_vect  _VECTOR(10)  /* Timer/Counter1 Capture Event */
#define TIMER1_COMPA_vect _VECTOR(11)  /* Timer/Counter1 Compare Match A */
#define TIMER1_COMPB_vect _VECTOR(12)  /* Timer/Counter1 Compare Match B */
#define TIMER1_OVF_vect   _VECTOR(13)  /* Timer/Counter1 Overflow */
#define TIMER0_COMPA_vect _VECTOR(14)  /* TimerCounter0 Compare Match A */
#define TIMER0_COMPB_vect _VECTOR(15)  /* TimerCounter0 Compare Match B */
#define TIMER0_OVF_vect   _VECTOR(16)  /* Timer/Couner0 Overflow */
#define SPI_STC_vect      _VECTOR(17)  /* SPI Serial Transfer Complete */
#define USART_RX_vect     _VECTOR(18)  /* USART Rx Complete */
#define USART_UDRE_vect   _VECTOR(19)  /* USART, Data Register Empty */
#define USART_TX_vect     _VECTOR(20)  /* USART Tx Complete */
#define ADC_vect          _VECTOR(21)  /* ADC Conversion Complete */
#define EE_READY_vect     _VECTOR(22)  /* EEPROM Ready */
#define ANALOG_COMP_vect  _VECTOR(23)  /* Analog Comparator */
#define TWI_vect          _VECTOR(24)  /* Two-wire Serial Interface */
#define SPM_READY_vect    _VECTOR(25)  /* Store Program Memory Read */

```

Further, \_ISR() is just a macro. It creates a suitable function prototype for your function, and if that happens to include a valid vector then it becomes an ISR.

```
#  define ISR(vector, ...)            \
    extern "C" void vector (void) __attribute__ ((signal,__INTR_ATTRS)) __VA_ARGS__; \
    void vector (void)

```

That is defined in "avr/interrupt.h" in the compiler's include files. With your gibberish you'd end up with:

```
extern "C" void GibERisH (void) __attribute__ ((signal,__INTR_ATTRS));
void GibERisH (void) {
    // something here
}

```

With a real vector you'd get the more meaningful:

```
extern "C" void _VECTOR(7) (void) __attribute__ ((signal,__INTR_ATTRS));
void _VECTOR(7) (void) {
    // something here
}

```

Of course, \_VECTOR() itself is a macro:

lib/avr/include/avr/sfr\_defs.h:#define \_VECTOR(N) \__vector\_ ## N

So that further expands out to:

```
extern "C" void __vector_7 (void) __attribute__ ((signal,__INTR_ATTRS));
void __vector_7 (void) {
    // something here
}

```

And magically, that new function name of `__vector_7` is directly referenced from the standard vector handling code in the startup library *crt* of the AVR compiler.

# Answer
> 0 votes
```
ISR(TIMER1_CAPT_vect) {
    Serial.Print("Entered Capture Vector");
}

```

Rule #1. Don't do serial prints inside an ISR. Doing that will likely hang the sketch.

> Because it doesn't appear to matter what I type inside ISR(), for instance I can write ISR(GibERisH) { }

Yes you can do that. It just degrades into some function that is never called. The way it is organized with all the defines, any non-valid ISR name effectively creates a non-ISR function, which is therefore ignored. Even getting the capitalization wrong can cause this.

> I need advanced control of the guts of this processor, and there is zero documentation about how to do this anywhere on the internet.

There is a considerable amount of detail on my site: http://www.gammon.com.au/interrupts

---
Tags: arduino-uno, interrupt, ide, atmel-studio
---


title: LCD-Display showing wrong numbers

text:
# Question
Title: LCD-Display showing wrong numbers
Hy guys,

I am having an issue with my new LCD16x2 display. I connected a potentiometer and read the values. The values are properly read and send to Serial. I also display the values on the display. I am having no issues when increasing the values, but when I go down again at a certain point the displays doesn't display the correct value anymore, but on the Serial I can still see the right readings.

I suppose this has something to do with the display still storing previous values for this digit in the buffer and when I go down the values are not properly reset. But I don't wan't to clear the whole buffer, since then the whole thing just blinks every iteration.

Here's my code

```
// ESC_Calibration.ino
#include <Wire.h>
#include <Adafruit_MCP23017.h>
#include <Adafruit_RGBLCDShield.h>
#include <Servo.h>

#define WHITE 0x7

Servo firstESC;
Servo secondESC;
int throttlePin = 2;
int firstESCPin = 2;
int secondESCPin = 3;

Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();

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

    lcd.begin(16, 2);
    lcd.setBacklight(WHITE);
    lcd.setCursor(0, 0);
    lcd.print("throttle:");

    firstESC.attach(firstESCPin);
    secondESC.attach(secondESCPin);
}

void loop() {
    int throttle = analogRead(throttlePin);
    throttle = map(throttle, 0, 1023, 0, 179);

    lcd.setCursor(0, 1);
        Serial.println(throttle);
        lcd.setCursor(0, 1);
    lcd.print(throttle);

    firstESC.write(throttle);
    secondESC.write(throttle);

    delay(500);
}

```

Does anyone have a suggestion how to improve this and fix it, so it'll display the right readings, but doesn't blink?

Thanks for your help in advance! :-)

# Answer
As you have surmised, the problem is that the LCD retains what was there before and you need to clear it away.

That means, as the numbers increase you get, say,

```
4
10
48
89
194
309

```

etc.

When they go down though, because the LCD remembers what was there, only the characters you print will be replaced:

```
309 (309)
194 (194)
894 (89 - the 4 remains from before)
484 (48 - the 4 remains from before)
104 (10 - the 4 remains from before)
404 (4 - the 04 remains from before)

```

Also, as you have noticed, clearing the whole screen is not very nice since it makes it flash.

To combat that it is important that you only overwrite the characters that you need to overwrite and leave those that want to stay. There's two common ways of doing this:

1. Append enough spaces after the number to force an overwrite: `lcd.print(throttle);
lcd.print(" "); // 3 spaces should be enough for 3 extra digits`
2. Format the data with `snprintf()`: `char temp[5]; // enough room for 4 numbers and one NULL character
snprintf(temp, 5, "%4d", throttle); // %4d = 4 digits, right aligned
lcd.print(temp);`

The latter method, though it is more complex and uses more resources, can be preferred because it creates a much nicer output with the numbers properly right-aligned. Also arbitrarily adding spaces after the number could overwrite things you want to keep.

You could also achieve a similar result doing it manually:

```
if (throttle < 10) lcd.print(" "); // 0-9 add one space
if (throttle < 100) lcd.print(" "); // 0-99 add one space
if (throttle < 1000) lcd.print(" "); // 0-999 add one space
lcd.print(throttle);

```

Just like with cats, there's many ways to skin this problem...
> 1 votes

---
Tags: lcd, display
---


# Question
Title: Reading I2C sensors with a timer interrupt
I would like to read a sensor connected via I2C using Timer3 and Arduino Mega. Values are read from the sensor in the interrupt service routine and timer3 is set to trigger an interrupt at 200Hz.

**Step I: testing the timer**

I tested the timer using a counter and incrementing its value in the ISR. The output is displayed every second. It works!

```
200
201
200
201

```

**CODE**

```
// Timer variable
volatile int cont=0;

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

  setupL3G4200D(2000); // Configure L3G4200  - 250, 500 or 2000 deg/sec
  delay(1500); //wait for the sensor to be ready

  // Initialize Timer
  cli();
  TCCR3A = 0;
  TCCR3B = 0;

  // Set compare match register to the desired timer count
  OCR3A=77; //16*10^6/(200Hz*1024)-1 = 77 -> 200 Hz
  //OCR3A=193; //16*10^6/(80Hz*1024)-1 = 194 -> 80 Hz

  TCCR3B |= (1 << WGM32);
  // Set CS10 and CS12 bits for 1024 prescaler:
  TCCR3B |= (1 << CS30) | (1 << CS32);
  // enable timer compare interrupt:
  TIMSK3 |= (1 << OCIE3B);
  // enable global interrupts:
  sei();

  k = micros();
}

void loop()
{
  delay(1000);
  Serial.println(cont);
  cont=0;
}

ISR(TIMER3_COMPB_vect)
{
  cont++;
}

```

**Step II: Reading values from the sensor in the ISR**

Now I add the I2C function in the Interrupt Service Routine, but the program is blocked after the calcBias() function which reads from the sensor, measures and saves the acquisition time in the samplingTime variable.

**CODE**

```
// Timer variables
volatile float phi=0;
volatile float theta=0;
volatile float psi=0;
volatile int x = 0;
volatile int y = 0;
volatile int z = 0;
volatile int cont=0;

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

  setupL3G4200D(2000); // Configure L3G4200  - 250, 500 or 2000 deg/sec
  delay(1500); //wait for the sensor to be ready

  calcBias():
  Serial.print("Readings take: (us)");
  Serial.println(samplingTime);

  // Initialize Timer
  cli();
  TCCR3A = 0;
  TCCR3B = 0;

  // Set compare match register to the desired timer count
  OCR3A=77; //16*10^6/(200Hz*1024)-1 = 77 -> 200 Hz
  //OCR3A=193; //16*10^6/(80Hz*1024)-1 = 194 -> 80 Hz

  TCCR3B |= (1 << WGM32);
  // Set CS10 and CS12 bits for 1024 prescaler:
  TCCR3B |= (1 << CS30) | (1 << CS32);
  // enable timer compare interrupt:
  TIMSK3 |= (1 << OCIE3B);

  Serial.println("Enabling interrupts..");
  // enable global interrupts:
  sei();

  k = micros();
}

void loop()
{
  delay(1000);
  Serial.println(cont);
  Serial.println(z);
  cont=0;
}

ISR(TIMER3_COMPB_vect)
{
  // Update x, y, and z with new values 2.5ms
  getGyroValues();
  cont++;
}

void getGyroValues()
{

  //starting samplingTimer
  samplingTime = micros();

  // Gets the angular velocity from the sensor
  byte zMSB = readRegister(L3G4200D_Address, 0x2D);
  byte zLSB = readRegister(L3G4200D_Address, 0x2C);
  z = ((zMSB << 8) | zLSB);

  samplingTime = micros()- samplingTime;
}

void calcBias()
{
  Serial.println("Bias");

  // Reads sensors and display three values
  getGyroValues();

  [...]

  Serial.println(bx);
  Serial.println(by);
  Serial.println(bz);
}

void writeRegister(int deviceAddress, byte address, byte val)
{
    Wire.beginTransmission(deviceAddress); // start transmission to device
    Wire.write(address);       // send register address
    Wire.write(val);         // send value to write
    Wire.endTransmission();     // end transmission
}

int readRegister(int deviceAddress, byte address)
{
    int v;
    Wire.beginTransmission(deviceAddress);
    Wire.write(address); // register to read
    Wire.endTransmission();

    Wire.requestFrom(deviceAddress, 1); // read a byte

    while(!Wire.available())
    {
        // waiting
       // Serial.println("No Data");
    }

    v = Wire.read();
    return v;
}

```

I thought that the interrupt frequency was to high and I tried with 80 Hz and 20 Hz. Same results.

Here is the output:

```
starting up L3G4200D
Bias
4.00
0.00
-3.00
Read

```

# Answer
> 5 votes
Try putting `sei();` at the start of the ISR. I think I2C needs interrupts enabled to work.

# Answer
> 5 votes
I2C requires interrupts to work, however enabling interrupts inside an ISR is **not recommended**. For one thing you may get into a race condition, where another interrupt occurs while processing the existing one.

Since you are doing virtually nothing in your main loop, a more sensible design would be to simply test if it is time to take a reading, and when that time is up, take the reading then.

As an example, your main loop could be rewritten as:

```
unsigned long lastReading;
unsigned long lastDisplay;
void loop()
{
  if (millis () - lastReading >= 5)   // 200 Hz
    {
    lastReading = millis ();
    // Update x, y, and z with new values 2.5ms
    getGyroValues();
    cont++;
    }

  if (millis () - lastDisplay >= 1000)  // one second
    {
    lastDisplay = millis ();
    Serial.println(cont);
    Serial.println(z);
    cont=0;
    }
}

```

Now you don't need the timer, and you are interrupt-friendly. :)

More information about interrupts: http://www.gammon.com.au/interrupts

---
Tags: serial, arduino-mega, i2c, interrupt, timers
---


# Question
Title: Leonardo and micro: high pitch noise when powered from Vin
I have an issue with several Leonardo and Micro boards.

On all of my boards, there is a sawtooth of about 690mV ptp @ 4kHz on the 5V supply when powered from Vin (external power). The frequency changes slightly when changing input voltage from 7V to 12V.

C12 is a capacitor on the Leonardo board that is making the acoustic noise, it is "singing" with the frequency of this sawtooth. It follows the voltage regulator NCP1117 for the 5V power supply generation.

According to the schematics of the Leonardo and micro, the voltage regulator used on these boards should be the NCP1117, but on the boards I have, there is no number printed on this component, so I suspect an alternative was used, with these annoying results...

For a project I have for generating audio signals, this noise was unacceptable, so I cut out the regulator and powered everything with an external LM7805. One should not power the module via USB then as long as the external power is connected!!!

Anyone having the same trouble with these boards? Other solutions?

(The Leonardo is a genuine Arduino board.)

# Answer
Yes, I've had this problem on a number of boards. It seems there are some faulty units coming out of the factory. I've had them replaced by my supplier, but I end up being sent more faulty boards.

It makes any kind of accurate ADC reading impossible.

A quick way to work out if your board has this problem

1. Place a jumper between 3.3v and A0
2. Put an analogRead in a loop and println the result
3. When powered by 5V you'll see a fairly constant value (around 670), varying by 1 or 2
4. When powered by 12V, if you have a faulty board, you'll see varying values, deviating by 50 or more.

There's a couple of solutions/workarounds to the problem listed here: http://forum.arduino.cc/index.php?topic=235729.0.
> 1 votes

# Answer
It does sound like the regulator is oscillating to me. That happens when the output capacitor is of the wrong type for the regulator - the ESR is wrong.

My Leonardo, when powered from 12V, is nice and clean. The regulator has 7CE50Z on it. I do notice, on the layout of the Leonardo, that the output capacitor is somewhat further away from the regulator than I like to put it - though that shouldn't cause that much of a problem. 800mV is way too much to be considered normal under *any* circumstances.

What is the power source you are using?
> 0 votes

---
Tags: arduino-leonardo, arduino-micro
---


# Question
Title: Smart Chess-board (possibly using RFIDs?)
I'd like to make a chess-board with the ability to detect the position of each piece.

The solution that occurs to me would be to put an RFID reader under each square and put RFID tags on the bottoms of each piece.

However, apart from the obvious cost (64 readers!) I'm concerned that:

1. Maybe RFID readers are too large for the squares of an ordinary chessboard
2. RFID reader range is too large, so a reader might pick up pieces on neighbouring squares
3. How the hell would I connect 64 readers anyway? Could an Arduino handle it?

So, questions.

Is this just stupid? And is there a better technology to use for this kind of application?

If RFIDs are basically a sane solution, what are the issues/suggestions? E.g. which RFID readers should I go for? (Based on size, energy, convenience for this application). What boards would let me handle this number of them?

# Answer
As I read your post an idea came to me that must be obvious in its simplicity. Since a chess board has pieces already on it we can simply use hall-effect sensors (dirt cheap) under each square and each piece has a magnet at its base. Since pieces on a chess board move from one square to another and the initial position of all pieces is known/constant, the detection of a move would be that a piece is lifted from the board (hall effect sensor detects a magnetic field removal) and a piece being placed on a square would be detected by a hall effect senor addition of a magnetic field. We wouldn't know which piece is placed on a square but we can calculate it by remembering what piece was lifted and it can only be the piece that was placed.
> 4 votes

---
Tags: rfid
---


# Question
Title: Cannot convert 'String' to 'uint8_t {aka unsigned char}' in initialization
Hey all I am trying to convert a string into a uint8\_t with the following code:

```
String data = "#255101987";
String tmp1 = data.substring(1, 3);

uint8_t first  = (String)tmp1;

```

I am getting the error of:

> cannot convert 'String' to 'uint8\_t {aka unsigned char}' in initialization

Any help would be great as I thought adding **(String)** in front of the varible would solve the issue but it hasn't as you can tell.

# Answer
> 3 votes
```
uint8_t first  = atoi (tmp1.substring(1, 3).c_str ());

```

Or even:

```
String data = "#255101987";
uint8_t first  = atoi (data.substring(1, 3).c_str ());

```

---
Tags: arduino-ide, string, compilation-errors
---


# Question
Title: How to read AC Voltage in arduino uno with 12V adaptor and usb cable.?
i want to ON-OFF two lights(white and red), one from main power source(white light) and one from ups(battery). When main power is present, white light should be ON and red should be off. And when main power fails, red should be ON and White should be OFF. I have Arduino, usb cable, external power supplier(adapter of 12V).

Can any one please suggest me how do i proceed for this ??

# Answer
> 1 votes
If your battery voltage is lower than 12 but sufficiently high to power the arduino (let's say 9V), you could put a white LED on the 12V line and a red LED on the battery line, like this:

```
         WHITE       RED
  _______|>|_________|<|________
 |             |                |
_|_          Arduino           _|_
 - 12V         |                -   Battery
 |_____________|________________|

```

This should work, as long as the LEDs can withstand the reverse voltage. And you do not need to drive them from the Arduino. If you still want to know the status fro mthe Arduino (mains or battery) you can sample the voltage level across the Arduino.

---
Tags: arduino-uno, usb
---


# Question
Title: What are the tools that I need to program the Arduino in C?
The Arduino IDE by default is oriented towards C++. The linker for example requires `.cpp` files and not `.c` files, otherwise it leads to errors during the linking process. See name mangling if you want to know more.

So, what are the tools that I need to setup a C environment? Can this be done from the Arduino IDE itself?

I work on a Linux system (Ubuntu 12.04).

# Answer
> 3 votes
Well, if you want to do more advanced stuff with your AVRs, you should definitely leave the Arduino environment, and integrate your AVR development in your "usual" favorite development environment, whatever it is.

Then you've got two choices, either do 100% pure C with AVR libraries, for which you only need a simple makefile that calls avr-gcc with avr-libc libraries as include path. You can also use Atmel Studio that helps you a lot on that stuff. But if you do so, you're loosing the advantages of the libraries built for/by the arduino community – which, sadly, is not a huge loss for a strong majority of those.

Or you can work your code out as a 100% C external library, used from within the sketch, and included at linking time. Then you'll have all the advantages of working with any C++ library you'd like to have, but still doing the important code in pure C. Having only the `.ino` used to generate the main `.cpp` and any `.cpp` library you'd need. Though, for many basic features like writing on the serial port, you'll have to do it \[the good old way\]\[2\] or by doing some weird encapsulation of `Serial.println()` call sent as a functor to the pure C parts.

In the makefile I've written (debian offers another one with the non-gui install of arduino), every `.c` file from declared libraries are detected and compiled with avr-gcc, every `.cpp` file is compiled with `avr-g++` and both gets linked when doing the `.elf`/`.hex` file.

# Answer
> 0 votes
Take a look at ino on linux and PCs and Mac. It's available in the fedora repos, not sure about other distros; though, I'm sure everyone can install it from the github project site, regardless of the distribution. According to the website, you can also install it with python setup tools:

```
pip install ino

```

or

```
    easy_install ino

```

*BTW: sorry for not including this "answer" in a comment due to reputation restrictions.*

Here's the description from the fedora repos; I think it's taken directly from the `ino` tool website:

> ```
> Summary     : Command line toolkit for working with Arduino hardware
> URL         : http://inotool.org/
> License     : MIT
> Description : Ino is a command line toolkit for working with Arduino hardware.
>             :
>             : It allows you to:
>             : Quickly create new projects
>             : Build a firmware from multiple source files and libraries
>             : Upload the firmware to a device
>             : Perform serial communication with a device (aka serial monitor)
>             :
>             : Ino may replace Arduino IDE UI if you prefer to work with command line and
>             : an editor of your choice or if you want to integrate Arduino build process
>             : to third party IDE.
>             :
>             : Ino is based on make to perform builds. However Makefiles are generated
>             : automatically and you'll never see them if you don't want to.
>
> ```

# Answer
> 0 votes
> The linker for example requires .cpp files and not .c files, otherwise it leads to errors during the linking process

No, it doesn't.

---

> So, what are the tools that I need to setup a C environment?

Why do you want to?

---

**The answer**

Make a new tab in the IDE (top RH corner). Call it, for example, foo.c. That's your C file.

Put whatever C code you want into it. For example:

```
#include <Arduino.h>
void foo ()
{
PORTD = bit (1);
}

```

Now in your "main" sketch call that function, eg.

```
extern "C"
 {
 void foo ();
 }

void setup ()
  {
  foo ();
  }  // end of setup

void loop ()
  {
  }  // end of loop

```

Repeat as required for any C functions you care to write.

Of course, you can't use Serial (that's a C++ class) or Wire (that's a C++ class) or SPI (that's a C++ class), but if you want to work with C, you can certainly do that.

# Answer
> 0 votes
You're already there with the Arduino IDE; C++ compilers understand plain C just fine, but may interpret C syntax slightly differently in some cases. I write most sketches in C, invoking C++ objects from libraries as necessary.

If you're to the point where you want finer grained control over which compiler, C or C++, gets used for a given module, then it's time to graduate to another environment. Eclipse is a very popular and flexible IDE for a large range of languages, compilers & cross-compilers, and provides a very flexible Arduino environment. Or your favorite shell, programming editor, Make, and the avr-gcc cross-compilation tool-set will give you the ultimate access to and control of every detail - perhaps more than you wanted - of the edit/compile/link/download/debug process.

---
Tags: programming, c
---


title: Capacitive Sensor gets stuck

text:
# Question
Title: Capacitive Sensor gets stuck
I want to use CapacitiveSensor library in order to make my own aluminum keys piano. I have seen many videos online showing projects like the one I'm trying to do, but for some reason mine doesn't work.

Here's my cuircit:

Here's my code:

```
#include <CapacitiveSensor.h>

CapacitiveSensor   cs_7_6 = CapacitiveSensor(7,6);  // 10M resistor between pins 7 & 6, pin 6 is sensor pin

void setup()
{
   //cs_7_6.set_CS_AutocaL_Millis(0xFFFFFFFF);     // turn off autocalibrate on channel 1 - just as an example
   Serial.begin(9600);
}

void loop()
{
    long start = millis();
    long total1 =  cs_7_6.capacitiveSensor(5);

    Serial.print(millis() - start);        // check on performance in milliseconds
    Serial.print("\t");                    // tab character for debug windown spacing

    Serial.print(total1);                  // print sensor output 1
    Serial.println("\t");

    delay(10);                             // arbitrary delay to limit data to serial port
}

```

This happens whenever I touch the aluminum foil:

First nothing happens (for ~1 sec), then it prints -2 as the capacity value, and when I release my finger from the foil it prints a very high value.

Anyone knows the reason for it? I'm searching for an answer for a long time and still can't find a solution...

# Answer
The problem is that you're touching the foil.

The "capacitive sensing" used in that library is crude at best.

If you read the Arduino Playground page for the Capacitive Sensing Library it discusses a lot of the problems with the library, including grounding. Make sure that the Arduino is properly grounded, or provide your own ground plane under the foil sensors.

Also they talk about the value of resistor and the sensitivity. With a 10MΩ resistor you get sensing at (supposedly) 4-6cm from the foil. That's the value you're seeing as you remove your finger. While you're touching the foil it's just having a complete brain haemorrhage and can't work out what is going on (completely unable to charge the pin since you are leeching off all the current). For "absolute touch" it recommends no more than 1MΩ.

Of course, as I mentioned, that method is rather crude. To do it properly you need to:

1. Discharge an analog input pin through a MOSFET to ground (low impedance).
2. Apply a constant current (typically 50µA is used but varies depending on ADC characteristics) to the analog input for a fixed amount of time.
3. Remove the current and measure the voltage on the ADC input.
4. Repeat.

More modern MCUs have this kind of functionality built in, in the form of a "CTMU" - *Charge Time Measurement Unit*. If you want to have anything more than "there's someone vaguely in the vicinity of the sensor" then I would suggest switching to a more modern MCU and doing it properly, or employing a specific CTMU chip as an external device.

Also, the sensor should be comprised of three parts - a ground plane, a sensor plane (connected to the ADC) and a dielectric layer between them. The sensor should also be insulated from direct touch.
> 2 votes

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


title: Arduino C++ library syntax

text:
# Question
Title: Arduino C++ library syntax
I am looking at modifying the H3LI331DL I2C library posted by Seed Studio for communicating with the H3LI331DL accelerometer. The library hardcodes the address for the accelerometer in the header file. My end goal is to make the library require a slave address input argument so I can talk to 2 accelerometers on the same I2C bus. The chip has a pin that sets the LSB of its address.

Now onto the question. The library's .h file has the following statement:

`#define H3LIS331DL_MEMS_I2C_ADDRESS 0x18//0x32`

Is the 0x32 simply commented out or am I missing something here?

Thanks,

Emach

# Answer
It is indeed commented out. SeeedStudio is a great company but their code (including code prettifying) is pretty sloppy, and sometimes a little dumbfounding.
> 1 votes

---
Tags: library
---


# Question
Title: Highly sensitive light sensor to calculate number of times each color LED blinks
I am working on a project and got stuck on a point, and I hope somebody will guide me. I have a hardware device which has different color LEDs (green, red and yellow) and I have to calculate how many times each color LED glows for each mode of operation.

The LEDs that are connected to the device are pretty small and will blink only for a couple of seconds, ao I am looking for a very sensitive light sensor.

So what kind of light sensor do I have to use with Arduino UNO to achieve this?

Should I go for BH1750 or do you have any other suggestion?

Thanks in advance.

# Answer
> 1 votes
Like the OP wrote, you can use very simple sensors, like a phototransistor. Even simpler, if you can somehow isolate each pair LED-phototransistor, you don't even need to care about the color of the led, just use some bluetac to stick one phototransistor on top of each LED and only measure the brightness.

**edit:**

A quick check on ebay shows the 3DU5C as good candidate: it has a metallic container, so it is more directional than one with full plastic body.

3DU5C ebay link and datasheet

It is shown to have a peak response at 880nm (red light), so you might not be able to use it directly as digital input for the other 2 colors you want to monitor and instead have to treat it as analog reading.

OTOH if you use them all as analog inputs, you will not have to add the resistor that would be required for binary mode.

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


# Question
Title: How to measure direction the car is coming to garage door?
my garage door is pretty narrow, about 10 cm (4") on each side of my car's rear mirrors. So every time I drive to garage, I need to go very slowly because I am afraid I might not be lined up correctly.

I am thinking about using Arduino and some sensors to help me. Output is pretty simple, just two leds, one for each side, showing me if I should turn little right or left to have perfect lineup to center. This I can handle with no problem

What I am asking for is idea how to measure the alignment of my car. I know how to use ultrasonic sensors for measuring distance. But I am not sure they are suitable for this project, because I want preferably to put arduino and sensors in my garage, not in my car.

Any idea how to work this out ?

# Answer
It is very hard to determine position accurately there is a new project on kickstarter called Pozyx, you can look at that but that's expensive, to be honest this sounds like a job for hanging tennis balls or strings or something like that. But if you have a lot of money to blow and you just want a project go for it, you may be able to do this with ultrasonic sensors but I reckon that would be painful. Anyway good luck
> 2 votes

# Answer
It seems like an ultrasonic sensor on each door-post should do it. You need, I'm guessing, 30cm to the sides of your car as its nose enters the doorway. Smooth the sensor reading, compute a difference and display the sign of the differences as right/left lights. Keep a small dead-band around zero-difference or you'll drive the driver crazy!

Do Ultrasonic sensors have the range and accuracy you need for the job? Time for a feasibility study.

Update: Is 10cm plus the length of a mirror = a couple of feet? But even if so, you have to keep to +/- 10cm of the centerline to prevent striking the mirrors, so you could project your sensors out into the doorway by an amount the still keeps them \> 10cm away from the car. You could mount them hinged (like the mirrors are) and padded to limit any damage from the occasional accidental touch.
> 1 votes

# Answer
Try to place two distance ranging sensors like ultrasonic or active infrared at the sides of the driveway or garage door. Make sure that their readings are similar so that you know that you are in the center. If one has a higher reading(farther distance) light an led to your right so you know to go that direction and vice versa. Use communication through xbees, bluetooth, or something similar.
> 0 votes

---
Tags: sensors
---


# Question
Title: Arduino Digital Input Causing Output Problems
I am working on a simple project using an Arduino Mega 2560 that involves reading a 12-bit binary encoder signal and which is used to cycle a digital pin high and low (depending on the angular location of the encoder).

My problem is that when the digital output pin is told to go low, it only goes down to about 4V. I also noticed that it would occasionally dip down to ground, instead of just 4V. Much to my surprise, when I unplug the Arduino, the digital output pin is still reading 4V. When I turned off power to my encoder which is connected up the the Arduino through 12 digital input pins, the output pin dropped down to 0V. When I turn the encoder back on it goes back up to about 4V.

I have tried connecting the output pin to ground and obviously the voltage goes to 0, but as soon as I remove the connection to ground the voltage springs back up to around 4V. It appears as though somehow the voltage being fed to the digital input pins (in the form of a ~5V digital input signal) is preventing the digital output pin from going to ground. I have no idea why this is the case, I have searched all over and could not find any similar complaints. My code is posted below, any help is greatly appreciated!

```
unsigned long CamAngle = 0;       // Variable to store encoder value
unsigned long PrevCamAngle = 0;   // Variable to store previous encoder value
int i = 0;                        // Cycle index
int BDC[] = {683,2048,3413};      // BDC angle (12-bit encoder value)
int TDC[] = {0,1365,2731};        // TDC angle (12-bit encoder value)

boolean TDCycle = false;          // TDC Cycle
boolean BDCycle = false;          // BDC Cycle
boolean Cycle = true;             // Encoder rollover cycle (replaces TDC cycle 0)

void setup()
{
  pinMode(37, INPUT);           // Encoder bit 0 (PORTC-0)
  pinMode(36, INPUT);           // Encoder bit 1 (PORTC-1)
  pinMode(35, INPUT);           // Encoder bit 2 (PORTC-2)
  pinMode(34, INPUT);           // Encoder bit 3 (PORTC-3)
  pinMode(22, INPUT);           // Encoder bit 4 (PORTA-0)
  pinMode(23, INPUT);           // Encoder bit 5 (PORTA-1)
  pinMode(24, INPUT);           // Encoder bit 6 (PORTA-2)
  pinMode(25, INPUT);           // Encoder bit 7 (PORTA-3)
  pinMode(26, INPUT);           // Encoder bit 8 (PORTA-4)
  pinMode(27, INPUT);           // Encoder bit 9 (PORTA-5)
  pinMode(28, INPUT);           // Encoder bit 10 (PORTA-6)
  pinMode(29, INPUT);           // Encoder bit 11 (PORTA-7)

  pinMode(30, OUTPUT);          // Set PORTC pin 8 to output (stop pin float)
  pinMode(31, OUTPUT);          // Set PORTC pin 7 to output (stop pin float)
  pinMode(32, OUTPUT);          // Set PORTC pin 6 to output (stop pin float)
  pinMode(33, OUTPUT);          // Set PORTC pin 5 to output (stop pin float)

  digitalWrite(30, LOW);        // Set PORTC pin 8 low (stop pin float)
  digitalWrite(31, LOW);        // Set PORTC pin 7 low (stop pin float)
  digitalWrite(32, LOW);        // Set PORTC pin 6 low (stop pin float)
  digitalWrite(33, LOW);        // Set PORTC pin 5 low (stop pin float)

  pinMode(53, OUTPUT);          // Set pin 53 (PORTB-0) as digital output
  digitalWrite(53, LOW);        // Set pin 53 (PORTB-0) LOW

}

void loop()
{

  // Cam Angle Update
  PrevCamAngle = CamAngle;      // Set variable to previous encoder value
  CamAngle = (PINA << 4) + PINC;    // Read encoder, set variable to value

  if (TDCycle == true && CamAngle >= TDC[i])  // Wait for encoder to reach angle if cycle active
  {
    PORTB = 0;                                  // Set digital pin 53 LOW
    TDCycle = false;
    BDCycle = true;
  }

  if (BDCycle == true && CamAngle >= BDC[i])  // Wait for encoder to reach angle if cycle active
  {
    PORTB = 1;                                  // Set digital pin 53 HIGH
    TDCycle = false;
    BDCycle = true;
    i++;
    if (i > 2)                                  // Reset every 3 cycles (3 cycles per revolution)
    {
      i = 0;
      BDCycle = false;
      Cycle = true;
    }
  }

  if (Cycle == true && CamAngle < (PrevCamAngle + 1))  // Wait for encoder to cycle back to 0
  {
    PORTB = 0;                                  // Set digital pin 53 LOW
    BDCycle = true;
    Cycle = false;
  }

}

```

As you can see I am utilizing direct port manipulation, however I have the same issues when I use the Arduino library commands as well. I'm fairly certain this is some sort of hardware issue, however I could be wrong.

# Answer
I think you have two issues here.

First:

> Much to my surprise, when I unplug the Arduino, the digital output pin is still reading 4V.

With a powered device connected to the input pins, the overvoltage protection diodes power your 5V line with what is called "parasitic power". Those diodes are supposed to clamp an input pin to not exceed 5V, but if the power is off, they actually **supply** 5V (assuming at least some of the pins are high), hence powering up the processor. It is not designed to do this, and you should not power off the processor in this way.

---

Second:

> My problem is that when the digital output pin is told to go low, it only goes down to about 4V.

I tried out your code, but without the encoder to hand, I just comment out the three "if" tests:

```
//  if (TDCycle == true && CamAngle >= TDC[i])
...
//  if (BDCycle == true && CamAngle >= BDC[i])
...
//  if (Cycle == true && CamAngle < (PrevCamAngle + 1))

```

A multimeter on pin 53 reads 0.98V, however this is because the pin is being turned on and off quickly. I can't work out for sure whether some or all of these conditions would be satisfied in sequence (they don't seem directly related). One thing you could do, since you seem to want pin 53 either on or off is use "else", eg.

```
if (TDCycle == true && CamAngle >= TDC[i])
{
...
} else if (BDCycle == true && CamAngle >= BDC[i])
{
...
}
else if (Cycle == true && CamAngle < (PrevCamAngle + 1))
{
...
}

```

Now you won't have multiple attempts to turn the pin on **and** off through one turn through the loop.
> 2 votes

---
Tags: arduino-mega, c++, pins, digital
---


# Question
Title: SoftSerial freezes on comparing getInt to int
I have a robot application on my Arduino which basically takes values from a SoftSerial instance on my 0/1 pins (connected to a Bluetooth board).

From the 'driver station' I send speed values to the Arduino through the aforementioned Bluetooth controller. The freezing happens when I compare the data (an integer) to a local integer (i.e 500). If I send the reverse command, I'm actually sending the int 500. If I compare my SoftSerial data like so:

```
if(softSerial.parseInt() == 500)
{
 //Reverse
}else{
 //Forward
}

```

it freezes. It only happens when I'm using my SoftSerial stack over Bluetooth, over USB it doesn't freeze. What are my options?

# Answer
> 1 votes
There is no point in using SoftwareSerial on pins 0 and 1, as you have HardwareSerial for that. Whatever the sketch does once it starts will not affect whether or not it uploads. If you have something connected to pins 0 and 1, during the upload, that may well stop the upload working, but what the sketch does afterwards does not.

It is hard to tell from your snippet, but if you also have activated HardwareSerial - eg. `Serial.begin(9600);` \- then the hardware takes over those two pins and SoftwareSerial won't work anyway.

---
Tags: serial, bluetooth, softwareserial
---


title: Tone inside interrupt

text:
# Question
Title: Tone inside interrupt
I am trying to play a tone with a buzzer connected on an arduino nano pin. I have also connected a reed switch with INPUT\_PULLUP on INT0 and a led. The program loops continuously (it's an environmental monitor and alarm personal project) until the reed switch is set on HIGH where a function is called and the buzzer should play an one-second high pitch tone.

```
void doorStateChange() {
  static unsigned long last_interrupt_time = 0;
  unsigned long interrupt_time = millis();
  if (interrupt_time - last_interrupt_time > 1000)
  {
    led_B_state   = !led_B_state;
    digitalWrite(buzzPin, HIGH);
    digitalWrite(led_A_Pin, HIGH);

    if (millis() - interrupt_time <= 1000 ){
        digitalWrite(buzzPin, LOW);
        digitalWrite(led_A_Pin, LOW);
    }

  }
  last_interrupt_time = interrupt_time;
}

```

The interrupt is called, the Led lights up but I can't make the buzzer sound right. I 've tried with `tone(buzzPin, 5000, 1000);` but seems that the delay does not work - The sound is heard but after the 1000ms it continuous to work in a different tone (strange?).

The only way I could make it work is with `buzzPin_state = ! buzzPin_state;` where the buzzer beeps as long as the reed switch is HIGH.

I also need to say that `attachInterrupt(0, doorStateChange, CHANGE);`.

The information I get from googling this issue is gibberish: some say that delays don't run in interrupts, others call external functions etc.

What is the proper way to achieve this ?

# Answer
Don't do delay() calls inside an ISR. In all probability it will hang indefinitely. If you want to play the tone for a second all you need to do in the ISR is set a flag, which you test in the main loop. Turn the buzzer on when the flag changes state. Remember when you did that. When a second is up turn the buzzer off again.

In fact in your case you probably don't need the interrupt at all. Test for the reed switch change in the main loop as well. Don't overcomplicate it.
> 4 votes

---
Tags: interrupt
---


# Question
Title: Do I need 3 full-size arduinos to control this LED setup?
I'm sourcing the parts now for an LED *persistence of vision* setup on a bicycle. Two wheels with anywhere between 16-32 LED's per wheel, as well as 24 LED's mounted on the frame of the bike itself

Since the Arduinos have to be mounted into the wheels to drive the POV displays - do I need a total of 3 arduinos?

Driven by 2x \[Nano 3.0 Atmel Atmega328P Mini-USB Board\]\[1\] + an Arduino Uno from the frame? So far I think I'll pick up 2 x \[433Mhz RF Transmitter Module + Receiver Module Link Kit\]\[2\] for wireless control, \[Reed Switch Magnetic Detection Sensor Module\]\[3\] for calculating velocity from a small magnet mounted somewhere on one of the forks. 4 x \[WS2811 RGB 8-LED Light Strip Module\]\[4\] as the POV LED's, or maybe some of the \[DotStar Digital LED\]\[5\] and miscellaneously perhaps are some of these required/ useful? maybe instead of the 4x8 I could go 4x \[SSC Seoul P4\]\[6\], or from \[SparkFun\]\[7\], following pieces of \[this guide\]\[8\]

* DIY AT89S52 Microcontroller Development Board Set
* \[KT0026 Electronic Parts Pack\]\[9\]
* \[Square Prototyping Plate\]\[10\]
* \[ZnDiy-BRY Z-069 MB102 Breadboard + Power Supply Module\]\[11\]

My main concern is refresh rates....getting everything controlled...and making sure I have enough I/O. Any help would be greatly appreciated. (URL's available on request :P)

# Answer
> 1 votes
Maybe look at NeoPixels Revealed: How to (not need to) generate precisely timed signals. The author there controlled 1000 Neopixels with a Duemilanove with fairly simple code. These were WS2812 not WS2811 but perhaps the code could be adapted to suit. Judging by the datasheets they are fairly similar.

Since he got 30 fps with 1000 pixels, your requirement of around 100 pixels would seem fairly straightforward.

# Answer
> 0 votes
Those WS2811 strips are a good idea. You can control them all from pins on the same port which will make the control a little more complex but multiply the refresh rate, or you can chain all of them off a single pin if you find the refresh rate high enough that way.

# Answer
> 0 votes
You wouldn't necessarily need full Arduinos - you could prototype them on Arduinos, then move them to just Atmel chips on your own board (e.g. stripboard). To do this, you would need your own resonator, power supply, and programming. Resonators are cheap and easy, you would probably want to set up your own power supply anyway (3 AA batteries is a perfect power supply for the Atmel), and you can program using a USBISP or similar, right from inside the Arduino IDE.

As for speed, I see a bicycle wheel is on the order of 26 inches/660mm diameter. This makes the perimeter about 6 foot 9 inches/2 meters (sounds like a lot, doesn't it?). Google tells me that a sprint on a bike by a fit person is about 40km/h, or 11 meters/second, making 5.5 revs/second of the wheel - about 180 milliseconds/revolution. This means that if you want 1 degree accuracy, you're going to have to change ALL the (changing) leds at about 2khz. The Arduino can run at up to 20mhz, giving you 10,000 instructions to change the leds. Plenty of time.

If you have strips, you should check the specs on the strips to see how fast you can change them. Remember that you probably have to update ALL of them, and you want most of the time to be spent between updates; while you are updating, it may show unwanted lights on/off.

---
Tags: arduino-uno, programming, sensors, led, electronics
---


title: Leonardo with xbee shield?

text:
# Question
Title: Leonardo with xbee shield?
I'm trying to get a XBEE shield to operate on an Arduino Leonardo. Usually i use the AltSerialLibrary to emulate an extra serial for the xbee. However since the Leonardo comes with two sets of serial, i figured I use that instead.

```
//#include <AltSoftSerial.h>

//AltSoftSerial XBee(5,13); // RX, TX

void setup() {

  Serial1.begin(9600);
  Serial.begin(9600);

}

void loop() {

  Serial.println("Odds");
  Serial1.println("Ends");

  delay(1000);

}

```

The code above aims to write values to both the serial monitor (serial) and xbee (serial1). However in the Xbee's XCTU program, the remote xbee does not recieve any data.

Any feedback on how I might fix this will be appreciated.

# Answer
You said you are using a Xbee shield. What shield is it, and what pins does it use for Serial communications?

If you were using software to emulate the second serial port on other arduinos, you were probably using different pins, and so if the shield is designed to communicate over (as an example) pins 2 and 3 then it will most likely not work with pin 0 and 1 without moving jumpers or switches. For example, this Xbee Shield: http://core-electronics.com.au/xbee-shield.html/?acc=9f61408e3afb633e50cdf1b20de6f466 has a switch to switch between pins 0 and 1 and pins 2 and 3.

You could also try some code that reads from Serial and prints the data to Serial1 and visa versa. This means you can experiment to get a greater understanding of the problem.
> 1 votes

---
Tags: serial, programming, xbee, arduino-leonardo
---


# Question
Title: How can I analyse large packets on an Arduino?
I'm trying to send a large packet to an Arduino with an ethernet shield on it. I'm using the built-in RX buffer of the W5100 controller to store the data, but I need more memory (at least 16K of buffer space, the W5100 only has 8K of RX buffer space). I have control over the server side of things as I'm writing the server process myself, so I can take solutions on that side.

Is there some hack I can use in the TCP protocol to have the packet broken up?

**Edit:** I'm using the SFML 2.1 network API on the server side.

# Answer
> 2 votes
All you need to do is analyse the packet on-the-fly using a state machine.

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

You certainly don't need to hold the entire packet at once, however you **do** need room for the information the packet contains.

Say, for example, that the packet, although wordy, contains 4 x 32-bit numbers of interest. All you need memory for is those 4 numbers, plus a minor extra amount for the current data you are processing (eg. the current state, and the current number being assembled).

Conceptually it is like streaming a movie to your PC. The PC doesn't need to hold the whole movie, it just needs to hold the current frame, and a few seconds in advance, just to keep things running smoothly.

---
Tags: ethernet, memory-usage
---


title: RS-485 with Arduino

text:
# Question
Title: RS-485 with Arduino
I have two Arduinos on a RS-485 line, one acting as a Master and the other as a Slave. The Master simply transmits information to the Slave, which parses it.

They work fine when the Master is turned on first and then the Slave is turned on. However, I'd like to make it so that the Slave can be disconnected and reconnected to the line and re-discover the connection (ideally without resetting either Arduino).

Here's the code from the Slave's loop

```
  void loop()
     {

       if (RS485Serial.available() >0 )  //Look for data from other Arduino
       {
        char byteSend = RS485Serial.read();    // Read received byte
        String str = String(byteSend);
         if (str == "<")  {      //  beginning of the transmission
       // does stuff here
      }
   }

```

}

Here is the relevant section of Master's loop:

```
  output_value ="<1,1,1,1,1,1,1>";
 RS485Serial.print(output_value);
 delay(250);
 RS485Serial.flush();

```

Any advice is appreciated...

# Answer
> 1 votes
```
    char byteSend = RS485Serial.read();    // Read received byte
    String str = String(byteSend);
     if (str == "<")  {      //  beginning of the transmission
   // does stuff here
  }

```

This is an extremely inefficient way of testing for one character. Much better would be:

```
    char byteSend = RS485Serial.read();    // Read received byte
    if (byteSend == '<')  {      //  beginning of the transmission
   // does stuff here
  }

```

---

> However, I'd like to make it so that the Slave can be disconnected and reconnected to the line and re-discover the connection (ideally without resetting either Arduino).

I know I'm not supposed to ask questions here, but what is stopping you?

---
Tags: serial, rs485
---


title: How to add .h file in library

text:
# Question
Title: How to add .h file in library
I am trying to make an ultrasonic distance meter using Arduino. For this I added the ultrasonic library. But on compiling it shows this error "ultrasonic.h not available". Please tell me how to add this .h file.

# Answer
> 4 votes
In you Arduino Sketch folder there is a folder called **Libraries**, create a folder there and put your header file in that folder and restart the Arduino IDE.

For example (PC):

```
Documents/Arduino/Libraries/ultrasonic/ultrasonic.h

```

You can now use it in all your projects.

If you only want to use with a particular sketch, place in in the same folder as you sketch and restart Arduino IDE.

---
Tags: library
---


# Question
Title: How to reset arduino Mega 2560 code automatically?
I am working on the temperature project using arduino to collect temperature. But sometimes arduino hang there so I have to unplug cord and plug it back in to restart the arduino. I do not when it is going to hang up again. So I decide to do some research on the internet but no luck for that. Here is the article I read about resetting arduino code with watchdog timer library.(unfortunately, it only work for arduino uno) If someone has any idea how to reset arduino mega 2560 code. Please help !!

# Answer
> 3 votes
avr-libc already has the appropriate functions created for you. Just include `<avr/wdt.h>`.

Sample usage

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

void setup()
{
   wdt_enable(WDTO_8S);
   ...
}

void loop()
{
   wdt_reset();// make sure this gets called at least once every 8 seconds!
   ...
}

```

# Answer
> 1 votes
I tried Gerben's suggestion with a display:

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

void setup ()
  {
  Serial.begin (115200);
  Serial.println ();
  Serial.println (F("Code starting ..."));
  wdt_enable(WDTO_8S);
  }  // end of setup

void loop()
{
//   wdt_reset();// make sure this gets called at least once every 8 seconds!
}

```

That does indeed print "Code starting ..." every 8 seconds or so.

> But sometimes arduino hang there so I have to unplug cord and plug it back in to restart the arduino.

You are better off working out **why**. There is probably a bug. Fix the bug rather than just restarting the Arduino.

# Answer
> 0 votes
You could also use an external circuit to reset the arduino when 'heartbeat' pulses are missed. You can even detect when a reset has occured and report accordingly. See here for an example

---
Tags: arduino-mega
---


# Question
Title: What is the best way to make a good but simple line follower?
I am new in this site, and like you can see I want to do a line follower, not a clumsy and slow line follower, but a fast and "fancy". I investigated about the PID method, but can someone explain me in simple words what is it. Thanks for your answers.

# Answer
Did you check wikipedia, for example?

I doubt it is possible to describe a PID controller in simpler words than those used by the article.

The pseudocode is quite simple and should be also very good for understanding the concept, when applied to a digital system.

See also the limitations of PID controllers.
> 2 votes

---
Tags: robotics
---


# Question
Title: Can a function be called automatically when an input changes?
Currently, my sketch is checking an input pin every time round the main loop. If it detects a change, it calls a custom function to respond to it. Here's the code (trimmed down to the essentials):

```
int pinValue = LOW;

void pinChanged()
{
    //...
}

void setup()
{
    pinMode(2, INPUT);
}

void loop()
{
    // Read current input
    int newValue = digitalRead(2);

    // Has the input changed?
    if (newValue != pinValue) {
        pinValue = newValue;
        pinChanged();
    }
}

```

Unfortunately, this doesn't always work properly for very short changes on the input (e.g. brief pulses), especially if `loop()` is running a bit slowly.

Is there a way to make the Arduino detect the input change and call my function automatically?

# Answer
You can do this using external interrupts. Most Arduinos only support this on a limited number of pins though. For full details, see the documentation on `attachInterrupt()`.

Assuming you're using an Uno, you could do it like this:

```
void pinChanged()
{
    //...
}

void setup()
{
    pinMode(2, INPUT);
    attachInterrupt(0, pinChanged, CHANGE);
}

void loop()
{
}

```

This will call `pinChanged()` whenever a change is detected on external interrupt 0. On the Uno, that corresponds to GPIO pin 2. The external interrupt numbering is different on other boards, so it's important to check the relevant documentation.

There are limitations to this approach though. The custom `pinChanged()` function is being used as an Interrupt Service Routine (ISR). That means the rest of the code (everything in `loop()`) is temporarily stopped while the call is executing. In order to prevent disrupting any important timing, you should aim to make ISRs as fast as possible.

It's also important to note that no other interrupts will run during your ISR. That means anything relying on interrupts (such as the core `delay()` and `millis()` functions) may not work properly inside it.

Lastly, if your ISR needs to change any global variables in the sketch, they should usually be declared as `volatile`, e.g.:

```
volatile int someNumber;

```

That's important because it tells the compiler that the value could change unexpectedly, so it should be careful not to use any out-of-date copies/caches of it.
> 27 votes

# Answer
Any state of change on any pin configured as digital input can create an interrupt. Unlike the unique vectors for the interrupts causes by INT1 or INT2 the PinChangeInt feature uses a common vector and then Interrupt Service Routine (aka ISR) for this vector needs to then determine which pin changed.

Fortunately PinChangeInt Library makes this easy.

```
PCintPort::attachInterrupt(PIN, burpcount,RISING); // attach a PinChange Interrupt to our pin on the rising edge
// (RISING, FALLING and CHANGE all work with this library)
// and execute the function burpcount when that pin changes

```
> 5 votes

# Answer
In the event that you want to detect a voltage passing a **threshold**, rather than being merely HIGH or LOW, you can use the analog comparator. Example sketch:

```
volatile boolean triggered;

ISR (ANALOG_COMP_vect)
  {
  triggered = true;
  }

void setup ()
  {
  Serial.begin (115200);
  Serial.println ("Started.");
  ADCSRB = 0;           // (Disable) ACME: Analog Comparator Multiplexer Enable
  ACSR =  bit (ACI)     // (Clear) Analog Comparator Interrupt Flag
        | bit (ACIE)    // Analog Comparator Interrupt Enable
        | bit (ACIS1);  // ACIS1, ACIS0: Analog Comparator Interrupt Mode Select (trigger on falling edge)
   }  // end of setup

void loop ()
  {
  if (triggered)
    {
    Serial.println ("Triggered!");
    triggered = false;
    }

  }  // end of loop

```

This can be useful for things like light-detectors, where you might need to detect a change from (say) 1V to 2V on an input.

Example circuit:

You can also use the Input Capture Unit on the processor, which will remember the exact time of certain inputs, by saving the current count of Timer/Counter 1. This lets you store the exact (well, almost exact) moment that the event of interest occurred, rather than introducing the delay (of probably a few microseconds) before an ISR can be used to capture the current time.

For timing-critical applications, this can give somewhat increased accuracy.

Example application: Turn your Arduino into a capacitor tester
> 0 votes

---
Tags: pins, interrupt, isr
---