body:
I have arduino Pro Mini 3.3V version with hc-05 module connected to 3.3V/GND and RXI/TX0 pins. I am then using my android phone to connect to the module. It shows up and pairs fine. Then I use BlueTerm app to view the output. I am seeing output that is occasionally as expected but mostly partially corrupted (characters replaced with random characters).

I am using 9600 baud rate and trasmitting the following:

    void serialTransmit(int data){
      // send to raspberry pi or other device(s).
      Serial.print("Serial Transmit: ");
      Serial.println(data); // this is hard coded as "12" for testing
    }

I tried switching rx/tx pins around but got same corrupt output. Tried changing baud rate but then it wouldn't transmit anything at all and default rate is 9600 so that was expected.

What could be the cause?

title: Corrupted output from HC-05 Bluetooth module

Answers: 3

body:
First thing to try:

Connect a 2.2k - 10k resistor from the arduino RX pin (the hc-05 tx pin) to ground.

If that didn't work, I recommend getting everything into a known state and eliminating some complexity. So, first let's remove the Android software from the equation.  And second, let's put the module into a known baud rate.

To do this wire up the arduino and module like this:![schematic][1]

Notice that the Key pin is connected to 3.3v.  That will ensure the module is at 38400 baud on power up.

Connect the arduino to your computer with the FTDI cable.  Upload the following sketch:

    /* Serial Loop */

    #include <SoftwareSerial.h>

    #define rxPin 8
    #define txPin 9

    SoftwareSerial mySerial(rxPin, txPin); // RX, TX
    char myChar ;

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

      mySerial.begin(38400);
      mySerial.println("AT");
    }

    void loop() {
      while (mySerial.available()) {
        myChar = mySerial.read();
        Serial.print(myChar);
      }

      while (Serial.available()) {
        myChar = Serial.read();
        Serial.print(myChar); //echo
        mySerial.print(myChar);
      }
    }

With the sketch now uploaded and running, open the Arduino serial console and enter these AT commands. The serial console baud rate should be set to 9600 and line endings should be "Both NL & CR"

    AT+ORGL //back to factory settings
    AT+ROLE=0 //slave role - transparent serial bridge
    AT+UART=9600,0,0 //default baud rate
    AT+INIT //init module

You should get "OK" back from the module after each command. If you've gotten this far, we know the module is working fine and we know what baud rate it will default to now.

Hook the module back up the way you had it before.  Make sure 3.3v is disconnected from key pin and make sure you have added the pulldown resistor on the RX line. Cycle the power to the module. The module should start up running 9600 baud, slave mode. Delete the module from the Android pairing list and re-pair it.  The name probably will have changed.  Hopefully it works correctly now.

Cheers

  [1]: https://i.stack.imgur.com/4zcck.png

body:
Add the module as software serial then add these lines to setup() these line tell us the Bluetooth to turn into data mode:

    bluetooth.begin(115200);
    bluetooth.print("$$$");
    delay(100);
    bluetooth.println("U,9600,N");
    bluetooth.begin(9600);

body:
I have the same problem with arduino pro mini and HC-06, only change the baud rate of your BTserial port... try diferent baud rates in my case:

    Serial.begin(9600);
    Serial.println("AT");

    BTSerial.begin(2400);
    BTSerial.println("AT");

Works fine, it happens because the arduino try to "understand" the module, but if the module speaks other leanguage, the arduino will never understand the command.

like me... sorry for my bad english. se ya.


body:
I'm trying to make an RF remote control using ATtiny85 running at 8MHz on internal oscillator, [this cheap RF 434MHz transmitter module](http://www.wenshing.com.tw/Products/RF_Module/ASK_RF_Transmitter_Module/TWS-DS-3_433.92MHz_Miniaturization_Wireless_Transmitter_Module/) (like the one below), and VirtualWire lib, **but had no success so far**.

![RF transmitter][1]

So, before I go any further, **is it possible to use VirtualWire with ATtiny85 running at 3.6V and 8MHz with its internal oscillator? If so, how?**

I've found a few scattered sources of information on the Net about it, but couldn't make much sense of it.

I have build ATMega328 versions of the receiver and transmitter using VirtualWire without any major problems. Both modules talk to each other will very little data drop out. Now, when I tried to replace the ATMega328 transmitter with a smaller version using the ATtiny85, I'm having problems.

Here are the symptoms:

1. The major one seem to be that when I add the VirtualWire include, **my sketch seems to slow down a lot**. So I figure it's a timing issue. But I'm not sure what the problem is.

2. I put a scope on ATtiny85 pin 6 (PB1) but **I don't see anything being transmitted**. I think I've messed up with the pin names.

3. I can make the LED blink and also can read the buttons without problems.

Here are the schematics and the board design for the remote controller:

![RC schematic][2]

The board is currently powered by 2 AA NiMH batteries that are currently at 2.6V. I can make the ATtiny85 blink with that voltage. I plan to power the RC with a 3.6V CR2 lithum battery.

Here are more details of my development enviroment:

* Arduino IDE 1.05
* I'm using ATtiny cores [from here](https://docs.google.com/file/d/0B4cPTBXMMjz9Q0NWN3Q1cWhuV0U/edit?pli=1)
* I'm programming the ATtiny85 using an Arduino UNO R3 as ISP, without problems (it's working as I can make the ATtiny85 blink an LED).

And here's my code:

    #include <VirtualWire.h>

    #define VCC_PIN  A1
    #define BTN_PIN  A2
    #define LED_PIN  A3
    #define TXD_PIN  PB1

    #define BLINK_UP_TIME  25

    #define BUTTON_NONE  0
    #define BUTTON_1     1
    #define BUTTON_2     2
    #define BUTTON_3     3
    #define BUTTON_4     4
    #define BUTTON_5     5
    #define BUTTON_6     6

    void setup()
    {
      pinMode(BTN_PIN, INPUT);
      pinMode(TXD_PIN, OUTPUT);
      pinMode(VCC_PIN, OUTPUT);
      pinMode(LED_PIN, OUTPUT);

      // leave RF transmitter off for now
      digitalWrite(VCC_PIN, LOW);

      // Initialise the IO and ISR
      vw_set_tx_pin(TXD_PIN);
      vw_setup(2000);  // Bits per sec

      // let the user know we are alive: heartbeat
      blink(3, 50);
      delay(1000);
    }

    uint8_t buf[VW_MAX_MESSAGE_LEN];
    uint8_t buflen = VW_MAX_MESSAGE_LEN;

    void loop()
    {
      byte button = ReadButtons();
      if (button != BUTTON_NONE) {
        // transmit button pressed
        digitalWrite(LED_PIN, HIGH); // Flash a light to show transmitting
        digitalWrite(VCC_PIN, HIGH); // turn tranmitter on
        delay(10);
        buf[0] = button;
        vw_send(buf, 1);
        vw_wait_tx(); // Wait until the whole message is gone
        digitalWrite(LED_PIN, LOW); // turn off LED
        digitalWrite(VCC_PIN, LOW); // turn tranmitter off
      }
      delay(100);
    }

    byte ReadButtons()
    {
      unsigned int buttonVoltage = analogRead(BTN_PIN);
      byte button = BUTTON_NONE;   // return no button pressed if the below checks don't write to btn
      if      (buttonVoltage < 10)   {    button = BUTTON_1; }
      else if (buttonVoltage < 200)  {    button = BUTTON_2; }
      else if (buttonVoltage < 400)  {    button = BUTTON_3; }
      else if (buttonVoltage < 550)  {    button = BUTTON_4; }
      else if (buttonVoltage < 720)  {    button = BUTTON_5; }
      else if (buttonVoltage < 900)  {    button = BUTTON_6; }
      else if (buttonVoltage > 1000) {    button = BUTTON_NONE; }
      return( button );
    }

So, **What's wrong with my setup?**

  [1]: https://i.stack.imgur.com/LHs0b.gif
  [2]: https://i.stack.imgur.com/skxbK.png

title: RF remote control using VirtualWire on ATtiny85 running at 8MHz on internal oscillator

Answers: 4

body:
I tried those Tiny cores you are using and had a lot of problems. I switched to http://code.google.com/p/arduino-tiny/ and it seems much better. Create a second Arduino installation folder and add the arduino-tiny cores.  The pin name constants are like PIN_A0, PIN_A1,...,PIN_B1, etc. So, try that out.

I looked briefly at the VirtualWire code and there are ifdefs specifically for the Attiny85, so it should work.  Here is a derivative project with working ATTINY85 examples: http://cosa-arduino.blogspot.de/2013/03/news-virtual-wire-interface.html

body:
Try the manchester library instead.
This post includes all the necessary info except wiring diagrams:
https://arduino.stackexchange.com/questions/1304/manchester-library-wont-compile-for-attiny85

body:
I spent some time getting VirtualWire to work on attiny84. I see two issues with your code:

1. Since the tiny85 only has one timer, that one is being used by both VirtualWire and `millis`/`micros`. So your delays won't work as expected.
1. VirtualWire uses default values for vw_ptt_pin (10) and vw_rx_pin (11). Those pins don't exist on the attiny85. When `vwsetup` calls `pinMode` with these values, it causes writes to arbitrary memory addresses. This is likely to make your sketch behave unpredictably. To fix set `vw_set_ptt_pin()` and `vw_set_rx_pin()` to pins that exist on the tiny85 or modify the VirtualWire source.

body:
Updated 26-08-2018: added tx(false); at the end of send.  Without it, the TX pin could remain high, flooding the 433MHz band and making any other communication on it almost impossible!!!

Although these are all pretty old posts, I've still been struggling to get VirtualWire or its successor RadioHead working on an Attiny85.  Typically the problem is that VirtualWire uses timer 0 and thereby breaks other stuff.

