title: Why when I press the reset button

text:
# Question
Title: Why when I press the reset button
Why when I press the reset button it takes 2 second before I see my sketch start? The model of Arduino is UNO, and the text in serial communication.

# Answer
Because first the bootloader is executed and takes 2 seconds (or more on a Leonardo) to time out when it doesn't receive a proper response from the computer.
> 3 votes

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


title: Lost Source Sketch

text:
# Question
Title: Lost Source Sketch
I wrote an interface to a radio about 1-year ago. I have since rebuilt that machine. Is there any way to retrieve the code. Now I do not expect it to be sources code. I know the radio code still works as I tried it the other day. Part of the problem is that I am using about 30 wires all on the rear end of the card and have to figure out which pins that they go to in my radio. My interface has two DB25 connectors. And the decoder 2 of 5 negative going signals.

# Answer
> 1 votes
Asusming the lock bits on the MCU haven't been set, you can use avrdude to download the contents of flash and EEPROM to your system. From there you can use avr-objdump to disassemble the .hex file and try to figure out how it works. I recommend looking at the disassembly of a .elf file from a current project as well as having both the avr-gcc and avr-libc documentation as well as the ATmegaXXX0 datasheet close at hand at all times.

---
Tags: arduino-mega
---


# Question
Title: Uploading to atmega328 over serial with arduino bootloader running at 2MHz
I want to run an atmega328 on a breadboard at 2MHz and upload to it via the serial pins (pins 2 and 3). So I am setting the clock divide by 8 fuse bit to enable this, meaning the atmega runs at 2MHz eith the 16MHz crystal. But I can't upload, probably because the bootloader is not expecting the clock to be running at 2MHz. The baud rates are probably mismatched by 8 times, the IDE is trying to upload at 57600 but since the bootloader code is not aware its being clocked at 2MHz, its probably running 8 times too slow. I've messed around a bit with the arduino conf files changing baud rates but had no joy. I was wondering if anyone knows how to do this off the top of their head.

Thanks, Pete

# Answer
Unprogram the CKDIV8 fuse and add the following to the sketch instead, near the beginning:

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

void setprescaler(void) __attribute__ ((naked)) \
  __attribute__ ((section(".init1")));

void setprescaler(void)
{
  clock_prescale_set(clock_div_8);
}

```

This will do essentially the same thing as the fuse, but won't interfere with the bootloader.
> 2 votes

---
Tags: atmega328, bootloader, frequency, fuses
---


# Question
Title: How to troubleshoot the Arduino Mini and Arduino usb2serial?
I am trying to get an Arduino Mini (R5, mega 328p) working.

Just connecting it to power has following effect: the on-board LED lights up. It's the power-on-led, I presume.

Since other Arduino devices often come with the blink-example pre-flashed I hooked up a LED to pin 13 - result: no blinking.

Curiously, connecting the LED to pin 12: blinking

Does the Mini come pre-flashed with a blink 'sketch' that blinks pin 12 instead of 13?

To test uploading I've connected it to an Arduino USB2Serial module. The module is labeled with 'made in Italy' and has printed 'USB2SERIAL LIGHT' on it where the LIGHT is overwritten with a blue marker.

I've connected it like described in the arduino mini guide.

In the IDE I've selected the board 'Arduino Mini' and the '328' CPU.

Unfortunately, uploading fails with:

```
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x00

```

The external reset is connected like in the guide. But I also tried to manually press the reset button (immediately before the upload, or long press and release after upload button is clicked). Still, the same error.

When the manual reset is pressed the pin-12-blinking stops for a while (perhaps the bootloader is then executed) but then starts again.

The Arduino2serial has 3 LEDs. The ON-LED lights up when connected to the USB. When hitting the upload button in the IDE, the RX-LED flashed shortly one time after a while. That's it.

Thus my question: How to I troubleshoot this? Can I test the arduino usb2serial on its own? What's up with the pin-12 blinking of the mini?

In case this matters, I am on Fedora Linux, uploading to other Arduino devices (Uno, Micro) works as expected.

**update usb2serial**: I just hooked up the Arduino usb2serial and connected the TX/RX pins via a jumper cable - a minicom session then results in text being displayed and the rapid flashing of the RX/TX LEDs. Disconnecting RX/TX again shows no display of any text inside minicom, and no flashing of the RX/TX LEDs.

I used following command line:

```
$ minicom -D /dev/ttyACM0 -b 115200

```

Thus, the usb2serial module seems to work.

**update:** I've checked all the jumper cables and there was a faulty one. With that replaced flashing works. After hitting the reset-button. The 'ext reset' pin is connected but the remote-reset does seem to work. Anyways, hitting the reset-button is easy-enough, for now.

**final update:** The root cause for remote-reset (a.k.a. auto reset) that the capacity of the used capacitor was too small. After exchanging it with a 100 nF one (as specified in the guide) the remote-reset works as expected. That means just hitting the upload button in the IDE automatically resets the device and the sketch is uploaded.

# Answer
As always, it makes sense to check the parts in isolation, if possible.

Host system (Linux):

* Tail the system log for errors
* Check that ModemManager does not occupies the `/dev/ttyACM0` device

USB2Serial:

* Connect it via USB to the host without anything else connected -\> the ON-LED should be on, the RX/TX LEDs should be off, the system log should display some udev progress messages (including vendor ids), the system should have a new serial device, e.g. `/dev/ttyACM0`
* Open the serial port with a terminal (e.g. via `minicom -D /dev/ttyACM0 [-b baudrate]`, disable local echo and type something -\> nothing should be displayed
* Connect the RX/TX pins to each other with a jumper cable -\> typing in the terminal session should now result in rapid flashing of the TX/RX LEDs and the echoing of the text

Arduino Mini:

* Connect just the minimum, e.g. just power from a 9V battery/5V power supply and the reset pin to +5 (with a 10KOhm resistor in series) -\> the power-on led should turn on
* The chance is high that the device comes with a pre-flashed blink examples that either uses pin 12 or 13 -\> connect external LEDs to pin 12 and 13 (in series with 220 Ohm resistors) -\> one LED blinks after power on
* Hit the reset button on the mini -\> any LED blinking should stop for a while and then continue

Arduino Mini with USB2Serial:

* Make sure that both RX/TX pairs are crosslinked (like a nullmodem cable), i.e. RX \<-\> TX and TX \<-\> RX.
* Follow the mini guide on arduino.cc or arduino.org it includes a picture of the cabling
* Verify that the capacitor connected between the USB2Serial 'ext reset' pin and the Mini reset pin has a capacity of 100 nF, otherwise, the auto-reset might not work
* In case the automatic reset does not work, press the on-board-reset-button just before the upload
* In case the error persists, check for dodgy cables with a multi-meter

IDE:

* Make sure that it works with 'easier' stuff, e.g. flashing to a Uno (the Uno is easier because the USB-2-Serial part is integrated)
* Enable verbose logging during upload (in the preferences)
* Update the IDE in case it is very old
> 0 votes

---
Tags: serial, arduino-mini
---


# Question
Title: Going from arduino & sketch to production
I've got a little proof of concept thing going here with an arduino & Ethernet shield. The basic idea is for it to ping out much like a heartbeat monitor every so often so I can see if my house still has internet connectivity.

The arduino works nicely and does exactly what I want. I've ordered a board to be made with just the basic components needed and now want to put the code on to it. They gave me an option to load the code (Dragon AVR) during checkout and I'd love to try that out. So, the question is - how on earth do I package up code for something like that? I've seen a number of people ask the same thing for large manufacturing scales / similar setup where they don't fancy using the arduino & IDE as a programmer.

I've asked around on IRC and various other places but nobody seems to be able to give me specific and clear advice on whether it's possible and how to go about doing it.

# Answer
"Intel Hex" is pretty much an industry standard and I'm quite certain the .hex files produced by the GNU AVR tools is Intel Hex format. Your vendor is almost certainly prepared to load your sketch from the .hex file.
> 3 votes

---
Tags: arduino-uno
---


# Question
Title: Did I break my new Arduino Leonardo Eth by restarting it?
I just bought a new Arduino Leonardo Eth, and, it was working perfectly.

I probably uploaded about 30 different sketches, and it did everything as expected.

The basic sketch was using the fade demo on pin 9 to ground with a LED attached.

I was then curious on how long the unit takes to restart, so, I unplugged the USB and put it back in.

When it started back up, the LED was on solid. I then restarted it again, and I honestly can't remember the state of it.

When I plug it in, it gets detected in the Arduino application and I see the port, but, after about 20 seconds, I get a popup on Windows saying about a malfunctioning USB device.

Pressing reset on the Arduino or unplugging/plugging it back does the same - I get about 20 seconds, and then it "goes bad".

Even if I am real quick in the IDE, or press restart after compiling/before upload, it just hangs.

I'm really annoyed with myself if I did break it, but, I'm not really sure what else I could have done differently... after all, there isn't an off switch.

Does anyone know what I have done, and, is there anyway to fix it?

# Answer
You should be able to use my board detector sketch on one of your other Arduinos to check out the problem board.

See also Have I bricked my Arduino Uno? Problems with uploading to board

Also my bootloader uploader sketch will reflash bootloaders on quite a few devices. I'm assuming that the "Arduino Leonardo Eth" has the same bootloader as the Leonardo.

Hmmm - I see that the "Arduino Leonardo Eth" is from Arduino.org, not Arduino.cc. The bootloader is probably slightly different. I'm really not an expert on what those boards use.

---

Before worrying too much, try the approach of holding down Reset and then uploading a sketch, letting go of Reset as the sketch starts to actually upload.

---

*Comment by William Hilsum*

> I didn't realise there was a difference between .org and .cc, and, I guess by using the leonardo template from .cc, I broke "something". The moment I downloaded the IDE from .org, & uploaded with the eth template , it worked flawlessly. I guess there are some changes between leonardo and leonardo eth. I wanted an arduino with ethernet, so I didn't need a separate shield. No idea if I picked the right "side" after reading all the crap with cc vs org!

That is very annoying that the split of the Arduino camps now produces a support nightmare for people who just want to use their virtually identical products, but have to go through this.

Thanks for the update.
> 1 votes

---
Tags: arduino-leonardo, uploading, usb
---


# Question
Title: What does serial data look like on an oscilloscope?
How I can find the data field on oscilloscope at 300 baud or at 9600 baud? Could someone show me picture on oscilloscope plase.

This is the picture

at 9600 Baud

# Answer
> 4 votes
I had these images lying around so here is an example of "Fab" being sent at 9600 baud:

And now a single byte (the letter "F"):

* A - no data (Tx is high)
* B - The "start bit". The line is taken low to tell the receiver that a character (byte) is commencing to be sent. The receiver waits for one and a half clock times before sampling the line.
* C - First character arrives (the letter "F" or 0x46 or 0b01000110). There is no clock bit as such, the incoming data is simply sampled at the baud (transmission) rate. In contrast to SPI communication the data arrives least-significant bit first (in case you are not sending 8 bits per byte). Thus we see 01100010 (rather than 01000110).
* D - The stop bit. This is always high, to ensure that we can distinguish between the end of this byte, and the start of the next one. Since the start bit is a zero, and the stop bit is a one, there is always a clear transition from one byte to the next.
* E - The start bit for the next character.

---

The time for one bit is shown on the logic analyzer as 0.1041667 ms (that is, 0.0001041667 seconds). This agrees with the inverse of the baud rate:

```
1 / 9600 bits per second = 0.0001041667 seconds per bit

