# Question
Title: Have I bricked my Arduino Uno? Problems with uploading to board
I can't upload sketches to my Arduino Uno.

* Have I "bricked" it?
* What steps can I take to work out what is wrong?
* What can I do to fix it?

# Answer
## It probably isn't bricked

I've got quite a few Arduinos, and over the last few years have only ever "bricked" one, and I think that was by zapping it with static electricity. Unfortunately that particular one had a SMD (surface mounted) processor chip, so it isn't easy to try swapping it with another chip.

Stay calm, and try the following steps ...

---

## Example board

An "Arduino Uno" is not just one *thing* that might fail. It has multiple major components, and possibly only one has failed (if any). See this reference photograph:

Major components are:

* Atmega16U2 processor - this handles the interface to the USB connection
* Atmega328P processor - this is the "main" processor which has your sketch on it
* Voltage regulator - this converts incoming power from the power jack to 5 V
* Power LED (green) - marked "On"
* Indicator LED (yellow) marked "L" - connected via an op-amp to digital pin 13
* Rx and Tx LEDs (yellow) - these indicate if the USB chip (Atmega16U2) is receiving or transmitting

Note that the Rx and Tx LEDs are not connected *directly* to digital pins 0 and 1 on the board (marked Rx and Tx). They only illuminate if you are doing serial communications *via USB*, not if you have something (like a GPS) plugged directly into digital pins 0 and 1.

Also note that since the "L" LED is connected via an op-amp, it may illuminate if pin 13 is set to an *input* in your sketch. This is normal. It doesn't mean that something is erroneously sending data.

---

## Check the power

### USB power

* Plug the board into your computer with the USB cable and check that the green "On" LED lights up.
* Use a multimeter and a couple of jumper leads to test between the 5V pin and the GND pin (arrowed at the bottom). You should get a reading of around 5.0 V (I got 5.04 V on mine).