Now, for RX you typically don't want to spend all your processing cycles waiting for bits to come in, so you want it to be interrupt-driven, but for TX you can often do without that ...  So, I did a bit of reverse-engineering of the VirtualWire TX code and implemented it as a simple send routine which can be used without needing a dedicated timer-interrupt.  Using the code below on Attiny85 and an Arduino Uno as receiver with the normal VirtualWire library and the same baudrate, works just great for me, so if someone else can benefit from it, then here it is (including some code to read out an ultrasonic distance sensor and driving some leds - up to the reader to strip out what he doesn't need):

    #include <util/crc16.h>

    #define LED_PIN           3
    #define LED2_PIN          4

    #define TX_PIN            2
    #define TX_BAUDRATE       2000
    #define TX_MICROINTERVAL  (1000000UL/TX_BAUDRATE)
    #define TX_MAXLEN         12

    #define TRIGGER_PIN       0
    #define ECHO_PIN          1

    inline void led(const bool onOff) { digitalWrite(LED_PIN, onOff ? HIGH : LOW); }
    inline void led2(const bool onOff) { digitalWrite(LED2_PIN, onOff ? HIGH : LOW); }
    inline void tx(const bool onOff) { digitalWrite(TX_PIN, onOff ? HIGH : LOW); }
    inline void trigger(const bool onOff) { digitalWrite(TRIGGER_PIN, onOff ? HIGH : LOW); }

    const uint8_t header[8] = { 0x2A, 0x2A, 0x2A, 0x2A, 0x2A, 0x2A, 0x38, 0x2C };
    const uint8_t conv4to6[16] = { 0x0D, 0x0E, 0x13, 0x15, 0x16, 0x19, 0x1A, 0x1C,
                                   0x23, 0x25, 0x26, 0x29, 0x2A, 0x2C, 0x32, 0x34 };

    void rawSend(const uint8_t * p, uint8_t len) {
      while (len--) {
        const uint8_t val = *p++;
        for (uint8_t mask = 1; mask != 0x40; mask <<= 1) {
          tx(val & mask);
          delayMicroseconds(TX_MICROINTERVAL);
        }
      }
    }

    void send(const uint8_t * buf, const uint8_t len) {
      //  First create the payload ...
      static uint8_t payload[(TX_MAXLEN+3)*2];
      uint8_t * p = payload;
      uint16_t crc = 0xFFFF;
      uint8_t v = len + 3;
      crc = _crc_ccitt_update(crc, v);
      *p++ = conv4to6[v >> 4];
      *p++ = conv4to6[v & 0x0F];
      for (uint8_t l = len; l--;) {
        v = *buf++;
        crc = _crc_ccitt_update(crc, v);
        *p++ = conv4to6[v >> 4];
        *p++ = conv4to6[v & 0x0F];
      }
      crc = ~crc;
      v = (uint8_t)crc;
      *p++ = conv4to6[v >> 4];
      *p++ = conv4to6[v & 0x0F];
      v = (uint8_t)(crc >> 8);
      *p++ = conv4to6[v >> 4];
      *p++ = conv4to6[v & 0x0F];

      //  Now transmit the header and the payload ...
      rawSend(header, sizeof(header));
      rawSend(payload, (len + 3)*2);
      tx(false);
    }

    void setup() {
      pinMode(LED_PIN, OUTPUT);
      pinMode(LED2_PIN, OUTPUT);
      led(false);
      led2(false);

      pinMode(TX_PIN, OUTPUT);
      tx(false);

      pinMode(TRIGGER_PIN, OUTPUT);
      pinMode(ECHO_PIN, INPUT);
      trigger(false);
    }

    int measure() {
      trigger(false); delay(10); trigger(true); delay(10); trigger(false);

      //  We support up to 6m, i.e. 6000mm, so that would take
      //  6000mm * 2 / 0.34mm/ms = 35294ms to get to the end
      //  and back, hence let's use a timeout along those
      //  lines ...
      unsigned long duration = pulseIn(ECHO_PIN, HIGH, 36000);
      if (!duration || (duration > 35500)) return 0;
      return (int)(duration * 34 / 200);
    }

    int bufferedMeasure() {
      static int lastVal = 0;
      static bool toggle = true;
      int newVal = measure();
      if (newVal) {
        led2(toggle);
        toggle = !toggle;
        lastVal += (newVal-lastVal)/10;
      }
      return lastVal;
    }

    // the loop routine runs over and over again forever:
    void loop() {
        //  Measure the distance ...
        int val = bufferedMeasure();
        if (val) {
          static unsigned long data;
          led(true);
          data = 0xD1570000UL|val;
          send((const uint8_t *)&data, sizeof(data));
          led(false);
        } else {
          led(true); delay(100); led(false); delay(100);
          led(true); delay(100); led(false); delay(100);
          led(true); delay(100); led(false);
        }
        delay(1000);
    }


body:
I'm completely new with Arduino and microcontrollers in general.

I have several 5V sensors, and need 3.3V because that's the max for the Due. Is it possible to use a resistor to connect it to the Arduino? Do I have to measure the current from the sensor and calculate the needed resistor like this?

    $$\frac{5.0 - 3.3}{\text{Measured current}}$$
    (5.0 - 3.3)/(Measured current)

title: How to connect 5V sensors to 3.3V digital input (Due)?

Answers: 1

body:
Well if you're not sure of what you're doing, you can always go with **level-converters** for your sensors (that does not apply to shields though)

Level-converters (sometimes called **level-shifters**) come in different flavors:

- breakout board (the easiest to work with)
- IC
- DIY circuits with a few components

Some are "one-way": they have pin-pairs with converters 3.3V -> 5V, and other pin-pairs with 5V -> 3.3V conversion; others are bi-directional, i.e. you can use the same pair of pins in 2 directions 3.3V <-> 5V.

There are plenty of these converters, and they are rather cheap; here are just a few examples:

- [one-way breakout][1] usable with 4 pairs of pins
- [bi-directional breakout][2] usable with 4 pairs of pins
- 74HC4050 IC discussed [here][3]

  [1]: https://www.sparkfun.com/products/11978
  [2]: https://www.sparkfun.com/products/12009
  [3]: http://forum.arduino.cc/index.php?topic=109493.0