```

---

Looking at your photo, my guess is you have inverted logic here. That is, RS232 levels (where 5V is a 0-bit and 0V is a 1-bit). Thus (and this is a guess because all the bytes are close together):

I marked the start and stop bits, and put a dot for each bit inbetween.

---

Also see What is Serial.begin(9600)?

---
Tags: arduino-uno, serial, baud-rate, rs232
---


# Question
Title: What happens when code is uploaded using the bootloader?
When I upload a new sketch to my Arduino Uno using the Optiboot bootloader, what *really* happens?

* What is sent to the Arduino?
* How does it respond?
* What does "not in sync mean"?
* What is "in sync" anyway?

---

*Note: This is intended as a "reference question"*.

# Answer
> 22 votes
When you reset a Uno running the Optiboot loader, the bootloader first flashes pin 13 three times.

Top line (gray) is sent **to** the Arduino, middle line (orange) is sent **from** the Arduino.

While that is happening, the program `avrdude` running on your computer is sending a query to the device:

```
STK_GET_SYNC / CRC_EOP  (0x30/0x20)

```

The Arduino doesn't notice the first "get sync" because it is busy flashing pin 13. Once it is done it notices the "get sync" (it would be buffered by the serial hardware) and replies:

```
STK_INSYNC / STK_OK (0x14/0x10)

```

It looks like avrdude got a bit impatient, and timed out, because it tries again with the "get sync" query. This time Optiboot responds immediately.

---

The rest of the uploading is described in the next image. Example produced uploading the stock "Blink" program.

*(Click on the image above for a larger version)*

---

The steps are:

* Query: Get Sync? Reply: In Sync.
* Query: Get parameter? (major version) Reply: version 4.
* Query: Get parameter? (minor version) Reply: version 4.
* Set device parameters. The following device parameters are sent to the chip:

```
0x42  // STK_SET_DEVICE
0x86  // device code
0x00  // revision
0x00  // progtype: “0” – Both Parallel/High-voltage and Serial mode
0x01  // parmode: “1” – Full parallel interface
0x01  // polling: “1” – Polling may be used
0x01  // selftimed: “1” – Self timed
0x01  // lockbytes: Number of Lock bytes.
0x03  // fusebytes: Number of Fuse bytes
0xFF  // flashpollval1
0xFF  // flashpollval2
0xFF  // eeprompollval1
0xFF  // eeprompollval2
0x00  // pagesizehigh
0x80  // pagesizelow
0x04  // eepromsizehigh
0x00  // eepromsizelow
0x00  // flashsize4
0x00  // flashsize3
0x80  // flashsize2
0x00  // flashsize1
0x20  // Sync_CRC_EOP

```

Optiboot **ignores all those** and replies with In Sync/OK. :)
* Set extended device parameters:

```
0x45  // STK_SET_DEVICE_EXT
0x05  // commandsize: how many bytes follow
0x04  // eeprompagesize: EEPROM page size in bytes.
0xD7  // signalpagel:
0xC2  // signalbs2:
0x00  // ResetDisable: Defines whether a part has RSTDSBL Fuse
0x20  // Sync_CRC_EOP

```

Optiboot **ignores all those** as well and replies with In Sync/OK.
* Enter program mode. Reply: In Sync/OK.
* Read signature. Optiboot replies with `0x1E 0x95 0x0F` **without actually reading the signature**.
* Write fuses (four times). Optiboot **does not write the fuse** but just replies In Sync/OK.
* Load address (initially 0x0000). The address is in words (ie. a word is two bytes). This sets the address for where the next page of data will be written.
* Program page (up to 128 bytes are sent). Optiboot replies "In Sync" immediately. Then there is a pause of about 4 ms while it actually programs the page. Then it replies "OK".
* Load address (now 0x0040). This is address 64 in decimal, ie. 128 bytes from the start of program memory.
* Another page is written. This sequence continues until all the pages are written.
* Load address (back to 0x0000). This is for verifying the write.
* Read page (up to 128 bytes are read). This is for verifying. Note that even if the verify fails, the bad data has already been written to the chip.
* Leave programming mode.

---

## What does "not in sync" mean?

As you can see from the above, every step through the programming sequence the Arduino is expected to reply with "In Sync" (0x14), possibly followed by some data, followed by "OK" (0x10).

If it is "not in sync" that means that avrdude did not get the "in sync" response. Possible reasons could be:

* Wrong baud rate used
* Wrong serial port selected in IDE
* Wrong board type selected in IDE
* No bootloader installed
* Wrong bootloader installed
* Board not configured to use the bootloader (in the fuses)
* Some device plugged into pins D0 and D1 on the Arduino, interfering with serial commications
* The USB interface chip (ATmega16U2) not working properly
* Wrong clock for the board
* Wrong fuse settings on the Atmega328P (eg. "divide clock by 8")
* Board/chip damaged
* Faulty USB cable (some USB cables provide power only, and are not for data, eg. cheap cables for USB fans)

---

## What is "in sync"?

As mentioned above, the response "In sync" means that the Arduino (bootloader) is synchronised with the uploading program.

---

## What protocol is being used?

The protocol is the STK500 protocol as documented by Atmel. See the references below.

---

## References

*Note*: STK500 Version 2 is not used in Optiboot, but it is included for information in case you are using boards like the Mega2560.

---

## STK500 constants

```
/* STK500 constants list, from AVRDUDE */
#define STK_OK              0x10
#define STK_FAILED          0x11  // Not used
#define STK_UNKNOWN         0x12  // Not used
#define STK_NODEVICE        0x13  // Not used
#define STK_INSYNC          0x14  // ' '
#define STK_NOSYNC          0x15  // Not used
#define ADC_CHANNEL_ERROR   0x16  // Not used
#define ADC_MEASURE_OK      0x17  // Not used
#define PWM_CHANNEL_ERROR   0x18  // Not used
#define PWM_ADJUST_OK       0x19  // Not used
#define CRC_EOP             0x20  // 'SPACE'
#define STK_GET_SYNC        0x30  // '0'
#define STK_GET_SIGN_ON     0x31  // '1'
#define STK_SET_PARAMETER   0x40  // '@'
#define STK_GET_PARAMETER   0x41  // 'A'
#define STK_SET_DEVICE      0x42  // 'B'
#define STK_SET_DEVICE_EXT  0x45  // 'E'
#define STK_ENTER_PROGMODE  0x50  // 'P'
#define STK_LEAVE_PROGMODE  0x51  // 'Q'
#define STK_CHIP_ERASE      0x52  // 'R'
#define STK_CHECK_AUTOINC   0x53  // 'S'
#define STK_LOAD_ADDRESS    0x55  // 'U'
#define STK_UNIVERSAL       0x56  // 'V'
#define STK_PROG_FLASH      0x60  // '`'
#define STK_PROG_DATA       0x61  // 'a'
#define STK_PROG_FUSE       0x62  // 'b'
#define STK_PROG_LOCK       0x63  // 'c'
#define STK_PROG_PAGE       0x64  // 'd'
#define STK_PROG_FUSE_EXT   0x65  // 'e'
#define STK_READ_FLASH      0x70  // 'p'
#define STK_READ_DATA       0x71  // 'q'
#define STK_READ_FUSE       0x72  // 'r'
#define STK_READ_LOCK       0x73  // 's'
#define STK_READ_PAGE       0x74  // 't'
#define STK_READ_SIGN       0x75  // 'u'
#define STK_READ_OSCCAL     0x76  // 'v'
#define STK_READ_FUSE_EXT   0x77  // 'w'
#define STK_READ_OSCCAL_EXT 0x78  // 'x'

```

---
Tags: arduino-uno, bootloader
---


title: Multiway Relay Dimmer

text:
# Question
Title: Multiway Relay Dimmer
I am looking for something like a **multiway "relay dimmer"**. Which lets me dim a light using an Arduino and a manual dimmer.

(The manual dimmer should work without any computer!)

# Answer
You could use a rotary encoder for that purpose!

Basically the rotary encoder is a knob that, for every "tick" you give it, it returns a different value to your Arduino. With a bit of programming you can sense the direction of the turn, if it is positive then you lighten up the LED, and vice versa.

I used that to control a RGB led, it works very well! here some more information on the rotary encoder and the code needed to use it.
> 2 votes

# Answer
I add another answer because I think I found something. After a few days searching on various sites that sell arduino stuff I found this http://www.dx.com/p/8-channel-5v-relay-module-extension-board-for-arduino-avr-arm-51-140703 that might be what you're looking for. One of the customers in the review states it can be used even without Arduino.

I know it's a relay, not a dimmer, but maybe you could add something to your circuit...
> 0 votes

---
Tags: relay
---


# Question
Title: How do I send an arduino PIN state to a local PC using the ethernet connection?
As a PIN goes high I need to trigger an event that will send the IP or MAC of the arduino and the PIN state over the wired Ethernet to a local computer. I am using an Ethernet shield to send and receive from the arduino but I am stumped on how to send and process the information at the PC. I will have 42 Arduinos on the network all set to send PIN information over the wired Ethernet. Sounds simple but after a days research I am now looking at other solutions. I currently have the faithful Uno with the network shield as my prototype. For the final install I can purchase any of the arduino range like the Yun,Duo etc. if this would help. Any direction would be welcomed.

# Answer
> 1 votes
The simplest method is to set up a web server on your PC. You haven't mentioned what OS you run (which is kind of critical), so looking into WAMP or LAMP ("Windows/Apache/MySQL/PHP", or "Linux/Apache/MySQL/PHP") is probably your best option.

Once you have a working web server you can pretty much use verbatim the Ethernet examples for connecting to a remote website ("Web Client"). That website would be your local PC address, and you send whatever parameters you want.

You then write a small PHP script (or whatever language you program your chosen web server in) to accept that web request and process it accordingly.

In general you never need to explicitly send the IP address since it is encapsulated as part of the actual socket connection information and is generally made available through various means to your web page (see `$_SERVER` in PHP for example).

If you want to get more "low level" and lighter weight then you would most likely be looking at writing a UDP server on your computer which receives UDP requests from the Arduinos and processes them as needed. The content of a UDP request is entirely up to you, but programming a server for dealing with it is beyond the scope of an answer here - suffice it to say there are plenty of resources online available for all the major operating systems and programming languages on how to write UDP servers.

# Answer
> 1 votes
In my opinion, a perfect solution for the "*As a PIN goes high I need to trigger an event*" problem is brought by **interrupts**. In the official documentation I read: "...*Arduino has two different kinds of interrupts: `external`, and `pin change`...*" and the latter seems very suited for your needs. So my idea (but, please, be aware that I'm not at all an Arduino developer... yet) is to simply develop an "interrupt-handler routine", and properly attach such a routine to your PINs. There are plenty of details to analyze (as well as plenty of documentation about Arduino interrupt handling) but... the idea should be clear.

Please, while developing such a routine **DON'T** be tempted to push all of your networking code inside the routine itself: for reasons deeply and clearly explained by @NickGammon, interrupt handlers should be executed as fast as possible. Here follow an important part of Nick's article:

> \[...\]
>
> **Hints for writing ISRs**
>
> In brief, keep them short! While an ISR is executing other interrupts cannot be processed. So you could easily miss button presses, or incoming serial communications, if you try to do too much. In particular, you should not try to do debugging "prints" inside an ISR. The time taken to do those is likely to cause more problems than they solve.
>
> **A reasonable thing to do is set a single-byte flag, and then test that flag in the main loop function**. Or, store an incoming byte from a serial port into a buffer. The inbuilt timer interrupts keep track of elapsed time by firing every time the internal timer overflows, and thus you can work out elapsed time by knowing how many times the timer overflowed.
>
> \[...\]

---

As for the "*...will send the IP or MAC of the arduino and the PIN state over the wired Ethernet to a local computer...*", @Majenko already answered that "source IP" and "source MAC" (of your Arduino) are **not** needed to be sent explicitely by your application, as if you're using an Ethernet shield (...and, on top of it, the IP protocol stack) it will be the shield itself in dealing with the "encapsulation" process, by which your data (the data "sent" by your own code) will be encapsulated in a proper Ethernet frame (that will include the source MAC) and a containing IPv4 packet (that will include the "source IP").

---

As for the "*...send \[the\] state over the wired Ethernet to a local computer...*" you're missing some very important details, like which operating system your local computer will be running and, more important, which programming language are you using to write your "server-application code".

The LAMP/WAMP approach proposed by @Majenko is relatively easy to implement, as the WebServer (Apache) will bring you a ready-made approach to handle network requests: afterall, you need a "server" application (an application "listening" to a socket, waiting for incoming messages/requests coming from network clients) and a web-server like Apache is exactly such an application.

Anyway, should you need something more specifically suited for your needs, nothing prevent you to write your own "server". There are plenty of libraries for plenty of programming-languages.

As I'm confident with PERL, I suggest you checking one of the many tutorial describing PERL client-server programming. Please note that PERL is a cross-platform language, supported also on Windows systems.

A final note: While implementing your "server-code", please check/consider if you need a "blocking server" (one who can handle only one single request at a time) or a "non-blocking server" (one who can handle multiple requests, coming from multiple arduinos, at the same time).

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


title: How to calculate voltage?

text:
# Question
Title: How to calculate voltage?
I want to check each cell voltage using arduino.

and how to calculate dc current using CT Sensor using Arduino?

# Answer
You have two problems here:

1. How to take 24 readings on an Arduino with only 6 analog inputs.
2. How to get the voltage in the range of 0 to 5 volts.

To take 24 readings you can use an analog multiplexer or two. For example the 74HC4051 (8 channels) or the 74HC4067 (16 channels). With both of those you could handle 24 channels.

---

To read the voltages you could successively read each cell, relative to ground (eg. the first one should be 2 V, the second should be 4 V, and so on up to 48 V).

Cells 1 and 2 are fine, they are lower than 5 V. Cells 3 to 24 are not. You need to set up a voltage divider to divide down the voltage into the range 0 to 5.

The formula for a voltage divider is:

```
Vout = Vin * R2/(R1+R2)

