message:
PWM-FILTERS -DAC

I want to implement a digital controller C(z) on an Arduino Uno
(transfer function in the z domain) in order to control a plant

    G(s) = 3750/[(s+10)(s+30)(s+100)].

I have implemented G(s) with electronics (op-amps, capacitors and
resistances). I want to realize C(z) on the Arduino Uno. The input to
the Arduino is the error signal `(reference − output of G)` and the
output of C(z) is the input of G(s). Finally, I will have a closed loop
system with negative unit feedback. The reference input is a unit step
signal (1 volt).

My problem is: how can I use PWM and filters in place of a DAC?

body:
If you want to use PWM in place of a DAC, the normal thing to do is to
use some kind of analog low-pass filter. However, many people skip the
filter when the signal is meant for some system that inherently acts as
a low-pass. Example: dimming an LED, where the human eye is the filter.

In your case, since your plant looks like a third order low-pass filter
with cuts at 1.6, 4.8 and 16 Hz, you can probably skip the filter.
If you output on pins 5 or 6, [the PWM frequency will be around
980 Hz](https://www.arduino.cc/en/Reference/analogWrite)
(exactly: fCPU/16384). At that frequency, your plant gain
relative to DC will be

G(j2π × 980 Hz) / G(0) ≈ 1.3 × 10−7 j

Probably low enough to not be an issue.


sender: user

message:
Arduino UNO with CD4510 Counter

I am new in Arduino but I have experience in electronics.

I was wondering how can I make a countdown timer using a CD4510 and an Arduino UNO. I know you would suggest that I should connect my seven segment display on the IO pins but I can't do that because I will use multiple seven segment displays.

sender: assistant

body:
The CD4510 does not seem at all appropriate for this task. It is a counter chip that counts up or down. You can do that with the Arduino. The output (of the CD4510) would be in "binary" and not suitable for driving a 7-segment display.

You can get 8 digit 7-segment displays on eBay for around $2. Surely that fits within your budget?


body: I can use CD4510 to make a countdown timer, I just need to connect CLOCK INPUT to the Digital IO pins located in the arduino microcontroller and use pulse with modulation (pwm) for the code


message:
Interrupt fires multiple times

I have a Photo Interrupter which I am using to count the RPM of a motor.

I am incrementing an integer to show the amount of interrupts there have been.

The issue is that there can be several interrupts fired for each time the "beam" of the Photo Interrupter is broken.

I have a 5mm length of plastic which breaks the "beam". If I make the plastic shorter than that, the Photo Interrupter doesn't pick up the break.

I am using the following, very basic code:

    int pin = 13;
    volatile  int tcnt = 0;
    volatile int state = LOW;

    void setup() {
      Serial.begin(9600);
      pinMode(pin, OUTPUT);
      attachInterrupt(0, blink, CHANGE);
    }

    void loop() {
      Serial.println(tcnt);
      digitalWrite(pin, state);
    }

    void blink() {
      tcnt = tcnt + 1;
      state = !state;
    }

body:
As far as it firing multiple times, are you aware that you have the interrupt mode set to CHANGE? This means the interrupt will fire once when something enters the beam, and again when something leaves the beam. You will probably want to set it to RISING or FALLING so that it only fires on one of those events, not both.

As to the not detecting issue I can think of a few reasons why this could be:

1. Your motor is moving so fast that the sensor changes again before it has had the chance to finish the interrupt service routine and reset the interrupt on the pin.
2. The photo interrupter you are using is too slow to report the piece of plastic passing through it. Sensors like this usually indicate a rise time and a fall time, and if it moves through the beam faster than these times it will not register the interruption.
3. The piece of plastic isn't large enough to block the beam. Depending on the photo interrupter, the beam used could be laser like and very narrow, or it could be wide and more like a flashlight. If it is more like the latter, you will need to have enough material present to block enough light to set off the sensor.


body:
Two other possible problems, apart from what Jake C has adressed in his answer are:

**1. Hardware bounce**

If your signal from the sensor isn't a clean transition from high to low but rather "bouncy" (see image below). The microcontroller will register multiple transitions in the meantime.

![Hardware bounce][1]

Solution to this would be to add a small capacitor (wil slow it down though) or add debouncing code... Best would be to get a "clean" sensor.

**2. Floating contact**

> When I even move my finger close to the wire running to PIN2 the interrupt fires.

That kinda seems like it's a floating contact, where it's not really connected to anything.

This is usually solved by using a pullup/pulldown resistor. Or maybe there is something wrong with the connection.

----------

Also:

> Maybe due to the type of sensor?

You should note the part number of the sensor or link a datasheet, so we can see if it's typical behaviour for this type of sensor.

  [1]: https://i.stack.imgur.com/6f1w9.gif


body:
I would recommend adding a comparator with hysteresis so as to get a clean digital pulse, pictured below:

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/EqgJp.png)

<!-- End schematic -->

This has the correct values.

I recommend the comparator with hysteresis as the phototransistors are prone to cause issues with interrupts even when used with pul-up/pull-down resistors, thus is as they very the voltage more than give a clean `0/1` digitally.

Here is your code, modified with the addition of `RISING` and of a 10mS delay.

    int pin = 13;
    volatile  int tcnt = 0;
    volatile int state = LOW;

    void setup() {
      Serial.begin(9600);
      pinMode(pin, OUTPUT);
      attachInterrupt(0, blink, RISING);
    }

    void loop() {
      Serial.println(tcnt);
      digitalWrite(pin, state);
       delay(10);
    }

    void blink() {
      tcnt = tcnt + 1;
      state = !state;
    }

This method produces very reliable results. It is also accurate with objects moving rapidly because of the interrupt.

_____
I would also say that the problem you have when you use a piece of plastic < 5mm is that the length of the slit in the sensor is *6.0±0.1*(seen below). If the plastic is less you probably find that the phototransistor still has enough IR falling on it to allow voltage to flow, but enough to trigger and interrupt. With the comparator you could probably use a smaller piece of plastic and find the voltage swing with a DMM and modify the voltage divider (**R1** and **R2**) to suite the needs.

![enter image description here][1]

  [1]: https://i.stack.imgur.com/4iHaF.jpg


body:
If you want to count RPM, maybe this link will help you:
http://rjbotics.blogspot.in/2015/07/counting-real-time-rpm-with-ir-sensors.html


message:
Arduino UNO with LMT86LP temperature sensor

I am trying to use the Arduino Uno with the LMT86LP temperature sensor, but I am getting strange output voltages from the sensor.

I have the pins (from left to right, flat side facing forward) as VDD, OUT, and GND. VDD is connected to 5V, GND to GND, and Vout to A0 (analog pin 0). The readings from the Arduino are consistently around 360 mV but should be somewhere around 1800 mV as I measured the output of the sensor using a multimeter and got a constant 1.8 V.

Right now the code is very simple. I am just doing `analogRead()` and printing to the Serial Monitor.

body:
The result from `analogRead()` is in counts of full scale, not in volts. Since you are using a 10-bit ADC, full scale is 1024.

1.8V/5V⋅1024=368.64


message:
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?

body:
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.


message:
Have I bricked my Arduino Uno? Problems with uploading to board

I can't upload sketches to my Arduino Uno.

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

body:
## It probably isn't bricked

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

Stay calm, and try the following steps ...

---

## Example board

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

![Arduino Uno major components][1]

Major components are:

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

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

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

---

## Check the power

### USB power

* Plug the board into your computer with the USB cable and check that the green "On" LED lights up.

* Use a multimeter and a couple of jumper leads to test between the 5V pin and the GND pin (arrowed at the bottom). You should get a reading of around 5.0 V (I got 5.04 V on mine).

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

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

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

### Power jack

* If you are using, or planning to use, the power jack (marked "power in" on the photo) disconnect the USB, and plug in a power supply - which should be 7 to 12 V DC with positive on the *center* pin.

* Measure the 5 V and 3.3 V pins as above. You should still see the same voltages on them.

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

---

## Check the power-on LED flash

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

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

---

## Try uploading a sketch

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

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

* The "L" LED should flash 3 times. This is because the main chip is being reset by a command from the uploading process.

* The "Rx" LED should flash quickly. This is the instructions from the uploading process trying to activate the bootloader.

* The "Tx" LED should flash quickly. This is the processor acknowledging the uploaded data.

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

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

### Check the board type

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

    avrdude: stk500_recv(): programmer is not responding

Check the board type:

![Board type menu][2]

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

### Check the comm port

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

Check the comm port:

![Comm port menu][3]

### Try a different PC / Mac if possible

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

### Do a loopback test

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

Wiring:

![Loopback test][4]

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

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

If nothing is echoed back, check:

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

---

## Test the Atmega16U2 chip

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

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

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

![Test the Atmega16U2 chip][5]

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

![ICSP header][6]

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

Connect up:

    Good board         Target Uno

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

Double-check your wiring.