body: When communicating over SPI, one byte is sent at a time. Is there a library (C or C++) that allows for sending strings? Essentially it would be a protocol library handling the start and the end of a message, as well as integrity checking. (I'm using an Arduino.)

title: Is there a transmission protocol library for SPI?

Answers: 1

body:
Each spi peripheral has its own protocol in the sense of commands and addresses if any and data.  Spi simply makes a common ground for chip select vs clocks and clocks vs data and separate miso and mosi data lines.

So a general purpose library doesnt make sense.

Also spi certainly is not limited to a byte, many peripherals and many spi controllers allow for long sequences of data, you are also not strictly limited to multiples of 8 bits either although that is the norm.

Your arduino spi master may have its limitations but that has nothing to do with spi in general.

Integrity testing is not part of the spi protocol, you get what you get.  Ideally all of the parts are soldered down on the same board or through known connectors and the margins have been designed in.  You would need to do something outside the spi protocol, for example if it is a spi flash then after you read a chunk of data you can do a checksum and compare it with a checksum you have embedded in the data (or crc).  If it is a spi ethernet part you may choose to leave the frame checksums in the frames and re-validate each frame yourself.  If you create your own peripheral (hardware design or cpld or fpga) then certainly you can add a crc or checksum to every transfer if you wish.


body:
I have a [Arduino Nano (Sainsmart)][1] that I'm trying to upload a sketch to. Under the Arduino IDE, the device selected was `Arduino Nano w/ ATmega328`.

However uploading the sketch gives me the error

    avrdude: stk500_recv(): programmer is not responding

I tried both USB ports (`/dev/tty.usbserial` & `/dev/cu.usbserial`) but the same error persist. The Arduino is connected to a Macbook Air via the USB cable, and the `PWR` LED indicator light on the Arduino is turned on and the `L` indicator LED blinks. There was no problem uploading to a Arduino Uno.

Retried after installing the latest FTDI drivers (MAC OSX, x64, v2.2.18, FTDIUSBSerialDriver_10_4_10_5_10_6_10_7.mpkg) from http://www.ftdichip.com/Drivers/VCP.htm. However that did not help.

What could have gone wrong?

  [1]: http://www.amazon.com/SainSmart-Nano-v3-0-Compatible-Arduino/dp/B00761NDHI/

title: Arduino Nano uploading gives error: avrdude: stk500_recv(): programmer is not responding

Answers: 12

body: This error message basically shows up for any communication problem, so by itself, it is not all that instructive. The Arduino Nano is supposed to have auto-reset, but maybe your clone does not? In that case, you'd have to press the reset key on the board just before starting an upload.

body:
Did you remember to tell the IDE that the board type is a Nano?

`Tools` -> `Board` => `Arduino Nano ...`

This gets me every time I swap between my Nano and Uno.

body:
I also had that error message. I think there are many possible causes, so I haste to specify my special case.

I have a hackintosh with OS X Yosemite 10.10.2, Arduino software 1.0.6 and Funduino UNO. Uploading the example for Serial.write() succeeded the first time. Thereafter most uploads failed. Even when the upload succeeded the serial monitor would not always show output.

This seemed to me to be due to miscommunication on the USB port. I had to repeatedly reset the funduino, unplug and replug the USB cable or even restart the system. When replugging the USB cable sometimes my system would freeze.

By googling I found a solution to "Inserting USB device causes Mavericks 10.9.1 to freeze".
Answer no 12 on tonymacx86.com basically instructs you to remove GenericUSBXHCI.kext from /System/Library/Extensions.

I am happy to report that after removing this kext I have no problems uploading the example and monitoring the output. Because I don't need to replug the USB cable I don't know whether this solves my system freeze. I'm not even sure it was a system freeze, because my system may only have become unresponsive to my USB keyboard and mouse.

body:
Having a similar issue with my `Sainsmart Nano`.

Under `Preferences` check "Show verbose output during [x] upload, then when uploading, you should get a red trace like this:

    avrdude: Version 5.11, compiled on Sep  2 2011 at 18:52:52
             Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
             Copyright (c) 2007-2009 Joerg Wunsch

             System wide configuration file is "/Applications/Arduino.app/Contents/Resources/Java/hardware/tools/avr/etc/avrdude.conf"
             User configuration file is "/Users/johannes/.avrduderc"
             User configuration file does not exist or is not a regular file, skipping

             Using Port                    : /dev/tty.usbserial-A403MRTP
             Using Programmer              : arduino
             Overriding Baud Rate          : 57600
    avrdude: Send: 0 [30]   [20]
    avrdude: Send: 0 [30]   [20]
    avrdude: Send: 0 [30]   [20]

You'll notice a little "pause" just before the first line of `avrdude: Send: 0 [30]   [20]`. Try uploading again and have you finger ready on the physical reset button of your `Nano`. *Just the moment before the first `avrdude: ...` appears, press the reset button.*

When you succeed, you'll see the screen filling with all sort of gibberish, and ending something like this after a few seconds:

    [78] . [00] S [53] h [68] o [6f] u [75] l [6c] d [64]   [20] b [62] e [65]   [20] 0 [30] x [78] 4 [34] 9 [39] D [44] 4 [34] . [00] . [01] . [00] . [00] . [00] . [02] . [00] . [03] . [00] . [04] . [00] . [00] . [00] . [00] . [00] . [e6] . [06] . [b5] . [06] n [6e] . [06] w [77] . [06] . [8c] . [06] . [9d] . [06] . [00] . [00] . [00] . [00] . [02] . [0d] . [aa] . [0d] . [95] . [0c] . [c9] . [0c] . [a9] . [0c] . [f2] . [0c] . [00]
    avrdude: Recv: . [10]
    # | 100% 3.71s

    avrdude: verifying ...
    avrdude: 8824 bytes of flash verified
    avrdude: Send: Q [51]   [20]
    avrdude: Recv: . [14]
    avrdude: Recv: . [10]

    avrdude done.  Thank you.

body:
I was having the same problem and got the same error message.  Turns out these boards don't come with a bootloader preinstalled.  If you have some jumper wires and another working arduino you can use this [tutorial][1] to install the bootloader and it should work great, mine did at least! :)

  [1]: http://www.instructables.com/id/How-To-Burn-a-Bootloader-to-Clone-Arduino-Nano-30/step3/Simple-few-steps/

body:
Had same issue and solution was as follows:

- identified my arduino as CH340/ATmega168P (written on PCB)
- went to IDE and picked from list not UNO but "Arduino Pro or Pro Mini"
- when this option is selected new menu "Processor" selection is available (just under Board selection)
- selected my processor ATmega168P there and upload worked like a charm!

body:
The Arduino IDE version 1.8.5 gave the same error every time I tried to connect it to my OSEPP Nano.  I tried with multiple nano boards with different versions of the IDE. I had the board set to "Arduino Nano".

The solution was: **Instead of Nano choose Arduino/Genuino Uno**. This worked for me.

body: If this doesn't work you will have to use spi to program the nano.  You'll need to look up the connection and use a uno since it has a serial chip at16u2 with a driver that recognizes all atmel products.  After connections setting uno as a programmer by flashing the uno as isp set the programmer as Arduino as isp and flash the chip.  Double check.  The benefit is it is less error prone than uart and has better timing but is a hassle to wire up.  Good Luck

body:
Know this is old but I ran onto it during my search for Nano(V3)'s not uploading so thought might help someone else.  Problem is the bootloader - Arduino IDE BUT I Found an easy solution (right under my nose).

I realized that my nano's had been uploading just fine then I had finally updated the Arduino AVR Boards from 1.6.20 to 1.6.21.  I didn't think there was any problems because it still showed my Nano and ATmega328 etc in the board manager after the change.

But the new boards manager has a new ATmega328 processor choice for the Nano. I changed processor: In the Arduino IDE select `TOOLS` > `PROCESSOR` > pulldown menu from ATmega328P to  `"ATmega328P (Old Bootloader)"`.

Since then, I have uploaded many programs to several different Nano's V3 (Prolofic interace Chipset) without issue.

body:
That problem, ocurred to me when I upgraded the Arduino IDE. I solved it by changing the processor to "old"

Tools->Processor->"ATmega328P (old bootloader)"
thanks!!!!

body:
I recently had the same issue with 3 Nano boards I just purchased from Amazon.  I can confirm that the suggested fix (changing to "old bootloader") solved my problem.

I think the main problem is the upload speed.  The "old bootloader" version successfully uploads at 57600, but the default "new" version tries to upload at 115200 and fails.

body:
Ok. I had the same `programmer is not responding` error on Arduino Nano on Atmel MEGA168PA, USB chip: CH340G. Macbook Pro under macOS 10.14.2.

It hand Blink example installed and the port wasn't visible in the list.

I was trying to figured out, whats wrong and connected my **Arduino Due** through the programming port. After 2 attempts the sketch was uploaded... Then I connected the Nano back, the port was visible this time (actually two of them: `/dev/cu.wchusbserial14120` and `/dev/cu.usbserial-14120`) and guess what, the upload had been successful!

Magic!


body:
There has been a lot of talk about shrinking sketches recently, but if you don't need the room, should it be done? Will it speed up my program?

Take this code:

    int led = 13;
    int val;

    void setup() {
      pinMode(led, OUTPUT);
    }

    void loop() {
      digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
      delay(1000);               // wait for a second
      digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
      delay(1000);               // wait for a second

      digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
      delay(1000);               // wait for a second
      digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
      delay(1000);               // wait for a second

      digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
      delay(1000);               // wait for a second
      digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
      delay(1000);               // wait for a second

      digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
      delay(1000);               // wait for a second
      digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
      delay(1000);               // wait for a second

      val = digitalRead(10);
    }
1,396 bytes on Arduino Uno. Now let's shrink it a bit:

    int led = 13;
    int val;

    void setup() {
      pinMode(led, OUTPUT);
    }

    void loop() {
      blink();
      val = digitalRead(10);
    }

    void blink() {
      digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
      delay(1000);               // wait for a second
      digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
      delay(1000);               // wait for a second
    }
1,270 bytes. A 10% decrease! It could be shrunk even more. **I have the space... is it more efficient (as far as speed) to make it the most compact I can or leave it "uncompressed?"** I would imagine that it would be a little more work (not much) calling `blink();`, therefore slowing down my code. Is this true? Are there other advantages/disadvantages of making it as small as possible (besides storage/distribution of C++ files)?

title: Should I try to make my sketches as small as possible, even when I have enough room?

Answers: 5

body:
Generally speaking, smaller is better. However, there is a point where too small actually makes the program run slower.

My suggestion is if you are working on a sketch and it is blatantly obvious that you are repeating code over and over again, I would rip that out and put it into a function, not only does it make the program smaller, it makes it easier to read.

There is also some optimization going on behind the scenes as well during compilation, so even though the C/C++ code looks to be large, chances are the compiler/linker are determining that something are repeats and consolidating them... Or at least the AVR compiler I used previously did, cannot remember if Arduino does this.

body:
You second code may be smaller in size but due to the function call overhead the max execution speed is reduced.
Does this matter in your case? No, because you have huge delays anyway, but if the code was an actual series of repeated calculations that should be executed as fast as possible then it would make a difference.

As a general rule, smaller code is not necessarily faster too.

For code optimization (either size or speed) you can refer to this application note from Atmel [AVR4027: Tips and Tricks to Optimize Your C Code for 8-bit AVR Microcontrollers](http://www.atmel.com/images/doc8453.pdf)

I could repeat everything it says here but I don't think there is a point, you can read the original article directly.

----------

Regarding the compiler optimization level. Arduino IDE uses the avr-gcc compiler with a setting for **Os** optimization.
The avr-gcc available optimization levels are ([source1](http://www.network-theory.co.uk/docs/gccintro/gccintro_49.html) [source2](http://gcc.gnu.org/onlinedocs/gcc-4.3.3/gcc/Optimize-Options.html#Optimize-Options))

 - **O0 or no -O option**
    At this optimization level GCC does not perform any optimization and compiles the source code in the most straightforward way possible. Each command in the source code is converted directly to the corresponding instructions in the executable file, without rearrangement. This is the best option to use when debugging a program and is the default if no optimization level option is specified.

 - **O1 or -O**
    This level turns on the most common forms of optimization that do not require any speed-space tradeoffs. With this option the resulting executables should be smaller and faster than with -O0. The more expensive optimizations, such as instruction scheduling, are not used at this level. Compiling with the option -O1 can often take less time than compiling with -O0, due to the reduced amounts of data that need to be processed after simple optimizations.

 - **O2**
    This option turns on further optimizations, in addition to those used by -O1. These additional optimizations include instruction scheduling. Only optimizations that do not require any speed-space tradeoffs are used, so the executable should not increase in size. The compiler will take longer to compile programs and require more memory than with -O1. This option is generally the best choice for deployment of a program, because it provides maximum optimization without increasing the executable size. It is the default optimization level for releases of GNU packages.

 - **O3**
    This option turns on more expensive optimizations, such as function inlining, in addition to all the optimizations of the lower levels -O2 and -O1. The -O3 optimization level may increase the speed of the resulting executable, but can also increase its size. Under some circumstances where these optimizations are not favorable, this option might actually make a program slower.

 - **Os**
    This option selects optimizations which reduce the size of an executable. The aim of this option is to produce the smallest possible executable, for systems constrained by memory or disk space. In some cases a smaller executable will also run faster, due to better cache usage.

body:
Your refactor should be done simply because it's better code, not because it's smaller. The advantage is that it's easier to modify.

If making the code size smaller results in a loss of clarity (not so in your case), then you should probably view it as a [premature optimization](http://c2.com/cgi/wiki?PrematureOptimization).

body:
When your time has more worth more than the gains to be had, stop optimizing.

Are you writing for someone for pay? Then this should be their call. But in this case, readability and clarity of your code is paramount; someday, someone else will have to modify your code in your absence. If you deliver working, high performance code that someone else can't read and get a handle on, you will not have fulfilled your obligation (unless this was specifically agreed to).

body:
When considering optimization, think carefully about what resource is most valuable.

You can optimize for code size; this will let you put more code onto your processor. What will the rest of the space be used for? If your code doesn't fit onto your arduino, and your alternative is buying a larger chip, then this is worth the effort.

You can optimize for speed - you can run more code in the same amount of time. If you are sampling data once per second, and sleeping the rest of the time, then this won't help.

You can optimize for power usage - very important if you're on a battery, less important if you are on mains. This might also not just be power consumed by the arduino, but also sensors & motors - can they be turned off for a while?

There are two optimizations that a lot of programmers forget - optimizing for development time, and optimizing for readability.

Any optimization for one thing will tend to de-optimize for at least one (often several) other things. If you don't know which optimization is going to be most useful, then go for readability, then development time (because today's readability = tomorrow's development time x 10!)

Usually, the most expensive thing is the development time (i.e. YOUR time, especially if you are on the clock for a customer). Most other optimization has a threshold - so long as you are over (under?) a specific threshold, further optimization doesn't help. Code size and execution speed (except when shared between competing tasks) are like this - if your code fits on the chip, then it is small enough. If it needs to do something else later, you can optimize it then. If your program can do all it needs to (assuming it is real-time; calculating Pi is a different case), then that's as fast as it needs to be.


body:
I have the below portable electric heater, but I would love to control it's start AND stop time using an Arduino. As-is, it does not come with a stop feature. SO, I have a burning question. How can I get an Arduino to start and stop this heater at specific times of the day?

As you can see, it does have a start time, but it does not have a stop time.
The power button is a simple push button. I suspect I would need to 'interject' into that and the board by using a switch? Apologies if the terminology is off, but I'm very green.
Where would a noob begin?

-EDIT-
The unit is always off when it's plugged back in. That likely means I cannot put a timer on the power cord.

![enter image description here][1]

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

title: What are some steps to attach an Arduino to an electric heater?

Answers: 5

body:
Would or should begin? Don't fiddle with the internals of the heater.

Set its switch to the always on position and control switching on and off with an external relay. Make a box that has plenty of room (you can reduce size at a later moment), a power cord, a mains adapter for your Arduino and a mains outlet in which you can plug your heater.

Use:

- an [RTC (real time clock) breakout](http://www.amazon.co.uk/s/?tag=duc08-21&url=search-alias=aps&field-keywords=rtc breakout) to keep accurate time
- optionally a [7 segment display](http://www.amazon.co.uk/MAX7219-8-Digit-Display-Segment-Digital/dp/B00IHSE6V6/ref=sr_1_6?ie=UTF8&qid=1395212225&sr=8-6&keywords=7+segment+display) to display date/time. Just make sure it has a driver chip on it so you don't need your Arduino to multiplex the individual LEDs
- couple push buttons to configure the device
- a [relay](http://www.amazon.co.uk/s/ref=nb_sb_noss_1?url=search-alias=aps&field-keywords=relay+5V&rh=i:aps,k:relay+5V) rated for the maximum power of the heater to turn it on/off, that can be driven from 5V. Possibly needs a transistor and flyback diode to be controlled from an Arduino GPIO line.

And be **very** careful when experimenting with mains power, it can be leathal.

body:
**I don't know if that heater will work for sure with this approach because the buttons are weird.** However, I am 99% sure this will work.

>![][1]

*(From http://keshavsaharia.com/2012/12/01/coffeeduino/)*

Basically here's what you do:

 1. Disassemble the control panel to find the PCB where the buttons are mounted. Find which button you want to simulate a press of.
 2. Find the solder joint where the button meets the PCB.
 3. Solder a wire to the two terminals that are connected. Some buttons have three or four terminals: look at the traces on the PCB to see which buttons are connected.
 4. Wire the relay with the two wires connected so the relay acts as a switch.
 5. Make the proper connections to the Arduino board to control the relay.

In code, you can just turn the relay on for a quarter of a second or so. Then, the IC on the heater will react like you pushed the button.

Make sure to seal all of this up and make sure you don't accidentally short out any of the wires. I would say to also isolate the Arduino and relay to make sure that you don't electrocute yourself at all if something goes wrong.

  [1]: https://i.stack.imgur.com/qx3F5.png

body:
Use the Arduino to set the start and stop time. Always leave the heater switched on and use something like the 'Mains Switch widget' from SF innovations to control the mains. This unit has a mains relay, is fused to protect against fire and is enclosed in a plastic case.
[http://www.sf-innovations.co.uk/mains-switch-widget.html][1]

  [1]: http://www.sf-innovations.co.uk/mains-switch-widget.html

body:
To be safe use a device like the power tail from spark fun(basically a sealed relay unit, ready for you to connect to the arduino)

Much easier and safer if you don't have any experience working with 120V/240V

uses a 3-12 input to switch 120v up to 15A
https://www.sparkfun.com/products/10747

body:
The following will work and meets the requirement that the heater does not auto turn on when powered up. You need to turn the heater on manually, so no different from existing, and this then allow you to either

 - Power it down at a preselected time of day, provided the Arduino is able to keep track of time, or

 - The Arduino will turn it off a set period after it has started to heat.

The latter is easier to do and meets the need well enough.
The only technical requirements are

 - Able to sense current drawn by heater.

 - Able to turn a heater control relay on/off

 - Able to set or select a time delay on Arduino.

Of these, the current detection is hardest and even then, not very hard. Possible means include:

 - Current transformer connected to heater lead.

 - Opto isolator with LED in series with lead with suitable parallel resistor across opto LED to drop enough voltage to trigger opto on voltage peaks when heater is on,  and backwards diode across opto LED for reverse mains cycles. This provides a series of pulses to Arduino when heater is on.

**Equipment:**

Arduino controlled external relay or solid state relay.

Some means of detecting that heater is drawing current - timer mode only.

Arduino.

__________

**Arduino cct can:**

 - Detect current draw.

 - Turn relay off/on

 - Be programmed to either stop time or run time.

 - Drives external relay or solid state relay.

 - Optional: Relay defaults on.

**Then:**

Set external Arduino timer to desired time.
Arduino sets relay ON.
Set heater to desired start time.
When heater start Arduino sees current and starts timing, or in time of day mode just turns off power at correct time.

This keeps all circuitry external.


body:
There are a lot of methods to power an Arduino from a large range of voltages:

- USB cable from PC or from a phone charger or an USB hub
- step down converters
- step up converters
- switching power supply
- batteries (connected to the power jack or USB or to Vin)

What I can't seem to find is a small 220V-5V converter. I'd like to put an Arduino in the wall, under a light switch, so size matters.

The last resort option is to open a 5V phone charger and replace the metal prongs that go in a socket with two wires, and replace the USB socket with another pair of wires that go the Arduino board, but still, an Arduino Pro Mini or an Arduino Nano is smaller than the phone charger.

title: Most compact method of powering Arduino from wall socket

Answers: 14

body: What if you replace the nearest outlet with some kind of [USB Wall Socket](http://www.alibaba.com/product-detail/Nice-Dual-USB-Wall-socket-For_1518461365.html) and attach to that (either through a standard USB plug, or inside the wall) ?

body:
> The last resort option is to open a 5v phone charger and replace the metal prongs that go in a socket with two wires, and replace the usb socket with another pair of wires that go the arduino board, but still, an Arduino Pro Mini or an Arduino Nano is smaller than the phone charger.

You will probably have to do something like that.

<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/7/7c/Wall_wart_opened.JPG/800px-Wall_wart_opened.JPG" >

Because of the nature of conversion between AC and DC, there has to be some large parts.* I'm not going to go into the specifics here. There is usually a diode bridge (because AC waveforms reverse the current ~60 times a second) and a transformer (to lower the voltage for the diode bridge). They almost always include a regulator and a capacitor to make sure voltage is exact and it outputs a "clean" power supply.

*[Switching power supplies](http://en.wikipedia.org/wiki/Switching_power_supply), although considerably more expensive, are a lot smaller and more power efficient.

[This adapter](http://www.amazon.co.uk/Xcessor-Compact-European-Wall-Charger/dp/B00DVLHZOE/ref=sr_1_1?s=electronics&ie=UTF8&qid=1395244016&sr=1-1&keywords=220v+usb+adapter) seems to be the most compact adapter I can find for 220V. You'll never get something near the size you are desiring, even with a switching power supply. I don't know the size of the Amazon adapter I gave a link for, but in the US (120V), iPhone chargers are very small and they should fit in a standard depth outlet box (with a little room left over for relays and such). If you *really* need to get everything smaller, I recommend using a ATtiny chip.

**How I recommend connecting this:**

I would avoid ripping this apart at all costs from a safety perspective. It would be really easy to send 220V to your Arduino if you're not careful. If you *absolutely have to*, you might want to coat it with some non-conductive epoxy or other coding. Note: this may act as a thermal insulator, therefore reducing the lifespan of the part. You should just coil some wire around the prongs, and then melt a little solder onto each of the terminals. Then, cover that with electrical tape and pigtail (with a wire nut) into a source power line. Note: you probably are doing wiring that could be illegal in your area. Check your local building codes before attempting this.

After that, attach a USB cord to the socket and to the Arduino or the ATtiny/ATmega328 chip 5V/GND input (of coarse, after cutting and stripping one end of the USB cord). I would also, after finalizing all the code and circuitry, seal that with some epoxy or somehow add it to an enclosure to make sure you don't fry your Arduino if a loose wire touches the Arduino circuitry.

## If you don't feel safe doing any of the above, *don't do it*. You can live without a Arduino light switch.
That being said, happy hacking! :P

body: The smallest is probably a plug-in USB charger such as Apple's tiny cube. The cheapest is bound to be a ~9v (output) wall-wart scrounged from the lost and found in a tourist's/traveller's hotel.

body:
I can suggest you to try this : [AC DC Step Down Converter][1]

It is as small as the Apple's tiny cube, and it can be placed inside of a wall easily. (I'm personally using this with an arduino micro)

  [1]: http://www.aliexpress.com/item/220V-to-5V-AC-DC-Step-Down-Converter-5V-800mA-Switching-Power-Supply-Module-AC-85/1488428284.html

body:
Nowadays, most smartphones come with a charger that is linked to the USB plug of the phone.

The charger for my HTC says: **5V**, **1A**, I guess this voltage must be regulated (but I haven't checked it has the charger is sealed).

![enter image description here][1]

The charger itself has a female USB socket on which you can plug any USB cord to link to your Arduino.

**IMPORTANT!** I have never tried it myself! I would not bet my life on it! It would be wise to check the output voltage is well regulated.

  [1]: https://i.stack.imgur.com/NYLJn.png

body: There are small board-mount AC/DC converters like this one http://www.digikey.com/product-detail/en/BP5063-5/BP5063-5-ND/658569

body:
This looks like the smallest and cheapest one from all of the above mentioned:
http://www.ebay.co.uk/itm/AC-DC-Power-Supply-Buck-Converter-Step-Down-Module-5V-700mA-for-Arduino-U-/121355318138

body:
An obvious answer has been omitted which is: transformerless power supply.
If your average power requirements are low (<10mA) then this is the most compact way to achieve the desired voltage.

For an in-depth study see: http://ww1.microchip.com/downloads/en/AppNotes/00954A.pdf

Another solution: jeelabs.org /2011/11/27/ultra-low-power-supply/

Some limitations:

- **safety - NONE** - your circuit might now be floating at line voltage
- heat dissipation - calculate here: www. daycounter.com/Circuits/Transformerless-Power-Supplies/Transformerless-Power-Supplies.phtml
- low current - no servos or relays
- voltage fluctuations on the line might affect the circuit

body:
wanted to do a similar thing and I found and just ordered these:

http://uk.farnell.com/recom-power/rac03-05scr-277/conv-ac-dc-3w-90-305v-in-5v-out/dp/2289701

A fully sealed power supply, disk-shaped, 5cm diameter and 11mm thick. THey are available in 3.3V, 5V, and 12V. They are designed to be put inside walls or behind switches.

body:
I use this one, 5V, 3W, very small, and only $3 on Aliexpress.
http://www.hlktech.net/product_detail.php?ProId=54

body: Try an LED driver. Their typical output is 11.8V DC, which is in perfect specs for the Arduino. You can find them nowadays in all shapes and sizes, round or square, low profile or boxy. A 500ma version (6W) is more than enough for your needs.

body:
Try something like [this][1]. It's 29x15mm and does 220V AC to 5V/3W DC.

  [1]: http://www.ebay.com/itm/1PCS-AC-DC-Isolated-Power-Supply-Module-220v-to-5v-Step-down-Power-module-/181777324025

body:
Nov 2016
Here is a list of compact PCB mounted power supplies that are small (~50mmx25mmx20mm) from Mouser:

http://www.mouser.com/Power/Power-Supplies/AC-DC-Power-Modules/_/N-dv0g5?Ns=Output+Current-Channel+1|0&No=25&P=1yxt7eu

These all take in 120-240VAC and provide outputs in the range of 3 - 5 vdc with varying options for current.

The 5V 1A from Meanwell (IRM-05-5) looks like a good deal at $8.52 each.
http://www.mouser.com/ProductDetail/Mean-Well/IRM-05-5/?qs=sGAEpiMZZMuWiaalG5TUgH52QN1%2bIKAVmGC9ENLDVf688EuOMfqROg==

Paul.

body: It's entirely dependent on whether or not you want to isolate the circuit from the mains. You could use a drop resistor a rectifier and a 5v zener diode but I do not recommend this if you are a hobbyist, in fact I don't recommend this at all, but it is done by some manufacturers with appropriate circuit protection.


body:
What are the advantages of each language when using the Arduino?

I'm thinking this is a good general question, but I'll add a bit about why I'm asking if anyone wants to give me a tip.

I'm experienced in preprocessed languages like JavaScript, PHP, and have fiddled with languages like Java and Visual Basic. In other words I know programming techniques and both classical and prototypal object orientation, but nothing about communicating directly with hardware.

I'm making an octocopter, and am thinking that an object oriented approach will be the easiest. (The software will have very many features...) However I have never written in C++.

Since this is a Q&A site that's supposed to help others, only the general question presented at the beginning is of much importance, but I'd appreciate any comments on my situation.

title: C++ vs. The Arduino Language?

Answers: 9

body:
My personal experience as professor (programming, mechatronics) is that if you have previous programming experience and you are aware of concepts as OOP, it is better to go for C/C++. The arduino language is really great for beginners, but have some limitations (e.g. you must have all your files in the same folder). And it is basically a simplification of C/C++ (you can practically copy&paste arduino code to a C/C++ file, and it will work). Also it makes sense that you can go and use a full well known IDE as eclipse:

http://playground.arduino.cc/Code/Eclipse

Initially it is required a bit more of setup and configuration of your dev environment, but IMHO it is worth it for programmers with experience in any other language.

In any case, it won't harm you to start using the arduino language and the arduino IDE for a few days to get familiar with the arduino hardware and then move to C/C++ with Eclipse for really developing your project.

body:
The Arduino language *is* C++, but it is very different from most C++ varieties. The Arduino language has a lot of abstraction built in, especially in the hardware interfaces, which makes it very simple to use. If you have a background in Java, C and C++ should be very similar.

The main differences between Arduino and C++ are in the memory storage. Usually a modern computer has more than 2GB of RAM, while the Arduino Uno has 2kB (1 million times less). The Arduino also uses 8-bit instructions in stead of the 32 bit ones a computer uses. This will mainly affect the amount of information you can store in a variable.

If you are very new to the Arduino world, you should look up a tutorial, as there are many good ones out there.

body:
**In theory...**
There isn't really an Arduino language as such. It's really just C++ with some domain-specific libraries. These add on various features, such as functions you can call to control the hardware. If you didn't have those functions, you'd need to fiddle directly with special registers to control everything. That's how embedded programming is usually done. It's fast, but it can be quite hard to learn and understand.

In addition to the functions, the libraries add alternative names for some types. For example, `boolean` and `byte` are not in the C++ standard. However, they are directly equivalent to `bool` and `unsigned char`.

All of these things mean you can probably port general C++ code directly to Arduino without difficulty. However, going back the other way may require some minor editing.

But note that not all features of modern C++ versions are available on all Arduino platforms. In some cases, they aren't realistically possible, such as `std::thread` on an 8-bit microcontroller. Others simply haven't been made available, such as `std::array`.

**In practice...**
Having said all of that, programming for Arduino isn't exactly the same as general C++ programming. A lot of the differences are common to all embedded programming though (such as limited memory and processing power).

It's also worth noting that if you're using the official Arduino IDE then there are all sorts of annoying quirks and limitations on how you setup your code. There are workarounds in all cases (as far as I'm aware), but they are sometimes quite frustrating.

For full flexibility, use a third-party IDE (such as Eclipse) with a plug-in to support Arduino. That should give you all the advantages of C++, along with the Arduino libraries.

body:
--- Update 170412

I wrote my original answer three years ago from the perspective of there existing a distinct "Arduino C++". The language used in the IDE _is_ standard C++, because it is implemented by the GNU C++ compiler. "Apparent" differences creep in because the IDE will do some pre-processing to help newcomers to the language avoid a couple of 'gotcha's, by filling in some #includes, f/ex. But you can - and I do - write correct C++ to it and get just what you expect to get.

--- end update

Do limit your use of C++ language features to those whose implementation you fully understand. There are some features that compile to more resource-intensive code than is obvious from reading the source code. The optionally generated .lss (merged source and assembly) listing can give you some good insight into what the C++ compiler did when you weren't looking.

To your question about memory: C++ does not garbage-collect. Stack-based languages like C and C++ do allocate temporary storage on the stack for automatic variables at function entry, which then gets released when the function returns, but this is not true garbage-collection. Objects created in heap- or global memory live until you explicitly delete them. Make sure you know where, when, and for how long different kinds of objects will be created. You really don't want your code `new`-ing and `delete`-ing objects willy-nilly. They will be built in heap memory, fragmenting it and causing it to grow up into the stack. That's when your code - and your nice 'copter - will crash.

C does less for you so it can do less **to** you. It's not a bad choice. C with a few of C++'s features can be an even better choice, given you choose the extra features judiciously.C++, if those are your two choices:

[Original answer]
 - C++ is a standardized language. It is widely deployed in many environments including embedded systems and therefore is more thoroughly tested than the very-like-C++ language that is "Arduino". This is especially important for mission-critical / safety-critical applications such as you are planning. Crashed code means a crashed 'copter and even if it doesn't hurt someone, it **will** break your expensive machine.

 - Being standard, C++ is portable. Need to upgrade your processor? Everything but silicon-specific code will port to the new one. Need to change your toolset, development system, host OS? C++ will be supported everywhere. Though Arduino IDE will run anywhere Java is supported, it is the only tool that uses Arduino C++ and it is a very limited tool. If you want to use Eclipse, the AVR tools, go barefoot on the command-line, develop within Emacs, or whatever other environment you prefer, standard C++ will be supported.

 - The Arduino IDE does things behind your back - specifically, it #includes .h files when it thinks you need them. Even if it is correct, you really want to write, or at least see and understand, everything the compiler is going to see. Programming languages aren't made for computers (computers eat bits for breakfast); they're made for people, specifically the people who follow you on the project, the most important of whom may be ... you!, when 6 months after you wrote a module, you have to come back to enhance it, or more likely, fix it. You really want to be able to see everything the compiler sees.

body:
> What are the advantages of C++ vs the Arduino language when using Arduino? I'm experienced in preprocessed languages like JavaScript, PHP, and have fiddled with languages like Java and Visual Basic.

First, the Arduino compiler/IDE accepts C and C++ as-is.  In fact many of the libraries are written in C++.  Much of the underlying system is not object oriented, but it could be.

Thus, "The arduino language" is C++ or C.

C++ is not garbage collected.  It does manage variables in scope - if you write:

    int led = 13;

    void blinkTimes(int value)
    {
       int i;

       for(i=0;i<value;i++)
       {
          digitalWrite(led, HIGH);
          delay(1000);
          digitalWrite(led, LOW);
          delay(1000);
       }
    }

Then you'll find that `led` and `i` don't grow or leak, no matter how many times you call `blinkTimes`.

If `i` were a class, it would similarly be disposed of once the function ended.  So as long as you aren't using `new` or similar memory allocation functions to create new objects, then you won't have to worry about leaks.

You may still run out of memory, if you create huge classes and use a lot of them in deeply nested functions, but in general you aren't going to run into trouble until you start dealing with `new` and `free` functions.

If you are using `new`, then you'll have to call `delete` at appropriate times.  C++, and by extension Arduino, has no automatic garbage collection, you have to explicitly manage your own memory.

body:
In my experience, it is best to avoid new and delete when running on machines with limited memory.

The memory management itself uses valuable program and RAM space

ISR vectors are set at compile tme. It is difficult (impossible?) for a class instance to claim an ISR at run time

Generally you will know at compile time what class instances you need - e.g. 3 button debouncers, a display driver and a 2-line display driver

Memory management introduces unknown delays when you use new or delete.

There may be cases where it is justified to use dynamic instance construction and destruction, but I suspect they are rare.

body: As mentioned in several answers, if you are programing an embedded system in general you should avoid **new** unless you are managing your own memory heap and you really know what your object life cycles will be. Static allocation or stack variables are much safer. That said, one common trick to manage things like variable length buffers allocated for the duration of a function is to have an automatic variable (on the stack) that is an object that calls **new** in its constructor, and then put the **delete** in the destructor so when the object goes out of scope the buffer is released back to the heap. Again, this is usually of limited use in little micros but it is a nice pattern to remember.

body:
In addition to the comments above, I would like to further stress the problems with working RAM that you have on Arduino boards, particularly with the Uno (and others that share the same microcontroller).  I recently wrote a simple Space Invaders game running on a 32x32 LED matrix and repeatedly ran into problems caused by low memory.

The Uno only has 2048 bytes of RAM.  The library for my matrix took over 3/4 of that leaving me with around 400 bytes for the game.  As it is my intention to "upgrade" the project at some point to run multiple games with the same program base on the more powerful Due, I designed the code with OO principals and a lot of class inheritance.  (The game class was inherited with virtual update and draw calls, the game entities were all inherited).

I pretty much ran out of memory just adding the invaders.  I tried to save memory by bit-fielding their member variables but ran out again when adding the shield objects.  After a bit more scraping I ran out adding the bombs/bullets.  At this point I scoured the code and removed all "virtual" tags (all my class prototypes are built from a Visual Assist snippet and destructors are all virtual automatically).  This halved my memory usage instantly, freeing enough to be able to complete the code.

Long story short, the end result is C++ code that doesn't really use any C++ features.  You might be as well just sticking to C and being very aware of your memory usage.  You get no help if you exceed the 2KB - particularly if you are using any dynamic allocation, the code just stops working and you are left scratching your head for a while until you consider the possibility of memory overflow.

PS - Bit fielding variables is bad.  Very bad.  Apart from adding processing overhead, I lost track of the number of times I'd add a new state to the game but the code wouldn't run and I couldn't understand why.  My state variable was not wide enough to hold the new state value so I was getting some unexpected state.

body:
## Arduino *is* C and C++ (it is a mix of the two, linked together); there is no "Arduino" programming language

**The Arduino language *is* C++** (albeit usually implemented in a style more like "C with classes," which is actually fairly common in the embedded systems microcontroller world). **End of story.** Enough with people thinking it's a different language already! It uses the g++ compiler.

## Proof:
**Enable verbose output during compilation in the Preferences and upload and you'll learn a lot just reading those lines.**

## Here's some additional insight:

### My own words:
**Arduino code *is* C++.** The Arduino [core functions](https://www.arduino.cc/reference/en/) are simply a set of C++ classes and libraries you can use. It is built and compiled using the [GNU gcc/g++ compiler](https://en.wikipedia.org/wiki/GNU_Compiler_Collection). Your `setup()` and `loop()` functions are simply placed into the mandatory (meaning: required by both C and C++ in order to even be considered a valid program) `main()` function ([right here actually](https://github.com/arduino/ArduinoCore-avr/blob/master/cores/arduino/main.cpp#L33)--notice the file is `main.cpp`, which is a C++ source file) automatically for you and there is some extra preprocessing done to make sure it is a valid C++ program (ex: scanning for all function prototypes [aka: declarations] for you so you can use a function even though its prototype comes later in your `.ino` file). Much of Arduino is written in C, however, and therefore requires the `# extern "C" {}` braces around it to prevent C++ from ["name-mangling"](https://www.geeksforgeeks.org/extern-c-in-c/) (also known as ["name decorating/name decoration"](https://en.wikipedia.org/wiki/Name_mangling)) function calls to C functions implemented by [AVR-libc](https://www.nongnu.org/avr-libc/), which is the C implementation for the ATmega328 and other [AVR-architecture](https://en.wikipedia.org/wiki/Atmel_AVR) microcontrollers.

### Arduino's words:
> "[Can I program the Arduino board in C?](https://support.arduino.cc/hc/en-us/articles/360018448219-Can-I-program-the-Arduino-board-in-C-)
In fact, you already are; the Arduino language is merely a set of C/C++ functions that can be called from your code. Your sketch undergoes minor changes (e.g. automatic generation of function prototypes) and then is passed directly to a C/C++ compiler (avr-g++). All standard C and C++ constructs [supported by avr-g++](https://www.nongnu.org/avr-libc/user-manual/FAQ.html#faq_cplusplus) should work in Arduino. For more details, see the page on the [Arduino build process](https://www.arduino.cc/en/Hacking/BuildProcess)."

Source: https://support.arduino.cc/hc/en-us/articles/360018448219-Can-I-program-the-Arduino-board-in-C-

## When to use the [Arduino library](https://www.arduino.cc/reference/en/) vs pure C or C++?
So, use the Arduino language where it simplifies things, and write your own functions where you need more specialization. I do recommend getting away from the IDE quickly though for writing code--just use it for compilation. Set the IDE preferences to use "External Editor." Then use a professional source code editor/IDE such as [Sublime Text 3][1], [Atom][2], [Visual Studio Code][3], or [Eclipse CDT][4] to write your code. You can then click back to the Arduino IDE to compile and upload. If you go with Eclipse, there are ways to do that in Eclipse (see the other answers here, and see the [Arduino playground Eclipse article][5] here too) so consider using those techniques too.

## Update: Eclipse setup

See [my answer here](https://arduino.stackexchange.com/a/75491/7727) and my document here: [Eclipse setup instructions on a new Linux (or other OS) computer](https://docs.google.com/document/d/1LbuxOsDHfpMksGdpX5X-7l7o_TIIVFPkH2eD23cXUmA/edit?usp=sharing). I wrote a detailed PDF to describe setup.

  [1]: https://www.sublimetext.com/3
  [2]: https://atom.io/
  [3]: https://code.visualstudio.com/
  [4]: https://www.eclipse.org/cdt/
  [5]: http://playground.arduino.cc/Code/Eclipse


body:
An XBee Series 2 is set to `Router AT` whose `TX` and `RX` pins are connected to an Arduino Nano's `Rx` and `Tx` pins respectively. The Arduino is connected to a Mac OSX via USB.

A second XBee Series 2 is connected to a Windows system via USB. It is set to `Coordinator API` mode.

Using the sketch below on the Arduino, a packet is sent from the `Router AT` XBee to the `Coordinator API` XBee, which is seen by `XCTU` as a Explicit RX frame. However the Arduino LED should blink once if it received a reply packet (should it?)

On another test, I wrote a script to send a frame for the `Coordinator API` XBee to send to the `Router AT` XBee. Once again the Arduino LED does not blink, and nothing is seen using Arduino's Serial Monitor.

**Testing the `Coordinator API` XBee**

Using the same script to send a packet from `Coordinator API` XBee to itself, the packet was received as well as a delivery confirmation packet. This shows that both the `Coordinator API` XBee and the script are working.

<!-- language: lang-none -->

 // Delivery confirmation
 received:  { type: 144,
   remote64: '0013a20040a74613',
   remote16: '0000',
   receiveOptions: 1,
   data: [ 116 ] }

 // Received the packet sent to itself
 received:  { type: 139,
   id: 1,
   remote16: '0000',
   transmitRetryCount: 0,
   deliveryStatus: 0,
   discoveryStatus: 0 }

**Testing the Arduino Sketch Code**

Using the same Arduino sketch which continuously sends API frames to the `Coordinator`, I connected the `Router AT` XBee's `RX` pin to Arduino's `RX` pin, so the frames the Arduino are sending out are going back into its `RX` pin.

This causes the Arduino's LED to light up! So there is nothing wrong with the code.

**Problem:** Does this mean the `Router AT` XBee is not configured properly? I do not think its `TX` pin is damaged because `XCTU` can still read the settings off this XBee. Any ideas on how we can troubleshoot this?

**Arduino Sketch (Connected to Router Xbee)**

<!-- language: lang-cpp -->

    #include <XBee.h>

    XBee xbee = XBee();
    uint8_t payload[] = { 0, 0 };

    // SH + SL Address of receiving XBee
    XBeeAddress64 addr64 = XBeeAddress64(0x0013a200, 0x40a74613);
    ZBTxRequest zbTx = ZBTxRequest(addr64, payload, sizeof(payload));
    ZBTxStatusResponse txStatus = ZBTxStatusResponse();

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

        Serial.begin(9600);
        xbee.setSerial(Serial);
    }

    void loop() {
        xbee.send(zbTx);
        delay(1000);

        xbee.readPacket();
        if (xbee.getResponse().isAvailable()) {
            // Response received, blink LED once
            Serial.println('resposne!');
            digitalWrite(13, HIGH);
            delay(1000);
            digitalWrite(13, LOW);
            delay(1000);
        }
    }

title: Arduino unable to read from XBee Series 2

Answers: 2

body:
As I mentioned in my comments to your question, if you are using [this][1] library
then it doesn't actually support AT mode. In fact, AT mode (otherwise known as Transparent Mode) is simply attached to the `Serial` port and accessed directly through the `Serial` object.

Example: put this into your Arduino attached to the AT Router.

    #define LED 13

    void setup() {
        pinMode(LED, OUTPUT);
        Serial.begin(9600);
        Serial.println("\nXBee AT communications test");
    }

    void loop() {
      static unsigned long previous = millis()/1000;
      if(previous != millis()/1000){
        previous = millis()/1000;
        char buffer[5];
        sprintf(buffer,"i",previous);
        Serial.println(buffer);
       digitalWrite(LED, !digitalRead(LED));
      }
    }

Then open the console on the XCTU software on the API Coordinator watch the packets.

 ![look at packet 0102][2]

You will see above the received packets from the router. Because the coordinator is in `API` mode, you see it like this. (In `AT` mode, you will see the raw packets.

Ichose numbers to send because they are easy to read in this form. Packet `0102` appears in the packets data as `30 31 30 32 0D 0A`

In `AT` mode there is no packet confirmation, validations, status or anything. They are all handled "transparently".

As a side note, I've seen many references that both XBees need to be in the same mode. That is, in fact, incorrect. If we modify our source to include `Serial.read` you would see data the other way as well.

**edit:** I thought I would add communications between `AT Router` and `API Coordinator`. I have modified the code in the `Router` to receive a constructed packet from the `Coordinator` via the XCTU software.

    #define LED 13

    boolean serialComplete = false;
    char bufferIn[64];
    char bufferOut[5];
    int count=0;

    void setup() {
        pinMode(13, OUTPUT);
        Serial.begin(9600);
        Serial.println("\nXBee AT communications test");
    }

    void loop() {
      static unsigned long previous = millis()/1000;
      if(serialComplete) {
        Serial.println(bufferIn);
        serialComplete=false;
        count = 0;
        memset(bufferIn,0,sizeof(bufferIn));
        digitalWrite(LED,!digitalRead(LED));
      }
      if(previous != millis()/1000){
        previous = millis()/1000;
        sprintf(bufferOut,"u",(uint16_t)previous);
        Serial.println(bufferOut);
      }
    }

    void serialEvent() {
      while (Serial.available()) {
        char inChar = (char)Serial.read();
        if (inChar == '\n' || inChar == '\0') {
          bufferIn[count++]=0;
          serialComplete = true;
        } else {
          bufferIn[count++] = inChar;
        }
      }
    }

Then in XCTU construct a packet for the `Coordinator`. I'm using version 6.1.0.

![add API frame][3]

and click "the create frame using form generator tool"

![form generator tool][4]

here is the packet being received by the router. I am only sending `9999` `nul` terminated.

![result][5]

Then once the pair are running, you can send the constructed packet from the XCTU software and it will be received by the router.

  [1]: https://code.google.com/p/xbee-arduino/
  [2]: https://i.stack.imgur.com/dEu73.png
  [3]: https://i.stack.imgur.com/C2tmh.png
  [4]: https://i.stack.imgur.com/QtGD0.png
  [5]: https://i.stack.imgur.com/db0eF.png

body:
`#include <XBee.h>
uint8_t text[] = {'H', 'e', 'l', 'l', 'o',' ','T','H','I','S',' ','I','S',' ', 'A','R','D','U','I','N','O'};
XBee xbee = XBee();
XBeeAddress64 remoteAddress = XBeeAddress64(0x00000000, 0x0000FFFF);//64 address of remote xbee:
ZBTxRequest zbTx = ZBTxRequest(remoteAddress, text, sizeof(text));// api 2 Tx request frame
ZBRxResponse zbRx = ZBRxResponse();// reading remote xbee response:
void setup()
      {
        Serial.begin(9600);
        xbee.setSerial(Serial);
        Serial.println("starting up yo!");
      }
void loop ()
      {
         xbee.readPacket();// This will read any data that is available:
         if (xbee.getResponse().isAvailable())//Now, to check if a packet was received:
          {
            if (xbee.getResponse().getApiId() == ZB_RX_RESPONSE)
              {
                xbee.send(zbTx);//sending data to remote xbee:
              }
          }
      }`


body:
Has anyone seen or know of a method of preloading (using a computer or whatever) a firmware as data onto one arduino set up to operate as an isp and then using that arduino plug the isp interface into another and upload the firmware.

To be clear - i'm looking for a way to make uploading arduino sketches possible without a direct connection to a full blown computer.

Ideally the steps involved would be:

1. Write new sketch/firmware
2. Compile firmware
3. Write a copy firmware onto Arduino A as data (Arduino A is set up to work as ISP)
4. Detach Arduino A from the computer
5. In a seperate location attach Arduino A to Arduino B using ISP headers
6. Using some method (maybe a pushbutton) trigger Arduino A to upload the preloaded firmware onto Arduino B.

I'm assuming that theoretically it could work because uploading firmware is just an exchange of bytes across the SPI interface but i'm not sure about the reality.

The scenario for which I'm considering is if I were to install an arduino (permanently) in a location that is remote from my computer (I don't have a laptop nor do I want to get one) it would be troublesome to reprogram it.

The other method I have considered is using the DIL packaged ATMEGA which I can then remove from the board and program at the computer and return to the board - however I would much prefer not to risk bending of pins and the hassle of having to remove the chip each time I want to reprogram.

title: Arduino as ISP without a computer

Answers: 2

body:
I have no direct solution for what you want, but yes it is possible to do it. You can hack a bootloader firmware so that it reads the firmware flash code and upload it over ISP.

Though you obviously can't upload 32k of firmware on the target AVR if both arduinos have only 32k of total flash in their MCUs, you'll need to have the flasher have more flash than the target if you want to do so (a 1284p or 2560 Mega will be far enough, or a 328/32u4 will be cood to flash a 168 or an attiny).
The only exception would be to have the firmware to be flashed way smaller than the total memory (like for a blink sketch).

In the end, that won't be easy, it's 100% pure AVR code, but you can do it. Have a look at:

 - [The bootloader FAQ](http://blog.schicks.net/wp-content/uploads/2009/09/bootloader_faq.pdf) ;
 - [The Optiboot Project](http://code.google.com/p/optiboot/) which goal is to make the smallest bootloader possible and
 - [AVRISP](http://code.google.com/p/micropendous/wiki/AVRISP) source code

The way I'd implement that would be to either make everything fit in the bootloader of the flasher device, so it reads the firmware (everything from 0x00 to the bootloader start address) and flashes it through ISP by merging AVRISP with Optiboot.

Anyway, that's an interesting project for a workshop about bootloaders and AVRs I may suggest at my local hackerspace! ;-)

HTH

body:
I think [µProg – tiny, fast, portable AVR programmer with SD](http://mdiy.pl/uprog-maly-szybki-przenosny-programator-avr-z-sd/?lang=en) does what you want. You can store multiple files in the SD card (hex, eep etc) and select from the device menu which one to write to the target MCU without any need for a PC.
The best part is that it's available for free (PCB, schematic, firmware etc).

> One of a kind, portable AVR programmer! Helps wherever you need to
> update the device firmware, where target device is in a hard-to-reach
> location and you can’t (or don’t want to) bring your laptop with a
> bunch of wires with you. Trivially easy to use, super cheap to make,
> super small, super fast, uses SD cards…
>
> Features:
>
> - super small – dimensions 44 x 39 x 5,5 mm
> - super fast – write up to 12,5kB/s, read up to 14,5kB/s
> - uses cheap storage medium – small MICRO SD cards
> - supports FAT16 and FAT32 file systems
> - can read, write, verify flash and eeprom memory
> - can read, write, verify fusebits and lockbits
> - write and read to BIN, HEX, and TXT files
> - can set default values of fusebits, erase memories
> - cheap, easy to obtain, LPH7779 graphic display
> - shows funny animations after every operation
> - standard programming header – Atmel 6-PIN ISP
> - has a function of auto-update its own firmware (from SD)
> - very simple to use, 4 buttons navigation
> - user-setting menu
> - programming speed auto-selection (up to 4MHz)
> - Operates at 3V, programs chips supplied from 3V to 5V

Supported chip list

![enter image description here][1]

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


body:
I am currently playing with Arduino timers (on UNO currently) and I am building a library that  has a function that must be called every millisecond.

There is plenty of code samples on Internet so I went with something that seemed perfect for my needs. I have then updated it to make it a reusable C++ class.

Here is my code (simplified to just isolate the issue):

    #define BIT(x) (0x01 << (x))

    static volatile uint32_t milliseconds = 0;

    class Timer
    {
        public:
        Timer()
        {
            // Disable interrupts
            uint8_t savedStatus = SREG;
            cli();
            // Use Timer2 with 1 ms interrupts
            // OC2A & OC2B disconnected, mode 2 (CTC, Clear Timer on Compare match)
            TCCR2A = BIT(WGM21);
            // Don't force output compare (FOCA & FOCB), mode 2, Clock Select clk/128 (CS = 5)
            TCCR2B = BIT(CS22) | BIT(CS20);
            // Set timer counter compare match (when value reached, 1ms has elapsed)
            OCR2A = 125 - 1;
            // Reset Timer2 counter
            TCNT2 = 0;
            // Set Timer2 interrupt mode (Set interrupt on OCR2A compare match)
            TIMSK2 = BIT(OCIE2A);

            // Restore interrupt enabling state
            SREG = savedStatus;
        }
    };

    static void callEveryMillisecond(uint32_t ms)
    {
        // Do something here
    }

    // Attach interrupt routine to the Timer Compare Interrupt
    ISR(TIMER2_COMPA_vect)
    {
        milliseconds++;
        callEveryMillisecond(milliseconds);
    }

After checking [ATmega328 datasheet][1] (section 17) several times, I came to the conclusion that what I do in `Timer` class constructor above is correct, and for Arduino UNO, the values used must lead to one call of the ISR every ms:

 - CPU frequency = **16MHz**
 - Prescaler = **128**
 - -> timer frequency = **16MHz/128 = 125KHz**
 - -> max counter value = **125**

I decided to use the **CTC** (Clear Timer on Compare match) mode, which means that when the timer `TCNT2` (which is incremented at 125KHz frequency), reaches `OCR2A` value, then it will trigger the ISR, and then will be reset on next tick; the additional tick to reset the counter explains why we use `125 - 1` for `OCR2A` and not just `125`.

Now comes the weird stuff. In order to check that my code worked, I decided to blink the LED on pin 13 every 10 seconds, hence I have added the following code to my program:

    static void callEveryMillisecond(uint32_t ms)
    {
        if (ms % 10000 == 0)
            digitalWrite(13, digitalRead(13) ^ 1);
    }

    static Timer timer;

    void setup()
    {
        pinMode(13, OUTPUT);
    }

    void loop()
    {
    }

Then I measured the time during which pin 13 LED is lit on (or off, both measures are the same). Measures are not very accurate (I just used my wristwatch) but good enough for my check.

I was surprised to see the measured time to be about **20 seconds instead of 10s**.

Initially I thought about a mismatch in CPU frequency, but after performing a lot of small changes, here is what I found which worked perfectly:

    //static Timer timer;

    void setup()
    {
        static Timer timer;
        pinMode(13, OUTPUT);
    }

Just moving the `Timer` instance into `setup()` did the trick: my measures rightly indicated **10 seconds** between 2 states of the pin 13 LED.

**Now my questions are:**

1. Why the second code sample works perfectly, whereas the first does not?

2. Is there, in standard Arduino included code, some code that would overwrite some of the settings I perform for Timer2 in `Timer::Timer()`?

3. Is there a way to make the first code sample work? Note that I don't like the second sample because it does not seem natural coding, also, I will need access to `Timer` `timer` instance in several locations of my future program, hence it can't be possible if it is declared in the scope of `setup()`.

  [1]: http://www.atmel.com/Images/doc8161.pdf

title: Timer2 does not work as it should

Answers: 4

body:
In your setup function, you need to instantiate your timer, like this:

    static Timer timer;

    void setup()
    {
        timer = new Timer();                       <<<--- here
        pinMode(13, OUTPUT);
    }

    void loop()
    {
    }

body:
I have located the source of the problem.

In file wiring.c (arduino-1.5.6-r2\hardware\arduino\avr\cores\arduino) which gets called before setup(), there is the following part that tries to changes the timer 2 prescaller to 64 by setting the `CS22` bit.

    // set timer 2 prescale factor to 64
    #if defined(TCCR2) && defined(CS22)
     sbi(TCCR2, CS22);
    #elif defined(TCCR2B) && defined(CS22)
     sbi(TCCR2B, CS22);
    #else
     #warning Timer 2 not finished (may not be present on this CPU)
    #endif

You already set `CS20` and  `CS22` so this doesn't affect you. What does affect you is the following part which sets bit `WGM20`

     // configure timer 2 for phase correct pwm (8-bit)
    #if defined(TCCR2) && defined(WGM20)
     sbi(TCCR2, WGM20);
    #elif defined(TCCR2A) && defined(WGM20)
     sbi(TCCR2A, WGM20);
    #else
     #warning Timer 2 not finished (may not be present on this CPU)
    #endif

and you have already set `WGM21` so `WGM21` and `WGM20` set changes the timer mode to fast PWM , top=0xFF which gives almost double delay that the mode you were trying to use (CTC top=124).

**How to workaround this issue?**

Timer2 is used when its associated PWM pins are used with an `analogWrite()` call, so the Arduino setup code sets all prescalers to well-defined values just in case the timers might get used later.

I would not try to fight that code; instead, I would just make sure that my setup code runs later, e.g. by moving it to a separate `setup()` method in your `Timer` class and calling that from the global `setup()` routine.

body:
As a follow-up up to @alexan_e answer, here is what I finally did to ensure that my Timer2 settings are not overwritten by the `init()` method in Arduino `wiring.c`.

    #define BIT(x) (0x01 << (x))

    static volatile uint32_t milliseconds = 0;

    class Timer
    {
        public:
        // Don't use the constructor anymore
        void init()
        {
            // Disable interrupts
            uint8_t savedStatus = SREG;
            cli();
            // Use Timer2 with 1 ms interrupts
            // OC2A & OC2B disconnected, mode 2 (CTC, Clear Timer on Compare match)
            TCCR2A = BIT(WGM21);
            // Don't force output compare (FOCA & FOCB), mode 2, Clock Select clk/128 (CS = 5)
            TCCR2B = BIT(CS22) | BIT(CS20);
            // Set timer counter compare match (when value reached, 1ms has elapsed)
            OCR2A = 125 - 1;
            // Reset Timer2 counter
            TCNT2 = 0;
            // Set Timer2 interrupt mode (Set interrupt on OCR2A compare match)
            TIMSK2 = BIT(OCIE2A);

            // Restore interrupt enabling state
            SREG = savedStatus;
        }
    };

    static void callEveryMillisecond(uint32_t ms)
    {
        if (ms % 10000 == 0)
            digitalWrite(13, digitalRead(13) ^ 1);
    }

    // Attach interrupt routine to the Timer Compare Interrupt
    ISR(TIMER2_COMPA_vect)
    {
        milliseconds++;
        callEveryMillisecond(milliseconds);
    }

    static Timer timer;

    void setup()
    {
        // Explicit call to Timer initialization; this occurs AFTER
        // Arduino wiring.c init() has been called
        timer.init();
        pinMode(13, OUTPUT);
    }

    void loop()
    {
    }

body:
The way most of the libraries do this is to put an instance of (in your case) Timer in the Timer.cpp file, and reference it with an extern definition when needed - typically in your main cpp file.
Also you are calling digitalWrite() and digitalRead() during an ISR. This can be bad since those functions are slow, and may not be guaranteed to behave when interrupts are disabled (as they are during an ISR). A safer approach is for your ISR to set a flag in your Timer class that can be read by an Timer.isExpired() or similar method in your loop() code.


body:
I have a list of set-ups and I only have 2 rows in the lcd , I'm trying to scroll down for the moment and I'm doing this by changing the row in the setcursor function to either 0 or 1.

However since that I'll be having about 10 set-ups I used an equation that will change the rows to 0 and one for the ones I want to display and a negative number for those that I don't want to appear.
The problem is when setting the cursor's row to -1 or 2, it will ignore the one with row one (which is the 2nd row).

Is there a way that I can overcome this problem ? by setting it to a row that will not appear on my LCD?
I'm using `#include <LiquidCrystal.h>`
and I already set `lcd.begin(16, 2);`

    int  colom[5] = {
        0-goDown,1-goDown,2-goDown,3-goDown,4-goDown  };
    for (int i = 0; i < 4; i++) {
        if (colom[i] > 1) colom[i] = -1;
    }

      lcd.setCursor(0, colom[0]);
      lcd.print("choise 1 ");
      lcd.setCursor(0, colom[1]);
      lcd.print("choise 2 ");
      lcd.setCursor(0, colom[2]);
      lcd.print("choise 3 ");
      lcd.setCursor(0, colom[3]);
      lcd.print("choise 4 ");
      lcd.setCursor(0, colom[4]);
      lcd.print("choise 5 ");

So here goDown is 0 so choice 1 and 2 should appear, but I'm only getting choice 1 and in the second row it's changing quickly between 2 and 5, it's not constant.

I thought about doing an if condition for each choice but that will be a lot of code to write and it won't be efficient for my application.

title: LCD scrolling down problem

Answers: 2

body:
This is a bad strategy in general. You should not be issuing print calls for things you *don't* want to print and relying on the lcd library to filter for you because they're out of bounds.

Call print for only the choices you want to display.

    char* menu[] = {
        "choice 1",
        "choice 2",
        "choice 3",
        "choice 4",
        "choice 5",
    };
    const int numMenuItems = sizeof menu / sizeof *menu;
    const int numLcdRows = 2;

    // start out at the top of the menu
    int scrollPos = 0;

    void drawMenu() {
        for (int i=0; i < numLcdRows; ++i) {
            lcd.setCursor(0, i);
            lcd.print(menu[i + scrollPos]);
        }
    }

To scroll up or down, just adjust the scroll offset:

    inline void scrollUp() {
        if (scrollPos > 0)
            scrollPos--;
    }

    inline void scrollDown() {
        if (scrollPos < numMenuItems - numLcdRows)
            scrollPos++;
    }

Note this is untested code written for a library I've never seen (just inferring how it works from your post); it's for illustration purposes only.

body:
I have written some abstraction code for handling LCD menus, located here: https://github.com/red-green/Arduino_Mobile_OS

Here is the main snippet:

    byte menu(String title,const String* strings,byte length) {
      boolean select, esc; static byte item, selection;
      select = false;
      esc = false;
      item = 1;
      lcd.clear();
        lcd.setCursor(0,0);
        lcd.print(title);
        lcd.print(": ");
        lcd.print(item);
        lcd.setCursor(0,1);
        lcd.print(strings[item]);
        delay(100);

      while (!select) {
        uint8_t buttons = lcd.readButtons();
        if (buttons) {
        if (buttons & BUTTON_UP) {
          item--;
        }
        if (buttons & BUTTON_DOWN) {
          item++;
        }
        if (buttons & BUTTON_LEFT) {
          esc = true;
        }
        if (buttons & BUTTON_SELECT) {
          selection = item;
          select = true;
        }

        item = constrain(item,1,length - 1);
        lcd.clear();
        lcd.setCursor(0,0);
        lcd.print(title);
        lcd.print(": ");
        lcd.print(item);
        lcd.setCursor(0,1);
        lcd.print(strings[item]);
        if (esc) {
          select = true;
          selection = 0;
        }
        delay(100);

      }
      }
      return(selection);
    }

You may need to change the button handling to work with your setup. To call, have an array of items before setup, like this:

    const String utilmenuitems[6] = {"back","Random Numbers","Uptime","Device Info"};

You can then call it like:

    byte return = menu("Utilities",utilmenuitems,4);


body:
I tried testing the system and I’m not sure if the problem is with the XBee’s, the transmitting code, or the receiving code. Before I post my code, I will explain what we are doing with the signals.

We have three analog signals that will be sent serially through one XBee using an Arduino and XBee shield.  We want to send these signals to the receiving xbee where the Arduino will output these signals to be connected to a third Arduino through wires to be used in a Simulink program.

We are using an Arduino mega for the transmitting side and an Arduino uno for the receiving side. I was told I need to do serial streaming but I’m not sure how that’s done. I understand the XBee and Arduinos both digitize signals but we are hoping to get a signal very similar to the analog signals we are transmitting. Any amount of help is greatly appreciated!!

This is how I have my XBees configured (series 1) both in AT mode:  <br/>

>    **Transmitting XBee**:
    Channel:10
    Pan id: 1234
    MY: 10
    DL: 11

>    **Receiving XBee**:
    Channel:10
    Pan ID: 1234
    MY: 11
    DL: 10

Transmitting Arduino code:

    void setup() {
      Serial.begin(9600);
    }
    void loop() {
      // read the input on analog pins
      int sensorValue1 = analogRead(A0);
      int sensorValue2 = analogRead(A1);
      int sensorValue3 = analogRead(A2);
      // print out the value you read:
      Serial.println(sensorValue1);
      Serial.println(sensorValue2);
      Serial.println(sensorValue3);
      delay(1);
    }

Receiving Arduino code:

    int received1=8;
    int received2=9;
    int received3=10;
    void setup(){
      pinMode(received1, OUTPUT);
      pinMode(received2, OUTPUT);
      pinMode(received3, OUTPUT);
      Serial.begin(9600);
    }
    void loop(){
      if(Serial.available() )
      {
        byte output1 = Serial.read();
        byte output2 = Serial.read();
        byte output3 = Serial.read();
        digitalWrite(received1, HIGH);
        digitalWrite(received2, HIGH);
        digitalWrite(received3, HIGH);
      }
    }

title: XBee+Arduino communication problem

Answers: 1

body:
There are several things here:

1. Increase your delay, you don't want to be sending the data that often, even if you only increase it to 100-200ms, although I'd recommend making it in the order of 1-30 seconds.

2. You're reading in analog inputs which will be in the range of `0-1023` but your serial reads are in byte format (which will actually be reading the first three bytes (or the first three DIGITS of the first reading). More about this below.

3. You're reading in three arbitrary bytes, you're not identifying them at all, you have no idea what you're reading (other than by testing for a 1ms delay--which over XBee is not practical).

You have two options, transmit the data as ASCII (not a good idea IMHO), pre-pending some identifier such that:

    1:259
    2:0
    3:1019

or even some other delimiter:

    259:0:1019

But I would probably lean towards byte encoding:

    byte0 :0xEA    // just some custom header for yourself
    byte1H:0x01
    byte1L:0x03
    byte2H:0x00
    byte2L:0x00
    byte3H:0x03
    byte3L:0xFB
    byte4 :0xXX    // checksum

Or you could `map` the inputs down to a range of `0-255` for single byte transmission.

Next you'll need to work on receiving the data, how you do that is going to depend on how you encode the stream.

_**edit:** I've removed the code sample that was here and replaced it with two working sketches below._

----------
I have two XBees, running in AT mode, mine are Series 2, but programatically _I THINK_ they are the same. If not, you'll have to tweak these, but I'm pretty sure you'll be right.

What we have are two apps, the first is the "SENDING" app, it takes three arbitrary values, they are: minutes (0-60) the micro has been running, seconds (0-60) the micro has been running, and 100 (it was random, and you can put that back if you want). Also, if you comment out the `#define TESTAPP` instead of using these values, it can pull three analog values from `A0`-`A2` instead. (If you change it in the receiving app, you could have three LEDS on Pulse Width channels and vary the brightness).

    /* * * * * * * */

    XBEE SENDER (131)

    #define TESTAPP        // Just serial data based on time

    #define PACKETLENGTH   7
    #define LED            13

    /* * * * * * * */

    void setup(){
        Serial.begin(9600);
        Serial.println("\nSender");
        randomSeed(analogRead(0));
        pinMode(LED,OUTPUT);
    }

    unsigned long m1 = 0;
    unsigned long m2 = 0;

    void loop(){
        m1 = millis()/1000;
        if(m2 != m1){
            m2 = m1;

    #ifdef TESTAPP
            uint8_t  s = m1 % 60;           // how many seconds on millis()
            m1 /= 60;                       // now we're working with minutes
            uint8_t  m = m1 % 60;           // how manu minutes on millis()
            uint8_t  r = 100; //random(256);
            Serial.print("x.x");            // this is just pre-pended data for testing
            Serial.print('<');
            Serial.write(m);
            Serial.print('-');
            Serial.write(s);
            Serial.print('-');
            Serial.write(r);
            Serial.print(">  x-x");        // we want to ignore these chars
    #else
            Serial.print('<');
            Serial.write(map(analogRead(A0),0,1023,0,255));
            Serial.print('-');
            Serial.write(map(analogRead(A1),0,1023,0,255));
            Serial.print('-');
            Serial.write(map(analogRead(A2),0,1023,0,255));
            Serial.print('>');
    #endif
            digitalWrite(LED,!digitalRead(LED));  // toggle the LED everytime we're here
        }
        // do other stuff here...
    }

You'll notice garbage characters around the data we are transporting, this is to demonstrate cycling through all serial communications to arrive at the 7 particular characters we need. That's done in the next app, the receiver:

    /* * * * * * * * */

    XBEE RECEIVER (121)

    #define TESTAPP  // if you attach 3 LEDS to 9, 10 and 11, the remove this line.

    //#define DEBUG  // uncomment this line to see all the data stream coming in

    #define PACKETLENGTH  7

    /* * * * * * * * */

    int LED[3]={9, 10, 11};

    void setup(){
      Serial.begin(9600);
      Serial.println("\nReceiver");
    }

    byte  buffer[PACKETLENGTH]; // what holds our serial data
    byte  idx         = 0;      // the index for the buffer character being written
    byte  validBuffer = 0;      // flag to tell us if we're ready to go

    void loop(){
      if(validBuffer){
          #ifdef TESTAPP
              // we're just going to print it out in a different format
              validBuffer=0;
              #ifdef DEBUG
                  Serial.print('\n');
              #endif
              Serial.print("Data: (");
              if (buffer[1]<10) Serial.print("0");
              Serial.print(buffer[1]);
              Serial.print(":");
              if (buffer[3]<10) Serial.print("0");
              Serial.print(buffer[3]);
              Serial.print(") (");
              Serial.print(buffer[5]);
              Serial.println(")");
          #else
              // this is the more practical side of things
              // instead of serial.printing, change the brightness
              // on three attached LEDs via PWM Pins (9, 10, 11)
              analogWrite(LED[0],buffer[1]);
              analogWrite(LED[1],buffer[3]);
              analogWrite(LED[2],buffer[5]);
          #endif
          memset(buffer, 0, PACKETLENGTH);  // we've used the data, clear it out
          idx = 0;                          // and reset the index marker
      }
    }

    // This is where the real magic is done. We have a buffer of
    // PACKETLENGTH that takes in all Serial data and waits until
    // it finds PACKETLENGTH characters in the format we're after
    // Probably not the best method, but it would be unlikely to
    // stumble across this pattern, although not impossible :)
    // use at your own risk

    void serialEvent(){
        if(validBuffer) return; //we don't want to process new Serial
                                //until we've processed the buffer
        buffer[idx] = Serial.read();
            #ifdef DEBUG
            Serial.write(buffer[idx]);
            #endif

        if (++idx==PACKETLENGTH){
            // we have enough bytes for testing, this next part could be handled better
            if(  buffer[0]=='<' &&
                 buffer[2]=='-' &&
                 buffer[4]=='-' &&
                 buffer[6]=='>' ) { // we have a valid data packet
                   validBuffer=1;
            } else {    // we don't have valid data yet, but keep
                        // what we have, shift it all over one byte and
                        // we'll check again once the next byte is received
                memmove(buffer, buffer + 1, PACKETLENGTH-1);
            }
            idx--;
        }
    }