```

Let's make R1 to be 10k ohms, and solve for R2 (given that we want Vout to be 5).

```
R2 = Vout * R1/(Vin - Vout)
R2 = 5 * 10000 / (Vin - 5)

```

Plugging that into a spreadsheet we get:

```
Vin    R
6  50000
8  16667
10 10000
12  7143
14  5556
16  4545
18  3846
20  3333
22  2941
24  2632
26  2381
28  2174
30  2000
32  1852
34  1724
36  1613
38  1515
40  1429
42  1351
44  1282
46  1220
48  1163

```

---

These aren't particularly easy resistor values to work with, so we'll use standard values and calculate what the output voltage should be (with the spreadsheet):

```
Vin   R   volts   Scale
2
4
6   47000 4.9474  1.2128    <--- R2 is 47 k
8   16000 4.9231  1.6250    <--- R4 is 16 k
10  10000 5.0000  2.0000
12   6800 4.8571  2.4706
14   5100 4.7285  2.9608
16   4300 4.8112  3.3256
18   3600 4.7647  3.7778
20   3300 4.9624  4.0303
22   2700 4.6772  4.7037
24   2400 4.6452  5.1667
26   2200 4.6885  5.5455
28   2000 4.6667  6.0000
30   2000 5.0000  6.0000
32   1800 4.8814  6.5556
34   1600 4.6897  7.2500
36   1600 4.9655  7.2500
38   1500 4.9565  7.6667
40   1300 4.6018  8.6923
42   1300 4.8319  8.6923
44   1200 4.7143  9.3333
46   1200 4.9286  9.3333
48   1100 4.7568 10.0909

```

The "Scale" column will be explained in a moment.

---

Now we are ready to make up a circuit along these lines:

I haven't shown all the battery cells here - I don't have that much energy! But the principle is the same.

---

The 2V and 4V inputs we can read directly. From 6V upwards we need to apply the scaling factor from the voltage divider network.

That is shown in the "Scale" column above.

The formula for the voltage on the pin is:

```
float voltage = ((float) rawADC  + 0.5 ) / 1024.0 * Vref;

```

So assuming Vref is 5V, and you have a reading of 512, then you apply it like this:

```
 ( 512  + 0.5 ) / 1024.0 * 5 = 2.502 volts

```

Now you multiply by the scale factor above, so if this was the 34 V input, the scale factor would be 7.25, and the voltage from the battery would be:

```
2.502 * 7.25 = 18.14  volts

```

---

The stage is now set to work out each voltage:

* Use the multiplexer "select" pins to choose one of the battery inputs
* Take an analog reading
* Scale it by the appropriate amount from the table
* Work out what the charge in the cell is (by comparing it to the previous one)

For example, if the first cell read 1.9V and the second cell read 3.85V then you know that the difference is 3.85 - 1.9 which is 1.95 volts.
> 2 votes

---
Tags: arduino-leonardo, voltage-level, battery, current, arduino-mini
---


title: get current time in nanoseconds

text:
# Question
Title: get current time in nanoseconds
On Arduino due, Is this possible to get the current time in nano seconds? At 84Mhz, I guess it will always be a multiple of ~12ns.

And a perfect solution would read a register/variable rather than call a function. Because I want to avoid the cost of calling a function which is in order of microseconds. what about counting clocks since start of execution. is this possible?

# Answer
Yes, it *should* be. At least according to the Cortex M3 Technical Reference Manual that I think I downloaded from ARM. (DDI0337E\_cortex\_m3\_r1p1\_trm.pdf)

In section 11.5 of said manual, there is a register called `DWT_CYCCNT` (Data Watchpoint and Trace Cycle Count Register) which is incremented once per clock cycle when the appropriate flag of the `DTW_CTRL` (DWT Control) register is set.

This flag is unset on reset of the CPU so it needs to be set manually (unless it is done by the Arduino IDE, but checking the header files of the IDE, it doesn't look like it as unlike many other CPU registers, there is no Arduino `REG_` define for these registers).

This untested code should be usable as the basis for your own code. I suggest you add some serial initialisation in there and dump the value of `currentCycles` to the serial log to test it. I am away from my hardware at the moment so can only test that it compiles.

```
#define REG_DWT_CTRL (*(unsigned int*)0xE0001000U)      /* Data Watchpoint and Trace Control Register */
#define REG_DWT_CYCCNT (*(unsigned int*)0xE0001004U)    /* Data Watchpoint and Trace Cycle Count Register */

#define CYCCNTENA ( 1 << 0 )                            /* DWT CTRL Cycle Count Enable Bit */

void setup()
{
    REG_DWT_CTRL |= CYCCNTENA;
}

void loop()
{
    unsigned int currentCycles = REG_DWT_CYCCNT;
}

```

Edit: Note that the counter is a 32 bit register, so at 84 MHz it will reset every 51.13 seconds. It is a read only register so writing to it will have no effect (you cannot manually reset it that way).
> 1 votes

---
Tags: arduino-due, oscillator-clock
---


# Question
Title: Error with Arduino/Processing Serial Communication
I am relatively new to both Arduino and Processing and I have been working on a code that utilizes serial communication between the two. My Arduino code is reading and printing values from a piezo sensor and then sending the values to Processing, which sketches certain shapes based on the values. The code has worked previously, but for some reason it is no longer working. Everything compiles, but when I run the Processing code the sketch window is empty and remains empty. A few times the "error, disabling serialEvent()" showed up, but I just unplugged my Arduino board, closed out the programs, and restarted everything. The error no longer shows up, but my Processing sketch is still not displaying on the screen. Can someone please let me know what is wrong with my code? I really appreciate the help.

**Arduino Code:**

```
int ledPin = 13;
int knockSensor = A0;
byte val = 0;
int statePin = LOW;
int THRESHOLD = 5;
int sensorReading = 0;

void setup() {
 pinMode(ledPin, OUTPUT);
 Serial.begin(9600);
}

void loop() {
 sensorReading = analogRead(knockSensor);

  if(sensorReading > 0){
   Serial.println(sensorReading, DEC);
   delay(100);
  }
}

```

**Processing Code:**

```
import processing.serial.*;

Serial port;

int centerX = 550;
int centerY = 400;

float val;
float ellipseX;
float ellipseY;
float ellipseW;
float ellipseH;
float ellipseXX;
float ellipseYY;
float ellipseWW;
float ellipseHH;
float lineX;
float lineY;
float lineXX;
float lineYY;

void setup(){
  background(255);
  size(1100,800);
  frameRate(10);
  smooth();

  String portname = "/dev/tty.usbmodem1411";

  //String portname = Serial.list()[0];
  port = new Serial(this, portname, 9600);
  println(Serial.list());
  //port.bufferUntil('\n');
}

void drawEllipse(float val)
{
  if(val > 0 && val < 50)
  {
    ellipseX = random(540,560);
    ellipseY = random(390,410);
    ellipseW = val + 10;
    ellipseH = val + 10;

    stroke(0);
    fill(random(255), random(200,255));
  }
}

void drawLines(float val)
{
  if(val > 50 && val < 70)
  {
    lineX = random(500, 600);
    lineY = random(360, 440);
    lineXX = random(500, 600);
    lineYY = random(360, 440);

    stroke(0);
  }
}

void drawEllipse2(float val)
{
  if(val > 70 && val < 120)
  {
    ellipseXX = random(460, 640);
    ellipseYY = random(330, 470);
    ellipseWW = val + random(20);
    ellipseHH = val + 10;

    stroke(0);
    fill(random(50, 100), random(50, 100), random(50, 100), random(220, 255));
  }
}

void serialEvent(Serial port)
{
  String inString = port.readStringUntil('\n');

  if (inString != null)
  {
      val = Float.parseFloat(inString);
  }

  drawEllipse(val);
  drawLines(val);
  drawEllipse2(val);
  println(val);
}

```

# Answer
> 1 votes
It seems like you need to do some basic debugging:

* Put a println() in setup. If this does not appear, you have a major problem talking to the Arduino board.
* Put a println() statement in the loop() that prints out the sensor reading. That should separate hardware problems from software defects.

# Answer
> -1 votes
Try using this code and run it on your Arduino

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

void loop() {

Serial.print('hello world');
}

```

After uploading the code open the serial monitor and see if it shows the string '`hello world`' and make sure that the baud rate of the serial monitor is set on 9600. If nothing shows this could mean that there is something wrong with your Arduino board.

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


title: C++ Pointer Issues - Mangled Data

text:
# Question
Title: C++ Pointer Issues - Mangled Data
I am having trouble getting my head around pointers in C++, specifically how they behave when passed around or used within objects. As far as my understanding goes as long as pointers, or more specifically values/objects pointed *to* \- do not go out of scope, I should be able to use that pointer.