Then on the "known good" board install the "Atmega_Board_Detector" sketch as described on the [Atmega bootloader programmer](http://www.gammon.com.au/bootloader) page. The code is at [GitHub - nickgammon/arduino_sketches](https://github.com/nickgammon/arduino_sketches). If you click the Download button on that page you will get a number of useful sketches. The one you want is called "Atmega_Board_Detector".

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

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

    Bootloader:

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

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

    First 256 bytes of program memory:

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

However if you get a message like this:

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

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

---

## Test the ATmega328P chip

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

![Test the ATmega328P chip][7]

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

![ICSP header][8]

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

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

    Good board       Target Uno

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

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

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

    Bootloader:

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

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

    First 256 bytes of program memory:

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

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

---

## Things you can fix

### Failed voltage regulator

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

---

### Failed ATmega16U2 chip

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

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

Examples of such devices plugged into the ICSP socket:

![USBtinyISP][9]

![AVRISP][10]

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

---

You can also get an FTDI cable, like this:

![Connect FTDI to Arduino][12]

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

![FTDI cable][11]

    FTDI    Arduino Uno

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

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

---

You can also use my [Atmega chip stand-alone programmer to upload .hex files](http://www.gammon.com.au/uploader) - this lets you copy the .hex file for a sketch onto an SD card, and then program the board via the ICSP header.

---

### Failed ATmega328P chip

The main processor can be replaced fairly easily if it is mounted in a socket. Get a replacement chip from somewhere like [Adafruit](https://www.adafruit.com/products/123) for around $US 6. Alternatively, try eBay. Try to get a chip which has the Optiboot bootloader already on it, to save hassle.

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

---

### ATmega328P responds but has no bootloader

I have a sketch at [Atmega bootloader programmer](http://www.gammon.com.au/bootloader) which will replace the Optiboot bootloader. The wiring is the same as for the chip detector sketch. The code is at [GitHub - nickgammon/arduino_sketches](https://github.com/nickgammon/arduino_sketches). If you click the Download button on that page you will get a number of useful sketches. The one you want is called "Atmega_Board_Programmer".

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

![Test the ATmega328P chip][7]

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

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

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

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

Type "G" to program the chip.

You should see:

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

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

---

## Watchdog timer problems

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

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

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

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

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

---

## Problems with the Mega2560 upload

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

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

Example code:

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

Solutions:

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

Or (more simply):

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

---

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

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

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

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

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

---

## References

* [Solving problems with uploading programs to your Arduino](http://www.gammon.com.au/forum/?id=11643)
* [Sketch to detect Atmega chip types](http://www.gammon.com.au/forum/?id=11633)
* [GitHub site with chip detector / bootloader programmer](https://github.com/nickgammon/arduino_sketches)
* [Atmega bootloader programmer](http://www.gammon.com.au/bootloader)
* [Atmega chip stand-alone programmer to upload .hex files](http://www.gammon.com.au/uploader)
* [Engbedded Atmel AVR® Fuse Calculator](http://www.engbedded.com/fusecalc)
* [Arduino Uno Rev3 pinouts photo](http://www.gammon.com.au/uno)

  [1]: https://i.stack.imgur.com/uxIPv.jpg
  [2]: https://i.stack.imgur.com/qDHGk.png
  [3]: https://i.stack.imgur.com/Ckt4q.png
  [4]: https://i.stack.imgur.com/0hfng.jpg
  [5]: https://i.stack.imgur.com/Pihx4.jpg
  [6]: https://i.stack.imgur.com/jwP1o.png
  [7]: https://i.stack.imgur.com/XQHMD.jpg
  [8]: https://i.stack.imgur.com/jwP1o.png
  [9]: https://i.stack.imgur.com/SedEP.jpg
  [10]: https://i.stack.imgur.com/glssw.jpg
  [11]: https://i.stack.imgur.com/Tkvzg.jpg
  [12]: https://i.stack.imgur.com/rdZTX.jpg


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

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

An example for stopping the upload:

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

See [Google Code issue][1].

  [1]: http://code.google.com/p/arduino/issues/detail?id=459


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

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

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

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

  [1]: https://www.adafruit.com/product/123


message:
XBee on Arduino Fio - how to read the status of a local digital XBee output pin?

I am using a Fio to control a set of relays. The unit uses an XBee (series 1 Pro) in transparent mode to receive commands over serial UART and everything works fine. The XBee is also configured for digital Input/Output Line Passing and the XBee on the Fio "mirrors" on an output pin the input state on a remote XBee and also this works fine.

How can I interrogate from the Fio the state of the output pin (e.g. D0) of the local (receiving) XBee? Is there an AT command that I could send via `Serial.println("ATxx")` that would trigger the XBee to send back over UART the status of the pin (high or low)?

body:
You cannot read the state of output pins via an AT command, you can only read the state of input pins using the ATIS command.

See: http://ftp1.digi.com/support/documentation/90000982_S.pdf


message:
How to use C Libraries for Arduino code

I have a code in Visual studio that I want to implement in Arduino. But
there is a problem. Many libraries usable in Visual Studio aren't usable
in the Arduino IDE. How can I use them in my Arduino code? To be
precise, the libraries I want to use are

<!-- language: lang-c++ -->

    #include <iostream>
    #include <iomanip>
    #include <queue>
    #include <string>
    #include <math.h>
    #include <ctime>

I know I have `<iostream>` available in Arduino. `<math.h>` is also
available I think along with the `<string>` library. The main problem is
to how to use `#include<queue>` and its functions such as
`priority_queue()` and other functions of iosteam like `.pop()`? Any
help would be highly appreciated.

body:
Some of the libraries you mention (iomanip, iostream, queue, string) are part of the STL - Standard Template Library. Whilst it does not ship with the IDE download, you can install it yourself. See [The Standard Template Library (STL) for AVR with C++ streams](http://andybrown.me.uk/wk/2011/01/15/the-standard-template-library-stl-for-avr-with-c-streams/) - a port to the Arduino by Andy Brown.

I have some [implementation notes here](http://www.gammon.com.au/forum/?id=11119).

Be aware that a lot of Arduinos don't have much RAM, so you need to use libraries like this with caution.

Library download: [AVR standard template library, version 1.1.1](http://andybrown.me.uk/wk/files/avr-stl-1.1.1.zip) - 197.29 kB


message:
Inappropriate ioctl for device

I am using an Arduino Uno and a Mac and trying to upload my code into the board.
I tried uploading the program from different computers(MacBook Air and Pro) and I still have this problem.

How do I fix this? I tried downloading the FTDI driver. I went to the website that they suggested and tried following the instructions. I even followed other posts in Stack Exchange but I still cannot upload the code.

### EDIT

Programmer -> AVRISP mkll

I am using a cable to connect to my Mac and I am using the Arduino software. The cable connected between the Arduino USB and Mac USB port.

I tried quitting and relaunching Arduino app. Once it launches I just press the upload button while my USB is plugged in. My available ports in the app are `/dev/cu.Bluetooth-Incoming-Port` and `/dev/cu.Bluetooth-Modem`

And this is the error

    avrdude: ser_open(): can't open device "/dev/cu.usbmodem1421": No such file or directory
    ioctl("TIOCMGET"): Inappropriate ioctl for device

body:
Plug your Uno into the Mac using a known good USB cable.

Go to the Apple menu -> About This Mac -> More Info -> System Report

Under the USB selection (on the left) please confirm whether or not you see something like this:

![Arduino USB in System Report][1]

You can also open a Terminal window and type:

    system_profiler SPUSBDataType

Amongst other things you should see:

    USB:

        USB High-Speed Bus:

          Host Controller Location: Built-in USB
          Host Controller Driver: AppleUSBEHCI
          PCI Device ID: 0x3b34
          PCI Revision ID: 0x0006
          PCI Vendor ID: 0x8086
          Bus Number: 0xfd

            Hub:

              Product ID: 0x2514
              Vendor ID: 0x0424  (SMSC)
              Version: 0.03
              Speed: Up to 480 Mb/sec
              Location ID: 0xfd100000 / 2
              Current Available (mA): 500
              Current Required (mA): 2

                Communication Device:

                  Product ID: 0x0043
                  Vendor ID: 0x2341
                  Version: 0.01
                  Serial Number: 9314036423335121A0B1
                  Speed: Up to 12 Mb/sec
                  Manufacturer: Arduino (www.arduino.cc)
                  Location ID: 0xfd130000 / 8
                  Current Available (mA): 500
                  Current Required (mA): 100

Note the "www.arduino.cc" entry.

In your Arduino IDE you should see the Arduino as a tty.usbmodemfd131 (or some similar number).

![Arduino Uno USB modem][2]

If you see all that it should work.

If not, please state in what way it differs.

> Programmer -> AVRISP mkll

The **Tools > Programmer** menu selection is only used when you do **Tools > Burn Bootloader** or "Upload Using Programmer. It is completely ignored when doing a standard "Upload". You should be doing an "Upload" (Command-U) not an "Upload using programmer" (Shift+Command+U). So it makes absolutely no difference what you select from the **Tools > Programmer** menu.

  [1]: https://i.stack.imgur.com/EQWxI.png
  [2]: https://i.stack.imgur.com/zcTbg.png


body: I've also had this error message when I've left another serial terminal connected to the same port the Arduino IDE is trying to use.


body: I got this error on my Macintosh system and the problem was that I needed to choose the correct port on the USB. Somehow it had auto-connected to a Bluetooth port which was listed under **Tools->Port** as `/dev/cu.Bluetooth-modem` and was my daughter's cell phone. I chose a port labeled `/dev/cu/wchusbserialfd`... and it worked fine.


body:
I solved this problem.  Maybe this post will help others.

I've come across this problem a couple of times.  I literally searched for hours for the answer and ended up using several suggestions.

Both scenarios I solved are documented below as 'Scenario A' and 'Scenario B':

======================
Scenario A

Plugged in a new Arduino Uno R3 board, successfully compiled the standard "Blink" sketch.  When I tried to upload it to the board, I got this message:

*Sketch uses 1,066 bytes (3%) of program storage space. Maximum is 32,256 bytes. Global variables use 9 bytes (0%) of dynamic memory, leaving 2,039 bytes for local variables. Maximum is 2,048 bytes. avrdude: ser_open(): can't open device "COM1": No such file or directory ioctl("TIOCMGET"): Inappropriate ioctl for device Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.*

The Port Options in the IDE (Tools--> Port) only showed  /dev/cu.incoming-bluetooth-port

Here's what worked:

1. Downloaded and [Installed the CH340 driver][1]
2. Removed the FTDI drivers from my mac.  Apple recently installed a new utility that prevents removal of what it considers to be critical components.

The process that enforces this rule is called csrutil.

You'll have to disable this process to remove the FTDI driver.  Then you'll need to re-enable it when you are done.  This required a restart in recovery mode.  Here's how to do that:

    a.)  power off the mac then hold 'command'+R during the restart until the image of the apple appears.
    b.)  when the screen refreshes, click on 'Utilities' menu then 'Terminal.
    c.)  type csrutil disable
    d.)  Hit enter
    e.)  Restart  [Note:  You may be able to execute the next two commands in the terminal before restarting.  I just didn't test it that way.  If the system will allow you to, then by all means run all three commands one after the other THEN restart and you should be on your way.]

3.  remove the FTDI drivers by opening the terminal program again and entering the following command:

           sudo rm -R /System/Library/Extensions/AppleUSBFTDI.kext

Type in your password when prompted.

4.  Restore the apple csrutil by following steps a and b above.  Task c will be the same EXCEPT you'll type this instead:

        csrutil enable

   Then follow steps d and e.

When you restart the arduino IDE, you should see a more comprehensive list of ports besides just the bluetooth port.

======================
Scenario B

This board was an import and clearly not an original Arduino/Genuino.  Attempts to load sketches resulted in this lovely error:

        Using Port                    : /dev/cu.usbmodem1421
        Using Programmer              : arduino
        Overriding Baud Rate          : 115200
avrdude: ser_open(): can't open device "/dev/cu.usbmodem1421": No such file or directory
ioctl("TIOCMGET"): Inappropriate ioctl for device

There was only one Port listed in the IDE, dev/cu.Bluetooth-Incoming-Port.

It had been a while since Scenario A had occurred and since then I'd installed a few OS updates.  Checked the drivers and low and behold, the darned FTDI drivers had RETURNED!!

I repeated the steps in scenario A above but the problem remained.

Then I installed an updated board configuration from arduino and it worked!  Testing on the first board I'd used under scenario A were successful as well.  Here's what I did:

1. In the IDE go to Tools-> Boards -> Boards Manager
2. I installed 'Arduino SAM Boards (32-bits ARM Cortex-M3) by Arduino version 1.6.8
3. Unplugged and replugged the USB cable into my arduino.
4. In the IDE go to Tools -> Port.  The /dev/cu.usbmodem1421 was listed as a port option.  Selected that.
5. Uploaded my sketch.
6. Bask in glory of SUCCESS!

I hope this was helpful to you.  I spent two days on Scenario A and 3 hours on Scenario B.

  [1]: http://www.wch.cn/download/CH341SER_MAC_ZIP.html


message:
Write to file in SD card in wave shield V3

I just started tinkering with Arduino. I'm curious to know though, is it possible to read and write to a file stored in the SD card in the Wave shield v3 by Elechouse? I'm able to play files stored in said SD card, but I don't know how I'd go about writing some logs. I'm using an Arduino Mega.

Thanks in advance.

body: No, you cannot.  The shield is basically a cheap WAV or AD4 (whatever THAT is) playing chip which loads the audio data direct from an (old, small) SD card.  The only control you have is IO pins that emulate pressing the buttons on an MP3 player.


message:
Choose the correct solar panel and battery for solar use

I am planning to build a weather station powered by solar power. I want to use an Arduino Nano because it's low power requirement. I want to connect some basic sensors to it (temperature, humidity…) as well as an anemometer, a wind vane and a rain gauge. The weather data should be sent wireless via 433 mhz to a raspberry pi, which acts as a web server. I do not have power cable access to the Arduino so solar is the only option.

Which solar panel should I use? I was planning to use 2 2.5W 5.5V panels which charge a Lithium-Ion battery which powers the Arduino using a step up converter. Assuming I have 2-4h of direct sunlight per day and I want to query the sensors every 5 minutes, how big of a battery should i choose? I don't want it to go out of power and want it to last a couple of days without sun.

body:
I won't be able to tell you which solar panel or battery to use, but I can tell you how to figure that out.

## Battery ##
For the battery there are a few different ways to figure this out:

 1. The most common way to do this at the professional level is to build the device and run it attached to an energy meter and measure it for an hour or two performing its usage, and use that to calculate how much it will use over a 48 hour period. That being said that type of test equipment is not really a hobbyist piece of equipment and probably not something you are wanting to obtain for this project.
 2. You can try and use the datasheets for all of your components to determine their idle and active current draw is, add them up for idle and active, adjust the values based upon the efficiency of your step up converter (so if it only 75% efficient, divide them by .75), guesstimate how long your sensor read process will take, multiply your active current draw times the voltage and times the time it will take (in hours, so if this is a few seconds, it will be a really small decimal), multiply your idle current draw times the voltage and times .083 hours (5 minutes), add those two together multiply it times 12 (12 - 5 minute periods per hour) and then by 48 (two days) and that will be an estimate of your energy usage for two days. Now this will be a very rough estimate as the datasheets only provide nominal values, and their actual usage in practice may be different, which leads me to the final option...
 3. A hybrid between the two above solutions. Set up your device and have it read the sensors and transmit continuously. Then use a multi-meter to measure the current usage of it actively being used. Repeat the measurement again but this time with it running on an indefinite timer to simulate being idle. Then take those two numbers and use the above formula substituting the datasheet estimates with your actual measurements to get a much more accurate picture of what your energy usage will be.

Once you have your energy usage (this will be in milli-Watt-Hours or mWH) pick a battery voltage you will be using (this is based on the charge circuit you are using, typically, single cell lithium ion batteries are 3.7 or 4.2, with multi-cell batteries being multiples of those), divide your energy by the voltage to get the power (in milli-Amp-Hours or mAH) and you'll want to pick a battery greater than that. You'll also want to double check the data sheet of your step up converter and see what the drop out voltage is, and then compare that to the datasheet for the battery and see at what capacity it hits that voltage. You'll want to make sure that it is at least 80%. Otherwise you'll have to pick a different battery with a larger capacity, or a different step up converter with a lower dropout voltage.

## Solar Panel ##
For the solar panel, what you will want to do is get a battery charger designed specifically for use with solar panels. This is because when it says 5.5v solar panel, that is it's nominal voltage in full sunlight, however, it most often will not be that and will vary greatly throughout the day. What this means is that solar panels are basically on unregulated power supply, and most battery chargers require a regulated power source. With a solar specific batter charger, it is designed such that it can handle voltage variation and sudden dropouts. Usually these chargers come with a recommendation as far as voltage and current requirements and those specifications should form the basis of your solar panel selection.

So for example, if you have a battery, on the datasheet it will list what its charge current is, and you'll want to make sure you have a charger circuit that can supply that amount of current. Then you'll want to take a look at the datasheet for the charger circuit, see what current it requires and then make sure that the solar panel can provide that current.


message:
Use Arduino to detect low battery state and shut it down

I wanted to know if it is possible to monitor a battery that is driving the Arduino and check its voltage. When the voltage drops below a certain level (i.E below 3.0V) it should shutdown and disconnect itself from the battery by using a relay or something. When the battery is full enough again it should power up again. Is that possible without any external sensors just by using the Arduino's inputs?

body:
It is not entirely beyond possible, in fact quite possible in theory.

I think the saying 'in theory, theory and reality are the same, but in reality they are not' is appropriate here.

So to monitor voltage, a simple voltage divider circuit can be used, and the Arduino can monitor that, and release a relay controlling the power line. The same relay could be wired to also reconnect when voltage reaches a threshold. I think the circuit actually requires 2 (or more) relays, and technically is it a kind of sensor, but since you indicated a relay was ok, it could work. So given those requirements, do you really need someone to draw it out, or were you just curious?

![enter image description here][1]

Simple battery monitoring from [http://arduinotronics.blogspot.com/2012/04/voltage-monitor.html][2]

  [1]: https://i.stack.imgur.com/8JvyC.png
  [2]: http://arduinotronics.blogspot.com/2012/04/voltage-monitor.html


body:
Have a look here
http://wp.josh.com/2014/11/06/battery-fuel-guage-with-zero-parts-and-zero-pins-on-avr/
It is for bare metal Atmel chip, but applicable to Arduino as well probably.
Step one in getting longer battery life is to move to a bare metal Atmel chip, choose ATMEGA or ATTINY depending on how many pins you need.
Also see my answer here
https://arduino.stackexchange.com/questions/6/what-are-or-how-do-i-use-the-power-saving-options-of-the-arduino-to-extend-bat/8556#8556


body:
I'm assuming Arduino is powered directly by the battery, and not via a voltage regulator. In that case you van measure VCC by first measuring the internal 1.1v voltage reference (in relation to Vcc). Since the internal 1.1v is constant and VCC will lower over time, the reading (0-1023) will increase.

See this article:
http://jeelabs.org/2012/05/04/measuring-vcc-via-the-bandgap/


message:
Industry Standard for Single-Board Computers?

Do Arduinos, or any other single-board computer, come in any sort of industry-standard form factor? I'm trying to sell management on using Arduino, but they are stuck on the question "what if Arduino goes out of business", and if I could answer "we can just switch over to using brand X because it's the same size and has the same connectors", my life would be much easier.

body:
* Whether or not the Arduino company goes out of business isn't all that relevant. For one thing, there are now two competing companies vying for the Arduino trademark - [arduino.cc](https://www.arduino.cc/) and [arduino.org](http://www.arduino.org/).

* The Arduino has such a ground-swell of popularity that clone boards are widely available on eBay and from other suppliers. While people are willing to buy them, someone will sell them.

* The design is open-source, which makes it a safer choice than other designs who keep their design proprietary. For one thing, it guarantees that someone will make compatible boards, even if Arduino(s) fold.

* The "heart" of the Arduino is (in most cases anyway) a chip from Atmel - so you really should ask if [Atmel](https://en.wikipedia.org/wiki/Atmel) will go out of business. Probably not, but in any case, an alternative supplier might just as easily go out of business.

* I wouldn't be building an "Arduino board" into a production system anyway - too much chance that wires would fall out of the prototyping sockets. However the prototyping board is good for learning about their capabilities, and testing your code.

> Do Arduinos, or any other single-board computer, come in any sort of industry-standard form factor?

I'm not aware of any industry-standard form factor. The Uno design has caused a *lot* of people to make "shields" that fit onto that form factor, so that is probably the closest you would get to an industry standard.


body:
If you need a real computer, there are nowadays various options based on the Intel NUC concept.
[The Gigabyte variant][1], for example. It also has GPIOS accessible through a normal pinheader, in case you need them.
And, being x86, there is virtualyl no risk of loosing the supplier.

[1]: http://www.gigabyte.us/products/list.aspx?s=47&ck=104


message:
iterate through values in an array of strings to print

I (think I) am trying to iterate through the values of an array and print the string to a tft. I have declared the array of 4 strings, and that works fine. But when I try to print it, I get garbage. Am I missing a nuance of print? Or do I just not understand how to use arrays and strings...?

The code is as follows:

Declarations:

    //Active System
    char hvacSystems[4][5] = {"Off", "Fan", "Cool", "Heat"};
    int activeSystem = 0;
    String displayActiveSystem = hvacSystems[activeSystem]; <-- Should now be String "off"

Use (note the fake if statement for the question)

      if(systemNeedsToBeCycled){
        activeSystem++;
        displayActiveSystem = hvacSystems[activeSystem]; <-- Should now be String "Fan"
        tft.print(displayActiveSystem);
      }

Instead I get random characters most of the time, sometimes nothing.

In case its a memory thing, please know that:

Sketch uses 26,480 bytes (92%) of program storage space. Maximum is 28,672 bytes. Global variables use 1,126 bytes (43%) of dynamic memory, leaving 1,434 bytes for local variables. Maximum is 2,560 bytes.

body:
I am not sure I understand 100% but here is my best shot. If the below is wrong
the issue is not due to being out of memory.
Try this

    //Active System
    char hvacSystems[] = {"Off", "Fan", "Cool", "Heat"};
    // or char hvacSystems[4] = {"Off", "Fan", "Cool", "Heat"}
    int activeSystem = 0;
    String displayActiveSystem = hvacSystems[activeSystem]; <-- Should now be String "off"

    if(systemNeedsToBeCycled){
        activeSystem++;
        displayActiveSystem = hvacSystems[activeSystem]; <-- Should now be String "Fan"
        tft.print(displayActiveSystem);
    }

Your line

char hvacSystems[4][5] = {"Off", "Fan", "Cool", "Heat"};

You are attempting to create a two dimensional array here. Essentially a 4x5 table. With your code if you do

tft.print(hvacSystems[0][1]);

It should give you "Off".  Basically you made a table that looks like

0{"Off", "Fan", "Cool", "Heat", null}

1{null, null, null, null, null}

2{null, null, null, null, null}

3{null, null, null, null, null }

Arrays:
https://www.arduino.cc/en/Reference/Array
2d Arrays:

http://forum.arduino.cc/index.php?topic=220385.0


body:
The problem does not appear to be what you think it is, because I can't reproduce it.

See this:

    //Active System
    char hvacSystems[4][5] = {"Off", "Fan", "Cool", "Heat"};
    int activeSystem = 0;

    String displayActiveSystem;

    bool systemNeedsToBeCycled = true;

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

      displayActiveSystem = hvacSystems[activeSystem]; // <-- Should now be String "off"

      Serial.println (displayActiveSystem);

      if(systemNeedsToBeCycled){
        activeSystem++;
        displayActiveSystem = hvacSystems[activeSystem]; // <-- Should now be String "Fan"
        Serial.println (displayActiveSystem);
        }
      }  // end of setup

    void loop ()
      {

      }  // end of loop

Output:

    Off
    Fan

Please post a complete sketch that reproduces the problem. The placement of variables, and their type, might influence the result.

I used Serial.println() to show the variable contents, which are what you expected.

---

Possibly this will work better:

    tft.print(displayActiveSystem.c_str ());


body:
If the variable `activeSystem` exceeds the length of the array, it's out of bounds, at which point the behavior is undefined.
In your case you get "garbage data", which is actually just data in memory after the array.

Because the is no implicit check for array bounds, you need to check them yourself.


body:
I think this is the correct way to create an array of C strings:

        char * hvacSystems[] = {"Off", "Fan", "Cool", "Heat"};
        int activeSystem = 0;
        char * displayActiveSystem = hvacSystems[activeSystem];

        if(systemNeedsToBeCycled){
            activeSystem++;    // make sure to set a bound for this variable
            displayActiveSystem = hvacSystems[activeSystem];
            tft.print(displayActiveSystem);
        }

Since strings are basically stored as char pointers so an array of strings is an array of char * variables. Or you could create an array of Arduino strings:

        String hvacSystems[] = {"Off", "Fan", "Cool", "Heat"};
        int activeSystem = 0;
        String displayActiveSystem = hvacSystems[activeSystem];

        if(systemNeedsToBeCycled){
            activeSystem++;    // make sure to set a bound for this variable
            displayActiveSystem = hvacSystems[activeSystem];
            tft.print(displayActiveSystem);
        }


message:
Arduino bluetooth module as a server

I was looking around becouse I need to simulate a OBDII device. I think about to use Arduino for that. I was reading some tutorials how to use bluetooth module but I didn't find any tutorial when Arduino is a server. Alway Android app is a server. Is there way to put SP server in Arduino and Android as a client? And do I need special shield/module for that? If you could gave me some links to tutorials or code would be grate.
Interesting for me would be also possibility to send data form computer by USB to Arduino then Arduino push it forward to Android. - but that is not must have, first possibility is more importand for me.

body:
There are two types of bluetooth devices for Arduino. Some are "slave" only and some are both "master or slave".

There is little difference in price so you should buy one that is master or slave.

This [page (HC-05)][1] describes one that appears to be commonly used but there are many and I do not have a recommendation. Some devices are in the form of small boards which connect to the pins on the Arduino (normally serial tx/rx) and some are shields that plug onto an Arduino. The article also shows the connection.

This appears to be an [ODBII bluetooth arduino forum thread][2] that uses bluetooth and ODBII. [Video][3]

By default Android is in bluetooth master mode. This [article][4] appears to show the Android programming required to enable a bluetooth slave.

  [1]: http://wiki.iteadstudio.com/Serial_Port_Bluetooth_Module_(Master/Slave)_:_HC-05
  [2]: http://forum.arduino.cc/index.php?topic=149453.0
  [3]: https://www.youtube.com/watch?v=iQki0TAHdRI
  [4]: https://stackoverflow.com/questions/8091184/android-device-as-a-slave-while-using-bluetooth


message:
Controlling DC motor speed?

I'm trying to control a DC motor through L293D motor controller

![circuit diagram using L293D motor controller and Arduino][1]

  [1]: https://i.stack.imgur.com/E21yz.jpg

    const int controlPin2 = 4; // connected to pin 2 on the H-bridge
        const int enablePin = 3;   // connected to pin 1 on the H-bridge

    void setup(){

      pinMode(controlPin2, OUTPUT);
      pinMode(enablePin, OUTPUT);

      digitalWrite(enablePin, LOW);
      digitalWrite(controlPin2, LOW);

    Serial.begin(9600);
    Serial.println("Ready");
    }

    void loop(){
    if (Serial.available() > 0) {
        int inByte = Serial.read();

        switch (inByte) {
        case '0':
      digitalWrite(enablePin, LOW);
       digitalWrite(controlPin2, LOW);
     Serial.println("OFF");
          break;
        case '1':

      digitalWrite(controlPin2, HIGH);
        analogWrite(enablePin, 50);
        Serial.println("CW slow");
          break;
              case '2':

      digitalWrite(controlPin2, HIGH);
        analogWrite(enablePin, 100);
        Serial.println("CW slow +");
          break;
              case '3':
      digitalWrite(controlPin2, HIGH);
        analogWrite(enablePin, 150);
        Serial.println("CW medium");
          break;
              case '4':
      digitalWrite(controlPin2, HIGH);
        analogWrite(enablePin, 200);
        Serial.println("CW fast");
          break;
              case '5':
      digitalWrite(controlPin2, HIGH);
        analogWrite(enablePin, 250);
        Serial.println("CW fast +");
          break;
        case '6':
      digitalWrite(controlPin2, LOW);
        analogWrite(enablePin, 50);
        Serial.println("CCW slow");
          break;
          case '7':
      digitalWrite(controlPin2, LOW);
        analogWrite(enablePin, 100);
            Serial.println("CCW slow +");
          break;
          case '8':
      digitalWrite(controlPin2, LOW);
        analogWrite(enablePin, 150);
            Serial.println("CCW medium");
          break;
           case '9':
      digitalWrite(controlPin2, LOW);
        analogWrite(enablePin, 250);
            Serial.println("CCW fast");
          break;
    }
    }
    }

It is working well except 1 to 5 are reversed:

- 1 should be the minimum speed
- 5 should be the maximum.

But it is back to front:

- 5 is the minimum speed
- 1 is the maximum speed

Any ideas?

body:
So first thing, you should try to be more disciplined with your code formatting and the question...

FYI: it's best to use #define as it doesn't use memory for storing pin numbers... It's like Find and Replace in a text editor, this:

    const int controlPin2 = 4; // connected to pin 2 on the H-bridge
    const int enablePin = 3;   // connected to pin 1 on the H-bridge

Becomes this:

    #define controlPin2 4  // connected to pin 2 on the H-bridge
    #define enablePin   3  // connected to pin 1 on the H-bridge

So this is the tidied up code, you can see the problem is a lot more approachable when the code is indented consistently, and good use of spaces and new lines is used...

    #define controlPin2 4  // connected to pin 2 on the H-bridge
    #define enablePin   3  // connected to pin 1 on the H-bridge

    void setup () {
     pinMode( controlPin2, OUTPUT );
     pinMode( enablePin, OUTPUT );

     digitalWrite( enablePin, LOW );
     digitalWrite( controlPin2, LOW );

     Serial.begin( 9600 );
     Serial.println( "Ready" );
    }

    void loop() {
     if ( Serial.available() > 0) {
      int inByte = Serial.read();

      switch ( inByte ) {

       case '0':
        digitalWrite( enablePin, LOW );
        digitalWrite( controlPin2, LOW );
        Serial.println( "OFF" );
       break;

       case '1':
        digitalWrite( controlPin2, HIGH );
        analogWrite( enablePin, 50 );
        Serial.println( "CW slow" );
       break;

       case '2':
        digitalWrite( controlPin2, HIGH );
        analogWrite( enablePin, 100 );
        Serial.println( "CW slow +" );
       break;

       case '3':
        digitalWrite( controlPin2, HIGH );
        analogWrite( enablePin, 150 );
        Serial.println( "CW medium" );
       break;

       case '4':
        digitalWrite( controlPin2, HIGH );
        analogWrite( enablePin, 200 );
        Serial.println( "CW fast" );
       break;

       case '5':
        digitalWrite( controlPin2, HIGH );
        analogWrite( enablePin, 250 );
        Serial.println( "CW fast +" );
       break;

       case '6':
        digitalWrite( controlPin2, LOW );
        analogWrite( enablePin, 50 );
        Serial.println( "CCW slow" );
       break;

       case '7':
        digitalWrite( controlPin2, LOW );
        analogWrite( enablePin, 100 );
        Serial.println( "CCW slow +" );
       break;

       case '8':
        digitalWrite( controlPin2, LOW );
        analogWrite( enablePin, 150 );
        Serial.println( "CCW medium" );
       break;

       case '9':
        digitalWrite( controlPin2, LOW );
        analogWrite( enablePin, 250 );
        Serial.println( "CCW fast" );
       break;

      }
     }
    }

So your actual problem is that you need to reverse cases 1, 2, 3, 4, 5 to be 5, 4, 3, 2, 1...

There are two solutions:

1. **Inelegant**: would be to simply change the case numbers, they don't have to be in-order.

2. **Elegant**: copy and paste the code in each of the 5 cases about.

The result of option 2 is as follows, please feel free to confirm this is working?

    #define controlPin2 4  // connected to pin 2 on the H-bridge
    #define enablePin   3  // connected to pin 1 on the H-bridge

    void setup () {
     pinMode( controlPin2, OUTPUT );
     pinMode( enablePin, OUTPUT );

     digitalWrite( enablePin, LOW );
     digitalWrite( controlPin2, LOW );

     Serial.begin( 9600 );
     Serial.println( "Ready" );
    }

    void loop() {
     if ( Serial.available() > 0) {
      int inByte = Serial.read();

      switch ( inByte ) {

       case '0':
        digitalWrite( controlPin2, HIGH );
        analogWrite( enablePin, 250 );
        Serial.println( "CW fast +" );
       break;

       case '1':
        digitalWrite( controlPin2, HIGH );
        analogWrite( enablePin, 200 );
        Serial.println( "CW fast" );
       break;

       case '2':
        digitalWrite( controlPin2, HIGH );
        analogWrite( enablePin, 150 );
        Serial.println( "CW medium" );
       break;

       case '3':
        digitalWrite( controlPin2, HIGH );
        analogWrite( enablePin, 100 );
        Serial.println( "CW slow +" );
       break;

       case '4':
        digitalWrite( controlPin2, HIGH );
        analogWrite( enablePin, 50 );
        Serial.println( "CW slow" );
       break;

       case '5':
        digitalWrite( enablePin, LOW );
        digitalWrite( controlPin2, LOW );
        Serial.println( "OFF" );
       break;

       case '6':
        digitalWrite( controlPin2, LOW );
        analogWrite( enablePin, 50 );
        Serial.println( "CCW slow" );
       break;

       case '7':
        digitalWrite( controlPin2, LOW );
        analogWrite( enablePin, 100 );
        Serial.println( "CCW slow +" );
       break;

       case '8':
        digitalWrite( controlPin2, LOW );
        analogWrite( enablePin, 150 );
        Serial.println( "CCW medium" );
       break;

       case '9':
        digitalWrite( controlPin2, LOW );
        analogWrite( enablePin, 250 );
        Serial.println( "CCW fast" );
       break;

      }
     }
    }


message:
xbee communication not established between arduino

I have 2 Xbee Series2 modules, one set to Coordinator AT (Connected to PC with XCTU via USB dongle) and other set to Router AT(Connected to Arduino is connected to PC USB... RX>TX  TX>RX and 5V GND)

http://continentalee.com.sg/xbee-adapter
My xbee adapter

I have the programme uploaded into Arduino, a very simple sketch to test xbee wireless communication.

Code is here

    char msg = ' '; //contains the message from arduino sender
    const int led = 13; //led at pin 13

    void setup() {
    Serial.begin(9600);//Remember that the baud must be the same on both arduinos
    pinMode(led,OUTPUT);
    }
    void loop() {
    while(Serial.available() > 0) {
               msg=(char) Serial.read();

               if(msg=='H') {
                   digitalWrite(led,HIGH);
               }
               if(msg=='L') {
                    digitalWrite(led,LOW);
               }
    delay(1000);
    }
    }

The problem comes.

When I type "H" in the Serial Com, the led light up, and the letter "H" appears in the XCTU console.

however, when I type something into the XCTU console, nothing appears on my Serial monitor and no light is seen on arduino

Thank you for your help in advance.

body:
Your example does not show your code that sends correctly but I will assume that it used 9600 speed and that the xbees are configured to 9600.

Not sure if this will help ...

> Arduino is connected to PC USB... RX>TX TX>RX

1) In this case maybe you should ensure that xbee tx is connected to the correct rx pin on the Arduino? I know you have stated this above but with the basic xbee configuration, if data works one way then it should also work the opposite way.

> however, when I type something into the XCTU console, nothing appears on my Serial monitor and no light is seen on arduino

2) Your example doesn't show any code to send data to XCTU and the pin13 LED will only light up when an 'H' is sent from XCTU

You could try this for better diagnostics

        void loop() {
    while(Serial.available() > 0) {
               msg=(char) Serial.read();

          Serial.print("data arrived from xctu: ");
          Serial.print(msg);
          Serial.println();

               if(msg=='H') {
                   digitalWrite(led,HIGH);
               }
               if(msg=='L') {
                    digitalWrite(led,LOW);
               }
    delay(1000);
    }
    }


message:
How to read pH value

I am trying to read the pH value from a analog pH meter, SEN-01454. From the source code I found, voltage maps to pH value. This is the code:

    pHArray[pHArrayIndex++]=analogRead(SensorPin);
          if(pHArrayIndex==ArrayLenth)pHArrayIndex=0;
          voltage = avergearray(pHArray, ArrayLenth)*5.0/1024;
          pHValue = 3.5*voltage+Offset;
          samplingTime=millis();

But then the value is not correct. So how do i actually do it.

The [example code from Wiki page][1] for product.

  [1]: http://dfrobot.com/wiki/index.php/PH_meter(SKU:_SEN0161)

body:
This is SOME of the code. We are missing the `avergearray()` function.. I suspect you're taking one reading and averaging it with both old & future ones, but this code clearly is meant to sit in a loop..

From another [source](http://www.sgbotic.com/index.php?dispatch=products.view&product_id=1454), I got this:

    /*
    # This sample codes is for testing the pH meter V1.0.
     # Editor : YouYou
     # Date   : 2013.10.12
     # Ver    : 0.1
     # Product: pH meter
     # SKU    : SEN0161
    */

    #define SensorPin 0          //pH meter Analog output to Arduino Analog Input 0
    unsigned long int avgValue;  //Store the average value of the sensor feedback
    float b;
    int buf[10],temp;

    void setup()
    {
      pinMode(13,OUTPUT);
      Serial.begin(9600);
      Serial.println("Ready");    //Test the serial monitor
    }
    void loop()
    {
      for(int i=0;i<10;i++)       //Get 10 sample value from the sensor for smooth the value
      {
        buf[i]=analogRead(SensorPin);
        delay(10);
      }
      for(int i=0;i<9;i++)        //sort the analog from small to large
      {
        for(int j=i+1;j<10;j++)
        {
          if(buf[i]>buf[j])
          {
            temp=buf[i];
            buf[i]=buf[j];
            buf[j]=temp;
          }
        }
      }
      avgValue=0;
      for(int i=2;i<8;i++)                      //take the average value of 6 center sample
        avgValue+=buf[i];
      float phValue=(float)avgValue*5.0/1024/6; //convert the analog into millivolt
      phValue=3.5*phValue;                      //convert the millivolt into pH value
      Serial.print("    pH:");
      Serial.print(phValue,2);
      Serial.println(" ");
      digitalWrite(13, HIGH);
      delay(800);
      digitalWrite(13, LOW);

    }

which reads in the array first and then averages it. Is this what your code does? If so, what sort of errors are you seeing?


message:
Change arduino.local server address

I have a Yun and I'm trying to change the URL I type in to access the Web UI.

I've successfully changed its hostname in `/etc/config/system`, which now lets me SSH in using the new name. However:

- Going to newname.local doesn't work (no response at all).
- Going to arduino.local pulls up the green page 'Wait a moment or click here...', after which no page is rendered.

How can I access my Yun by typing in newname.local in my browser?

body:
That should be working fine.

I just logged into my Yún and changed its name by editing that file.  I then restarted `avahi-daemon` since that is what broadcasts its name (faster to restart the daemon that reboot the whole Yún).

Browsing to the new name worked fine.

    matt@dell:~$ ssh root@arduino.local
    root@Arduino:~# vi /etc/config/system
    (edit the config file)
    root@Arduino:~# hostname skybridge
    (manually changing the hostname so I don't have to reboot)
    root@skybridge:~# /etc/init.d/avahi-daemon restart
    (restart the avahi daemon)

Browsing to `skybridge.local` now shows me the Arduino login as it should.

As a further test I have just rebooted my Yún so it runs everything from scratch and it still works fine.

There are a number of caches involved in the system, any of which may be getting in the way.  It could be that the browser has cached incorrect or out of date information about the FQDN (*fully qualified domain name*) for the name you have given your Yún, in which case just closing and re-opening your browser may help.  It may be that the mDNS lookup system on your computer (you haven't mentioned which operating system you are using, which is a big factor) has cached old or out-dated information for the FQDN, in which case flushing that cache may help (how you do that depends on your OS), or just rebooting your computer.

Incidentally, if you are on Linux (Windows lacks these basic networking facilities along with many other basic tools), you can query the network for your Arduino Yún with the `avahi-browse` and `avahi-resolve` commands.  OS X has similar tools, but I don't know off hand what the commands are:

    matt@dell:~$ avahi-browse _arduino._tcp
    +  wlan0 IPv4 skybridge                                     _arduino._tcp        local
    ^CGot SIGINT, quitting.
    matt@dell:~$ avahi-resolve -n skybridge.local
    skybridge.local 192.168.0.252


message:
How do I upload sketch (and parameters) through a user interface

I'm pretty new to Arduino and I'm developing my first real-world project.

I have a Arduino Mega with a full working sketch in it which is going to be placed in several distant places and I have a number of "mantainers" that will need to get to the place, connect the board with their Windows (Vista+) laptop (USB), upload a new version of the sketch (if available), download some data from EEPROM and change (if needed) some parameters stored in PROGMEM. This just to give you the full picture, now I come to the questions.

What I'm trying to attempt is to write (in c++) a software that gives non-programmers a UI to do this stuff easily, so I wonder:

 1. How do I load the .hex file to the board? I kinda got I have to use AVRdude: is there any c++ example/tutorial/library I can use not to reinvent the wheel?
 2. When can I write to PROGMEM? When I connect with the serial cable Arduino stops the running sketch, waits for a new sketch and, if it does not arrive, it starts the old sketch back again. I guess that is the time to write to PROGMEM: if there is a running sketch I cannot do it, am I right?

body:
1) Why not just

<!-- language: lang-c -->

    system("avrdude ...");

That's more or less what the Arduino IDE does.

2) If you really want to embed the data in the executable, see
[Embedding Blobs in
Binaries](http://gareus.org/wiki/embedding_resources_in_executables).
You would need to re-link and re-upload the program each time you change
that data. You won't need the Arduino IDE, as it's only job is basically
to call avr-g++ and avrdude. You _can_ use the IDE if you find it's CLI
easier than those of the standard tools.

If you put the data in EPPROM instead, the avrdude can upload it without
re-uploading the program.


body:
> How do I load the .hex file to the board? I kinda got I have to use AVRdude: is there any c++ example/tutorial/library I can use not to reinvent the wheel?

Yes, you have to use avrdude.  The simplest way is just to bundle avrdude.exe and the avrdude.conf file with your program and call it, along with its required parameters, with `system()` or some similar (eg `execv()`) method (or whatever Windows has decided to provide instead of those standard functions - who knows what goes through the minds of Windows developers...).

> When can I write to PROGMEM? When I connect with the serial cable Arduino stops the running sketch, waits for a new sketch and, if it does not arrive, it starts the old sketch back again. I guess that is the time to write to PROGMEM: if there is a running sketch I cannot do it, am I right?

When you upload a new sketch you are writing to PROGMEM.  That's really the only time you can do it.  Yes, there are ways you can write pages of data to PROGMEM, and that's exactly what the bootloader does when you upload a sketch, but manipulating individual variables in PROGMEM is not possible without major brain surgery being done in your sketch.  To store these kind of tweakable parameters you would normally use the EEPROM.

It can also be good to use external storage for some of these things to - either an SD card (overkill) or an external SPI or I2C EEPROM or Flash chip.  This keeps all the data completely separate from your sketch so you can never overwrite that data when you upload a new sketch.

It is, of course, up to your sketch to provide some kind of interface to tweak the settings, whether stored in internal EEPROM or an external EEPROM chip.  Creating some kind of serial protocol which your C++ program can interface with will be essential.  Only while your sketch is running will you be able to change those variables.  If you don't want to allow end users access to that interface then one method could be to have a separate sketch which is a "calibration and configuration" sketch which your program uploads in order to adjust the settings.  Once you have finished it then re-uploads the original (or new) sketch to allow normal operation again.


body:
The avrdude/upload part has been fairly well covered by the other answers, but what has not been mentioned yet is that it is fairy trivial to modify program memory contents by modifying the hex file to be uploaded.

Basically, you just write hex-encoded bytes in the correct place in the file, and then update the checksum at the end of each line you modify.  It can help if you put a readily recognizable placeholder sequence in the desired location in your source code, which you can look for in the hex file as an extra verification you are making your substitutions in the correct place.  This is fairly straightforward string processing and unsigned byte math which you can accomplish in the language of your choice.  There are also tools which can convert between hex files and binary images, and probably tools or libraries which can fix the checksums for you.

Do pay attention to the license terms of avrdude and any other non-original code or tools you distribute.


message:
Reading Arduino from Java is way too slow

I am trying to write a simple Java program to display the analog input fed to an Arduino board upon a stimulus from a user on some physical sensors.

If I use the Arduino program itself and look at the serial monitor, I see the analog read based on user input updated instantly. However, when reading the input from my Java program, there is a significant delay (8-12 seconds) between the physical stimulus and the display of the value.

The code uploaded to Arduino is very simple, just cycle through a bunch of analog ports and print the data:

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

    void loop()
      digitalWrite(30, HIGH);

      for (int i = 0; i < 10; i++) {
        int sensorValue = analogRead(i);
        Serial.print(String(i) + ":");
        Serial.println(sensorValue);
      }
    }

The Java code I am using is almost entirely copied from the example provided [here](http://playground.arduino.cc/Interfacing/Java), with the exception that I updated the port name to work for my system (Mac OS X 10.10.3).

Here is the Java code:

    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.io.OutputStream;
    import gnu.io.CommPortIdentifier;
    import gnu.io.SerialPort;
    import gnu.io.SerialPortEvent;
    import gnu.io.SerialPortEventListener;
    import java.util.Enumeration;

    public class SerialTest implements SerialPortEventListener {

     SerialPort serialPort;

        /** The port we're normally going to use. */
     private static final String PORT_NAMES[] = {
       "/dev/cu.usbmodem1411",
                "/dev/cu.usbmodem1451",
     };

     /**
     * A BufferedReader which will be fed by a InputStreamReader
     * converting the bytes into characters
     * making the displayed results codepage independent
     */
     private BufferedReader input;

     /** The output stream to the port */
     private OutputStream output;

     /** Milliseconds to block while waiting for port open */
     private static final int TIME_OUT = 2000;

     /** Default bits per second for COM port. */
     private static final int DATA_RATE = 9600;

     public void initialize() {
      CommPortIdentifier portId = null;
      Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();

      //First, Find an instance of serial port as set in PORT_NAMES.
      while (portEnum.hasMoreElements()) {
       CommPortIdentifier currPortId = (CommPortIdentifier) portEnum.nextElement();
       for (String portName : PORT_NAMES) {
        if (currPortId.getName().equals(portName)) {
         portId = currPortId;
         break;
        }
       }
      }
      if (portId == null) {
       System.out.println("Could not find COM port.");
       return;
      }

      try {
       // open serial port, and use class name for the appName.
       serialPort = (SerialPort) portId.open(this.getClass().getName(),
         TIME_OUT);

       // set port parameters
       serialPort.setSerialPortParams(DATA_RATE,
         SerialPort.DATABITS_8,
         SerialPort.STOPBITS_1,
         SerialPort.PARITY_NONE);

       // open the streams
       input = new BufferedReader(new InputStreamReader(serialPort.getInputStream()));
       output = serialPort.getOutputStream();

       // add event listeners
       serialPort.addEventListener(this);
       serialPort.notifyOnDataAvailable(true);
      } catch (Exception e) {
       System.err.println(e.toString());
      }
     }

     /**
      * This should be called when you stop using the port.
      * This will prevent port locking on platforms like Linux.
      */
     public synchronized void close() {
      if (serialPort != null) {
       serialPort.removeEventListener();
       serialPort.close();
      }
     }

     /**
      * Handle an event on the serial port. Read the data and print it.
      */
     public synchronized void serialEvent(SerialPortEvent oEvent) {
      if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
       try {
        String inputLine=input.readLine();
        System.out.println(inputLine);
       } catch (Exception e) {
        System.err.println(e.toString());
       }
      }
      // Ignore all the other eventTypes, but you should consider the other ones.
     }

     public static void main(String[] args) throws Exception {
      SerialTest main = new SerialTest();
      main.initialize();
      Thread t=new Thread() {
       public void run() {
        //the following line will keep this app alive for 1000 seconds,
        //waiting for events to occur and responding to them (printing incoming messages to console).
        try {Thread.sleep(1000000);} catch (InterruptedException ie) {}
       }
      };
      t.start();
      System.out.println("Started");
     }
    }

All the program does is print out the values of the Arduino serial monitor, yet it takes way longer (8-12 seconds) through Java than it does from the Arduino program itself.

1) Why is this happening?
2) How do I fix it?

body:
Timing tests show that the Java code lags something like 25 or more seconds behind the input from the Arduino. This can be fixed by changing in the Java code these lines:

           try {
                String inputLine=input.readLine();
                System.out.println(inputLine);
            } catch (Exception e) {

to:

           try {
                while (input.ready ())
                  {
                  String inputLine=input.readLine();
                  System.out.println(inputLine);
                  }
            } catch (Exception e) {

This extra loop "drains" the input buffer of data in the one serialEvent call, rather than relying upon a serialEvent call per line of data.

I found when testing that the output is now highly responsive, even without a delay on the Arduino side.

---

My other answer of adding a `delay` call slowed output down enough for the Java app to catch up, but I must admit it isn't the best solution.


body:
One more thing you could do is create a `while(true)` loop, after `initialize()` and call `input.readLine()`, so that you don't wait for the event to appear.

For some reason the event is delayed, but doing the while loop hasn't created any issues or exceptions for me so far.

My code is like this:

    public void initialize() {
       //initializing stuff
       while(true){
           try {
               String inputLine = input.readLine();
               //do stuff here
           } catch (Exception e) {
               System.err.println(e.toString());
           }
       }
    }


message:
Blutooth shield LED control

I am trying to control a led ON/OFF using Arduino UNO and a Bluetooth shield

I have this

![enter image description here][1]

![enter image description here][2]

![enter image description here][3]

which is based on hc-05. The tutorials I found about hc-05 are not working for me. I have the hc-05 embedded in the shield and I did not  find any tutorials  for this shield.

Here is my code (it is working when I use the USB serial ctrl + shift + m).

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

    Serial.begin( 9600 );
    Serial.println( "Ready" );
    }

    void loop() {
    if ( Serial.available() > 0) {
        int inByte = Serial.read();

        switch ( inByte ) {

            case '0':
                digitalWrite( 13, LOW );
            break;

            case '1':
                digitalWrite( 13, HIGH );
            break;

        }
     }
    }

I connected my android phone to the shield successfully using blurterm2. When I send 1 or 0 nothing happens. What am I missing?

  [1]: https://i.stack.imgur.com/35Gsq.jpg
  [2]: https://i.stack.imgur.com/Sgi9C.jpg
  [3]: https://i.stack.imgur.com/o7cPz.jpg

body:
Have you tried the turning just running a simple program to check if the led still works, such as

    void setup () {
    pinMode( 13, OUTPUT );
    }
    void loop() {
     digitalWrite( 13, HIGH );
     delay(1000);
     digitalWrite(13,LOW);
     delay(1000);
    }


body:
From your code I cannot see anything that actually initializes the shield and tells it what pins to use and how to use them. This github (https://github.com/jdunmire/HC05) has a library for the HC-05 shield and it appears to have instructions for setting baud rate and all of that good stuff.

Also, their read-me mentions that, if properly configured, you should see traffic to and from the shield in your serial monitor. Are you seeing any traffic?

NOTE: This tutorial (http://www.instructables.com/id/Arduino-AND-Bluetooth-HC-05-Connecting-easily/?ALLSTEPS) seems to have step by step instructions to do exactly what you are asking.


body: You should use a **different baud rate** if your hc-05 does not work with the code. The default is 9600. Use this baud rate and if not, try to find out the baud rate using AT commands, you will get several tutorials on this.


body:
Here is your problem:

    if ( Serial.available() > 0) {
    int inByte = Serial.read();

You are not listening to the bluetooth-hardware, but to the build-in serial port of the Arduino.

I had a look at the url you can see on the board, but i could not find any example code. If you are lucky your bluetooth should might be compatible with the freetronics bluetooth shield, which has some [example code on the bottom of this page][1] to get you started:

    #include <SoftwareSerial.h>

    SoftwareSerial bt(2,3); // RX, TX

    int thisByte = 33;

    void setup() {
      bt.begin(9600);
      bt.println("ASCII Table ~ Character Map");
    }

    void loop() {
      bt.write(thisByte);

      bt.print(", dec: ");
      bt.print(thisByte);
      bt.print(", hex: ");
      bt.print(thisByte, HEX);
      bt.print(", oct: ");
      bt.print(thisByte, OCT);
      bt.print(", bin: ");
      bt.println(thisByte, BIN);

      if(thisByte == 126) {
        thisByte = 32;
      }
      thisByte++;
    }

This only sends, and "bt" is your bluetooth hardware here. It behaves like the Serial hardware for the most part.

Note: based on your picture, you might have to change the RX/TX pins on your board to 2,3 - currently they are set to 2,4.

  [1]: http://www.freetronics.com.au/pages/bluetooth-shield-quickstart-guide


message:
xBox receiver code output is scrambled

I'm running the following code:

    #include <XBOXRECV.h>

    // Satisfy the IDE, which needs to see the include statment in the ino too.
    #ifdef dobogusinclude
    #include <spi4teensy3.h>
    #include <SPI.h>
    #endif

    USB Usb;
    XBOXRECV Xbox(&Usb);

    void setup() {
      Serial.begin(115200);
    #if !defined(__MIPSEL__)
      while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
    #endif
      if (Usb.Init() == -1) {
        Serial.print(F("\r\nOSC did not start"));
        while (1); //halt
      }
      Serial.print(F("\r\nXbox Wireless Receiver Library Started"));

    }

    void loop() {
      Usb.Task();
      if (Xbox.XboxReceiverConnected) {
        if (Xbox.getAnalogHat(LeftHatY) == 0) {
          Serial.print(Xbox.getAnalogHat(LeftHatY));
        }
       Serial.print("TEST");
      }
    }

After running the example that the library includes and a spin off I wrote for test purposes I keep getting random output, this is just some of it:

> 9�]==�=�~=���y��:.�:�:����9�=��������:�:�\=���^=�?�}�:^���:�|]=9�\=_�_�������:�ܗ��.\�~=���

body: Seems like wrong baud-rate. Change baud-rate in the Arduino IDE serial monitor.


message:
Is it possible to setup a CAN-BUS Arduino Shield to communicate with SocketCAN for UNIX?

I have an Arduino + SparkFun CAN shield, and I was hoping to set it up to work with candump on an Ubuntu system. Is this doable, or is candump made specifically for raspberry Pi's?

body:
Yes. Normally you would write a linux kernel driver to communicate with your device (arduino) following your own protocol, but SocketCAN provides by default a way to interface with [Lawicel](http://www.can232.com/) dongles, whose communication protocol is publicly available: [CANUSB / CAN232 protocol](http://www.can232.com/docs/canusb_manual.pdf).

Many people have built arduino sketches that implement this protocol so you can use your arduino with SocketCAN in Linux (candump, cansniff...) as if it were a Lawicel dongle.

You may find this useful:

https://github.com/autowp/arduino-canhacker

https://github.com/kahiroka/slcanuino


message:
Writing MIDI Notes More Quickly to a Shift Register with Arduino

I'm working on an Arduino code which will interpret a given MIDI note message and output the corresponding note number to a string of LEDs as a binary integer. I have adapted it from existing code found on the site [Notes & Volts](http://www.notesandvolts.com/2015/02/midi-and-arduino-build-midi-input.html) which features a similar circuit designed to trigger an LED every time a key is pressed.

My circuit takes this further by telling the user exactly *which* note is being pressed. The note value byte is information is passed to a 74HC595 shift register which displays the note as a binary via a line of LEDs.

In a loose sense the code I have adapted "works". When a key is pressed a series of LEDs light up corresponding to the MIDI note designated to that key. The issue is that this only happens sporadically. Many times a key press won’t be followed by any LEDs but other times it will. Even quick, successive presses tend to result in only a handful of "read" notes.

Why does this happen? To my intuition it would seem that the Arduino is "missing" notes, that is, spending so many clock cycles writing bits to the shift register that it falls out of sync with incoming bytes from the keyboard. Notes & Volts describes almost this exact situation in one of their [instructional videos](http://www.notesandvolts.com/2015/02/midi-for-arduino-input-test.html) (relevant part at around 6:57). The author cautions against including too many time consuming processes in the code but doesn't mention how many is *too* many. I can only assume that a ShiftOut command takes a good deal longer than a digitalWrite and that this explains why the example code works but my adaptation does not. Given this information, how long exactly does ShiftOut take and what could be done to speed up my program?

    #include <MIDI.h>
    MIDI_CREATE_DEFAULT_INSTANCE();

    int latchPin = 8;
    int clockPin = 12;
    int dataPin = 11;  //The pins I am using

    void note_On(byte channel, byte pitch, byte velocity) {  //Runs when note is pressed

      digitalWrite(latchPin, LOW);
      shiftOut(dataPin, clockPin, MSBFIRST, pitch);
      digitalWrite(latchPin, HIGH);  //Write 'pitch' to 74HC595. Standard fare
    }

    void note_Off(byte channel, byte pitch, byte velocity){ //Writes '0' when note is off (all LEDs off)
      digitalWrite(latchPin, LOW);
      shiftOut(dataPin, clockPin, MSBFIRST, 0x00);
      digitalWrite(latchPin, HIGH);
    }
    void setup() {
      pinMode(latchPin, OUTPUT);
      pinMode(clockPin, OUTPUT);
      pinMode(dataPin, OUTPUT);

      MIDI.begin(MIDI_CHANNEL_OMNI);
      MIDI.setHandleNoteOn(note_On);
      MIDI.setHandleNoteOff(note_Off);
    }

      void loop() {
      MIDI.read();  //This function which must be re-run in quick succession
    }

###UPDATE###

@CL @Nick I wrote a code comparing the execution time difference between shiftOut and digitalWrite. While I am not perfectly confident in all of the numbers (1K digitalWrites takes a full 44mS??) one result did not surprise me - shiftOut is slower. By my numbers it is 3.75 times slower. That said, I welcome critiques on my methodology and I will address them as soon as I can. In the meantime I will make a point to research Arduino SPI and welcome any other alternatives to shiftOut.

    int latchPin = 8;       //Declaration of serial register pins
    int clockPin = 12;
    int dataPin = 11;

    int led = 13;          //On-board LED

    void setup() {
      pinMode(latchPin, OUTPUT);
      pinMode(clockPin, OUTPUT);
      pinMode(dataPin, OUTPUT);

      Serial.begin(9600);

      pinMode(led, OUTPUT);

    }

    void loop() {

      unsigned long startTime = millis();    //Writes to SR 1K times.
      for(int i = 0; i < 1000; i++){       //Prints difference between
        digitalWrite(latchPin, LOW);       //start and end times.
        shiftOut(dataPin, clockPin, MSBFIRST, 0xFF);
        digitalWrite(latchPin, HIGH);
      }

      Serial.print("\nsO:");
      Serial.print(millis() - startTime);

      delay(1000);

      startTime = millis();
      for(int i = 0; i < 8000; i++){    //Performs digitalWrite 8K times
        digitalWrite(led, HIGH);
      }

      Serial.print("\t\tdW:");          //
      Serial.print(millis() - startTime);

      delay(1000);
    }

**UPDATE**
While working on a [similar issue][1] I discovered that a dramatic change to my code seems to perfectly clear up the issue. I'd still like to know why this particular example does not, however, so I'll keep poking around until I get somewhere.

  [1]: https://arduino.stackexchange.com/questions/14054/interfacing-an-attiny85-with-midi-via-software-serial/14304#14304

body:
`shiftOut` is slow, yes.  It is basically "bit banging" a synchronous serial interface, which is a bit daft really when the Arduino has a hardware synchronous serial interface built in that can operate at much higher speeds.

That built in synchronous serial interface is called **SPI**.  I suggest you switch to SPI instead of shiftOut.

Also you should check what codes the MIDI keyboard is actually sending out.  I had a similar experience to you recently, but as far as I can tell it's down to the keyboard, not my software.  I built a system which reads in MIDI NoteOn codes through a serial port and plays a sample of a bass guitar at the right pitch.  The system worked perfectly when wired to the computer through a USB MIDI adapter, but as soon as I connected it to a keyboard (I don't have one, so I only had the one chance to test it recently with a real keyboard) it would only react to a key pressed after a long delay.  Almost as if the keyboard only sends a NoteOn if there is nothing happening for a while, and sends something else at other times.  I need to examine the keyboard's output data in more detail to see exactly what is being sent and why.

You might like to manually examine the MIDI codes being sent by the keyboard to be sure that it is actually sending a NoteOn when you think it should be and not something else (it'd be very interesting to see the results of your experiments too).


body:
I can't believe it is the shiftOut that is the issue. There is more going on here than meets the eye. I wrote a [MIDI decoder](http://www.gammon.com.au/forum/?id=12746) a while back. That reads from MIDI and outputs to serial. That would be a **lot** slower than doing one shiftOut. It runs perfectly, not just with you sitting there tapping notes, but with the synth generating its inbuilt music. See [video of it in action](https://vimeo.com/80328016).

Either the library is doing something weird, or your 74HC595 is wired strangely. Do you have current-limiting resistors for each LED? Please show your wiring.

Also add a Serial print to display when your `note_On` and `note_Off` are called, and with what values. In my test I was able to connect MIDI up to Software Serial (pins D2 and D3 in my case) which was fine for receiving MIDI.


message:
Standalone Atmega 2560 ISP program

First I need to say, I'm a complete electrics newbie, so I need your help.

I have got a standalone Atmega 2560, which I want to program. I connected MISO, MOSI, SCK, RESET, 5V and GND to an Arduino Uno.
In addition a 16MHZ oscillator is connected to XTAL1 and XTAL2 plus I pull all VINs of the Atmega with a 100nF to GND. Plus I connected a separate VIN and GND to the 2560.

I programmed the Arduino Uno as an "Arduino as ISP". Afterwards I connected the 2560 as mentioned above, changed the board to "Mega 2560" and tried to upload a sketch through the Arduino and I get the error message:
avrdude: stk500v2_getsync(): timeout communicating with programmer

Is there something I missed?

Cheers
jb

body:
I have a [sketch that programs bootloaders](http://www.gammon.com.au/bootloader). A side-effect of that sketch is it fixes up the "divide clock by 8" fuse.

It looks like the wiring will be the same, but cross-check on that page (scroll down to the part about programming the Mega2560).

Once a bootloader is installed you could use it, if you get an FTDI cable, or simply go back to using the ArduinoISP now that the fuse is fixed.