*(You can buy a cheap multimeter for around $10 if you don't have one, but you are better off getting a better one for around $50 - check all the electronics web sites and stores.)*

* Also test between the 3.3 V pin and the GND pin - you should get 3.3 V.

If you do not get 5 V with the USB cable plugged in make sure the other end is connected to your computer. Also try a different cable.

### Power jack

* If you are using, or planning to use, the power jack (marked "power in" on the photo) disconnect the USB, and plug in a power supply - which should be 7 to 12 V DC with positive on the *center* pin.
* Measure the 5 V and 3.3 V pins as above. You should still see the same voltages on them.

If you get 5 V with the USB connected, but not with the power supply then the voltage regulator (marked on the photo) is probably damaged. Or, possibly the power supply has failed. Try a different power supply to confirm which it is.

---

## Check the power-on LED flash

If you have the Optiboot bootloader (the Uno normally ships with that) then if you press and release the Reset button, or unplug and plug the USB or power cable back in, the "L" LED should flash quickly 3 times. The "on" and "off" times are 50 ms each, the three flashes should be over within about 1/3 of a second.

If it doesn't, you may have a problem with the bootloader, or the main processor chip (Atmega328P).

---

## Try uploading a sketch

*Important:* If you are having trouble uploading sketches remove any connected devices (like shields). Also remove jumper wires plugged into the board sockets. In particular, there should be *nothing plugged into digital pins 0 and 1* (Rx and Tx) because that will interfere with communicating with the uploading computer.

Choose one of the simple example sketches (eg. Blink) and try to upload it. This is what you should see:

* The "L" LED should flash 3 times. This is because the main chip is being reset by a command from the uploading process.
* The "Rx" LED should flash quickly. This is the instructions from the uploading process trying to activate the bootloader.
* The "Tx" LED should flash quickly. This is the processor acknowledging the uploaded data.

You may see the above, even if the uploading process fails. This could be because the wrong board type is selected.

If only the "Rx" LED flashes, it could be because of a problem with the bootloader, or the main processor chip (Atmega328P). Someone is knocking, but no-one is at home!

### Check the board type

If the LEDs flash, but you get a message like this:

```
avrdude: stk500_recv(): programmer is not responding

```

Check the board type:

If you have the wrong board type selected it will probably send the wrong uploading instructions, and time-out or otherwise fail. If you are like me and have different boards lying around it is easy to forget that the last upload you did was for a different board type.

### Check the comm port

If the LEDs don't flash at all, you may have the wrong comm port selected.

Check the comm port:

### Try a different PC / Mac if possible

Try your Arduino on a different PC/Mac if you have one to hand. This can narrow down whether or not you have an issue with the particular computer you have plugged it into, or computers in general.

### Do a loopback test

* Disconnect all shields and other wires
* Remove the board from the power
* Connect a jumper wire from RESET to GND (orange wire in photo)
* Connect a jumper wire from Rx to Tx (white wire in photo)

Wiring:

* Plug in the USB cable, and start up a terminal program - such as the Terminal Monitor in the Arduino IDE. Type something and send it (eg. hit *Enter* in the Terminal Monitor).
* Everything you type should be echoed back.

If everything is echoed back: That confirms you have the right comm port, the USB cable is OK and the USB interface chip (Atmega16U2) is probably OK.

If nothing is echoed back, check:

* You have the correct comm port.
* Try a different cable. Some cheap USB cables only have power wires and not data wires.
* Check the device driver for the Arduino is installed. You probably don't need to do this if that board worked previously on this computer, but it can be worth doing if this is the first time you plugged this board into this computer.

---

## Test the Atmega16U2 chip

If your board fails the loop-back test, and you are certain the USB cable is OK, then you can test the Atmega16U2 chip itself. There is an ICSP (In Circuit Serial Programming) header on the board, adjacent to the Atmega16U2 chip, and near the USB socket.

Disconnect the power first (unplug the USB cable and any power cable).

Then you can connect the ICSP header via 6 jumper wires to a known good Uno, as shown in the photo:

The pin-outs for the ICSP header are (from the top):

Pin 1 on the ICSP header near the Atmega16U2 chip is marked with a small white dot, near the "F" in "AREF". Pin 1 on the ICSP header near the ATmega328P chip is marked with a small white dot, below the "N" in "ON".

Connect up:

```
Good board         Target Uno

  MISO                MISO    (pin with dot - pin 1)
  VCC                 VCC
  SCK                 SCK
  MOSI                MOSI
  D10                 /RESET
  GND                 GND

```

Double-check your wiring.

Then on the "known good" board install the "Atmega\_Board\_Detector" sketch as described on the Atmega bootloader programmer page. The code is at GitHub - nickgammon/arduino\_sketches. If you click the Download button on that page you will get a number of useful sketches. The one you want is called "Atmega\_Board\_Detector".

Once installed, open the serial monitor, set it to 115200 baud, and you should see something like this:

```
Atmega chip detector.
Written by Nick Gammon.
Version 1.17
Compiled on Jul  9 2015 at 08:36:24 with Arduino IDE 10604.
Attempting to enter ICSP programming mode ...
Entered programming mode OK.
Signature = 0x1E 0x94 0x89
Processor = ATmega16U2
Flash memory size = 16384 bytes.
LFuse = 0xEF
HFuse = 0xD9
EFuse = 0xF4
Lock byte = 0xCF
Clock calibration = 0x51
Bootloader in use: No
EEPROM preserved through erase: No
Watchdog timer always on: No
Bootloader is 4096 bytes starting at 3000

Bootloader:

3000: 0x4B 0xC0 0x00 0x00 0x64 0xC0 0x00 0x00 0x62 0xC0 0x00 0x00 0x60 0xC0 0x00 0x00
3010: 0x5E 0xC0 0x00 0x00 0x5C 0xC0 0x00 0x00 0x5A 0xC0 0x00 0x00 0x58 0xC0 0x00 0x00
3020: 0x56 0xC0 0x00 0x00 0x54 0xC0 0x00 0x00 0x52 0xC0 0x00 0x00 0xEE 0xC4 0x00 0x00
...
3FE0: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
3FF0: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF

MD5 sum of bootloader = 0xD8 0x8C 0x70 0x6D 0xFE 0x1F 0xDC 0x38 0x82 0x1E 0xCE 0xAE 0x23 0xB2 0xE6 0xE7
Bootloader name: Arduino-dfu-usbserial-atmega16u2-Uno-Rev3

First 256 bytes of program memory:

0: 0x90 0xC0 0x00 0x00 0xA9 0xC0 0x00 0x00 0xA7 0xC0 0x00 0x00 0xA5 0xC0 0x00 0x00
10: 0xA3 0xC0 0x00 0x00 0xA1 0xC0 0x00 0x00 0x9F 0xC0 0x00 0x00 0x9D 0xC0 0x00 0x00
20: 0x9B 0xC0 0x00 0x00 0x99 0xC0 0x00 0x00 0x97 0xC0 0x00 0x00 0x48 0xC4 0x00 0x00
30: 0x0C 0xC4 0x00 0x00 0x91 0xC0 0x00 0x00 0x8F 0xC0 0x00 0x00 0x8D 0xC0 0x00 0x00
...

```

However if you get a message like this:

```
"Failed to enter programming mode. Double-check wiring!"

```

That would appear to indicate that your ATmega16U2 is not working.

---

## Test the ATmega328P chip

Disconnect the power from the "known good" Arduino Uno and rewire the ICSP jumpers as per this photo, to connect them to the "main" processor on your Uno:

The pin-outs for the ICSP header are (from the top):

Pin 1 on the ICSP header near the ATmega328P chip is marked with a small white dot, below the "N" in "ON".

The wiring is the same as before, except you are connecting to the other ICSP header - the one at the end of the board, furthest from the USB socket.

```
Good board       Target Uno

  MISO                MISO    (pin with dot - pin 1)
  VCC                 VCC
  SCK                 SCK
  MOSI                MOSI
  D10                 /RESET
  GND                 GND

```

Once connected, open the serial monitor, set it to 115200 baud, and you should see something like this:

```
Atmega chip detector.
Written by Nick Gammon.
Version 1.17
Compiled on Jul  9 2015 at 08:36:24 with Arduino IDE 10604.
Attempting to enter ICSP programming mode ...
Entered programming mode OK.
Signature = 0x1E 0x95 0x0F
Processor = ATmega328P
Flash memory size = 32768 bytes.
LFuse = 0xFF
HFuse = 0xDE
EFuse = 0xFD
Lock byte = 0xEF
Clock calibration = 0x83
Bootloader in use: Yes
EEPROM preserved through erase: No
Watchdog timer always on: No
Bootloader is 512 bytes starting at 7E00

Bootloader:

7E00: 0x11 0x24 0x84 0xB7 0x14 0xBE 0x81 0xFF 0xF0 0xD0 0x85 0xE0 0x80 0x93 0x81 0x00
7E10: 0x82 0xE0 0x80 0x93 0xC0 0x00 0x88 0xE1 0x80 0x93 0xC1 0x00 0x86 0xE0 0x80 0x93
...

MD5 sum of bootloader = 0xFB 0xF4 0x9B 0x7B 0x59 0x73 0x7F 0x65 0xE8 0xD0 0xF8 0xA5 0x08 0x12 0xE7 0x9F
Bootloader name: optiboot_atmega328

First 256 bytes of program memory:

0: 0x0C 0x94 0x35 0x00 0x0C 0x94 0x5D 0x00 0x0C 0x94 0x5D 0x00 0x0C 0x94 0x5D 0x00
10: 0x0C 0x94 0x5D 0x00 0x0C 0x94 0x5D 0x00 0x0C 0x94 0x5D 0x00 0x0C 0x94 0x5D 0x00
20: 0x0C 0x94 0x5D 0x00 0x0C 0x94 0x5D 0x00 0x0C 0x94 0x5D 0x00 0x0C 0x94 0x5D 0x00
30: 0x0C 0x94 0x5D 0x00 0x0C 0x94 0x5D 0x00 0x0C 0x94 0x5D 0x00 0x0C 0x94 0x5D 0x00
...

```

In this case it confirms that the main processor is working, and has the Optiboot bootloader on it.

---

## Things you can fix

### Failed voltage regulator

This isn't easy to replace, but it is only needed if you use the power jack. If you run from USB then it is not required. Alternatively you could arrange for a 4 to 5 V supply (eg. 3 x AA batteries) and connect them to the 5 V socket on the board directly.

---

### Failed ATmega16U2 chip

This is only required for uploading sketches via the USB port, and serial debugging. It isn't particularly easy to replace because it is a SMD (surface mounted device). However you can manage without it.

You can upload sketches via the ICSP header, if you purchase a ICSP programming device.

Examples of such devices plugged into the ICSP socket:

(Those photos were taken of a Ruggeduino, but the concept is the same).

---

You can also get an FTDI cable, like this:

Connect it to your board's serial ports like this:

```
FTDI    Arduino Uno

GND       GND  (black wire on FTDI cable, blue jumper wire)
CTS       not connected
VCC       5V
TxD       D0 (RX)
RxD       D1 (TX)
RTS       To RESET with a 0.1 µF capacitor in series with it (green wire)

```

Now you can upload sketches directly to the main processor, bypassing the USB chip.

---

You can also use my Atmega chip stand-alone programmer to upload .hex files \- this lets you copy the .hex file for a sketch onto an SD card, and then program the board via the ICSP header.

---

### Failed ATmega328P chip

The main processor can be replaced fairly easily if it is mounted in a socket. Get a replacement chip from somewhere like Adafruit for around $US 6. Alternatively, try eBay. Try to get a chip which has the Optiboot bootloader already on it, to save hassle.

Carefully prise the existing chip out of the socket, and install the new one, taking note of the location of pin 1. Pin 1 has a notch on the chip, and its correct orientation is noted on the first photo in this post with a yellow dot (closest to the edge of the board). You will probably need to straighten the legs slightly. Hold the chip by the ends and gently push down onto a flat surface, like a desk, until the are pushed inwards a bit. Try to *not* touch the metal pins, you may zap them with static electricity.

---

### ATmega328P responds but has no bootloader

I have a sketch at Atmega bootloader programmer which will replace the Optiboot bootloader. The wiring is the same as for the chip detector sketch. The code is at GitHub - nickgammon/arduino\_sketches. If you click the Download button on that page you will get a number of useful sketches. The one you want is called "Atmega\_Board\_Programmer".

Install the sketch on your "known good" Uno, and connect it to the target board with the wiring shown earlier.

Open the Serial Monitor on your "good" Uno and you should see this:

```
Atmega chip programmer.
Written by Nick Gammon.
Version 1.35
Compiled on Jul  9 2015 at 15:06:58 with Arduino IDE 10604.
Attempting to enter ICSP programming mode ...
Entered programming mode OK.
Signature = 0x1E 0x95 0x0F
Processor = ATmega328P
Flash memory size = 32768 bytes.
LFuse = 0xFF
HFuse = 0xDE
EFuse = 0xFD
Lock byte = 0xEF
Clock calibration = 0x83
Type 'L' to use Lilypad (8 MHz) loader, or 'U' for Uno (16 MHz) loader ...

```

Type "U" for the Uno (Optiboot) loader.

```
Using Uno Optiboot 16 MHz loader.
Bootloader address = 0x7E00
Bootloader length = 512 bytes.
Type 'Q' to quit, 'V' to verify, or 'G' to program the chip with the bootloader ...

```

Type "G" to program the chip.

You should see:

```
Erasing chip ...
Writing bootloader ...
Committing page starting at 0x7E00
Committing page starting at 0x7E80
Committing page starting at 0x7F00
Committing page starting at 0x7F80
Written.
Verifying ...
No errors found.
Writing fuses ...
LFuse = 0xFF
HFuse = 0xDE
EFuse = 0xFD
Lock byte = 0xEF
Clock calibration = 0x83
Done.
Programming mode off.
Type 'C' when ready to continue with another chip ...

```

This takes about one second. Now the bootloader is installed.

---

## Watchdog timer problems

The watchdog timer (off by default) can be configured to reset the processor after a certain time. The intention is to recover from a "hang" for a processor deployed in the field. However if the timer is set for a short period (like 16 ms) then the processor can reset again before the bootloader has a chance to do anything.

The symptoms are that you cannot upload any new sketches. Some modern bootloaders (like Optiboot) take steps to stop this problem as one of the first things they do. However others do not.

This can be difficult to recover from, because once the sketch runs, you have the problem of it resetting, and if you have the problem you can't replace the sketch. People often report that they have to burn a new bootloader to recover. However that is only because, as a side-effect, burning a bootloader erases the current sketch.

There *is* a way of recovering. Take these steps:

* Power off the board completely (remove the USB cable).
* Hold down the Reset button, and *keep it held down* (or, run a jumper wire from the RESET pin to the GND pin). This stops the problem sketch from starting, and thus activating the watchdog timer
* Still holding down Reset, reconnect the USB cable.
* Start uploading a sketch that does not have this problem (eg. Blink)
* Once the IDE reports "Uploading" release the Reset button (or remove the jumper wire).
* It should now upload OK - as the sketch which activated the watchdog timer never started.

---

## Problems with the Mega2560 upload

I mention this here, even though this post is really targetting the Uno board, because it is quite common.

Some versions of the Mega2560 bootloader look for "!!!" in the incoming upload from the PC, and if they see that, drop into debugging mode. This causes the upload to fail.

Example code:

```
Serial.println ("Furnace overheating!!!");

```

Solutions:

* Install a more recent bootloader. My "bootloader uploader" sketch mentioned earlier in this reply should install a bootloader that does not have that issue.

Or (more simply):

* Do not use "!!!" in your sketch.

---

## Problems uploading to the Leonardo / Micro / Esplora etc.

Boards with the ATmega32u4 as their main (and only) processor can be trickier to upload to. This is because the same chip has to handle uploads and also run your code.

There is a small window of opportunity, after the board is reset, when it looks for a new sketch to be uploaded. The technique for uploading to these boards is:

* Compile your sketch without errors.
* Start the upload
* As soon as the IDE reports "Uploading" press and release the Reset button.

You only have a second or so to do this, before the old sketch starts running. Don't be discouraged if you have to repeat this process a couple of times. That is normal.

---

## References
> 139 votes

# Answer
At least - as I assume you upload your sketch via avrdude - please give more information about the upload failure (e.g. output of sketch uploader) so people here can help you better.

Additionally to the great answer of Nick Gammon, please search for exclamation marks in your sketch. If your sketch contains a string with more than or equal to 3 exclamation marks, the upload will fail, as old versions of the Arduino Bootloader will interpret these exclamation marks as another function and the upload will stop.

An example for stopping the upload:

```
char* test = "This will stop the upload!!!";

```

See Google Code issue.
> 16 votes

# Answer
I have bricked 2x ATMega328P on my Arduino Uno board due to static (I think).

The static seems to have killed the TX pin and hence the program can't be downloaded using the USB cable.

The easiest solution is to replace the microcontroller. You can buy a new ATMega328P DIP programmed with the Arduino bootloader (such as this one from Adafruit) and you are ready to go again.

Alternatively, you can still program the ATMega328P's by using the Atmel Ice or AVRISPmkII programmer or by using another Arduino as an ICSP programmer. When you do, all but the Tx pin work fine.
> 3 votes

---
Tags: arduino-uno, uploading, atmega328, icsp
---


# Question
Title: Random numbers being printed back after entering data
I am currently working with an Arduino Micro / Linduino and making a program based on a lot of switch statements to execute certain functions that will be passed to a microprocessor (`LT2974`) on a board serially. For the most part, all of the functions I have work, except there is one that I am trying to determine if it is my program that is causing issues, or the Linear Tech libraries that are provided. Upon research, I did discover something strange in my code that I cannot explain.

Here is a quick snippet of my code:

```
unsigned long serialdata;
int inbyte;

long getSerial()
{
  serialdata = 0;
  while (inbyte != '/')
  {
    inbyte = Serial.read();
    if (inbyte > 0 && inbyte != '/')
    {
      serialdata = serialdata * 10 + inbyte - '0';
      Serial.print(serialdata);
      Serial.print("test \n");
    }
  }
  inbyte = 0;
  return serialdata;
}

void loop()
{
  getSerial();
  // Switch statement represents Slot choices
  switch (serialdata)
  {

    case 1:
      {
        commands(Slot1);
        break;
      }
    case 2:
      {
        commands(Slot2);
        break;
      }
    case 3:
      {
        commands(Slot3);
        break;
      }
    case 4:
      {
        commands(Slot4);
        break;
      }
  }
}

```

I have left out the following switch statements that are found in the commands function as they are not where the issue lies.

For some reason, when I pass data through to the Arduino, and then go to reprint it out with my `Serial.print` command in `getSerial()`, there is an additional number printing, and I believe the issue to lie here.

So, for example, if I type `"/1/"` (the slashes were used to pass multiple variables as shown in the function, but I'm only passing one for now), the Arduino reponds with:

```
1test
4294967268test

```

here is `"/2/"`

```
2test
4294967258test

```

and here is passing multiple variables with `"/2/9/"`

```
2test
9test
4294967258test

```

All of the values I just showed you do not correspond to any of my switch statements implemented, and so no actual data is being returned besides the print command from `getSerial()`. So can anyone explain what is going on here?

EDIT: I added the data types of `serialdata` and `inbyte` to the top of the post.

# Answer
> 1 votes
The problem is that you are blindly reading serial data without first looking to see if there is actually any serial data available to read.

If there is no data there `Serial.read()` will return -1. Since you have only provided a snippet of your program I can't say what data type `inbyte` is, but my guess is it's some form of unsigned 32-bit value, since -1 mapped into an unsigned 32-bit value is 4294967295.

You need to be checking the presence of data, and only reading when you should read, and also looking for the end of your data sequence (add some terminating character, like a line feed) to know when to stop looking for and reading characters.

---
Tags: serial, arduino-micro
---


# Question
Title: Arduino Nano - Upload verification error
I'm new to Arduino; and I'm trying to upload a simple sketch to a new Arduino Nano

I tried a few sketches (blink / helloworld / empty one); and changing the USB PORT. Windows find the correct serial port (but it's a CH340 USB-Serial; I think that's some Chinese clone). I tried a few USB ports.

When I upload the sketch, it seems to upload. But a verification error appears:

```
avrdude: verifying ...
avrdude: verification error, first mismatch at byte 0x00ea
         0x8c != 0x8d
avrdude: verification error; content mismatch

```

This is the command line

```
D:\Arduino\hardware\tools\avr/bin/avrdude -CD:\Arduino\hardware\tools\avr/etc/avrdude.conf -v -patmega328p -carduino -PCOM6 -b57600 -D -Uflash:w:C:\Users\corti\AppData\Local\Temp\build462236accad2415310c5b24cce7ccca0.tmp/Blink.ino.hex:i

```

This is the full verbose log of the flashing:

```
avrdude: Version 6.0.1, compiled on Apr 15 2015 at 19:59:58
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2009 Joerg Wunsch

         System wide configuration file is "D:\Arduino\hardware\tools\avr/etc/avrdude.conf"

         Using Port                    : COM6
         Using Programmer              : arduino
         Overriding Baud Rate          : 57600
         AVR Part                      : ATmega328P
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PC2
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    20     4    0 no       1024    4      0  3600  3600 0xff 0xff
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff
           lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : Arduino
         Description     : Arduino
         Hardware Version: 2
         Firmware Version: 1.16
         Vtarget         : 0.0 V
         Varef           : 0.0 V
         Oscillator      : Off
         SCK period      : 0.1 us

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.00s

avrdude: Device signature = 0x1e950f
avrdude: reading input file "C:\Users\corti\AppData\Local\Temp\build462236accad2415310c5b24cce7ccca0.tmp/Blink.ino.hex"
avrdude: writing flash (1066 bytes):

Writing | ################################################## | 100% 0.32s

avrdude: 1066 bytes of flash written
avrdude: verifying flash memory against C:\Users\corti\AppData\Local\Temp\build462236accad2415310c5b24cce7ccca0.tmp/Blink.ino.hex:
avrdude: load data flash data from input file C:\Users\corti\AppData\Local\Temp\build462236accad2415310c5b24cce7ccca0.tmp/Blink.ino.hex:
avrdude: input file C:\Users\corti\AppData\Local\Temp\build462236accad2415310c5b24cce7ccca0.tmp/Blink.ino.hex contains 1066 bytes
avrdude: reading on-chip flash data:

Reading | ################################################## | 100% 0.24s

avrdude: verifying ...
avrdude: verification error, first mismatch at byte 0x00ea
         0x8c != 0x8d
avrdude: verification error; content mismatch

```

# Answer
> -1 votes
I have seen this once before when one of my mates was having troubles programming a ATMega328P on a custom board. It turned out to be his physical serial port. We later confirmed it with a scope - indeed the first packet wasn't what it was meant to be sending. So we switched to a USB-to-Serial dongle that I had and the problem was resolved.

In your case, I highly suspect that it is the CH340 to blame here.

Try programming the Adruino with the AVRISPmkII or another USB-to-TTL converter.

**Edit:** Alternatively you could program your microcontroller using a genuine Arduino Uno board (such as a friends) and then place it back onto your board.

---
Tags: arduino-nano
---


# Question
Title: Why does this code show me a lot of space?
I want to make a 4hz reading of GSR and temperature, in the following format for every second:

```
697,20.8744
696,20.86521
695,20.8653
699,20.8777

```

The print, in python, would be print(GSR+","+Temp) The tries in C are giving problem, here's my actual code:

```
#include <OneWire.h>

const int GSR=A0;
int threshold=0;
int sensorValue;
unsigned long startTime = 0;
#define MEASURE_PERIOD 250
OneWire  ds(3);

void setup(){
  long sum=0;
  Serial.begin(115200);

  for(int i=0;i<500;i++)
  {
  sensorValue=analogRead(GSR);
  sum += sensorValue;
  delay(5);
  }
  threshold = sum/500;
  }

void loop()
{
  byte i;
  byte present = 0;
  byte type_s;
  byte data[12];
  byte addr[8];
  float celsius;
    if((millis() - startTime) >= MEASURE_PERIOD)
    {
        startTime += MEASURE_PERIOD;
        // Do your job, such as
        sensorValue=analogRead(GSR);
        Serial.print(sensorValue);
        Serial.print(",");
        if ( !ds.search(addr)) {
    ds.reset_search();
    return;
  }

  if (OneWire::crc8(addr, 7) != addr[7]) {
      return;
  }
  // the first ROM byte indicates which chip

  ds.reset();
  ds.select(addr);
  ds.write(0x44, 1);        // start conversion, with parasite power on at the end

   // maybe 750ms is enough, maybe not
  // we might do a ds.depower() here, but the reset will take care of it.

  present = ds.reset();
  ds.select(addr);
  ds.write(0xBE);         // Read Scratchpad

  for ( i = 0; i < 9; i++) {           // we need 9 bytes
    data[i] = ds.read();
  }

  // Convert the data to actual temperature
  // because the result is a 16 bit signed integer, it should
  // be stored to an "int16_t" type, which is always 16 bits
  // even when compiled on a 32 bit processor.
  int16_t raw = (data[1] << 8) | data[0];
  if (type_s) {
    raw = raw << 3; // 9 bit resolution default
    if (data[7] == 0x10) {
      // "count remain" gives full 12 bit resolution
      raw = (raw & 0xFFF0) + 12 - data[6];
    }
  } else {
    byte cfg = (data[4] & 0x60);
    // at lower res, the low bits are undefined, so let's zero them
    if (cfg == 0x00) raw = raw & ~7;  // 9 bit resolution, 93.75 ms
    else if (cfg == 0x20) raw = raw & ~3; // 10 bit res, 187.5 ms
    else if (cfg == 0x40) raw = raw & ~1; // 11 bit res, 375 ms
    //// default is 12 bit resolution, 750 ms conversion time
  }
  celsius = (float)raw / 16.0;
  Serial.print(celsius);

    }
    Serial.println("\n");

}

```

How can I reach the upper format?

# Answer
From the point of view of what you print, your loop boils down to:

```
if (millis() - startTime >= MEASURE_PERIOD) {
    startTime += MEASURE_PERIOD;
    sensorValue = ...;
    celcius = ...;
    Serial.print(sensorValue);
    Serial.print(",");
    Serial.print(celsius);
}
Serial.println("\n");

```

You are printing *two* newlines on every loop iteration. One is written as `"\n"`, the other is the “ln” of `Serial.println` (“println” means “print some stuff followed by a new line character sequence”). Instead, you probably want to print a *single* newline, and only when there is actual data being printed:

```
if (millis() - startTime >= MEASURE_PERIOD) {
    startTime += MEASURE_PERIOD;
    sensorValue = ...;
    celcius = ...;
    Serial.print(sensorValue);
    Serial.print(",");
    Serial.println(celsius);  // notice the ln in println
}

```

But since you are doing nothing else in `loop()`, you could simplify a bit and avoid having everything inside a big `if` statement:

```
if (millis() - startTime < MEASURE_PERIOD)
    return;

startTime += MEASURE_PERIOD;
sensorValue = ...;
celcius = ...;
Serial.print(sensorValue);
Serial.print(",");
Serial.println(celsius);

```

**Edit**: Here is a simple test demonstrating this logic. In both the second and the third case, it generates an output in the requested format.

```
const uint32_t MEASURE_PERIOD = 250;

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

void loop()
{
    static uint32_t startTime;
#ifdef SECOND_CASE
    if (millis() - startTime >= MEASURE_PERIOD) {
        startTime += MEASURE_PERIOD;
        int sensorValue = random(695, 699);
        float celsius = map(sensorValue, 695, 699, 208653, 208777) / 1e4;
        Serial.print(sensorValue);
        Serial.print(",");
        Serial.println(celsius, 3);  // notice the ln in println
    }
#else  // third case
    if (millis() - startTime < MEASURE_PERIOD)
        return;

    startTime += MEASURE_PERIOD;
    int sensorValue = random(695, 699);
    float celsius = map(sensorValue, 695, 699, 208653, 208777) / 1e4;
    Serial.print(sensorValue);
    Serial.print(",");
    Serial.println(celsius, 3);  // notice the ln in println
#endif
}

```
> 1 votes

---
Tags: arduino-uno, arduino-nano, c
---


# Question
Title: serial communication dead slow after a while
I'm workin on a node for blender to control an arduino. I notice it goes really slow after a while so I isolated the problem. It is good in maintaining 60 frames a second, then after around 40 seconds (pretty exact), it drops to a pretty exact 1 fps for some reason.

What could be going on?

```
import serial
import time

ser = serial.Serial('COM3', 115200)

c = 0

while True:
    c+=1
    print("ok ", c)
    numIn = "100n"
    ser.write(numIn.encode('ascii'))
    time.sleep(1./60)

```

arduino code:

// special thx to Nick Gammon

```
const unsigned int MAX_INPUT = 50;

unsigned long delay_time = 300;
unsigned long last_toggle_time = 0;
int current_state = LOW;

void setup () {
  Serial.begin (115200);
  pinMode(12, OUTPUT);

}

void process_data (const char * data) {
  Serial.println (data);
  delay_time = atoi(data);
}

void processIncomingByte (const byte inByte) {
  static char input_line [MAX_INPUT];
  static unsigned int input_pos = 0;

  switch (inByte) {

    case 'n':   // end of text
      input_line [input_pos] = 0;  // terminating null byte
      process_data (input_line);
      input_pos = 0;
      break;

    case 'r':
      break;

    default:
      if (input_pos < (MAX_INPUT - 1))
        input_line [input_pos++] = inByte;
      break;

  }
}

void loop() {

  while (Serial.available () > 0) {
    processIncomingByte (Serial.read ());
  }

  unsigned long m  = millis();

  if (m > last_toggle_time + delay_time) {
      current_state = current_state == HIGH ? LOW : HIGH;
      digitalWrite(12, current_state);
      last_toggle_time = m;
  }

}

```

# Answer
> 0 votes
If you print from arduino to serial and you don't read it then the buffer gets full. Causing it to go in a second delay. So make sure you read as well when you send data over.

A short sleep is required between the sleep and the read for some reason. Else it hangs.

```
import serial
from time import sleep

ser = serial.Serial('COM3', 115200)
sleep(1)

c = 0

while True:
    c+=1
    print("ok ", c)
    numIn = "100"
    ser.write((numIn + '\r\n').encode())
    sleep(1./120)

    inp = ser.readline()
    print(inp.decode("utf-8"))
    sleep(1./120)

```

---
Tags: python
---


# Question
Title: What does serial monitor send with 'Both NL & CR'
There is something I don't understand about serial monitor.

As far as I know the `Newline` option is `\n`.

The `Carriage return` option is `\r\n`.

But does that make the `Both NL & CR` option `\n\r\n`?

# Answer
Newline is `\n`

Carriage Return is `\r`

Both NL & CR is `\r\n`
> 8 votes

# Answer
"Both" means 1 Carriage Return and 1 Newline (formerly known as "Line Feed"). Our present day "standards" are descended from mechanical teletypes that used those separate codes for the two separate mechanical functions: Returning the print carriage to the left side of the page, and scrolling the paper up one line.

The DOS/Windows world adopted the teletype standard (both) as is.

The unix world dropped the carriage return as unnecessary, letting a single character stand for the end of a line, and more modern hardware (or its software drivers) could figure out what to do for the particular device.

The Apple world chose Carriage Return for its standard back in the mists of time, dropping it in later years for a selectable end-of-line sequence where appropriate, but more usually using the unix standard once it's OSes became hosted on unix.
> 3 votes

---
Tags: serial
---


# Question
Title: Arduino project - will this fit together?
I'm about to order parts for my project and I'd like to avoid some rookie mistake I might've missed. I'll be using Arduino chip and a wifi module to host a very simple webpage and a battery to make this all portable. I've decided to use Arduino Mini Pro 8MHz because of 3.3V input voltage, same as ESP8266, also FT232RL to program the board and TPS73601 for my battery. This is where I have some doubts, the battery I've picked is Li-Ion from my old Samsung Galaxy S AFAIK when charged it supplies ~4.2V and nearly discharged ~2.7V so the regulator should work (?). Is using Li-Ion in any way different from regular AA or just +/- because I see 3 pins on the back of it? Except for charging of course I'll be using the phone for that. Thanks in advance for any suggestions.

# Answer
> 0 votes
From what you've provided everything seems to be compatible.

Concerning the battery, a quick look at the Arduino website shows:

> Input Voltage 3.35 -12 V (3.3V model)

Meaning the regulator will work as long as the battery provides voltage above 3.35 but since your battery's voltage drops as it gets depleted you might not get the battery life you'd expect :/. In other words: it'll work initially until the voltage drops below 3.35V and then you would have to recharge it.

> Is using Li-Ion in any way different from regular AA

Yes and No. No : both provide a stable DC source and both can be used in similar applications.

Yes: Li-Ion batteries can be recharged and have a longer life-span, and most importantly, Li-Ion batteries don't have a sharp voltage drop as they get depleted, unlike regular AA batteries. Which is a bonus for this project ( i guess :p )

> I see 3 pins on the back of it

There are only 2 pins that actually provide the power from the battery while the third is usually used to monitor temperature or battery life remaining.So you can use this battery by only connecting the power providing pins (usually indicated by + and - ) and safely ignore the third.

Gd Luck!

---
Tags: project
---


# Question
Title: Arduino Uno + Jaguar Speed Controller + CIM Motor (12V DC)
I have connected a CIM motor to a Jaguar speed controller, powered by a 12V battery. The Jaguar is connected to an Arduino Uno via the signal and ground. Also, I have two switches connected to the Arduino, for forward and reverse of the motor.

In the code, for speed of the motor, I have set 90 as the mid point and 100 for forward and 80 for reverse. When I push the reverse button, the motor runs smoothly in the reverse direction at the set speed. However, the problem is, when I press the forward button, the motor runs seemingly **slower** in the forward direction than the set speed.

My logic here was, if I have set speeds in forward and reverse at +/- 10 from the mid-point, the motor should run at the same speed in the forward and reverse direction, but this is not happening.

I am pasting my code below. Any help would be much appreciated. Thank you!

```
#include <Servo.h>

int forwardPin = 2;
int reversePin = 4;
int motorPin = 10;
int fwdReading = 0;
int revReading = 0;

Servo myservo;

void setup() {
  TCCR1B = TCCR1B & 0b11111000 | 0x04; // PWM Freq. at 122Hz
  pinMode (forwardPin, INPUT);
  pinMode (reversePin, INPUT);
  myservo.attach(motorPin);
  myservo.write(90);  // set servo to mid-point
}

void loop() {
  fwdReading = digitalRead(forwardPin);
  revReading = digitalRead(reversePin);
  if (fwdReading == HIGH) {
    myservo.write(100); // forward
  } else if (revReading == HIGH) {
    myservo.write(80); // reverse
  } else
    myservo.write(90); // neutral
}

```

# Answer
I searched for the library you're using and the arduino website mentions :

> 0 being full-speed in one direction, 180 being full speed in the other, and **a value near 90 being no movement**

From this we can take that the value 90 is not perfectly in the middle of the speed range therefore 10 points under 90 won't necessarily be equivalent to 10 points above 90. My only advice is to try and find the equivalence point yourself by trail and error. Even though 90 seems to cause no movement, try 89 or 91 see if they also have the result and so on.

Or simply try different values to get same speeds in different directions, it's ok if you use different values (away from 90) for the two different directions :P.

Gd Luck
> 1 votes

---
Tags: arduino-uno, motor
---


# Question
Title: Flickering LCD backlight with fingerprint scanner
I have the following problem: for some \*** reason, my LCD is flashing when my fingerprint scanner turns on. Here is a video of the behavior: https://www.dropbox.com/s/mqk4u0vu8yvhiwz/IMG\_3171.m4v?dl=0.

More details: I have a membrane keypad. When I start typing on it, the LCD turns on, and when I type the correct code, the fingerprint scanner turns on, and the LCD prompts the user to press a finger upon the scanner. However, then the LCD backlight starts flashing badly. Interestingly, if I just plug the wall adapter into the arduino and try the scenario, the LCD does not flash. However, if let's say 10-15 have passed since the adapter is plugged in, the LCD flickering becomes visible and irritating (again, when the fingerprint scanner is turned on). So, what could be the reason and how to fix it? Why if I just plug the adapter and execute the scenario, the LCD does not flash, and if I wait some time with the adapter plugged in, and then execute the scenario, the LCD flickers?

Just to add: My fingerprint scanner is GT511C1R (https://www.sparkfun.com/products/13007) and I am using the standard scheme for wiring it (560/1000 ohm for the RX). I am not using lcd.clear() command as I know it's heavy, and even if I don't write any text, the still LCD flickers.

Best regards, Nike

# Answer
> 2 votes
The backlights on these LCDs are just an LED array with a series resistor so the intensity will be directly proportional to the input voltage; flickering voltage = flickering backlight.

Check these things:

1. Measure the output of the 5V regulator with an AC volt meter to see if the regulator is oscillating when the backlight flickers, i.e. AC voltage \>\> 0V. If it is, then you probably need to increase the size of the output and possibly the input capacitors.
2. Measure the Input-to-Output voltage differential of the regulator and multiply it by the output current. If you dissipate more power than the thermal design allows this will heat the regulator making (1) more likely as well as driving the regulator into thermal shutdown.

If the regulator is linear, i.e. 7805 etc, you can solve both (1) and (2) by changing the regulator to a drop in switching type. These will dissipate heat as a percentage of the output power instead of as a function of the input voltage and can be made self contained with regard to input/output capacitors which would be on-board instead of off-board. A switcher can also do something a linear can't do: Supply more current than the source. A 12V 0.5A power supply into a 5V regulator can supply 5V at 0.5A with 3.5 watts of waste heat. That same 12V supply into a decent switcher can deliver 1.14A at 5V with only 300mW of waste heat!

This PDF is an example circuit that runs about 95% efficient and fits on a 7805 footprint.

This PDF is the circuit of the 1516 switcher linked above configured to replace the NCP1117 linear regulator use on the Uno Rev3.

This PDF is a full thermal analysis of the Arduino Uno NCP1117 regulator running under the conditions stated in your question. As you can see, you were right on the edge of what the NCP1117 could handle at 200mA (LCD plus scanner). I have included a thermograph showing the same unit supplying 1.85A at 5V using a drop in switching regulator with no issues.

# Answer
> 0 votes
A huge thanks for your detailed replies! They lead me into the very right direction. So here is what was it: As I mentioned, the situation gets worse as more time passes with the 12v jack plugged in. At the same time, the regulator was getting damn hot, I could not stick my fingers to it for more than half a second. So, I kind of did what you recommended - got a regulator and put down the voltage to 7V (with 5V the display did not want to show any text). With 7V the regulator is still getting warm, but even if I left it for 10 minutes running it's not getting hot any further further. The display - it's flickering very little and only if you look at it at a specific angle, but it's not flickering overall if you look straight at it. Interestingly, I also took a look at the schemes of the display and the fingerprint scanner and it sounds like it would not be possible for the arduino to feed these two. But, the whole project is running flawlessly (at least looks so). I just hope that math equations in regards to the mA would not cause harm to the fingerprint scanner or the arduino.

So, thanks again, for your kind and detailed replies, much appreciated.

All the best, Nike

---
Tags: lcd
---


title: Serial Data Formatting not Correct?

text:
# Question
Title: Serial Data Formatting not Correct?
I am writing two Arduino Uno programs. One is a remote with a joystick and the other has five LED's indicating which direction the joystick is pointing. They are Bluetooth, so everything is sent and received through `Serial`. I am sending three variables by joining them into one string, separated by colons. Then I separate them back into three variables on the other arduino The joystick, Bluetooth, and LED's part of the programs work, I'm having trouble receiving the data and separating it. I have included both programs below. As it is now, it doesn't work. In the slave code, you can change the `int xPosition = getValue(input, ':', 0).toInt();` to `int xPosition = getValue(input2, ':', 0).toInt();`( also change `yPosition` and `buttonState`) and everything works. What is the difference between that string and what I'm receiving?

# Slave code:

```
#include <SoftwareSerial.h>
#define RxD 7
#define TxD 6
SoftwareSerial BlueToothSerial(RxD,TxD);
char flag=1;
String input;
int xPosition;
int yPosition;
int buttonState;
char outstring[30];
char *input2 = "510:609:1\r\n";

void sendBlueToothCommand(char *Command)
{
  BlueToothSerial.print(Command);
  Serial.print(Command);
  delay(100);
  while(BlueToothSerial.available())
  {
     Serial.print(char(BlueToothSerial.read()));
  }
}

String getValue(String data, char separator, int index)
{
 int found = 0;
  int strIndex[] = {0, -1  };
  int maxIndex = data.length()-1;
  for(int i=0; i<=maxIndex && found<=index; i++){
  if(data.charAt(i)==separator || i==maxIndex){
  found++;
  strIndex[0] = strIndex[1]+1;
  strIndex[1] = (i == maxIndex) ? i+1 : i;
  }
 }
  return found>index ? data.substring(strIndex[0], strIndex[1]) : "";
}

void setup()
{
   pinMode(12, OUTPUT);
   pinMode(11, OUTPUT);
   pinMode(10, OUTPUT);
   pinMode(9, OUTPUT);
   pinMode(8, OUTPUT);
   Serial.begin(38400);
   BlueToothSerial.begin(38400);
   delay(500);
   Serial.println("Starting...");
}

void loop()
{
    if(BlueToothSerial.available())
    {
      input = char(BlueToothSerial.read());
      int xPosition = getValue(input, ':', 0).toInt();
      int yPosition = getValue(input, ':', 1).toInt();
      int buttonState = getValue(input, ':', 2).toInt();
      Serial.println("xPosition");
      Serial.println(xPosition);
      Serial.println("yPosition");
      Serial.println(yPosition);
      Serial.println("buttonState");
      Serial.println(buttonState);
      if ((xPosition == 507)&&(yPosition == 506)){
        clear();
        digitalWrite(8, HIGH);
      } else if ((xPosition == 507)&&(yPosition == 0)){
        clear();
        digitalWrite(12, HIGH);
      } else if ((xPosition == 507)&&(yPosition == 1023)){
        clear();
        digitalWrite(10, HIGH);
      } else if ((xPosition == 1023)&&(yPosition == 507)){
        clear();
        digitalWrite(11, HIGH);
      } else if ((xPosition == 0)&&(yPosition == 1023)){
        clear();
        digitalWrite(9, HIGH);
      }
    }
}

void clear() {
  digitalWrite(12, LOW);
  digitalWrite(11, LOW);
  digitalWrite(10, LOW);
  digitalWrite(9, LOW);
  digitalWrite(8, LOW);
}

```

# Master code:

```
#include <SoftwareSerial.h>
#define RxD 7
#define TxD 6
SoftwareSerial BlueToothSerial(RxD,TxD);
int xPin = A1;
int yPin = A0;
int buttonPin = 2;
char outstring[30];
int xPosition = 0;
int yPosition = 0;
int buttonState = 0;

void sendBlueToothCommand(char *Command)
{
  BlueToothSerial.print(Command);
  Serial.print(Command);
  delay(100);
  while(BlueToothSerial.available())
  {
     Serial.print(char(BlueToothSerial.read()));
  }
}

void setup()
{
   Serial.begin(38400);
   BlueToothSerial.begin(38400);
   delay(500);
   pinMode(xPin, INPUT);
   pinMode(yPin, INPUT);
   pinMode(buttonPin, INPUT_PULLUP);
   BlueToothSerial.println("Hello");
}

void loop()
{
  joy();
  sprintf(outstring, "%d:%d:%d\r\n", xPosition, yPosition, buttonState);
  BlueToothSerial.println(outstring);
  Serial.println(outstring);
}

void joy() {
  xPosition = analogRead(xPin);
  yPosition = analogRead(yPin);
  buttonState = digitalRead(buttonPin);
}

```

# Answer
The problem is you are only reading one character and trying to split that single character into other smaller units. It just isn't going to happen.

Instead you need to append each character to the end of a string until you receive the end-of-line characters (`\r\n`). Then you can split that entire string into parts.

Alternatively you can read numbers until you hit a `:` or a `\r\n` and build up the numbers directly without having to store anything.

My preferred method is the first, but I know Nick Gammon prefers the second, so I shall leave it to him to describe his favourite Finite State Machine for you.

To store all the data in a string I use a C string, not one of Arduino's dodgy String objects.

```
char input[15];
int ipos = 0;

```

Then you read the data:

```
if (BlueToothSerial.available()) {
    char c = BlueToothSerial.read();
    if (c == '\r') continue; // Skip the carriage return
    if (c == '\n') { // We have the line ending
        // Split the data on :
        char *xtxt = strtok(input, ":");
        char *ytxt = strtok(NULL, ":");
        char *btxt = strtok(NULL, ":");
        // Convert the text to integers
        if (xtxt) xPosition = atoi(xtxt);
        if (ytxt) yPosition = atoi(ytxt);
        if (btxt) buttonState = atoi(btxt);
        ipos = 0; // Reset the string to the start
    } else {
        // If there is still room in the array
        if (ipos < 14) {
            // Add the incoming character
            input[ipos++] = c;
            // and terminate the string.
            input[ipos] = 0;
        }
    }
}

```
> 0 votes

# Answer
In the slave's `loop()`, when you say

```
input = char(BlueToothSerial.read());

```

I'd expect just the first character of the serial stream to be read and stored. Without further investigation, I don't know just what a `String` class does when you assign a character to it, but I doubt that any of the following code ever has more than one character at a time to work on. This will keep your `getValue()` calls from working like you want.

Instead of using `String` objects and your `getValue()` code, consider using code like the following to handle the serial input. The data format that this code expects is `nnnxnnnynnnb`, where each `nnn` is a series of digits, and x, y, b are literal characters.

This code shortens two of the overly-verbose parts of your code by:
• Use of an array and subscripting to replace the long list of `if` statements that sort out the combinations of low/medium/high x and y values.
• Use of `Streaming.h` (which you can install by unzipping Streaming5.zip from arduiniana.org into your sketchbook/libraries directory) to clean up long lists of `Serial.println()` statements, without increasing code size.

```
#include <Streaming.h>
int numVal = 0;

void doAction() {
  byte pins[] = { 9,0,0, 12,8,10, 0,11,0 };
  byte xy = 3*(x/500)+y/500;
  byte pin = pins[xy];
  if (pin) {
    clear();
    digitalWrite(pin, HIGH);
  }
  Serial << "xPosition =  " << xPosition << endl;
  Serial << "yPosition =  " << yPosition << endl;
  Serial << "buttonState = " << buttonState << endl;
  numVal = 0;
}

void loop() {
  while (BlueToothSerial.available()) {
    byte c = BlueToothSerial.read();
    if ('0' <= c && '9' >= c) {
        numVal = 10*numVal + c - '0';
    } else {
      switch (c) {
      case 'x':  xPosition = numVal;   break;
      case 'y':  yPosition = numVal;   break;
      case 'b':  buttonState = numVal; doAction(); break;
      }
      numVal = 0;
    }
  }
}

```
> 0 votes

---
Tags: serial, programming, string
---


title: a mega 2650 power supply mystery

text:
# Question
Title: a mega 2650 power supply mystery
Something happened to my mega2650 as I was experimenting the other day. It no longer turned on when powering from the 2.1mm jack or from Vin, regardless of the voltage applied. A plastic bubble had formed on the 5V regulator, I assumed I had shorted something and fried it. If I applied 5V to the 5V pin everything worked fine. It also works fine when powered from USB. So I replaced the 5V regulator with a NCP1117 version. But I have the same situation. If I apply voltage directly to the 5V regulator input pin I get 5V on the output pin and everything is fine. I tested up to 12V and it is dead on at 5V. I also checked the PNP switching transistor, and found it was working correctly. As far as I can tell, the only thing remaining is that the trace is severed somewhere between just after the Vin pin and the 5V regulator, maybe the regulator input is not soldered well to the trace? But this was one of the better solder joints I made, so I thought. Any other ideas as to the root cause?

Thanks

# Answer
You obviously have some form of DMM or volt meter at your disposal, since you know the voltages around the regulator.

Some places you should, therefore, probe for voltages, and what voltages you should expect. With the barrel jack connected and powered up, and assuming a 12V supply, you should expect:

1. At the rear of the socket: 12V
2. At the socket side of the M7 diode: 12V
3. At the header side of the M7 diode: 11.4V
4. At the right-hand (VIN) pin of the regulator: 11.4V
5. On the tab of the regulator: 5V

If you find any of those are wrong then the component that comes before it may well be faulty.
> 1 votes

# Answer
Well the answer is ... I fried the rest of the board when I was trying to troubleshoot it further :( I think 12V went to the 328p, it got hot. Oh well, thanks everyone!
> 1 votes

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


# Question
Title: Beat 1 LED light is always on - should turn off
```
/**************************************/
const int lowestPin = 1;//the lowest one attach to
const int speaker = 13;
int ts = 4;//how many beats you want
int count = 1;
const int keyPin = 11;
const int keyPinR = 10;
int buttonState = LOW;
int buttonState2 = LOW;
int bpm = 120;
int rthm = 1;
/**************************************/
void setup()
{
  Serial.begin(9600);
   for(int thisPin = 1;thisPin <= ts;thisPin++)
   {
 pinMode(thisPin,OUTPUT); //initialize thisPin as an output
 pinMode(8, INPUT);

 pinMode(keyPin, INPUT);
 pinMode(keyPinR, INPUT);
 digitalWrite(keyPin, HIGH);
 digitalWrite(keyPinR, HIGH);
 }

}

/****************************************/
void loop()
{
 buttonState = digitalRead(keyPin);
 buttonState2 = digitalRead(keyPinR);
 if(buttonState==LOW){
 ts++;
  if(ts==6)
   {
    ts = 2;
   }
  }
 if(buttonState2==LOW){
  rthm++;
    Serial.println(rthm);
  if(rthm==5)
  rthm = 1;

  }
  for(int thisPin = 1;thisPin <= ts;thisPin++)
  {

  for(int r = 1; r<=rthm; r++){
   bpm = pulseIn(6, HIGH);
    digitalWrite(thisPin,HIGH);

    pinMode(13,OUTPUT);

    if(count == 1&&r==1)
    tone(13,1500,40);
    else if(r==1)
    tone(13,1000,40);
    else
    tone(13,500,40);
    delay((bpm-52)/rthm);

    digitalWrite(thisPin,LOW);
    pinMode(13,INPUT);

   }
    count++;
    if(count >ts)
    count = 1;
    }

   }

```

This is a metronome project. Each LED represents a beat. However, The LED for beat 1 is always on. It should turn off when it's on a different beat other than one. Is there anything wrong with the code?

# Answer
> 1 votes
You are using PIN1 as an output pin and you are writing data to the Serial interface. The serial interface uses pin 1 and 0. Change lowestPin to 2 and ts to 5 and it will work.

---
Tags: arduino-uno
---


title: Using Arduino and XBee at the same time

text:
# Question
Title: Using Arduino and XBee at the same time
I have 2 Arduino Unos, 2 XBees and 2 Wireless Proto Shields. The first setup has a humidity/temperature sensor (SHT21P) and it writes data to serial and it works (I've tested it).

Now, the other Arduino with shield and XBee is plugged in my PC to get data from the sensor. So here's the problem: as far as I understand, I can't use XBee and Arduino at the same time, because USB and Arduino both use TX/RX pins to communicate to PC/XBee. I've tested both of the XBees when they are powered with DC jack and they both work. So can anyone confirm that it's true that they're not made for being used by PC and Arduino at the same time? If so, how can I get the data to my computer?

# Answer
Okay, I guess I figured it all out. So right now I have the following setup:

1 Arduino Board with Wireless Proto Shield (switch in Micro position) and XBee hooked up via DC jack pin, sends data to serial with `Serial.print(variable)` where `variable` is a predefined char array.

1 Arduino with Wireless Proto Shield (switch in Micro position) and XBee is hooked to the PC via USB and with `Serial.read()` I'm able to read data via the Serial Monitor. No configuration required whatsoever, the only thing you need to do this is to declare `Serial.begin(9600)` to both boards.

So it's true that I can't use Arduino and XBee at the same time, but this still works for me to solve the problem I had.
> 0 votes

# Answer
If I understand correctly your goal is to receive data on your computer from an arduino connected with xbee? You could use a USB \> Xbee board similar to Sparkfun's Xbee USB explorer board. I am not familiar with the shield that you are using, but some xbee shields allow you to select the pins that the xbee is connected to. It sounds like yours is defaulting to Pin 0 and Pin 1, hardware serial on the Uno. If you can switch it to Pin 2 and Pin 3 (or any two digital pins) you could use software serial with the xbee, leaving hardware serial free for your USB connection.
> 0 votes

---
Tags: arduino-uno, communication, xbee
---


title: Arduino Mega with nRF24L01+ module

text:
# Question
Title: Arduino Mega with nRF24L01+ module
I am having trouble getting this module to work using the tmrh20 lib. I am using these modules with two arduino mega and a 3.3V external power supply. I also placed 10 uF in parallel with the modules power pin. I would really appreciate any comments or suggustions.

In the code below all I am trying to do is turn on a led. Here are my pin assignment for both arduinos CE -\> 7 CSN -\> 8 SCK -\> 52 MOSI -\> 51 MISO -\> 50 IRQ -\> unconnected

**Transmitter**

```
//#include <DigitalIO.h>
#include <SPI.h>
#include "RF24.h"
#include <printf.h>
RF24 radio(7,8);
const uint64_t pipe = 0xE8E8F0F0E1LL;
unsigned long msg = 375983;

void setup() {
    Serial.begin(115200);
    printf_begin();
    Serial.println("Transmitter");
    pinMode(9, INPUT);
    radio.begin();
    radio.setChannel(108);
    radio.openWritingPipe(pipe);
    radio.startListening();
    radio.printDetails();
}

void loop() {
  radio.stopListening();
  if (digitalRead(9) == HIGH)
  {
    while (!radio.write(&msg, sizeof(msg))){
      radio.write(&msg, sizeof(msg));
}
  Serial.println("Sending.....");
  }
  else {
    Serial.println("Awaiting Input....");
  }
  delay(500);

}

```

print detail report

```
STATUS = 0xff RX_DR=1 TX_DS=1 MAX_RT=1 RX_P_NO=7 TX_FULL=1
RX_ADDR_P0-1 = 0xffffffffff 0xffffffffff
RX_ADDR_P2-5 = 0x7f 0xff 0x7f 0xff
TX_ADDR = 0x0000000000
RX_PW_P0-6 = 0xff 0x7f 0xff 0x7f 0xff 0xff
EN_AA = 0xff
EN_RXADDR = 0xff
RF_CH = 0xff
RF_SETUP = 0xff
CONFIG = 0xff
DYNPD/FEATURE = 0x7f 0xff
Data Rate = 1MBPS
Model = nRF24L01
CRC Length = Disabled
PA Power = PA_MAX

```

**Receiver**

```
//#include <DigitalIO.h>
#include <SPI.h>
#include "RF24.h"
#include <printf.h>
RF24 radio(7,8);
const uint64_t pipe = 0xE8E8F0F0E1LL;
unsigned long msg;

void setup() {
    Serial.begin(115200);
    printf_begin();
    Serial.println("Receiver");
    pinMode(9, OUTPUT);
    radio.begin();
    radio.setChannel(108);
    radio.openReadingPipe(0,pipe);
    radio.printDetails();

}

void loop() {
   radio.startListening();
   digitalWrite(9, LOW);
  if(radio.available()){
    while(radio.available())
    {
    radio.read(&msg, sizeof(msg));
    Serial.println("Incoming...");
    delay(500);
    Serial.println(msg);
    }
  }
  else{
    Serial.println("No Msg");
  }
  radio.stopListening();
  Serial.println(msg);
  if (msg == 375983){
    digitalWrite(9, HIGH);
    Serial.println(msg);
  }
  delay(500);
}

```

print detail report

```
STATUS = 0x00 RX_DR=0 TX_DS=0 MAX_RT=0 RX_P_NO=0 TX_FULL=0
RX_ADDR_P0-1 = 0x0000000000 0x0000000000
RX_ADDR_P2-5 = 0x00 0x00 0x00 0x00
TX_ADDR = 0x0000000000
RX_PW_P0-6 = 0x00 0x00 0x00 0x00 0x00 0x00
EN_AA = 0x00
EN_RXADDR = 0x00
RF_CH = 0x00
RF_SETUP = 0x00
CONFIG = 0x00
DYNPD/FEATURE = 0x00 0x00
Data Rate = 1MBPS
Model = nRF24L01
CRC Length = Disabled
PA Power = PA_MIN

```

UPDATE: Transmitter PrintDetail

```
STATUS       = 0x0e RX_DR=0 TX_DS=0 MAX_RT=0 RX_P_NO=7 TX_FULL=0
RX_ADDR_P0-1     = 0x00000000e1 0xc2c2c2c2c2
RX_ADDR_P2-5     = 0xc3 0xc4 0xc5 0xc6
TX_ADDR      = 0x00000000e1
RX_PW_P0-6   = 0x20 0x00 0x00 0x00 0x00 0x00
EN_AA        = 0x3f
EN_RXADDR    = 0x02
RF_CH        = 0x6c
RF_SETUP     = 0x07
CONFIG       = 0x0f
DYNPD/FEATURE    = 0x00 0x00
Data Rate    = 1MBPS
Model        = nRF24L01+
CRC Length   = 16 bits
PA Power     = PA_MAX

```

Results form tmrh20 Getting Started Example

First Arduino

```
Sent 8340224, Got response 0, Round-trip delay 547172 microseconds
Now sending
Sent 9889124, Got response 0, Round-trip delay 511072 microseconds
Now sending
Sent 11401920, Got response 0, Round-trip delay 43348 microseconds
Now sending
Sent 12446992, Got response 0, Round-trip delay 635580 microseconds
Now sending
Sent 14084352, Got response 0, Round-trip delay 1620788 microseconds
Now sending
Sent 16706968, Got response 0, Round-trip delay 1227548 microseconds
Now sending
Sent 18936340, Got response 0, Round-trip delay 145372 microseconds

```

Second Arduino

```
*** PRESS 'T' to begin transmitting to the other node

```

The second arduino is not printing anything on the serial monitor, no matter what I enter.

# Answer
(not enough point to comment, so here's a potential answer) I had enormous troubles getting these things to work reliably. I tried all kinds of caps over the power supply. In the end I went for a 1$ piggy back board that takes 5v input and regulates to 3.3V. It also has the right pin female header to fit the nfr nicely. Since then I've had no issues. I also did a bit of experimentation and found that the RX side was the side giving problems.
> 1 votes

# Answer
Try these:

* Set pin 9 on the TX side as a pulled-up input i.e. `pinMode(9, INPUT_PULLUP);` Connect one end of the switch to GND and the other to pin 9. Then in your code, test for a button press like this: `if (digitalRead(9) == LOW){...}`
* Use a byte array for holding the address instead of the 64-bit int you're using.
* Remove the `stopListening()` call in your RX loop(); there is no need for it since all its doing is receiving.
* Remove the 500 ms delays in the RX loop() just in the unlikely case that its causing you to lose bytes
> 0 votes

---
Tags: arduino-mega, nrf24l01+
---


# Question
Title: What is the necessity of “Prototyping Shield” for an arduino UNO R3?
I just want to learn arduino and make some small projects.But in beginner starter kit there's a part named Prototyping Shield .Is it necessary or will it help me?

# Answer
> 1 votes
The prototyping shield can be used to build your own circuits up in a more permanent form which can be plugged direct into the Arduino.

You can think of it as a blank canvass on which you can paint your own shield design.

---
Tags: arduino-uno, shields
---


title: SDA/SCL pins Arduino Uno

text:
# Question
Title: SDA/SCL pins Arduino Uno
I am trying to figure if SDA and SCL pins from Arduino Uno is a TTL or a CMOS technology. I am not able to find this info anywhere but regarding it is a I2C protocol it does make sense to be a TTL technology. Can someone kindly confirm this info, please?

# Answer
> 2 votes
It is CMOS in that the IO pins of the MCU use MOSFETs not BJTs.

However I2C is slightly different in that it is open-drain not push-pull, so it's not really either TTL or CMOS since it doesn't conform to either logic level standard (since there is no "high" voltage, only what is pulled up by the external resistor). That said, since the ATMega is normally CMOS when in input or push-pull mode the logic levels of the I2C should conform to CMOS not TTL in order for the Arduino to read them properly.

It's closer to RTL than TTL or CMOS.

# Answer
> 1 votes
Your question makes no sense. I²C uses open-drain/open-collector drivers which can even be discrete transistors or FETs although the inputs correspond to CMOS/TTL. These can be mixed - the Arduino uses MOS technology.

Of more significance is the supply voltage and the high/low trigger points (and of course the value of the mandatory pullup resistors which determine speed and/or range).

It is possible to use mixed 3.3V/5V levels. I use a Pi (3.3V) to communicate to Arduino (5V) which works (provided pullup is to 3.3V) although technically the Arduino input high levels are marginal.

---
Tags: arduino-uno, i2c
---


# Question
Title: What are some "must-have" sensors or shields for an Arduino robot or motor?
I am starting to learn Arduino and wanna make some projects.which components will I have to buy?please help me.

# Answer
> 2 votes
It largely depends on your interests but since you've mentioned robotics, a motor shield, motor power supply, and one or a couple of hobby servos or DC motors will get you started on learning about controlling mechanical motion. You may be able salvage a DC motor from something else, like the vibrator motor from a dead cell phone.

If you want to start inexpensively, a few LEDs and a ~200 Ohm resistor for each one, and a couple of light or temperature sensors will give you plenty to play with. It's amazing how much real-world data you can collect and infer from a couple of well placed temperature sensors.

LM34 and LM35 are inexpensive and easy to use analog thermo-sensors that read directly in 0.01 Volts / degree (Fahrenheit and Celsius respectively), so only minimal arithmetic conversion is required (because along the way, you'll learn about Analog to Digital conversion, too).

Get some experience with those simple parts, and the coding to make them useful, and you'll have a much better idea of what you want to do next and what you'll need to acquire to do it.

---
Tags: arduino-uno, sensors, motor, components
---


# Question
Title: How can I use my old cellphones camera on my arduino robot?
The pins are so small I dont know which pin needs to go to the which pin socket and if t's compatible or not. I have the selfie camera of Xperia Z phone and a Arduino Uno r3.

# Answer
> How can i use my old cellphones camera on my arduino robot?

No! Even if you got all the details on the camera there are too many limitations with the Arduino for any serious application. You will need more memory and processing power.
> 2 votes

# Answer
Camera modules usually talk a protocol called CSI-2 or CSI-3. That's the Camera Serial Interface protocol.

It transfers very large amounts of data very fast. More data than a little Arduino can cope with. For instance, a current typical mobile phone camera is measured in multiples of megapixels. Each pixel takes 3 bytes to represent at 24-bit, so say you have a 2 megapixel camera that would be in excess of 6 megabytes of data per image. To put that into perspective the Arduino Uno has 2kB of RAM.

So no there is no way you will be able to directly interface a mobile phone camera to any of the microcontroller based Arduinos. That's not to say that something might not be able to be hacked on to one of the new-fangled things they try and pass off as Arduinos these days but are actually some strange SoC made by Intel. You're very much on your own with those though...

There are camera modules available aimed at the Arduino, but they are not directly readable by the Arduino due to lack of memory. They do, though, generally have a UART interface for controlling the camera, and then a separate streaming interface (often with a FIFO buffer to access the data slowly) for grabbing a snapped picture. The Arduino can't really do much with that data other than save it to an SD card or pass it on to a computer through USB, so they're pretty pointless really.
> 2 votes

---
Tags: sensors, pins
---


# Question
Title: How to design and debug a custom I2C master-slave system?
How to proceed, when in need of a custom I2C master-slave system?

What are the design criteria to apply?

What are the debugging tools one can use to troubleshoot problems?

# Answer
> 11 votes
This tutorial I gave at the Embedded Linux Conference tries to answer the questions, providing links to more detailed description of the topics addressed and using the practical example of driving a 4WD drone, where an Arduino Mini Pro acts as slave and controls the 4 independent wheels. The original document can be found here.

Note: This answer is currently work in progress, as I adapt the highlights from the link.

---

# Typical Applications of the I2C bus

* Interfacing with relatively slow peripherals. Ex: sensors, mechanical actuators.
* Controlling “fast” peripherals, that use other channels for exchanging data. Ex: codecs.

In a PC, the Operating System usually interacts over I2C with:

+ temperature and battery voltage meters;
    + fan speed controllers;
    + audio codecs.

In case multiple bus controllers are available, peripherals are grouped by speed, so that fast ones are not penalized by slower ones.

---

# A quick introduction to the I2C bus - key features

* Serial bus.
* Only 2 lines: Serial CLock and Serial DAta (plus ground).
* 4 speeds: 100kHz, 400kHz, 1MHz, 3.2MHz.
* Typically, 1 master device and 1 or more slaves.
* Communications are always initiated by a master device.
* Multiple masters can co-exist on the same bus (multi-master).
* Open-Drain: both SDA and SCL need pull-up resistors.
* “Clock Stretching”
    + The master controls SCL, but a slave can hold it down (because open drain), if it needs to adjust the speed.
    + The master must check for this scenario.
    + A slave can get stuck and jam the bus: need for reset lines from the master to the slave.
* Typically 7-bit addressing, but also 10 bit is supported.
* Logical protocol: actual voltage levels are not specified and depend on individual implementations. Ex: 1.8V / 3.3V / 5.0V

Reference URLs:

# Example of Bus Configuration

---

# Characteristics of the Protocol (simplified)

* 2 message types: *read* and *write*
* Start / Stop bit - represented as “\[“ and “\]” in the rest of the answer
* Address: 7 or 10 bits
* R/W bit: R = 1 / W = 0 Used to discriminate the type of message sent.
* Data on the bus: (Address \<\< 1 | R/W)
* Registers as information handlers, within the selected device.

# Example of Bus traffic

---

# Custom Slaves

*Why create a custom I2C slave?*

* Desired sensor/actuator unavailable with I2C interface.
* Less unique addresses available than slaves needed.
* Desired custom functionality on the slave:
    + Semi-autonomous reactions to stimuli.
    + Filtering/preprocessing input data.
* Power optimization: custom “sensor hub” does the housekeeping while the main processor is idle.
* Realtime response to inputs.
* \[your imagination here\]

*How to design a custom I2C slave?*

* Define requirements (see previous slide).
* Choose microcontroller or microprocessor.
* Choose Scheduler or Operating System (if any).
* Define communication sub-protocol:
    + Define parameters and commands to be exchanged.
    + Organize them into “registers” and choose a free address.

---

# Design of the I2C Master

Key design criteria:

* Weight/Dimensions.
* Required computational power and average latency.
* PC-like device
    + Embedded device, typically headless.
    + Preferred programming language: interpreted vs compiled.
* Availability of busses/gpios for driving the slave(s):
    + GPIOs only: bitbang the protocol
    + I2C: user-space application vs kernel driver.
    + No GPIOs/I2C interfaces available: USB to I2C adapter.

---

# Debugging: Divide and Conquer

Take direct control of the bus with an ad-hoc device. Examples:

* Bus Pirate (useful also for other busses)
* USB to I2C Master adapter, also based on the FTDI FT232R chip.
* Custom device (could be a separate project).
* Snoop the bus with a logic analyzer or a scope/advanced meter. Examples:

+ sigrok/pulseview with compatible logic analyzer
    + 2-channels standalone scope/meter
    + Use slave-specific In Circuit Debugger/In Circuit Emulator.

    Example: AVR Dragon for AVR chips (Arduino UNO, Nano, Mini, MiniPro)

---

# BUS Pirate

* Primarily for development purposes.
* Can both sniff the bus and drive it.
* Console interface over serial (ttyACM) port, including macros, or programmatic access for several programming languages.
* Built-in pullup resistors and voltage sources (5V / 3.3V)
* Supports many other protocols.
* References: Wikipedia, main page

---

# USB to I2C Adapter

* Small footprint.
* Suitable for permanent installations.
* No need for special connections on the host: it can be used to interface with a typical PC.
* Variant available that is also SPI-capable.
* No console interface, only serial binary protocol.
* Requires protocol wrapper.
* Reference: protocol

---

# sigrok and pulseview

sigrok(bakend component) logo

pulseview (visualizer) example

Example of low end logic Analyzer

* De-facto standard for PC-driven measurements on linux (but available on other OSes too).
* Support for vast range of logic analyzers, scopes and meters.
* Various protocol decoders, including I2C.
* Useful for visualizing the logical signals and debugging protocol errors.
* Even very low end, inexpensive HW can provide a whole new dimension to debugging.
* References: sigrok, pulseview, supported hardware

---

# Example: steering a 4WD drone

Prototype built using 2 Arduino Mini Pro.

---

# What does the slave do in the example?

The I2C slave:

* Controls the amount of torque applied to each wheel.
* Controls the direction each wheel spins.
* Measures the rotation speed of each wheel through an optical encoder (Odometer).
* Exposes the parameters above to the I2C Master.

High level block diagram of the I2C Slave.

---

# Selecting the Slave: Arduino Mini Pro

* Enough pins/functions to provide for each wheel:
    + 1 PWM output with independent configuration of the duty-cycle.
    + 1 GPIO for registering odometer input as IRQ.
    + 2 GPIOs for selecting:
        - Forward
        - Reverse
        - Idle
        - Lock
* I2C HW block for interrupt-driven i2c exchanges.
* Dedicated pins for SPI-based programming.
* Small footprint.
* Low Cost.
* The board layout of the clone represented in the picture is optimized for mounting on a DIL socket.

---

# Slave-specific ICD: AVR Dragon

---

# Selecting the OS: ChibiOS

* RTOS: preemption, tasks, semaphores, dynamic system tic, etc.
* Small footprint: link only used code/data.
* Distinction between RTOS and BSP through HAL.
* GPLv3 for non-commercial use.
* Actively developed, but already mature.
* Supports 8bit AVR.

However it had limited BSP support for AVR, lack of: \- interrupts driver for AVR GPIOs (added). \- I2C support for AVR slave mode (custom). Which had to be developed separately as part of the Drone SW for the AVR.

---

# Defining the Communication Parameters

*For each wheel:*

* **Duty Cycle** of the PWM signal used to drive it - 1 byte. 0xFF = max torque / 0x00 = no torque.
* **Direction** of rotation - 1 byte.

+ 0x00 = idle
    + 0x01 = reverse
    + 0x02 = forward
    + 0x03 = locked
* **Average period** in between slots of the optical encoder - 2 bytes.

+ Writing anything resets the measurement.
* **Parameter Index** \- 1 nibble:

+ 0 = Duty Cycle
    + 1 = Direction
    + 2 = Average Period
* **Wheel indexes** \- 1 nibble:

+ 0 = Left Rear
    + 1 = Right Rear
    + 2 = Right Front
    + 3 = Left Front
    + 4 = All

---

# Sub Protocol: Defining the Registers

**Register format: 0xαβ** \- α = Parameter Index \- β = Wheel Index

**Address** (chosen arbitrarily): 0x10

**Bus Pirate format:** \- \[ = start bit \- \] = end bit \- r = read byte \- address times 2 (left shift 1), for R/W bit

---

# Example - in Bus Pirate Format

**\[ i2c\_addr reg\_addr=(parm,wheel) reg\_value \]**

```
[0x20 0x20 0x02]  Left Rear Forward
[0x20 0x21 0x01]  Right Rear Backward
[0x20 0x22 0x01]  Right Front Backward
[0x20 0x23 0x02]  Left Front Forward
[0x20 0x14 0xFF]  Wheels set to max torque

```

*The car spins clockwise.*

---
Tags: motor, i2c, rotary-encoder, drone, debug
---


# Question
Title: Port Manipulation - fastest implementation
I'm working on an Arduino program but am getting bogged down on what is the 'correct' implementation. I understand that multiple versions may work, so for my needs the 'correct' version will be the fastest (i.e. executing in the fewest clock cycles)

I need to set three analog input pins on my Mega 2560 - let's call them PF2-0.

* I could use pinMode() - but that performs some extra checks that I want to leave out.
* I could use \_BV() in the process, but that's another function call I wish to avoid.

So, using port manipulation, I can write:

```
DDRF = 0x07; //PF2, PF1, PF0 as input
PORTF = 0x07; // Disable pullups

```

This should configure my three pins as inputs - and reduce any extraneous function calls. This should even be faster than writing:

```
DDRF = (1 << PF2) | (1 << PF1) | (1 << PF0)

```

Is this the fastest implementation?

\*To be honest, I'm not sure how to profile this to know for sure.

# Answer
The standard Arduino way of doing this is to use `pinMode()`. It's not fast, but it's easy to understand, especially for beginners. And it's portable across architectures.

If you want to go fast, then you should skip the Arduino functions and use port manipulation, and avr-libc. The standard avr-libc way of doing what you want is:

```
DDRF = _BV(PF2)   // set PF2 as output
     | _BV(PF1)   // also PF1
     | _BV(PF0);  // and PF0

```

This compiles to two assembly instructions: one for loading a CPU register with the constant, and the other to copy the register to the DDRF IO port. Notice that you set the bits for the pins you want to set as *outputs*, and you clear the bits for the inputs. By default, all the pins start as inputs.

The `_BV()` here is not a function call: it's a macro that expands to `(1 << (x))`. The way you write the expression to the right of the `=` sign is irrelevant as long as it is recognised to be a compile-time constant. If you want to see for yourself, you can disassemble the generated binary with the command

```
avr-objdump -S -C my_prog.elf > my_prog.lst

```

You get an assembly listing interspersed with your source. Doing this on the example above yields:

```
    DDRF = _BV(PF2)   // set PF2 as output
         | _BV(PF1)   // also PF1
         | _BV(PF0);  // and PF0
100:    87 e0           ldi r24, 0x07   ; 7
102:    80 bb           out 0x10, r24   ; 16

```

Here, the `ldi` instruction means “load immediate”, i.e. load a register (r24) with a constant value (0x07). The “out” instruction copies that register into port 0x10 (namely DDRF). Both are single cycle instructions, so the whole sequence takes two CPU cycles.
> 3 votes

# Answer
AFAIK the compiler should be smart enough to use bit manipulation instructions when in presence of \_BV().

When unsure, you can always add -save-temps to the gcc options, to see what the compiler actually does. It will not give you profiling information, but you can see in detail how your C gets turned into assembly.

Remember to pay attention to what level of optimization you use. You should use the same that will be employed in the final version of your code (probably O2).
> 0 votes

---
Tags: code-optimization, input
---


# Question
Title: What is the best way to attach TMP36 sensor to the copper coil?
I am very new to this site and this question may not be strictly related to Arduino, but I do small Arduino project which needs to measure the temperature of the copper coil using TMP36GZ sensor.

What is the best way to glue it to the coil for best measurements? Shoul I use silikone or epoxy? Should I take extra steps to ensure proper readings from the coil surface (f.ex.: using thermal paste)?

# Answer
> 1 votes
If you don't have to worry about conductivity from the electrical standpoint, you could use a thermal epoxy such as Arctic Silver which uses "microfine" particles of silver to conduct heat. It's a two part (redundant when using the term epoxy, I think) adhesive that is engineered to transfer heat, but may also short conductors. I've used the stuff and unless subject to intentional separating force, it holds well.

# Answer
> 0 votes
The datasheet devotes a whole page to mounting and thermal conductivity (though not to specific adhesives), particularly with respect to the plastic, through-hole devices, as the leads provide more a direct conductivity path to the sensing junction than the plastic bead does. If the surrounding air is at a different temperature from the coil surface you'll either need to insulate the leads from the air, or better, epoxy them to the coil with a thermally conductive but electrically insulating epoxy.

Here's an excerpt:

> Caution should be exercised, especially with T-3 packages, because the \> leads and any wiring to the device can act as heat pipes, introducing errors if the surrounding air-surface interface is not isothermal. Avoiding this condition is easily achieved by dabbing the leads of the temper-ature sensor and the hookup wires with a bead of thermally conductive epoxy. This ensures that the TMP35/TMP36/ TMP37 die temperature is not affected by the surrounding air temperature. Because plastic IC packaging technology is used, excessive mechanical stress should be avoided when fastening the device with a clamp or a screw-on heat tab. Thermally conductive epoxy or glue, which must be electrically nonconductive, is recommended under typical mounting conditions.

Update: I also noticed they didn't specify an epoxy, which I take to mean the feel it isn't critical. You'll need one compatible with "most" plastics and with copper. I'd probably use a big "wad" (that's a technical term :) of any off-the-shelf non-electrically conductive epoxy over the whole sensor and its leads, getting the sensor face as close to the copper as possible. I might even wrap some thermal insulation around the connecting wires for a foot or so, or even wrap that much of them around the coil and tape them to it, just to keep the sensor and the wires at as close to the coil temperature as possible. My guess is that will be more than sufficient to get temperature readings of the coil to within the sensor's limits of accuracy.

---
Tags: temperature-sensor
---


# Question
Title: Project 2: Arduino controlled spaceship interface
The circuit diagram attached shows that the switch is open. Yet, the LED connected to pin 3 of the arduino board lights up.

I don't understand this - the circuit is open, so why should pin 3 light up?

I discussed this with one of my friends - he said that each pin on the board receives voltage after the battery is connected. If this is true, then that would answer my question.

This is my code:

```
int switchState = 0;
//configures the digital pins
void setup() {
  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(5, OUTPUT);
  pinMode(2, INPUT);
}

//Checks the voltageo of the digital input and chooses the pin for voltage ( pin 2 )
void loop() {
  switchState = digitalRead(2);

  if (switchState == LOW) {
    //Button is not pressed

    digitalWrite(3, HIGH); //Green LED
    digitalWrite(4, LOW); //Red LED
    digitalWrite(5, LOW); //red LED
  }

  else { //the button is pressed
    digitalWrite(3, LOW);
    digitalWrite(4, LOW);
    digitalWrite(5, HIGH);

    delay(250); //wait for a quarter second
    //toggle the LEDs
    digitalWrite(4, HIGH);
    digitalWrite(5, LOW);
    delay(250); //wait for a quarter second
  }
} //go back to the beginning of the loop

```

# Answer
> 1 votes
So everyone else knows where this is from enter image description here.

---

*EDIT*

I have edited the image you gave to attempt to answer your question on 'wiring' :

The first image shows simply and crudely how the parts are basically connected or there relationship.

The second one shows how the current flows on the circuit, there is a key.

What you need to do is take the information from the link you give in the comment and apply logic to it, like if you used a logic probe and stuck it one end of the switch, the right side in that image, it would be `high`, if though you do so on the left it would be `low`. Hence no current flows in that circuit but there is current flow in the circuit looking at it.

---

What you have not examined is the code related to your project or the description of the project.

Looking at the code:

```
// Create a global variable to hold the
// state of the switch. This variable is persistent
// throughout the program. Whenever you refer to
// switchState, you’re talking about the number it holds
int switchstate = 0;

void setup() {
  // declare the LED pins as outputs
  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(5, OUTPUT);

  // declare the switch pin as an input
  pinMode(2, INPUT);
}

void loop() {

  // read the value of the switch
  // digitalRead() checks to see if there is voltage
  // on the pin or not
  switchstate = digitalRead(2);

  // if the button is not pressed
  // turn on the green LED and off the red LEDs
  if (switchstate == LOW) {
    digitalWrite(3, HIGH); // turn the green LED on pin 3 on
    digitalWrite(4, LOW);  // turn the red LED on pin 4 off
    digitalWrite(5, LOW);  // turn the red LED on pin 5 off
  }
  // this else is part of the above if() statement.
  // if the switch is not LOW (the button is pressed)
  // turn off the green LED and blink alternatively the red LEDs
  else {
    digitalWrite(3, LOW);  // turn the green LED on pin 3 off
    digitalWrite(4, LOW);  // turn the red LED on pin 4 off
    digitalWrite(5, HIGH); // turn the red LED on pin 5 on
    // wait for a quarter second before changing the light
    delay(250);
    digitalWrite(4, HIGH); // turn the red LED on pin 4 on
    digitalWrite(5, LOW);  // turn the red LED on pin 5 off
    // wait for a quarter second before changing the light
    delay(250);
  }
}

```

From this we see that the default state of this code in the first `if()` statement is to turn on PIN3 and leave the rest off when the button is not pressed.

From Arduino:

> A green LED will be ON, until you press a button. When the Arduino gets a signal from the button, the green light will turn off and 2 other lights will start blinking.

# Answer
> 0 votes
Where is all this confusion coming from?

```
  if (switchState == LOW) {
    //Button is not pressed

    digitalWrite(3, HIGH); //Green LED

```

Your code says, if the switch is **not** pressed, light LED on pin 3.

> I don't understand this - the circuit is open, so why should pin 3 light up?

Because that is what the code tells it to do.

> Does that mean that there is some internal wiring between ground and pin 3 that supplies current to the green LED?

Get the idea out of your head that this is some wiring issue. Your device is doing exactly what you are telling it to do.

When you `digitalWrite` HIGH to some pin, the processor activates the output driver MOSFET that attempts to drive the pin to +5V. Therefore current flows through the resistor to the LED which lights up.

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


title: Maximum potentiometer resistance

text:
# Question
Title: Maximum potentiometer resistance
I want to hook up a potentiometer to my arduino (Leonardo) as a voltage divider with the middle pin to an analog pin. I want to use the highest resistance to save power. I looked on the datasheet and it said the maximum output impedance is 10kOhm (§24.7.1 on Atmega32u4 datasheet). I also found another question that said I should use a 10kOhm potentiometer. What doesn't make sense is if the knob was turned towards the middle so that there is 5k on both sides, it's not the maximum capable resistance. So should I use a 20kOhm potentiometer?

# Answer
There is a lengthy discussion about this on the Arduino Forum. As I understand it, the input impedance is only important if you are sampling a rapidly varying signal, as it takes a finite time to charge the sample/hold capacitor. However your potentiometer would not vary rapidly (certainly not in the order of thousands of herz). Thus I don't think the potentiometer resistance will be particularly important, particularly if you are not changing the analog inputs (eg. from one channel to another). The continuous current through the 10k pot would be 0.5 mA.

If you are worried about power, then rather than connecting the +5V side directly to 5V, connect it to an output pin, which you can bring high when you want to take a measurement, and make low at other times. That reduces the power through the pot, since there won't be a voltage potential. You might allow a few microseconds for the reading to stabilize when you need to take one.

---

> So the lower the pot resistance, the faster response time? Also I will constantly always be taking a measurement

No, I don't think this is an issue. The "response time" is really the time taken to do the ADC calculation (nominally 104 µs if you don't fiddle with the registers).

See ADC conversion on the Arduino (analogRead). As mentioned on that page you can speed up the measurement by changing the ADC prescaler. However even with a prescaler of 128 you get 9615 conversions per second. I doubt you can turn the pot fast enough for this to be a meaningful issue.

Regardless of the response time, the issue here is *accuracy*. Will a lower pot value give more accurate results? Well, I doubt it. The ADC effectively copies the analog input into a 14 pF capacitor (the "sample and hold" capacitor) which it then tests against the reference voltage divided up in various ways.

The input impedance would be relevant if you were sampling a *high-frequency input*. On the page I linked I sampled a 4 kHz sine wave and got good results. You just won't be turning the pot that fast (4000 times a second).

---

> I'm still unsure with how potentiometer resistance affects the data ...

If you keep sampling the same ADC input (eg. A0) then I think the sample and hold capacitor can be charging in the background (while your code is doing other things).

But even if that were not the case, the datasheet says the sample and hold operation takes place 1.5 ADC cycles after the conversion starts. So at 16 MHz clock rate, and a prescaler of 128 for the ADC clock, this means we have:

```
128 * 62.5 ns * 1.5 = 12 µs

```

Now since the datasheet says the sample-and-hold capacitor is 14 pF, and the time taken to (almost fully) charge a capacitor is reckoned to be:

```
5 * R * C

```

Given R = 110k and C = 14e-12 (14 pF) then it will take:

```
5 * 110000 * 14e-12 = 7.7 µs

```

I quoted 110k because the datasheet mentions a resistance of 1 to 100k in series with the capacitor, plus the 10k impedance they recommend.

This means the capacitor will charge within the 12 µs it has available. Bump R up to 1e6 (1 megohm) and the calculation now gives:

```
5 * (100e3 + 1e6) * 14e-12 = 77 µs

```

This exceeds the 12 µs quoted for the sample-and-hold.

This is why, I suggest, that for fast-changing signals they recommend a lower input impedance.

However if I am correct that the sample-and-hold capacitor is normally connected to the ADC input, then that 77 µs can be spread over the time you deal with the calculation. Still, that is quite a few clock cycles. :)

---

My recommendation is to stick with 10k or so potentiometer (as recommended by the datasheet) and use my earlier suggestion of connecting the 5V side of the pot to an output pin instead of continually having it connected to the +5V signal. That way you only need to "power" the pot when you actually need to take a reading. However you can see that a 20k pot (or even 50k) will probably still be in an acceptable range for an accurate conversion.

For example, a 50k pot could charge the capacitor in:

```
5 * 150000 * 14e-12 = 10.5 µs

```

---

I would also be cautious about a 1 megohm pot because then slight variances in other things (eg. heat on the wire, nearby noise) could swamp the reading from it.

---

> Wait, sorry do I need to half my potentiometers' resistance if I'm using two analog inputs?

No, because the multiplexer chooses one input at a time (the others are effectively out of circuit).

However if you are choosing between two pots (to measure two) then the resistance becomes more relevant. As I showed, with a high value pot it takes longer to charge the capacitor, so if you read A0 and then immediately afterwards A1, you don't want a lengthy charging time for the capacitor, because that would give erroneous readings.
> 4 votes

---
Tags: analogread, potentiometer
---


# Question
Title: nrf24l01 (8pin) + adapter board (10pin) oops?
I just got my first arduino boards and have been learning the basics (so I know very little). I got the 2.4GHz NRF24L01+ (this one: NRF24L01+) and along with it a breakout board (this one: NRF24L01+ board) which I didn't realize was 10pin (nor that there is an 8pin version) vs the wireless board's 8pin. So my question is, is it safe to connect the module to this adapter board in some way? From the pinout of both I would assume not, since for example the bottom two pins on the board are ground (and therefore connected together) and the ground pin on the NRF24L01+ is next to the VCC (NRF24L01+ pinout) and the top two on the board are both VCC 3.3 and from what I can tell by looking at the etched lines, it seems it leads to the resistors (not sure if they are resistors or what, like I said, I know very little still). There seems to be an LED on this board as well, connected to the AMS1117 chip (that's a voltage regulator, correct?).

So, I am guessing I cannot just connect the NRF24L01+ to the adapter board straight in, right? But, can it with some wires? Would that even make sense? Also, is this board even necessary for anything? I bought it having read something somewhere (been reading too much to keep track of where exactly) that recommended it, but a tutorial I saw today didn't make use of it, instead just soldering a capacitor to two of the pins saying some other place recommended it to reduce noise.

# Answer
> 2 votes
To be honest, I don't see much added value for this breakout board.

First, as you mentioned, you won't be able to plug your NRF24 directly into it because the pinout is not compatible; hence, **you will have to use wires for that**. But you could as well use wires directly from your Arduino to the NRF24 module.

Second, regarding power (you are right, AMS1117 is a voltage regulator), the **Arduino 3.3V pin is enough** (**50mA** for UNO) to power your NRF24 as its current consumption is low (max **13.5mA** as per the datasheet):

Please note these are specifications for the chip itself not for the board, which may need a bit more current, but not much more according to my own experiments.

As a side note, I have created my own very simple breakout for the NRF24 board, with just a tiny piece of stripboard, that's something you can easily do by yourself if you have the right tools (saw, cutter, soldering iron), a few pin headers and some stripboard scrap:

Last, the only utility I see with your breakout board is to be used as 3.3V supply for higher currents in future experiments.

**EDIT:**

as commented by @Hans-Neve, a capacitor would be useful between 3.3V and GND pins, as near the NRF24L01 board as possible, so that short consumption peaks do not impact correct function of the board. The breakout board has one (or more exactly 2: 100nF and 10uF) It is advised you add those two (at least the large 10uF cap) in your circuit. I saw some people directly soldering one cap on the pins of the NRF24 board, but if you use short enough wires to connect it, you can perfectly put this cap on a breadboard during your experiments.

---
Tags: nrf24l01+
---


title: Funduino Uno with 5V 1A power supply?

text:
# Question
Title: Funduino Uno with 5V 1A power supply?
Can I use a "Funduino Uno" arduino with power from a power bank with DC 5V 1A output?

# Answer
Yes. As long as it connects the the arduino clone via USB and can maintain a stable power output then it's suitable.
> 1 votes

---
Tags: arduino-uno, power, voltage-level
---


title: Can you use both 3.3v and 5v

text:
# Question
Title: Can you use both 3.3v and 5v
Can you use an Arduino EtherMega's 3.3v and 5v pins with two sensors, one requiring 3.3v and the other 5v and a sketch that combines both?

# Answer
Yes. As long as you take into account that the outputs of the Arduino will be 5V so you may need to reduce that to 3.3V for the 3.3V sensor (if it has any connection to an output).
> 1 votes

---
Tags: arduino-mega
---


title: Arduino Yún shield password reset

text:
# Question
Title: Arduino Yún shield password reset
I'm using a Yún shield from Dragino with an Arduino Uno, but the default wifi password for the shield (which should be "dragino") isn't working.

I tried the wifi reset (holding down the reset button for 5 seconds) and a factory reset (holding down the reset button for 30 seconds) but the password still seems to be incorrect.

Is there any way I can reset the password?

# Answer
> 1 votes
Try connecting via ethernet to 192.168.255.1 with root/root

The SSH access for Dragrove is: IP: 192.168.255.1 on LAN port. If you want to connect to the Dragrove via WiFi, the IP should be 192.168.1.108. Username: root Password: root

http://www.seeedstudio.com/wiki/Dragrove\_-\_Generic\_gateway\_for\_internet\_of\_things

# Answer
> 0 votes
Dragino is just the password for the first initial setup. You probably set a new password. Even if you reset the shield, it keeps your password. This happened to me to and then I put in my password and it worked.

---
Tags: arduino-uno, shields, arduino-yun
---