I have been playing around with some test code on my Arduino Uno and I am bumping into behaviour I cannot explain.

I have read rather a lot on the topic of pointers in C++ and thought I had a good grasp of it. However, practice doesn't seem to match the theory in my head. I don't know if this is a lack of understanding or if the Arduino platform has idiosyncrasies that I am not aware of.

In my test code I have created two classes, `Alpha` and `Beta`. Alpha simply holds a C-type string in a member variable called `alpha`. `Beta` is designed to hold two `Alpha` instances in an array\*.

\*While this is "toy" code, the general structure mirrors my actual project. I have used this toy code as it more succinctly describes the set up and the issue I am facing.

**pointers.h**

```
#import "Arduino.h"
class Alpha {
    private:
        char alpha[20];
    public:
        Alpha();
        ~Alpha();
        char* getAlpha(char* s, int size=20);
        void setAlpha(char* value, int size=20);
        void debug();
};

class Beta {
    private:
        Alpha** alphas;
    public:
        Beta();
        ~Beta();
        Alpha* getAlpha(int index);
        void setAlpha(Alpha* alpha, int index);
        void doStuffWithAlpha(int index);
};

```

**pointers.cpp**

```
#import "pointers.h"

Alpha::Alpha() {
    setAlpha("Initial");
}

Alpha::~Alpha() {}

char* Alpha::getAlpha(char* s, int size/*=20*/) {
    *s = *alpha;
    return s; //return not strictly needed here since s is passed in
}

void Alpha::setAlpha(char* value, int size/*=20*/) {
    strncpy(alpha, value, size-1);
    alpha[size-1] = '\0';
}

void Alpha::debug() {
    Serial.println(alpha);
}

Beta::Beta() {
    alphas = new Alpha*[2];
}

Beta::~Beta() {}

Alpha* Beta::getAlpha(int index) {
    return alphas[index];
}

void Beta::setAlpha(Alpha* alpha, int index) {
    alphas[index] = alpha;
}

void Beta::doStuffWithAlpha(int index) {
    Alpha* alpha = getAlpha(index);
    /* Alpha* alpha = alphas[index]; */ //This doesn't work either - same outcome.
    alpha->debug();
}

```

**sketch.ino**

```
#import "pointers.h"
Alpha a1;
Alpha a2;
Beta b1;

void setup() {
    Serial.begin(9600);
    Serial.println("SETUP()");
    Serial.println();

    a1 = Alpha();
    a1.setAlpha("Hello");

    Serial.println("----- a1.debug -----");
    Serial.println("Expected: Hello");
    Serial.print("Actual: "); a1.debug();
    Serial.println();

    a2 = Alpha();
    a2.setAlpha("Goodbye");

    Serial.println("----- a2.debug -----");
    Serial.println("Expected: Goodbye");
    Serial.print("Actual: "); a2.debug();
    Serial.println();

    Beta b1 = Beta();
    b1.setAlpha(&a1, 0);
    b1.setAlpha(&a2, 1);

    Serial.println("----- b1.doStuffWithAlpha -----");
    Serial.println("Expected: Hello");
    Serial.print("Actual: "); b1.doStuffWithAlpha(0);
    Serial.println("Expected: Goodbye");
    Serial.print("Actual: "); b1.doStuffWithAlpha(1);
    Serial.println();
}

void loop() {
    Serial.println("LOOP()");
    Serial.println();

    Serial.println("----- a1.debug -----");
    Serial.println("Expected: Hello");
    Serial.print("Actual: "); a1.debug();
    Serial.println();

    Serial.println("----- b1.doStuffWithAlpha(0) ------");
    Serial.println("Expected: Hello");
    Serial.print("Actual: "); b1.doStuffWithAlpha(0);
    Serial.println();

    Serial.println("----- a2.debug -----");
    Serial.println("Expected: Goodbye");
    Serial.print("Actual:   "); a2.debug();
    Serial.println();

    Serial.println("----- b1.doStuffWithAlpha(1) ------");
    Serial.println("Expected: Goodbye");
    Serial.print("Actual:   "); b1.doStuffWithAlpha(1);
    Serial.println();

    delay(10000);
}

```

This sketch is quite straight-forward. It creates 2 `Alpha` objects and a `Beta` object and passes the two Alphas into Beta. The myriad `Serial.print()` statements produces the output below.

**output**

```
SETUP()

----- a1.debug -----
Expected: Hello
Actual:   Hello

----- a2.debug -----
Expected: Goodbye
Actual:   Goodbye

----- b1.doStuffWithAlpha -----
Expected: Hello
Actual:   Hello

Expected: Goodbye
Actual:   Goodbye

//everything is fine up to this point...

LOOP()

----- a1.debug -----
Expected: Hello
Actual:   Hello

----- b1.doStuffWithAlpha(0) ------
Expected: Hello
Actual:   CÃoçëyc=Lä^ÜŽYw¸Nv†Ý¿  //uh oh...

----- a2.debug -----
Expected: Goodbye
Actual:   Goodbye

----- b1.doStuffWithAlpha(1) ------
Expected: Goodbye
Actual:   ÿß/ï //uh oh again...

```

Everything works as expected when running `a1` or `a2.debug()` or `b1.doStuffWithAlpha()` in the `setup()` function.

The result of `a1.debug()` and `a2.debug()` works as expected in the `loop()` function.

The issue, as you can see, is when running `b1.doStuffWithAlpha(0)` or `b1.doStuffWithAlpha(1)`. The output is usually junk, which suggests to me the pointer has been mangled and points in the wrong place.

I don't understand what is happening between the transition from `setup()` to `loop()`. At first I thought the issue was the "Hello" and "Goodbye" strings going out of scope, but `Alpha::setAlpha()` makes a copy of the C-string. Also, accessing `Alpha::debug()` in `loop()` works, as shown above.

I have tried variations on the above code, such as using a struct or an int for `alpha` instead of a C-string and the results are the same: Mangled values.

Have I done something obviously silly that my scant C++ experience hasn't picked up on, or is there some fundamental Arduino shenanigans at play?

# Answer
> 4 votes
Problem is local shadow variable `b1` in setup() function declared as `Beta b1 = Beta();`. In `loop()` is considered uninitialized global variable `b1`.

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


# Question
Title: What are the different types of high-speed serial data transfer protocols, and how do they work (ex: baudrate, synchronous vs asynchronous, etc)?
Otherwise worded: How do I resolve my understanding about baud rates and high speed serial data transfer?

From what I understand, serial communication is relatively slow. By slow, I mean that the fastest common rate of transmission of data is 115.2 kBaud.

However, also from what I understand there are fast ways of transferring data serially. I know that some serial configurations through Firewire or Ethernet can transfer data at speeds that are orders of magnitude higher than 115.2 kBaud. These data streams are able to be read on simple computers that you can buy from Staples. I don't know how these systems receive data at such a high speed if common baud rates are so low.

I know something is wrong with my understanding of it all. I am new to electrical engineering and I am trying to teach myself some basic ideas for my research project - with much frustration. I know that I need to have a system that can receive a pulse train at a minimum speed of 10MHz (hopefully up to 500MHz). I will then program it to process this data. The system that I currently have to receive the data is an Arduino certified product:

http://store.arduino.cc/product/E000052

Programming in the Arduino language is not a problem, I already know how to do this. I just want to understand what I can do to receive this data stream. Do I need something faster than this? Or will this suffice? I'm more interested in the theory than the device; it is more valuable for me to bolster my education than for me to solve my problem (though it needs to be solved).

# Answer
Basically there are two kinds of serial: Asynchronous and Synchronous.

With *asynchronous*, which is what serial as in UART and RS-232 are, it's all down to how accurate a system's clock is. Both ends of the line have to agree on the same speed (baud rate) and any deviation from that causes transmission errors. The more accurately the two ends can agree on their baud rates the faster you can transfer data.

Note that on many systems (Arduino included) when you ask for one baud rate you actually get a slightly different baud rate. That's due to the way that the internal UART hardware works - it divides the system clock into finer and finer bits to get as close to the requested baud rate as possible. Lower baud rates are easer to get close to, but higher ones are much harder. So it's "safer" to use a lower baud rate which gives more reliable communication to a greater variety of devices.

The other kind of serial, *synchronous*, uses an extra wire for the transmitting (or *master*) end of the connection to send the clock to the receiving (*slave*) end. The receiver uses the incoming clock to know precisely when it should look at the data line to receive a bit of data. This is how things like SPI and I²C work, and very high baud rates can be achieved. Speeds in the tens of megahertz are common.

Some synchronous systems (such as Ethernet), instead of providing the clock as a discrete wire, encode the clock into the data stream. This keeps the number of wires to a minimum yet allows high speed data transfer. The down side is that this usually means the maximum speed you can run at is actually slightly lower since the effective size of the data being transmitted is increased.
> 7 votes

# Answer
The other answers have really good info in them, but I'd still like to expound a bit on the different types of serial protocols, and how they vary in speed. I'll also mention a few devices and show some comparisons. **For *synchronous* vs *asynchronous* and what that means, see Majenko's really good answer.**

# Clarification:

Your phrasing of "receive a pulse train at a minimum speed of 10MHz" is quite confusing to me. Perhaps this is because when I hear "pulse train" I think you mean you want to read pulse widths in order to obtain data, ie: like the PPM pulse train used in Radio Control communication signals.

Is what you mean simply that you want 10Mbps (megabit per second) transmission rates? If so, the Arduino Intel Galileo can do SPI serial communication at a rate of up to **25MHz**, or you can do Ethernet communication with this board up to **10 MHz** or **100 MHz** (see previous link as well). Note that some Ethernet devices can communicate up to **1000 MHz** (like the Orange Pi Plus), but the Intel Galileo only goes up to **100 MHz**, according to the link above.

USB3.1 serial communication, if a device supports it, however, can be done up to **10Gbps**.

# Standard RS-232 0-5V (TTL) Serial, and example:

Now, as for standard RS-232-type serial done with TTL logic levels (ie: signal voltage levels 0 to 5V), via a UART (piece of hardware that allows this type of asynchronous communication protocol), I have written C++ code on a PC and on a standard Arduino (ex: Nano, Uno, or Pro Mini--under $10 cost + $2 external UART) which communicates at **250kbaud** (though **2Mbaud** is possible on an Arduino Uno--see Connor Wolf's answer here).

When communicating via a serial UART type device, plugged into a PC via a USB plug, a Windows-based computer sees it as a "COM" port. The UART simply does USB to RS-232 TTL data conversion, so I can use this COM port as a serial port on the PC. Since pretty much every Arduino supports standard Serial communication, even the cheapest ones, this is very appealing to me to learn how to write C++ code to do this. I spent the last couple weeks working on my communication code.

At a serial communication speed of **250kbaud** (**250kbps** in my case) I am able to transfer 25-byte binary data packets from my PC to my sub-$10 Arduino at a rate of up to **1000 packets/sec**, while doing error checking on the Arduino receiving the data. In my case, each packet contains 8 commands, plus error checking bytes and a couple other things, to control an RC vehicle.

---

# Here's a few key serial protocols, and their associated speeds, to be aware of.

All of these are different types of serial communication protocols:

1. ## I2C:

Normal Arduino (ex: Uno) default speed is 100kbps; it can be increased to 400kbps. Some non-Arduino devices can do 1Mbps or 3.4Mbps.
2. ## SPI:

Arduino default speed is 4Mbps. Normal Arduinos can go up to 8Mbps; Galileo can do 25Mbps. I have seen some devices (ex: Wiznet W5200 Ethernet chip), which can do SPI serial communication up to 80Mbps (source).
3. ## RS-232 TTL via UART:

This is what most people mean I think when they just use the word "serial" without specifying it further by saying "SPI," "I2C," etc. Whenever you see the term "baud" or "baudrate," this is the type of serial communication they are referring to too. Hardware (UART)-based serial communication is done via pins 0 and 1 on most Arduinos. Normally, the "high-end" speed is considered 115200bps, but I regularly use 250kbps on an Arduino. Up to 2 Mbps is theoretically possible under the right conditions for the Atmel AVR-based Arduinos, like the Uno. See Connor Wolf's answer here. Arduino also includes a software serial library for this type of serial communication on any of the Arduino's pins, and I have used it up to 250kbps. I haven't yet tested it beyond that speed, but being software-based, I'd expect it to become unreliable much beyond that.
4. ## USB:

USB Speeds (https://en.wikipedia.org/wiki/USB)
USB 1.0: Low Speed mode (1.5Mbps), Full Speed mode (12Mbps)
USB 2.0: High Speed (480Mbps)
USB 3.0: SuperSpeed (5Gbps)
USB 3.1: SuperSpeed+ (10Gbps)
5. ## Ethernet:

Standard rates are 10/100/1000 Mbps.

---

# Conclusions:

* If you must have a minimum of 10MHz (AKA mbps) communication rates, you can use the SPI, USB, or Ethernet protocols. I2C and RS-232 TTL serial are too slow.
* If you really want the ~500MHz communication rate, you can use USB 2.0 or higher, or Ethernet 1000Mbps. All the rest are too slow.

Note that embedded boards and devices, microcontrollers, etc, can *all* do some type of serial communication, even if it's just slow bit-banged RS-232 TTL-type or SPI-type serial. Nevertheless, some high-end devices can do really high speed serial communication via USB, USB 3.0, high-speed Ethernet, high-speed SPI, etc. When it comes to really fast serial communication methods (~3Mbps and higher), *synchronous* techniques must generally be used rather than *asynchronous* techniques, as the errors in clock-rates caused by using separate clocks begin to be too pronounced.

You just need to look at your actual needs. For most of my needs, 250kbaud is plenty fast using the built-in UART inside every cheapo low-end AVR-based Arduino device. Your needs, however may be different.
> 4 votes

# Answer
Different serial communications protocols use different signal modulation methods to encode data; if you want to roll your own wire protocol, you'll want to learn about those.

Back in the day, low-rate UART serial systems were mostly used with modems that had to transmit long distances over voice telephone circuits. Those circuits were bandwidth-limited to the needs of voice communication, and were frequently "noisy", so phone line modems never evolved beyond 56Kbit/s rates. The UARTs themselves could go faster, so if you were doing a local serial connection you could get up to 115kbps. These UARTs were relatively cheap.

More advanced encoding schemes plus more expensive hardware (with a lower noise floor) allowed connections about 100 times faster -- 10mbps ethernet. That's a much more common standard now than RS-232 serial connections, and as it became widely adopted it got cheap, and so 100mbps and gigabit ethernets followed the same form factor and basic electrical characteristics because (under good conditions) all could work over the same wiring, so compatibility with existing systems was good; the endpoints for the most part can automatically downgrade to whatever speed is supported by both ends of a given wire.
> 1 votes

---
Tags: serial, edison
---


# Question
Title: How to print a line with a variable in it?
I want to know if there is a way to write like in C programming:

```
  printf("the num is %d",num);

```

I know that to print a line or a variable the command will be Serial.println when I write:

```
 Serial.println("the num is %d",num);

```

It's not working.

Is there a way to write it in just one line?

# Answer
> 2 votes
```
Serial.print("the num is "); Serial.println(num);

```

is how you do it with the Serial object. There is a printf in the library and it's a lot easier to use (as you already know) but a little bit more work to set up. Here is a simple program using printf:

```
// Define a file descriptor for the serial output:
static FILE uartout = { 0 };

// Declare our put-character function:
static int uart_putchar (char c, FILE *stream);

void setup() {
   // Fill in UART file descriptor with pointer to my char-out func.
   fdev_setup_stream(&uartout, uart_putchar, NULL, _FDEV_SETUP_WRITE);
   stdout = &uartout;

   Serial.begin(9600);   // open serial port, sets baud rate
}

void loop( void ){
   printf("Run time: %ld\n", millis());
   delay(1000);          // wait 1 sec
}

// My char output function
static int uart_putchar (char c, FILE *stream)
{
   if( c == '\n' )
      Serial.write('\r');
   Serial.write(c) ;
   return 0 ;
}

```

# Answer
> 3 votes
I use:

```
Serial.println("The temperature is " + String(temperature) + " degrees C");

```

With this solution you can't format the variable's value but I find this quick and dirty for debug messages.

# Answer
> 2 votes
You can try "extending" the Print class to include a printf() function. It requires modification of the Arduino core to add it, and it's something I have been meaning to suggest to the Arduino guys as a permanent modification, but I often manually add a function such as this:

```
void Print::printf(const char *fmt, ...) {
    va_list va;
    va_start(va, fmt);
    char temp[1];
    uint32_t slen = vsnprintf(temp, 1, fmt, va);
    va_end(va);
    char out[slen + 2];
    va_start(va, fmt);
    vsnprintf(out, slen+1, fmt, va);
    va_end(va);
    print(out);
}

```

to my core.

It's not wonderfully efficient from a processing point of view - it first runs a `vsnprintf()` to a single byte target. This allows it to work out how long the formatted string will need to be:

> If the output was truncated due to this limit, then the return value is the number of characters (excluding the terminating null byte) which would have been written to the final string if enough space had been available.

So it then knows how much memory is needed to store the formatted string. It then goes ahead and allocates that much memory on the stack and re-formats the string again into that newly allocated memory. It can then go ahead and send that data to the serial port.

It's a "quick and dirty" hack, but it works. A better solution would be to re-write the `printf()` parser in the function and instead of formatting to memory then printing, to format the data stream directly to the `Serial` device, thus saving the double-processing and memory allocation.

You can then quite happily do things like:

```
Serial.printf("The temperature is %d degrees C\n", temperature);

```

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


# Question
Title: Measurement of pulse duration greater than 3mins
Is it possible to measure the width of a pulse which is longer than 3 minutes? The pulseIn function can only measure duration of maximum 3 minutes accurately. I've tried using interrupts but haven't come up with a correct solution yet.

I'm measuring the duration of pulse (HIGH) generated by AND gate connected to the outputs of two comparators. AND gate output voltage is around **4.9 volts**.

Any logical solution or idea would be appreciated. Thanks!

# Answer
The concept is actually quite simple.

You need to record the time when the signal goes high, and record the time when it goes low. The pulse width is the difference between the two times.

Yes, you can do it with interrupts, but you don't need to if you're not trying to do anything else at the same time.

A simple polling code could be something like this:

```
while (digitalRead(pin) == LOW); // Wait for input to go high
unsigned long startTime = millis(); // Record start time
while (digitalRead(pin) == HIGH); // Wait for input to go low
unsigned long endTime = millis(); // Record end time
unsigned long pulseDuration = endTime - startTime;

```

You basically sit doing nothing until the leading rising edge of your pulse. You then record the time, and again sit doing nothing - this time while looking for the trailing falling edge of the pulse. Then record the end time and subtract the two.
> 1 votes

# Answer
Here is some code I used to time a ball running down a ramp:

```
const byte LED = 12;
const byte photoTransistor = 2;

unsigned long startTime;
volatile unsigned long elapsedTime;
volatile boolean done;

void ballPasses ()
{
  // if high, start timing
  if (digitalRead (photoTransistor) == HIGH)
    {
    startTime = micros ();
    }
  else
    {
    elapsedTime = micros () - startTime;
    done = true;
    }

  digitalWrite (LED, !digitalRead (LED));
}

void setup ()
{
  Serial.begin (115200);
  Serial.println ("Timer sketch started.");
  pinMode (LED, OUTPUT);
  attachInterrupt (0, ballPasses, CHANGE);
}

void loop ()
  {
  if (!done)
    return;

  Serial.print ("Time taken = ");
  Serial.print (elapsedTime);
  Serial.println (" uS");
  done = false;
  }

```

Using `micros()` here is probably overkill, but that should be good for an interval up to 71 minutes.
> 1 votes

---
Tags: arduino-uno, millis, pulsein
---


# Question
Title: Can I stack an Arduino to another Arduino?
I'm using Arduino clones, which have pin headers the same as Arduino's shields have (with extended "legs" below the board to be stackable).

Can I stack my Arduino (Mega) clone to an Arduino (Uno) clone without destroying both? Wouldn't it explode or something?

Just asking before trying it.

Thanks!

# Answer
No, I don't think that is a good idea. You would basically short the pins of each of them together, plus their power supplies. The only way it might conceivably work was if one Arduino had all its pins as inputs and the other as outputs, otherwise they would be "fighting" each other to drive a pin high or low. You would also have connected together their Reset pins so they would both reset at the same time. And doing serial comms would be problematic as the serial ports would be fighting each other.

---

Also, uploading sketches would be virtually impossible, as when you started the upload, both would be reset, both bootloaders would try to read the incoming data, and reply at the same time. Plus, the Mega and the Uno have different uploading protocols. So at the very least, you would have to separate them every time you uploaded new code, to either one.
> 5 votes

---
Tags: arduino-uno, arduino-mega, clones
---


title: Hi-speed external ADC

text:
# Question
Title: Hi-speed external ADC
I would like to detect signals in nanosecond scale. For that, an ADC with at least 500 MSPS is required.

My question is if its possible to use an external ADC with 500 MSPS with a 16MHz Arduino Mega? If not, is there any additional hardware like FIFO buffer to overcome this problem?

Please help, thanks!

# Answer
> 3 votes
From the Arduino reference on AnalogRead: "It takes about 100 microseconds (0.0001 s) to read an analog input, so the maximum reading rate is about 10,000 times a second."

500msps is an awfully high rate - my first instinct is, perhaps you need to revisit what you are after, and why.

There are indeed chips that will do this for you. It is still not possible with an Arduino, since the Arduino can't even receive the data this fast, let alone process it. Assuming 8-bit sampling, this would generate a stream of data at 4gigabits/second - I doubt any disk drive could write that fast (SATA3 is 4.8gbit/sec, which is 20% more, I suspect that the 20% would be eaten up by overhead - you can't just send raw data to a drive, you also have to tell it where to put it. That just accounts for getting the data to the drive circuitry, not actually storing it).

Perhaps what you're looking for is an oscilloscope. An oscilloscope takes high speed readings and displays them. Oscilloscopes are often used for testing circuits (e.g. looking at what an Arduino puts out/reads in when it's being programmed). Looking on National Instruments' websites, their cheapest one I could find that does \> 500msps is worth about US$8,000 (ballpark). You will still not be able to store this to disk, or process it in any meaningful way, in realtime - a board like this will typically capture data (based on a trigger, sample until the memory is full, then slowly move the data to the PC to process.

# Answer
> 3 votes
No, it's certainly not possible to directly sample at 500Msps on an Arduino using an external ADC. Simple maths:

* The Arduino can perform 16 million instructions (best case) per second
* The ADC performs 500 million samples per second.
* 500 / 16 = 31.25

Therefore the ADC would be generating 31.25 samples for every clock of the Arduino, so unless you can build in a time compressor (maybe with a flux capacitor too), it just ain't gonna do it.

So you will have to think creatively instead. A possible solution would involve:

* A high speed *flash* or *pipelined* ADC, ideally with parallel output.
* A large chunk of memory to act as a buffer.
* A high speed clock source to set the timing (500MHz?).
* Glue logic and counters to take one sample, store it in the buffer, and increment the buffer address.
* More glue logic and interfacing to allow the Arduino access to the buffer memory and to control the operation of the sampling system.

This, to me, sounds like a job for an FPGA, and at 500MHz, quite a fast FPGA. You should investigate some of the FPGA development boards from Xilinx and Altera.

---
Tags: arduino-mega, adc
---


# Question
Title: How does Yun identify itself to Windows?
When I plug in my Yun, Windows pops up a box saying `Windows needs to install driver software for your Arduino Yun`.

What does Windows use to identify my device as an Arduino Yun? Is it written in a file somewhere, so I could for example, *remove* that driver prompt, or *change* it to `Windows needs to install driver software for your Foo Bar?`

# Answer
> 1 votes
It is written in what is called the *USB String Descriptor*. I don't have my Yun to hand right now (it's acting as a wireless bridge temporarily), but all USB devices have these *USB String Descriptors*. Here's an example for the Leonardo (which you can easily inspect on Linux):

```
$ sudo lsusb -v -d 2341:0036

Bus 001 Device 015: ID 2341:0036 Arduino SA
Device Descriptor:
  bLength                18
  bDescriptorType         1
  bcdUSB               1.10
  bDeviceClass            2 Communications
  bDeviceSubClass         0
  bDeviceProtocol         0
  bMaxPacketSize0         8
  idVendor           0x2341 Arduino SA
  idProduct          0x0036
  bcdDevice            0.01
  iManufacturer           2 Arduino LLC      <<== String descriptor ID 2
  iProduct                1 Arduino Leonardo <<== String descriptor ID 1
  iSerial                 0
  ... etc ...

```

Internally the strings are stored as an indexed table - there's two there, ID 1 and ID 2. The *Device Descriptor* then has a couple of bytes in it that says "The manufacturer is string ID 2, and the product name is string ID 1". The operating system then requests those string descriptors so it can display the friendly message for you.

If you want to change that name you basically have to both re-program the bootloader (which has the USB descriptors when in program upload mode) and the Arduino core (that has the string descriptors programmed into it).

---
Tags: arduino-yun
---


# Question
Title: Arduino ethernet shield not getting correct IP
I have a very simple sketch which I'm using to (try to) prove out an ethernet shield. The complete sketch is below. When I upload the sketch, the IP address that the shield gets is 0.140.140.140, which is incorrect. I just received the shield today from SparkFun, it is this one. Am I doing something wrong, or is my shield and/or Arduino broken? The Arduino is an Uno R3. The sketch works otherwise (the LED blinks as expected).

Sketch:

```
#include <SPI.h>
#include <Ethernet.h>

// Network information
byte mac[] = {0xDE, 0xAD, 0xBE, 0xCF, 0xFE, 0xEE };
byte ip[] = { 172, 31, 42, 201 };

void setup() {
  pinMode(4,OUTPUT);
  digitalWrite(4, HIGH);
  delay(1);

  // initialize serial:
  Serial.begin(9600);
  Serial.println("Starting sketch...");
  Ethernet.begin(mac,ip);
  delay(1000);
  Serial.println(Ethernet.localIP());
  Serial.println("Setup done.");
  pinMode(13, OUTPUT);
}

void loop() {
  digitalWrite(13,HIGH);
  delay(1000);
  digitalWrite(13,LOW);
  delay(1000);
  Serial.println(Ethernet.localIP());
}

```

# Answer
> 1 votes
The sketch you have written works perfectly with a cheap Ethernet Shield clone from eBay. Those (and the older Arduino Ethernet Shields) use the Wiznet W5100 chip.

The new shields, of which you have one, use the newer, more powerful, Wiznet W5500 chip.

You can't use the old Ethernet library with the new Wiznet W5500 chip. It doesn't work.

You have to use the "Ethernet 2" library as described here:

> Note: this library is used to work with the new Ethernet shield (version 2) and Leonardo Eth that uses a new Controller W5500.

That page is linked from the product page you link to above. If you had read the product page you would already know this.

---
Tags: arduino-uno, ethernet
---


title: Using nrf24l01 with mpu 6050 unstable

text:
# Question
Title: Using nrf24l01 with mpu 6050 unstable
I am trying to connect the wireless module nrf24l01 with the gyro mpu-6050. Each works perfectly on its own. However, when connecting both to a single atmega328 (in order to send over wireless the gyro data), the code runs for between 30 seconds and 5 minutes.

I have seen many people have issues, none of the suggestions have worked, but it seems like it is more about the combination than the mpu itself. I have not had any errors, in that all the attempts have uploaded fine.

Some things I have tried (If you have experience with this device, im sure you will know what i am referring to ): Changing clock rates from 24 to 12, and 400 to 200 Changing the header file for mpu from 100 hz to 20 hz and back Adding pullup and pulldown resistors on sla/sda Using external variable power supply to make sure exact voltage Powering devices off arduino 3.3 and external 3.3 Running code without using serial reader on computer and just transmitting data

Edit:

After more debugging, I reduced the issue (I think). As each module works fine independently, i thought there could be a code issue. It seems though, that the issue is the combination of buffers. I don't think this is exactly right, but to us it seems like the gyro needs to run quickly to stop the risk of causing the arduino to hang(even though we clear the buffer).

The second part is the wireless. It seems like the code is looking by default for an acknowledgment the package is received. This slows down the broadcasting. So, if we disable the ack requirement, the gyro becomes stable. However, the receiver stops receiving any packets at all. If someone knows why, please explain.

So what we thought would work is by sending only some packets as the write with ack on a particular pipe. This way, the gyro will be able to run stably, and the data can sometimes be sent and we can see if this is really the problem. Again, this does not get recognized by the receiver at all.

Questions: Does it make sense that the buffers are working against eachother, and this is not solvable through hardware. Is there a clear reason why the receiver can not find packets that are being sent, just without the ack requirement?

# Answer
> 1 votes
I could not figure out what was wrong, but I changed to this library for NRF24: http://tmrh20.github.io/RF24/

and I started using the GY-85 with the FreeIMU Library : http://www.varesano.net/projects/hardware/FreeIMU

Following this advice: http://forum.arduino.cc/index.php?topic=164222.msg1539961#msg1539961

It works now, so if it was SRAM as @Avamander suggested, it was not on my side.

# Answer
> -1 votes
It seems to me you are running out of memory (SRAM). https://www.arduino.cc/en/Tutorial/Memory

---
Tags: nrf24l01+, mpu6050
---


title: Unexpected output form Serial.println

text:
# Question
Title: Unexpected output form Serial.println
So I have a teensy and an arduino uno connected together via I2C, however some very odd behavior is occurring, when monitoring the serial connection for shorter data sent over I2C I receive the expected serial output. However if the data is longer I only receive 2 characters. More strange even is that if I send the longer data again I receive none, but if I send the shorter data I receive the expected output. After sending the shorter data again sending the longer data will result is the odd 2 characters.

Uno code //#include

```
 #include <Wire.h>

boolean pinout = 0;
byte current[512];

void setup() {
  // put your setup code here, to run once:
  Wire.begin(1);
  Serial.begin(115200);
  Wire.onReceive(data);
  //DmxSimple.usePin(3);
  //DmxSimple.maxChannel(30);
}

void loop() {

}

void data(int numBytes){
//Serial.println("DATA RECIVED");

 delay(500);

 char input[20];
 int pos = 0;

 while(Wire.available()){
   input[pos++] = Wire.read();
  }
  input[pos++] = '\0';

  Serial.print("Recived \"");
  Serial.print(input);
  Serial.println("\"");

  char* next = strchr(input, ',');
  while(next != 0){
  *next = 0;
  next++;
  char* splitter = strchr(next, ':');
  if(splitter != 0){
  *splitter = 0;
  splitter++;
  int channel = atoi(next);
  int value = atoi(splitter);
      //DmxSimple.write(channel,value);
      Serial.print(channel); Serial.print(":"); Serial.println(value);
    }
  }
}

```

Teensy code

```
            #include <i2c_t3.h>
            //#include <ArduinoPebbleSerial.h>

     /*
    static const uint16_t SERVICE_ID = 0x1001;
static const uint16_t UPTIME_ATTRIBUTE_ID = 0x0002;
static const size_t UPTIME_ATTRIBUTE_LENGTH = 4;
static const uint16_t LAMP_ATTRIBUTE_ID = 0x0003;
static const size_t LAMP_ATTRIBUTE_LENGTH = 20;

static const uint16_t SERVICES[] = {SERVICE_ID};
static const uint8_t NUM_SERVICES = 1;

static const uint8_t PEBBLE_DATA_PIN = 1;
static uint8_t buffer[GET_PAYLOAD_BUFFER_SIZE(4)];

typedef struct __attribute__((packed)){
  uint8_t channel;
  uint8_t value;
} DMXP;*/

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);
  Wire.begin();
  Serial.begin(9600);
  /*
 #if defined(__MK20DX256__) || defined(__MK20DX128__)
  // Teensy 3.0/3.1 uses hardware serial mode (pins 0/1) with RX/TX shorted together
 ArduinoPebbleSerial::begin_hardware(buffer, sizeof(buffer), Baud57600, SERVICES, NUM_SERVICES);
#elif defined(__AVR_ATmega32U4__)
 // Teensy 2.0 uses the one-wire software serial mode
 ArduinoPebbleSerial::begin_software(PEBBLE_DATA_PIN, buffer, sizeof(buffer), Baud57600, SERVICES,
                                  NUM_SERVICES);
#else
#error "This example will only work for the Teensy 2.0, 3.0, or 3.1 boards"
#endif
*/
/*for(int i = 1; i < 8; i++){
  sendChannel(i,0);
}
*/

}

/*
void handle_dmx_request(RequestType type, size_t length) {
if (type != RequestTypeWrite) {
  return;
}

DMXP cmd = *(DMXP*)buffer;
sendChannel(cmd.channel, cmd.value);

// ACK that the write request was received
ArduinoPebbleSerial::write(true, NULL, 0);
ArduinoPebbleSerial::notify(SERVICE_ID, UPTIME_ATTRIBUTE_ID);
}
*/

void loop() {

  /*
  if (ArduinoPebbleSerial::is_connected()) {
  digitalWrite(13,true);
} else {
  digitalWrite(13,false);
}

uint16_t service_id;
uint16_t attribute_id;
size_t length;
RequestType type;
if (ArduinoPebbleSerial::feed(&service_id, &attribute_id, &length, &type)) {
  // process the request
  if (service_id == SERVICE_ID) {
    switch (attribute_id) {
      case LAMP_ATTRIBUTE_ID:
        handle_dmx_request(type, length);
        break;
      default:
        break;
    }
  }
}
*/

}

void serialEvent(){
  if(Serial.read() == 't'){
  digitalWrite(13,true);
  Serial.println("Starting Controller");
  int chans[8] = {1,2,3,4,5,6,7,8};
  int vals[8] = {2,4,6,8,16,32,64,128};
  sendChannel(chans,vals,4);
  } else {
    sendChannel(1,1);
  }
  while(Serial.available()){
    Serial.println(Serial.read());
  }
}

void sendChannel(int chan, int val){
 char chno[8];
  itoa(chan,chno,10);
  char vano[8];
 itoa(val,vano,10);
 char message[20];
 int messagei = 0;
 for(int i = 0; i < 7; i++){
 if(chno[i] == '\0'){
   break;
  }
 message[messagei++] = chno[i];
}
 message[messagei++] = ':';
 for(int i = 0;i < 7; i++){
 if(vano[i] == '\0'){
  break;
 }
 message[messagei++] = vano[i];
 }
  //message[messagei++] = '\n';
//message[messagei++] = '\r';
message[messagei++] = '\0';

Serial.println(message);

Wire.beginTransmission(1);
Wire.write(message);
Wire.endTransmission();
}

void sendChannel(int chan[], int val[], int num){
 char message[20*num + 1];
 int at = 0;

 for(int i = 0; i < num; i++){
char chno[8];
itoa(chan[i],chno,10);
char vano[8];
itoa(val[i],vano,10);
for(int i = 0; i < 7; i++){
  if(chno[i] == '\0'){
    break;
  }
  message[at++] = chno[i];
}
message[at++] = ':';
for(int i = 0;i < 7; i++){
  if(vano[i] == '\0'){
    break;
  }
  message[at++] = vano[i];
  }
  if(i+1!=num){
  message[at++] = ',';
  } else {
  message[at++] = 0;
 }
 }

 char finalMessage[at+1];
 for(int i = 0; i <= at; i++){
finalMessage[i] = message[i];
 }

 Serial.println(finalMessage);

Wire.beginTransmission(1);
Wire.write(message);
Wire.endTransmission();

}

```

(If modifying the teensy code to run on a second arduino replace the line `#include <i2c_t3.h>` with `#include <Wire.h>` no other changes should be necessary)

To use the Teensy code open a serial terminal to access it, press 't' to send a long packet, or any other character to send a shorter one.

# Answer
> 1 votes
Your code which I will reproduce here as it wasn't in the question has a major issue:

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

#include <Wire.h>

boolean pinout = 0;
byte current[512];

void setup() {
  // put your setup code here, to run once:
  Wire.begin(1);
  Serial.begin(115200);
  Wire.onReceive(data);
  //DmxSimple.usePin(3);
  //DmxSimple.maxChannel(30);
}

void loop() {

}

void data(int numBytes){
  //Serial.println("DATA RECIVED");

  delay(500);

  char input[20];
  int pos = 0;

  while(Wire.available()){
    input[pos++] = Wire.read();
  }
  input[pos++] = '\0';

  Serial.print("Recived \"");
  Serial.print(input);
  Serial.println("\"");

  char* next = strchr(input, ',');
  while(next != 0){
   *next = 0;
   next++;
    char* splitter = strchr(next, ':');
    if(splitter != 0){
      *splitter = 0;      Wire.onReceive(data);
  //DmxSimple.usePin(3);
  //DmxSimple.maxChannel(30);
}

```

---

Your function `data` does `Serial.print`s. It is called as an interrupt service routine effectively, and thus should not do serial prints:

```
      Wire.onReceive(data);
    }

    void loop() {

    }

    void data(int numBytes){

...

      Serial.print("Recived \"");
      Serial.print(input);
      Serial.println("\"");

```

---

> More strange even is that if I send the longer data again I receive none, ...

Yep, that will definitely happen. The serial printing "blocks" if you print a lot, and thus the code will hang indefinitely.

---

```
  delay(500);

```

You definitely should not use `delay` in an interrupt routine. It will almost certainly hang because the timer interrupts which are needed for `delay` to work are not being serviced.

---

```
  Wire.begin(1);

```

You should not be choosing to use I2C address 1. It is reserved. See:

7-bit, 8-bit, and 10-bit I2C Slave Addressing and I2C specification (pdf)

```
Slave Address   R/W Bit     Description
000 0000    0   General call address
000 0000    1   START byte(1)
000 0001    X   CBUS address(2)
000 0010    X   Reserved for different bus format (3)
000 0011    X   Reserved for future purposes
000 01XX    X   Hs-mode master code
111 10XX    X   10-bit slave addressing
111 11XX    X   Reserved for future purposes

```

> (1) No device is allowed to acknowledge at the reception of the START byte.
>
> (2) The CBUS address has been reserved to enable the inter-mixing of CBUS compatible and I2C-bus compatible devices in the same system. I2C-bus compatible devices are not allowed to respond on reception of this address.
>
> (3) The address reserved for a different bus format is included to enable I2C and other protocols to be mixed. Only I2C-bus compatible devices that can work with such formats and protocols are allowed to respond to this address.

---
Tags: arduino-uno, serial, i2c, teensy
---


title: I2C hookup - sketch just crashes

text:
# Question
Title: I2C hookup - sketch just crashes
I am encountering problems with I2C when trying to attach a 9DoF Sensor to my Arduino Uno. Following these instructions (the hardware setup I have is like in the schematic) I noticed the basic example not working. I've since debugged different aspects and when I use the "I2C Scanner" example from this page it seems something basic with I2C must be wrong. The code from there I am using is:

```
// I2C Scanner
// Written by Nick Gammon
// Date: 20th April 2011

#include <Wire.h>

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

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

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

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

void loop() {}

```

Instead of this suggested sample output:

```
I2C scanner. Scanning ...
Found address: 42 (0x2A)
Done.
Found 1 device(s).

```

The output I am getting is in Serial monitor on the correct baud rate is:

```
ù
I2C s

```

With other examples I have tried I have similar results. As soon as something calls `Wire.endTransmission()` things start to crash and burn.

Any ideas what this could be or how to debug it?

# Answer
`Wire.endTransmission()` is where the action is. Nothing is actually sent until that point. `Wire.beginTransmission` just gets ready for sending and `Wire.write` (if used) adds stuff to an internal buffer.

If it hangs at that point you probably have dodgy hardware. Check the connections are correct (ie. SDA/SCL the right way around, and that it is powered, and that you have a common ground).

Then try a pull-up resistor between SDA and +5V, and SCL and +5V. A typical value resistor (for both resistors) would be 4.7k.

I see from the linked page that the board already has 10k resistors. Hopefully you did not cut the jumper links. Whether or not you did you might want to augment them with 4.7k resistors. Also keep the cable runs short.
> 1 votes

---
Tags: arduino-uno, serial, i2c, debugging, wire-library
---


title: Convert the Serial.Println to string

text:
# Question
Title: Convert the Serial.Println to string
I'm working with VirtualWire and I'm trying to get a string value out of the Serial.println in the loop. I've tried create a string and add the message\[i\] , but surprisingly message\[i\] becomes an int when added. Serial.println outputs the string correctly, but the string that I get from message\[i\] is just numbers...

```
#include <VirtualWire.h>
byte message[VW_MAX_MESSAGE_LEN]; // a buffer to store the incoming messages
byte messageLength = VW_MAX_MESSAGE_LEN; // the size of the message
String sensorname;
void setup(){
  Serial.begin(9600);
  Serial.println("Device is ready");
  // Initialize the IO and ISR
  vw_setup(2000); // Bits per sec
  vw_rx_start(); // Start the receiver
  }
void loop(){

  if (vw_get_message(message, &messageLength)){
    Serial.print("Received: ");
    for (int i = 0; i < messageLength; i++){
      Serial.write(message[i]);
      sensorname += message[i];
      }
      Serial.println();
      Serial.pintln("Name of sensor: " + sensorname);
      sensorname="";  //Reestart the string
      }
}

```

I'm quite new with VirtualWire so I don't know if there is command to get the message and pass it directly to string...Any help will be appreciated!

**EDIT** I think I dind't express myself well. In my original question I didn't add the String sensor name

The Response I get in the Serial is the following:

```
Device is ready
SensorA
Name of sensor: 8310111011511111465

```

My aim is to instead of having as sensorname=8310111011511111465, have sensorname=SensorA

# Answer
Those numbers are the numerical ASCII representation of the characters.

```
83 = S
101 = e
110 = n
... etc ...

```

(Find the whole list here: http://www.asciitable.com/)

The reason you are ending up with numbers is because of the *type* of variable you are receiving the data into - a *byte*.

A *byte* stores a number between 0 and 255. When you add that *byte* to a *String* the compiler assumes you want to append a number, since it is a numerical type that you are using.

If you instead tell it to use a *char* type then the compiler should realise "Ah, this is the numeric representation of a character - I will add the character instead".

You can either change the whole array type:

```
char message[VW_MAX_MESSAGE_LEN]; // a buffer to store the incoming messages

```

Or *cast* the variable to be the right type when you append it:

```
  sensorname += (char)message[i];

```

Or better still, don't use the String class since it is really too heavyweight and prone to memory issues for use on a little microcontroller. Stick to C strings. They take a little more getting used to, but are so much more microcontroller friendly.
> 0 votes

---
Tags: virtualwire
---


# Question
Title: Consulting and inserting a string into an array if it doesn't exist (Arduino IDE) 1
Sorry that I repeat my question, I can't enter to my user...

In the project I'm doing, I connect an arduino mega with ethernet and Post some Strings to the server. The arduino mega has a receiver(315MHz). I have some arduinos nano connected with PIR sensors that sends a some int with transmitters (315MHz). What I want to do is a list in my arduino mega that stores the values sent by the arduinos nanos to use them to my server (using POST). my question is the following:

If I had an empty array, what I would like to do is

```
listOfSensors[]={}

void funtion (String sensor){
    if (sensor is inside listOfSensors){
         //dont do anything
    }
    else {
         add sensor to listOfSensors
    }

```

I have been looking for hours, but I haven't found anything so far... Anyone has any idea? Thanks!!

# Answer
> 0 votes
In C there is no such thing as an "empty array". All arrays have a finite pre-defined size.

```
String sensors[10]; // Room for up to 10 sensors

```

The usual way of storing an unknown number of entries that will be added to "as and when" is to use a *linked list* or *doubly-linked list*.

A *linked list* is a list of items where each item also contains a pointer to say where the next item in the list is located.

Also you shouldn't use the String class as it is not good when working with linked lists (or in general - stick to C strings).

**Warning: linked lists aren't for the faint of heart.**

First you would define a *struct* to store the data you want in the linked list:

```
struct sensor {
    char *name;
    int currentValue;
    struct sensor *next;
};

```

That would store the name of the sensor ("name"), the current value from the sensor ("currentValue") and also contains a pointer ("\*next") to the next entry in the list. That last bit is the most important.

Now you create a "head" pointer variable to start your list off:

```
struct sensor *mySensors = NULL;

```

That starts out as *NULL* to say "This variable has nothing in it at the moment".

Now that was the easy part. The hard part is adding entries to the list...

A couple of *helper* functions can be of use here. Let's start by defining a function that will look for a specific entry by name in the list:

```
struct sensor *findSensor(const char *name) {
    for (struct sensor *scan = mySensors; *scan; scan = scan->next) {
        if (strcmp(scan->name , name) == 0) {
            return scan;
        }
    }
    return NULL;
}

```

That will start off with a pointer variable *scan* pointing to the first entry in the linked list (mySensors). While it's pointing to a valid entry (not NULL) compare the name to the given string and if they match then return the entry we are pointing to. Next point to whatever the "next" pointer is pointing to, so you move down the list.

Now to add a sensor:

```
struct sensor *addSensor(const char *name, int value) {
    // First look to see if it exists:
    struct sensor existing = findSensor(name);
    if (existing != NULL) { // We found it
        existing->currentValue = value; // Update the value
        return existing;
    }
    // We haven't got it in our list, so create a new entry:
    struct sensor newsensor = (struct sensor *)malloc(sizeof(struct sensor));
    // And fill in the data:
    newsensor->name = strdup(name); // Create a COPY of the string
    newsensor->currentValue = value; // Store the value
    newsensor->next = NULL;
    // IMPORTANT: The new entry must point to NULL to mark the end of the list:
    newsensor->next = NULL;

    // Now where to add it in the list? Is there even a list?
    if (mySensors == NULL) {
        // No? Then we just make our new entry the head of the list:
        mySensors = newsensor;
        return newsensor;
    }
    // Otherwise we need to scan through the whole list to find
    // where the tail of the list is:

    struct sensor *scan = mySensors;
    // While the current entry points to a valid next entry
    while (scan->next) {
        // move on to that next entry
        scan = scan->next;
    }
    // There must be no valid next entry now (scan->next == NULL), so
    //  add our new sensor as the next valid entry:
    scan->next = newsensor;
    return newsensor;
}

```

Removing a sensor from the list is a much more involved process (even more than adding a sensor). You need to "splice" the list around the deleted entry. I'll add detail on that if you need it, but by the sound of things you won't be removing entries, only adding them.

The routines shown there (I haven't actually tested them, but it is standard code I write all the time) aren't as efficient as they could be. If you are adding and removing entries all the time and you end up with quite a large list it can take longer and longer to scan right through the list to find the last entry to add to. If that is the case you can maintain a "tail" pointer that you always update to point to the last added entry whenever you add one. That can then be used to rapidly add to the end of the list without having to scan through the whole list every time.

Another optimisation if you do a lot of scanning around within a list is to make a *doubly linked list*. This is just like the linked list above except it works in both directions. Not only do you store a *next* pointer, you also store a *previous* pointer. You can now scan in either direction - from head to tail or from tail to head, or hopping around at will inside the list. That is especially useful if you want to do things like ordering the list alphabetically.

# Answer
> 0 votes
If you only need to add items of a fixed size to your sensor list (i.e. you don't need to delete items or sort them), you can use an uninitialized array large enough for the maximum number of items it will need to hold:

```
#define MAXSENSORS 30               // max sensor count
#define SNAMELEN 12                 // max sensor name length

struct sensorData {
    char sname[SNAMELEN+1];
    uint16_t svalue;
};                                  // defines data for 1 sensor

uint8_t sensorCount = 0;
struct sensorData listOfSensors[MAXSENSORS]={0}; // array of sensor data, initialized to 0, 0, ...

```

You'll also need an unsigned int (perhaps only a byte) to keep track of the count of items in the array, which you'll increment every time you add another sensor (up to the maximum number).

I think this is what you meant by "empty array". You would add your next sensor data at `listOfSensors[i]`, then increment i. Likewise, you would search for a sensor in the array from `listOfSensors[0]` to `listOfSensors[i-1]`.

---
Tags: arduino-ide
---


title: Arduino for Wi-Fi hotspot?

text:
# Question
Title: Arduino for Wi-Fi hotspot?
I want to create a Wi-Fi hotspot and redirect all connections to a custom login page.

I would like to know if the Arduino Yún is a good choice in this case?

# Answer
> 2 votes
Better use a regular router and flash DD-WRT or OpenWRT to it (check the supported router list on their websites). Next use something like NoCatSplash, to create a captive portal with login.

Arduino's just are not fast enough for this. Arduino Yuns are typically more expensive.

# Answer
> 0 votes
Here is a project where I make a Yun into a hotspot and even have it act like a captive portal so users can control things though the Yun...

http://wp.josh.com/2014/05/01/a-platform-for-casual-encounters-with-interactive-technology/

Even though it does work, I can not recommend using the Yun for something like this unless you have no other choice. It is just not a good platform and you end up wasting huge amounts of time on unnecessary problems.

Much better to use something like a BeagleBone or Raspberry PI to handle to Wifi stuff. You can then connect these to a normal Arduino if necessary to deal with your hardware.

---
Tags: arduino-yun
---


# Question
Title: Adafruit_NeoPixel define pin for different setups
I am looking for a way of defining multiple pins for my RGB strips. Currently the defined variable is set with the pin within it. This works just fine if I only had one RGB strip connected to the Arduino but I have 4 so I will need to define.

I currently run this code here:

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

int rgb1 = 18;
int rgb2 = 17;
int LEDs = 11;
int ledFadeTime = 5;

Adafruit_NeoPixel strip1 = Adafruit_NeoPixel(LEDs, rgb1, NEO_GRB + NEO_KHZ800);
Adafruit_NeoPixel strip2 = Adafruit_NeoPixel(LEDs, rgb2, NEO_GRB + NEO_KHZ800);

void setup() {
  strip1.begin();
  strip1.show(); // Initialize all pixels to 'off'
  strip2.begin();
  strip2.show(); // Initialize all pixels to 'off'
}

void loop() {
  rgbFadeInAndOutStrip1(0, 0, 255, ledFadeTime); // Blue
  rgbFadeInAndOutStrip2(255, 0, 0, ledFadeTime); // red
}

void rgbFadeInAndOutStrip1(uint8_t red, uint8_t green, uint8_t blue, uint8_t wait) {
  for(uint8_t b = 0; b <255; b++) {
     for(uint8_t i=0; i < strip1.numPixels(); i++) {
        strip1.setPixelColor(i, red * b/255, green * b/255, blue * b/255);
     }

     strip1.show();
     delay(wait);
  };

  for(uint8_t b=255; b > 0; b--) {
     for(uint8_t i = 0; i < strip1.numPixels(); i++) {
        strip1.setPixelColor(i, red * b/255, green * b/255, blue * b/255);
     }
     strip1.show();
     delay(wait);
  };
};

void rgbFadeInAndOutStrip2(uint8_t red, uint8_t green, uint8_t blue, uint8_t wait) {
  for(uint8_t b = 0; b <255; b++) {
     for(uint8_t i=0; i < strip2.numPixels(); i++) {
        strip2.setPixelColor(i, red * b/255, green * b/255, blue * b/255);
     }

     strip2.show();
     delay(wait);
  };

  for(uint8_t b=255; b > 0; b--) {
     for(uint8_t i = 0; i < strip2.numPixels(); i++) {
        strip2.setPixelColor(i, red * b/255, green * b/255, blue * b/255);
     }
     strip2.show();
     delay(wait);
  };
};

```

Which works when trying out just one out of the 2. But when the LEDs fade out it has a pause (i still see a hint of blue on the strip). If i comment all the code out for the second strip2 and run that, it pulses just fine without the hint of blue or the delay to start bright again.

What could I be doing incorrectly?

# Answer
The “hint of blue on the strip” is a consequence of your second loop in `rgbFadeInAndOutStrip1()` ending with the test `b > 0`. Because of that, the last `strip1.setPixelColor()` call sets the color to (0,0,1), a faint blue, instead of (0,0,0), off. Here is some revised code that works ok:

```
#include <Adafruit_NeoPixel.h>
#include <avr/power.h>
enum { rgbPin1=8, rgbPin2=7, LEDcount=11, ledFadeTime=5};

Adafruit_NeoPixel strip1 = Adafruit_NeoPixel(LEDcount, rgbPin1);
Adafruit_NeoPixel strip2 = Adafruit_NeoPixel(LEDcount, rgbPin2);

void setup() {
  strip1.begin();
  strip1.show(); // Initialize all pixels to 'off'
  strip2.begin();
  strip2.show(); // Initialize all pixels to 'off'
}

void loop() {
  rgbFadeInAndOutStrip1(0, 0, 255, ledFadeTime); // Blue
  rgbFadeInAndOutStrip2(255, 0, 0, ledFadeTime); // red
}

void fadeStrip(Adafruit_NeoPixel *strip, int bval, int bdir, uint8_t red, uint8_t green, uint8_t blue, uint8_t wait) {
  for(uint8_t b=0; b<255; ++b) {
    bval += bdir;
    for(uint8_t i=0; i<strip->numPixels(); ++i) {
      strip->setPixelColor(i, red * bval/255, green * bval/255, blue * bval/255);
    }
    strip->show();
    delay(wait);
  }
}

void rgbFadeInAndOutStrip1(uint8_t red, uint8_t green, uint8_t blue, uint8_t wait) {
  fadeStrip(&strip1, -1, 1,   red, green, blue, wait);
  fadeStrip(&strip1, 255, -1, red, green, blue, wait);
}

void rgbFadeInAndOutStrip2(uint8_t red, uint8_t green, uint8_t blue, uint8_t wait) {
  fadeStrip(&strip2, -1, 1,   red, green, blue, wait);
  fadeStrip(&strip2, 255, -1, red, green, blue, wait);
}

```

Note, since I ran tests on an Uno rather than a Leonardo, I attached pixel strings to pins 7 and 8 rather than 17 and 18. I used `enum` to define constants, rather than declaring constants as variables, and factored some common code into functions rather than reduplicating it.

Following is another program (which I call neocycle6) you can use to test two strips. Note, it only counts colors down to 1 rather than 0 because I like the effect of leftover pixels glowing faintly. Also note: the round boards I used have only 7 LEDs each, so I set `PixelCount` to 7, not 11; this uses pins 7 and 8, not 17 and 18; I don't drive the brightness beyond 77 since the LEDs are so bright anyway; and it doesn't have an `#include <avr/power.h>` statement, which you can add if needed.

```
// Drive 2 sets of 7 ea. WS2812 NeoPixels through sets of colors.
// jw 11 September 2015
#include <Adafruit_NeoPixel.h>

// Select pin# connected to NeoPixels strand, and number of NeoPixels.
enum { PixelPinA=7, PixelPinB=8, PixelCount=7 };
// Create a NeoPixels device structure
Adafruit_NeoPixel pixelA = Adafruit_NeoPixel(PixelCount, PixelPinA);
Adafruit_NeoPixel pixelB = Adafruit_NeoPixel(PixelCount, PixelPinB);

void setup() {
  byte i, j=0;
  pixelA.begin();               // Init. NeoPixel data structure
  pixelB.begin();               // Init. NeoPixel data structure
}

uint8_t c=1, d=1, p=0, v=1;
void loop() {
  c += d;
  if (c>76)
    d = -1;                     // Go down when done going up
  else {
    if (c<2) {                  // Set up for next pixel
      d = 1; p = (p+1)%PixelCount;
      if (!p) ++v;              // Rotate the weights to next color
    }
  }

  pixelA.setPixelColor(p, c*(v&1), c*((v&2)/2), c*((v&4)/4));
  pixelB.setPixelColor(p, c*((v&2)/2), c*(v&1), c*((v&4)/4));
  pixelA.show();               // Show updated colors
  pixelB.show();               // Show updated colors
  delay(9 + 300/c);            // Ramp small numbers more slowly
}

```
> 1 votes

---
Tags: arduino-ide, arduino-leonardo, adafruit, rgb-led
---