title: Arduino as ISP without a computer

text:
# Question
Title: Arduino as ISP without a computer
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.

# Answer
I think µProg – tiny, fast, portable AVR programmer with SD 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
> 5 votes

# Answer
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 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
> 4 votes

---
Tags: programming, uploading, isp
---


title: Bootup on lower power not functioning

text:
# Question
Title: Bootup on lower power not functioning
I have a custom Arduino ATMega328 board that generally runs at 5V @ 8MHz (using the Arduino Pro 3.3V 8MHz profile and bootloader). The main reason I'm using this setup is so that I can put the board to sleep when main power is disconnected and it starts being run off of battery power (3V from a coin cell). The 5V and 3V sources are diode OR'ed together and the 5V input is tied to INT0. In code, when it detects that INT0 has fallen low, it initializes sleep mode and everything powers down with the exception of the watchdog timer that keeps a 1Hz cycle to keep an internal count and check it the chip should be woken back up. This works *beautifully* when 5V power is applied first, then the battery is inserted, *then* 5V is disconnected. It goes to sleep and when 5V is brought back it wakes up and I can see it hasn't lost count.

However, the problem comes when 3V is applied *first*. I'm honestly not sure if it's even booting. But what it is supposed to do is boot, check if INT0 (Digital 2) is low and, if so, go right to sleep. By watching the current draw I see that it powers up to a few mA for a couple seconds, then drops to about 0.3mA (still higher than it should be in sleep mode). But when I re-apply 5V, *nothing*. The power draw goes back up but it is unresponsive (over FTDI serial).

Is there maybe something I'm missing that it can't be booted on 3V... in theory it should run just fine.

**Update:** I dropped an LED onto D13 and tried the blink sketch. Works fine when starting from 3V or 5V. However, when I run my firmware and start it from 3V, the LED just starts flashing wildly. I have no idea what's causing it since I never even setup D13 as anything in my code. But it makes me thing it's something to do with the bootloader...

# Answer
So... turned out what was happening was all in code. Turns out that I was initializing an interrupt on INT0, when it was low, at the very beginning of my code. Problem was that when it started up on 3V backup power, INT0 was always low because INT0 is tied to the 5V line (it's how it knows to go to sleep). Because INT0 was low and the interrupt was triggering on low it was causing a constant interrupt to occur, never giving the rest of the program any time to run. Switched to enabling that interrupt only once I've entered full waking mode and it works fine now.
> 6 votes

# Answer
Exactly what is happening and why cannot be determined based on the amount of info provided. However, I see at least one potential problem which would at least partially explain the symptoms described.

You said that you are using diodes to select the voltage supply, and one supply is a 3V battery. If you are using standard diodes that drop ~0.6V then the supply voltage to the MCU is only ~2.4V. If you are using Schottky diodes with a voltage drop between 0.15-0.45, the supply voltage is potentially as low as 2.5V. You have the BOD voltage set to 2.7 volts, so in theory the MCU will never boot with the battery.

As for why you can start it at 5v, drop to 3v, and bring it back up again- I'm not sure. You could be disabling the BOD in code...maybe… Not sure why it works, but it's likely not guaranteed to work.

I setup a diode switch circuit with 5v and 3.3v to see what it looks like on my oscilloscope when the voltages switch. When at 3.3v switching up to 5v, the voltage oscillates quite a bit initially. This may potentially cause some problems when the MCU tries to come out of sleep. Putting a cap between VCC and GND smoothed the signal very nicely. When switching from 5v to 3.3v, there really wasn't any oscillating, just a clean drop.

From this information, it seems that you should lower the BOD threshold or turn off the BOD, and put a decoupling cap between VCC and GND. You probably also should make sure you have a pull-down resistor on INT0, and read the MCU datasheet sections explaining the various sleep modes all the considerations for sleeping and waking – it’s pretty involved. Cheers
> 4 votes

# Answer
I think the problem is with your bootloader, but not in the way you think.

When an Arduino starts up, a bootloader profiting several tasks, such as looking for a serial host or loading program data from flash is going to take a lot more energy than a sleeping Arduino.

I think the reason why your Arduino will not start is because the bootloader requires an accurate clock source, but applying 3v to it will mess up that clock and it will perhaps crash or wait for 3.3v to be applied for a stable source.

Looking at the datasheet:

We see that current draw while waking up (running the bootloader) is probably going to be around 2mA, while sleeping current is about *0.8 microamps*. This could certainly lead to a blackout on startup without the proper current.

Perhaps you should only turn it on with 5v power, or maybe you need a higher current, higher voltage battery.
> 2 votes

---
Tags: battery
---


# Question
Title: How to use RS-232 sheild as software serial port?
I would like to be able to use a USB port at the same time as an RS-232 port with my Arduino Uno board. I unwittingly bought a shield that (I think?) overrides the USB port when it is mounted to the Arduino board:

http://www.dfrobot.com/wiki/index.php/RS232\_Shield

Would anyone be able to give me any advice on how to connect the hardware so that I can have two serial ports accessible from my Arduino Uno? The format I was thinking was (Arduino =\> RS-232 Sheild):

GND =\> GND 5V =\> 5V Digital Pin 2 =\> 232RXD Digital Pin 3 =\> 232TXD

The accompanying code for initializing the serial port which I've written:

```
const int rxpin = 2; // pin used to receive
const int txpin = 3; // pin used to send
SoftwareSerial Serial_rs232(rxpin, txpin); // new serial port

```

Any ideas as to why this may or may not be a good method of using the hardware I have available for the purpose I had in mind?

# Answer
> GND =\> GND 5V =\> 5V Digital Pin 2 =\> 232RXD Digital Pin 3 =\> 232TXD

A better choice of board would be the Leonardo, since you could connect such a shield *and* use the USB port right out of the box. However, since you have the Uno, there is a solution.

*From Arduino:*

> The SoftwareSerial library has been developed to allow serial communication on other digital pins of the Arduino, using software to replicate the functionality (hence the name "SoftwareSerial"). It is possible to have multiple software serial ports with speeds up to 115200 bps. A parameter enables inverted signaling for devices which require that protocol.

It then goes on to reccomend the library AltSoftSerial.

Here is some example code from the link above:

```
#include <AltSoftSerial.h>

AltSoftSerial altSerial;

void setup() {
  Serial.begin(9600);
  Serial.println("AltSoftSerial Test Begin");
  altSerial.begin(9600);
  altSerial.println("Hello World");
}

void loop() {
  char c;

  if (Serial.available()) {
    c = Serial.read();
    altSerial.print(c);
  }
  if (altSerial.available()) {
    c = altSerial.read();
    Serial.print(c);
  }
}

```

It acts like a standard serial port, only you declare the connection as a variable first. This code is written for a board with an additional serial port, like you have.

## All is good, except for one problem:

The problem is the shield is wired to connect to pins 0 and 1: the ones used by the USB adapter. The AltSoftSerial library uses pins 8 for TX and 9 for RX. (Note: You cannot use PWM on pin 10 on the Uno... it should still work as a digital pin.) In that case you would **not attach the shield by plugging it into the Arduino**, and you would wire it like this:

> GND =\> GND | 5V =\> 5V | Digital Pin 8 =\> 232RXD pin 0 on the shield headers | Digital Pin 9 =\> 232TXD 1 on the shield headers

So then, you would be manually wiring the shield to the Arduino with jumpers. As long as it doesn't connect to any other Arduino pins I'm not aware of (it shouldn't besides maybe 13 for a LED or something like that), it should function like it would stacked and using pins 0 and 1.

Note: (Obviously) You cannot connect anything to the headers on the shield (You cannot connect to pin 5 and get a signal).
> 4 votes

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


# Question
Title: How to build (concat) a string with big numbers
new to arduino I'm struggling with what sounds like fairly n00b problem... I've wired up a adafruit GPS-board to my Arduino and it is working as it spits out GPS data to the serial port with `Serial.print(GPS.latitude, DEC)`

I Now want to concat a string which I can process (read: I want to sent it via an ethernet client.) This is what I got already:

```
......
String vnnt = "$VNNT,";

if (GPS.fix) {
   vnnt += "GPS,";

   //this works:
   vnnt.concat(GPS.fix);

   //but this not:
   vnnt.concat(GPS.latitude);

}else{
   vnnt += "INFO,Acquiring Sats";
}

Serial.println(vnnt);

```

The error message is: `Call of overloaded 'concat(float&)' is ambiguous` When I `Serial.print(GPS.latitude, DEC)` it results in: `4418.5937996050`

So it is probably to big or something...

**How can I concat the vars and create the long string?**

# Answer
> 7 votes
The concat function does not implement a float version, but some of char, int, unsigneds...

```
unsigned char String::concat(long unsigned int)
unsigned char String::concat(unsigned int)
unsigned char String::concat(int)
...

```

so the compiler does not know how to cast (truncating probably the float) to integer, as there are several options.

You have to convert first your float to string, use dtostrf() or sprintf() then concat to your string.

```
char outstr[25];
sprintf(outstr, "%f", GPS.latitude);

```

or

```
dtostrf(GPS.latitude, 6, 2, outstr);  //check docs for 6, 2 values, and set them for your needs

```

And then:

```
vnnt.concat(outstr)

```

Also note that sprintf is very handy for compact creation of a (char) string:

```
char msg[80];
sprintf(msg, "$VNNT,GPS, %s %f", GPS.fix, GPS.latitude);

```

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


# Question
Title: Connect to more than one Arduino with Adobe AIR
I am using the arduinconnector ANE to connect to an arduino baord in an AIR application. https://code.google.com/p/as3-arduino-connector/

Can anyone tell me if its possible to connect to more than 1 board, simply by instantiating additional instances of the ANE and passing in unique port #'s?

Or is there some reason why this isn't possible and a unique AIR application is required for every arduino you connect to?

# Answer
This seems to be possible with `as3Glue` as per the docs:

> as3Glue is an ActionScript 3 library that enables communication between Flash/Flex/AIR applications and Arduino boards. **It can together with one or several Arduino boards** be used to monitor sensors (such as rotary encoders and motion detectors), control actuators (such as LEDs and motors) and interface other electronics (such as RFID readers) from Flash, Flex and AIR applications.

`as3Glue` can be used with `as3-arduino-connector` as mentioned in the docs:

> Using with as3Glue
>
> Download either the SWC or Source Code from the Downloads section of this project for a patched version of as3Glue. This patched version has the exact same interfaces as v20, with a notable exception of the constructor. When you instantiate a new "Arduino" object, replace the IP address and port with the COM port and baud rate. For example :
>
> public var myArduino:Arduino = new Arduino("COM10", 57600);
> 2 votes

---
Tags: arduino-uno
---


# Question
Title: Can I corrupt my Arduino if it's unplugged during an upload?
When messing around with code and uploading a sketch to my Arduino board, I almost accidentally pulled out the USB cord. Everything is fine, but then I started thinking what would've happened if I had pulled it out.

How safe is avrdude? Could it damage or brick the board? I'd imagine that you would just have to upload code to it again... but what would happen before you upload the new code? I've seen something about how you can always upload new code if the bootloader is intact, but I would imagine that there would be some problems. If this were to happen, should I unplug everything connected in case Arduino writes a HIGH to an input (or similar) that would damage the component?

# Answer
AVRDUDE does not actually *perform* the write, it merely *directs* it. The actual writes are performed either by the bootloader or by the ISP firmware/hardware within the MCU itself.

With the bootloader it depends on how itself is coded, but at worst it would finish off the flash byte or page or EEPROM page zero- or one-filled and then fail to communicate further with AVRDUDE, aborting programming.

With ISP, the page write command would never be received and the programming would be aborted at the last full page. Fuse bytes are done singly and so programming a single fuse can be viewed as an atomic operation.

In either case, a chip erase operation should reset the MCU to a known working state, fuse changes excepted.
> 7 votes

# Answer
One safety feature that hasn't been mentioned so far is that the ATmega328 has a set of lock bits that prevent read/write access to certain areas. To the best of my knowledge, the way Arduinos are set up, those bits are always set to prevent writing to the boot loader area unless the "Burn Bootloader" command is currently active, and since you can only use that command with an external programmer, you can always write a new bootloader if something goes wrong.

I think the only way of bricking the board (in the sense of leaving the MCU in a state that is functional, yet almost irrepairably unresponsive) is writing bad fuse settings.
> 2 votes

# Answer
It should be fine.

Most boards don't require you to reupload the bootloader every time you upload a sketch, so your program will be corrupted but your bootloader won't. I assume the bootloader is similar to the bootloader on other chips I have seen*, it will stop execution if the code doesn't work properly. I would also think that the micro would not accept a transmission if it's checksum is missing.

I wouldn't try it if I were you, but you can be a little less cautious about this sort of thing.

*: the Propellor chip, among others
> 1 votes

---
Tags: uploading, safety, avrdude
---


# Question
Title: Opamp for amplifying 1V signal voltage to 2V
I'm doing my first electronics project where a signal that varies between -1 to 1 V is going into an analog pin on the Arduino. The amplified signal has to be read as fast as possible by Arduino. The source signal is at 60 Hz.

Will this LM324 be a suitable 4-channel opamp for my needs? How concerned should I be about the 2 mV input offset and 20 nA input current bias?

To make full use of the 10bit ADC, would you recommend using an opamp with gain of 2 and biasing the signal by +2.5V? If so, will it be better to create the bias using a potential divider across +5V and GND, or using a 2.5V voltage regulator?

Or would it be better to set AREF to 2V and bias the signal by +1V? In this case, will it be better to use a 2V voltage regulator, or a voltage divider across Arduino's 3V3 and GND using 20M and 33M resistors?

# Answer
> 2 votes
A 2mV offset voltage will become a 4mV error after amplification. You haven't shown the schematic for your amplification, but the current bias will also become error after amplification.

*That* LM324 variant is surface mount, but there are other LM324 variants in a DIP package, which will work fine in a breadboard.

# Answer
> 1 votes
Just an alternate idea I saw: If you dont need high accuracy, you can use a voltage divider to bias -1 to +1 into 0 to 1, and set the analog reference to 1.2, and get almost the same result but skip the op amp.

A voltage divider with 2 equal resistors will give you the voltage halfway between its two inputs. If the bottom of the voltage divider is at 1v, and the top input is at -1, you get 0 out.

If the bottom is at +1, you get 1 out.

I saw a really clever design using 2 1 megaohm resistors, and actually using the aref pin as an output to provide the bias for the divider, setting the reference to the 1.2v setting, putting the signal in the top of the divider and ground and connecting the adc to the output of the divider.

Aref wasnt meant as a current source, but they use 1meg resistors so the current draw will be at most a few microamps.

A filter cap on aref probably draws more than that if vcc is noisy(if there wasnt current to filter we wouldnt need the cap!) So a few uA should be fine.

They put a 1nf capacitor betcan the input and ground to fix the issues with the ADC input current causing voltage drop. It worked up to 100hz. They never tested accuracy because it wasnt needed though. I'd guess that the adc internal reference was the major error source, probably a few percent.

You can also actually bias with a voltage divider to the 5V supply, and get a 0 to ~1.6V output, it's just a little harder to understand.

This simulation explains the concept(5v version) http://www.falstad.com/circuit/#%24+1+5.0E-6+81.92041607667615+50+5.0+50%0Ar+304+160+304+224+0+1000.0%0Ar+304+224+304+304+0+5000.0%0AR+304+304+256+304+0+0+40.0+5.0+0.0+0.0+0.5%0AR+304+160+208+160+0+1+40.0+1.0+0.0+0.0+0.5%0Aw+304+224+400+224+0%0Ax+368+208+456+214+0+24+To+ADC%0Ao+3+64+0+35+2.5+0.00625+0+-1%0Ao+4+64+0+35+2.5+9.765625E-5+1+-1%0A

Left click the output, use view in scope.

---
Tags: pins, sensors, arduino-nano
---


# Question
Title: Ultrasonic Sensor scanning too often resulting in a whirring noise
I am using an HC-SRO4 ultrasonic sensor for a wall-avoidance, maze-solving robot. However, I have recently run into an issue where I am getting a whirring noise from the sensor because it is taking measurements way too often.

This is the code I have right now:

```
const int serialPeriod = 250;       // only print to the serial console every 1/4 second
unsigned long timeSerialDelay = 0;

const int loopPeriod = 20;          // a period of 20ms = a frequency of 50Hz
unsigned long timeLoopDelay   = 0;

// specify the trig & echo pins used for the ultrasonic sensors
const int ultrasonic2TrigPin = 8;
const int ultrasonic2EchoPin = 9;

int ultrasonic2Distance;
int ultrasonic2Duration;

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

    // ultrasonic sensor pin configurations
    pinMode(ultrasonic2TrigPin, OUTPUT);
    pinMode(ultrasonic2EchoPin, INPUT);
}

void loop()
{
    debugOutput(); // prints debugging messages to the serial console

    if(millis() - timeLoopDelay >= loopPeriod)
    {
        readUltrasonicSensors(); // read and store the measured distances

        timeLoopDelay = millis();
    }
}

void readUltrasonicSensors()
{
    // ultrasonic 2
    digitalWrite(ultrasonic2TrigPin, HIGH);
    delayMicroseconds(10);                  // must keep the trig pin high for at least 10us
    digitalWrite(ultrasonic2TrigPin, LOW);

    ultrasonic2Duration = pulseIn(ultrasonic2EchoPin, HIGH);
    ultrasonic2Distance = (ultrasonic2Duration/2)/29;
}

void debugOutput()
{
    Serial.print("timeSerialDelay: ");
    Serial.print(timeSerialDelay);
    Serial.println();

    if((millis() - timeSerialDelay) > serialPeriod)
    {
        Serial.print("ultrasonic2Distance: ");
        Serial.print(ultrasonic2Distance);
        Serial.print("cm: ");
        Serial.println();

        timeSerialDelay = millis();
    }
}

```

and my wiring:

Link to product

Does anyone know why the scanning is happening constantly? It should only be happening every 1/4 of a second, not constantly. The weird thing is that this wasn't happening earlier before I started using the cable.

I believe it has something to do with the 8.5" extension cable I have (needed because I can't mount three sensors, one facing to each side and one in front, on a single breadboard). This is because when I mounted the sensor directly onto the breadboard, the delay was correct and the whirring was not present. However, as I just mentioned, I *need* the extension cable to be able to have the three sensors.

Does anyone have a solution for this?

Thanks!

# Answer
If you want to sample at 4Hz (4 times per second), you need to change your headers accordingly:

```
const int serialPeriod = 250;       // only print to the serial console every 1/4 second
unsigned long timeSerialDelay = 0;

const int loopPeriod = 250;          // a period of 250ms = a frequency of 4Hz
unsigned long timeLoopDelay   = 0;

```
> 3 votes

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


# Question
Title: Is there a way to make wiring a bare microprocessor to a shield easier?
I currently do most of my AVR work on breadboards, but the large variety of Arduino shields and code out there makes me wonder if I'm not beating my head against the wall sometimes, and looking up port to pin mappings both wastes time and slows me down. Is there any convenient way to adapt AVRs (*other* than those pin-compatible with current Arduinos) to Arduino shields?

# Answer
> 4 votes
You can make adapter boards (one for each mcu model).

The bottom side (male headers) would plug to the breadboard and the upper side would have female headers with the same pinout as an Arduino board (female hearers placed in the appropriate positions to match Arduino shields).

Such a board shouldn't be difficult to design.

Here is an image that resembles what I describe

It would adapt the pinout of a bare AVR to the pinout of a typical Arduino so that shields can by directly plugged on top of it.

---

Also a pinout diagram may come handy to speedup things when you use a bare chip with Arduino code.
(image source)

Another similar solution is a small printed sticker placed on top of the AVR
(image source)

# Answer
> 2 votes
The Arduino-way of doing that is making a lookup table that translates pin number to PORTn / DDRn / PINn SFR and the related bit. You can use the same trick and make GPIO pins count in a convenient way as they are in the package. Only special peripherals (like SPI / PWM) cannot be accounted for in this way because they are hard wired to a pin.

A good start is the below `Arduino.h` library sniplet if you want to re-use that concept.

```
// Get the bit location within the hardware port of the given virtual pin.
// This comes from the pins_*.c file for the active board configuration.

#define analogInPinToBit(P) (P)

// On the ATmega1280, the addresses of some of the port registers are
// greater than 255, so we can't store them in uint8_t's.
extern const uint16_t PROGMEM port_to_mode_PGM[];
extern const uint16_t PROGMEM port_to_input_PGM[];
extern const uint16_t PROGMEM port_to_output_PGM[];

extern const uint8_t PROGMEM digital_pin_to_port_PGM[];
// extern const uint8_t PROGMEM digital_pin_to_bit_PGM[];
extern const uint8_t PROGMEM digital_pin_to_bit_mask_PGM[];
extern const uint8_t PROGMEM digital_pin_to_timer_PGM[];

// Get the bit location within the hardware port of the given virtual pin.
// This comes from the pins_*.c file for the active board configuration.
//
// These perform slightly better as macros compared to inline functions
//
#define digitalPinToPort(P) ( pgm_read_byte( digital_pin_to_port_PGM + (P) ) )
#define digitalPinToBitMask(P) ( pgm_read_byte( digital_pin_to_bit_mask_PGM + (P) ) )
#define digitalPinToTimer(P) ( pgm_read_byte( digital_pin_to_timer_PGM + (P) ) )
#define analogInPinToBit(P) (P)
#define portOutputRegister(P) ( (volatile uint8_t *)( pgm_read_word( port_to_output_PGM + (P))) )
#define portInputRegister(P) ( (volatile uint8_t *)( pgm_read_word( port_to_input_PGM + (P))) )
#define portModeRegister(P) ( (volatile uint8_t *)( pgm_read_word( port_to_mode_PGM + (P))) )

```

The `pinMode`, `digitalWrite` and `digitalRead` functions are defined in `/usr/share/arduino/hardware/arduino/cores/arduino/wiring_digital.c` which can be used for further inspiration.

---
Tags: shields, avr, hardware
---


# Question
Title: What happens if I power the Arduino with both the USB and external power voltage simultaneously?
I am a new Arduino user. I am not sure whether I can connect both USB and external supply through power adaptor to Arduino simultaneously. Would this burn the controller?

Basically, I want to automatically shut down the computer after saving all open documents before my UPS battery goes out whenever I am not there to manually shut it down. I am trying to notify the computer about the power failures of main supply - AC 220V 50 Hz (notification/signal sent when power goes out) via USB using Arduino. I am thinking that this can be done by using the external voltage power supply pin. Whenever power goes out in the mains, the external voltage power supply pin will drop to 0 V from 7 V. The value of the voltage can be read using software ( I am unclear about this: Can it be done? If yes, how?). The Arduino will still be powered up as it is connected to USB of computer and thereby communicates to the computer about the power failure.

# Answer
From arduinoBoardUno:

> # Power
>
> The Arduino Uno can be powered via the USB connection or with an external power supply. The power source is selected automatically.

Put the external power through a voltage divider or transistor-based inverter and into an analog (divider) or digital (inverter) pin and check the appropriate value from the pin. Note that this does not require powering the Uno from external power, only connecting the grounds.
> 12 votes

# Answer
> I am a novice user of Arduino. I am not sure whether I can connect both USB and external supply through power adaptor to Arduino simultaneously. Would this burn the controller?

Lets study the schematic of Arduino UNO R3

The input from the power supply plug (PWRIN, the power jack) goes through a diode D1 (to prevent reverse polarity), and feeds a NCP1117 regulator that down converts it to the 5v supply that feeds the 5v parts.

The alternative supply comes from the USB plug (USBVCC). The relevant circuit is shown below

The USB power lines goes through a P-mosfet (T1) that operates as a switch and then goes to the +5V node (that is the +5v regulator output as shown in the first schematic).

The mosfet is controlled by an LMV358 operational amplifier (OPAMP) that operates as a comparator.
The negative input of the opamp is tied to 3.3V and the positive one fed through a voltage divider with half the Vin supply level.

* When Vin \>6.6V then the + input of the opamp become higher than the - input and the opamp turns the mosfet off.
* When Vin \<6.6V then the + input of the opamp become lower than the - input and the opamp turns the mosfet on.

Note that Vin is after the input diode so it's about 0.6V lower than the external connected power supply level. So when there is power supply connected to the power input that is higher than 6.6V+0.6V (where 0.6V is the diode D1 voltage drop), then the USB supply line is cutoff (because the mosfet turns off) and the power is provided from the power plug. Connecting or disconnecting the USB supply in this case will not make a difference, so you can have both power supplies connected simultaneously, only when the power input drops below the specified level (about 6.6V+0.6V=7.2V), the USB will start powering the board.
> 65 votes

---
Tags: arduino-uno, power
---


# Question
Title: How to find out whether an arduino can control a servo motor
I have a servo motor with following specs Torque - 1.08Nm Max rpm - 3000 Current rating - 7.8 amp Max voltage - 56V DC

Please tell me how to calculate whether an arduino board - uno rev 3 can control the servo motor? If not, how to find out how many such boards are required?

# Answer
An Uno most definitely cannot directly control that motor. According to the specs here,

> They operate at 5 volts. Each pin can provide or receive a maximum of 40 mA

So your motor has needs about ten times the voltage and *200* times the amps that the Uno can supply. Of course, you can always get a driver of some sort for the servo.
> 4 votes

# Answer
The optical encoder you link to has 500 pulses per revolution. This means at 3000rpm , you will be generating pulses 25,000 times a second. You will also need to deal with overshoot (as there is nothing worse than a motor going overspeed and the feedback loop being unable to detect it).

Dealing with an optical encoder generating pulses this quickly is actually quite a challenge, especially with Arduino (which has rather slow native I/O using digitalRead and digitalWrite), and the ATmega328 (which doesn't have any dedicated hardware to deal with high speed optical encoders).

Driving a 56VDC, 7.8A motor isn't an easy challenge either - a motor driver for this isn't going to be easy to design.

I'd probably look for a dedicated servo or CNC motor controller to deal with something like this.
> 2 votes

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


# Question
Title: Can I compile c/c++ code on the linux part of the Arduino Yun?
Can I compile c/c++ code on the linux part of the Arduino Yun?

How complete is the linux part of the Arduino Yun? Can I scp some c/c++ code onto the Atheros AR9331 chip compile it?

Or must I first crosscompile all software and then put them onto the Atheros?

# Answer
> 5 votes
The Yun's OS (Linino) is based on OpenWRT, and the official toolchain from OpenWRT does not appear to have changed much. It could probably be done, the question is if you'd really want to though.

The limited resources (storage, RAM, CPU) means you would most likely not fit all the parts of the toolchain for C/C++ compilation (perhaps with the exception of very basic programs without many dependencies). The YUN's package manager (opkg) should contain pre-built packackes if they exist, but given that even the list of packages is only kept in RAM to conserve space, I doubt the entire toolchain with libraries needed to compile useful stuff would fit.

The official way to build things for OpenWRT appears to be cross-compilation on a much beefier machine, if only because it takes a fraction of the time needed by a native compiler. All in all, you're also very likely to save time and resources by cross-compiling and have more resources left on the YUN itself.

---
Tags: arduino-yun, linux, compile
---


# Question
Title: Should a delay be expected to cause deadlock?
I have made a simple program using the `int main() {}` function. It has a delay in it. It is evident the code before the delay is running, but the delay never seems to time out and let the next instructions through. Is this by design?

If I rename the method and call it exactly once from the `loop() {}` function though, it does work.

**Edit:**

The code borrowed the 'main()' function and I suppose redefined it:

```
int main() {
    Forward();
    delay(3000);
    Reverse();
}

void Forward() {
    //...
}

void Reverse() {
    //...
}

```

I can see this redefinition of `main()` could cause some serious issues based on the answer below.

# Answer
You don't seem to use standard Arduino stuff since you defined your own `main()` which is normally avoided when programming Arduino.

If you take a look at Arduino provided `main()` (in **hardware/cores/arduino/main.cpp**), you'll see how it is defined:

```
#include <Arduino.h>

int main(void)
{
    init();

#if defined(USBCON)
    USBDevice.attach();
#endif

    setup();

    for (;;) {
        loop();
        if (serialEventRun) serialEventRun();
    }

    return 0;
}

```

Did you notice the `init()` function call at the beginning?

Its code is defined in **hardware/cores/arduino/wiring.c**; what it does is setup all timers used by Arduino functions, in particular a timer that is needed by `delay()`.

In the same **wiring.c** file, you can also find the definition of `delay()`:

```
void delay(unsigned long ms)
{
    uint16_t start = (uint16_t)micros();

    while (ms > 0) {
        if (((uint16_t)micros() - start) >= 1000) {
            ms--;
            start += 1000;
        }
    }
}

```

This will turn into an infinite loop if `micros()` always return the same value, and it does so if `init()` has never been called before.

This is what happens with your code.
> 7 votes

---
Tags: arduino-mega, timers
---


# Question
Title: Warning Arduino CMakeLists "Policy CMP0022 is not set: INTERFACE_LINK_LIBRARIES"
I'm trying to build an Arduino example without using its IDE. My OS is **Windows 8.1** and I'm using the last version of **CMake (2.8.12.2)** and **MinGW (GNU Make 3.82.90)**.

I downloaded the Arduino CMakeLists and I learned all about `make/upload` any firmware in my Arduino. I'm using **Arduino UNO**.

Then, if I modify the CMakeLists saved in `~/arduino-cmake-master/example/CMakeLists.txt` (***arduino-cmake-master*** is the repository folder) to build the WiFi example ***WiFiWebClient*** too:

```
...

#Add the WiFi example -> WiFiWebClient
generate_arduino_example(wifi_example
                     LIBRARY WiFi
                     EXAMPLE WiFiWebClient)
...

```

And execute:

```
  $ cmake -G "MinGW Makefiles"

  ...

  CMake Warning (dev) in example/CMakeLists.txt:
  Policy CMP0022 is not set: INTERFACE_LINK_LIBRARIES defines the link
  interface.  Run "cmake --help-policy CMP0022" for policy details.  Use the
  cmake_policy command to set the policy and suppress this warning.

  Target "uno_example" has an INTERFACE_LINK_LIBRARIES property.  This should
  be preferred as the source of the link interface for this library but
  because CMP0022 is not set CMake is ignoring the property and using the
  link implementation as the link interface instead.

  INTERFACE_LINK_LIBRARIES:

    uno_CORE;uno_example;uno_Wire

  Link implementation:

    uno_CORE;uno_Wire

This warning is for project developers.  Use -Wno-dev to suppress it.

CMake Warning (dev) in example/CMakeLists.txt:
  Policy CMP0022 is not set: INTERFACE_LINK_LIBRARIES defines the link
  interface.  Run "cmake --help-policy CMP0022" for policy details.  Use the
  cmake_policy command to set the policy and suppress this warning.

  Target "uno_Wire" has an INTERFACE_LINK_LIBRARIES property.  This should be
  preferred as the source of the link interface for this library but because
  CMP0022 is not set CMake is ignoring the property and using the link
  implementation as the link interface instead.

  INTERFACE_LINK_LIBRARIES:

    uno_CORE;uno_Wire

  Link implementation:

    uno_CORE

This warning is for project developers.  Use -Wno-dev to suppress it.

CMake Warning (dev) in example/CMakeLists.txt:
  Policy CMP0022 is not set: INTERFACE_LINK_LIBRARIES defines the link
  interface.  Run "cmake --help-policy CMP0022" for policy details.  Use the
  cmake_policy command to set the policy and suppress this warning.

  Target "uno_SPI" has an INTERFACE_LINK_LIBRARIES property.  This should be
  preferred as the source of the link interface for this library but because
  CMP0022 is not set CMake is ignoring the property and using the link
  implementation as the link interface instead.

  INTERFACE_LINK_LIBRARIES:

    uno_CORE;uno_SPI

  Link implementation:

    uno_CORE

This warning is for project developers.  Use -Wno-dev to suppress it.

CMake Warning (dev) in example/CMakeLists.txt:
  Policy CMP0022 is not set: INTERFACE_LINK_LIBRARIES defines the link
  interface.  Run "cmake --help-policy CMP0022" for policy details.  Use the
  cmake_policy command to set the policy and suppress this warning.

  Target "uno_WiFi" has an INTERFACE_LINK_LIBRARIES property.  This should be
  preferred as the source of the link interface for this library but because
  CMP0022 is not set CMake is ignoring the property and using the link
  implementation as the link interface instead.

  INTERFACE_LINK_LIBRARIES:

    uno_CORE;uno_WiFi

  Link implementation:

    uno_CORE

This warning is for project developers.  Use -Wno-dev to suppress it.

-- Generating done
-- Build files have been written to: ~/arduino-cmake-master

```

Later I execute:

```
$ mingw32-make

...

Linking CXX static library libuno_WiFi.a
[ 89%] Built target uno_WiFi
Scanning dependencies of target wifi_example
[ 92%] Building CXX object example/CMakeFiles/wifi_example.dir/wifi_example_WiFiWebClient.cpp.obj
Linking CXX executable wifi_example.elf
libuno_WiFi.a(WiFiClient.cpp.obj): In function `WiFiClient::status()':
C:\Program Files\Arduino\libraries\WiFi/WiFiClient.cpp:160: undefined reference to `ServerDrv::getClientState(unsigned char)'
libuno_WiFi.a(WiFiClient.cpp.obj): In function `WiFiClient::stop()':
C:\Program Files\Arduino\libraries\WiFi/WiFiClient.cpp:131: undefined reference to `ServerDrv::stopClient(unsigned char)'
libuno_WiFi.a(WiFiClient.cpp.obj): In function `WiFiClient::peek()':
C:\Program Files\Arduino\libraries\WiFi/WiFiClient.cpp:117: undefined reference to `ServerDrv::getData(unsigned char, unsigned char*, unsigned char)'
libuno_WiFi.a(WiFiClient.cpp.obj): In function `WiFiClient::read()':
C:\Program Files\Arduino\libraries\WiFi/WiFiClient.cpp:101: undefined reference to `ServerDrv::getData(unsigned char, unsigned char*, unsigned char)'
libuno_WiFi.a(WiFiClient.cpp.obj): In function `WiFiClient::read(unsigned char*, unsigned int)':
C:\Program Files\Arduino\libraries\WiFi/WiFiClient.cpp:107: undefined reference to `ServerDrv::getDataBuf(unsigned char, unsigned char*, unsigned int*)'
libuno_WiFi.a(WiFiClient.cpp.obj): In function `WiFiClient::available()':
C:\Program Files\Arduino\libraries\WiFi/WiFiClient.cpp:90: undefined reference to `ServerDrv::availData(unsigned char)'
libuno_WiFi.a(WiFiClient.cpp.obj): In function `WiFiClient::write(unsigned char const*, unsigned int)':
C:\Program Files\Arduino\libraries\WiFi/WiFiClient.cpp:73: undefined reference to `ServerDrv::sendData(unsigned char, unsigned char const*, unsigned int)'
C:\Program Files\Arduino\libraries\WiFi/WiFiClient.cpp:78: undefined reference to `ServerDrv::checkDataSent(unsigned char)'
libuno_WiFi.a(WiFiClient.cpp.obj): In function `WiFiClient::connect(IPAddress, unsigned int)':
C:\Program Files\Arduino\libraries\WiFi/WiFiClient.cpp:36: undefined reference to `ServerDrv::startClient(unsigned long, unsigned int, unsigned char, unsigned char)'
libuno_WiFi.a(WiFi.cpp.obj): In function `WiFiClass::hostByName(char const*, IPAddress&)':
C:\Program Files\Arduino\libraries\WiFi/WiFi.cpp:228: undefined reference to `WiFiDrv::getHostByName(char const*, IPAddress&)'
libuno_WiFi.a(WiFi.cpp.obj): In function `WiFiClass::status()':
C:\Program Files\Arduino\libraries\WiFi/WiFi.cpp:223: undefined reference to `WiFiDrv::getConnectionStatus()'
libuno_WiFi.a(WiFi.cpp.obj): In function `WiFiClass::RSSI()':
C:\Program Files\Arduino\libraries\WiFi/WiFi.cpp:181: undefined reference to `WiFiDrv::getCurrentRSSI()'
libuno_WiFi.a(WiFi.cpp.obj): In function `WiFiClass::SSID()':
C:\Program Files\Arduino\libraries\WiFi/WiFi.cpp:169: undefined reference to `WiFiDrv::getCurrentSSID()'
libuno_WiFi.a(WiFi.cpp.obj): In function `WiFiClass::localIP()':
C:\Program Files\Arduino\libraries\WiFi/WiFi.cpp:149: undefined reference to `WiFiDrv::getIpAddress(IPAddress&)'
libuno_WiFi.a(WiFi.cpp.obj): In function `WiFiClass::begin(char*, char const*)':
C:\Program Files\Arduino\libraries\WiFi/WiFi.cpp:87: undefined reference to `WiFiDrv::wifiSetPassphrase(char*, unsigned char, char const*, unsigned char)'
C:\Program Files\Arduino\libraries\WiFi/WiFi.cpp:92: undefined reference to `WiFiDrv::getConnectionStatus()'
libuno_WiFi.a(WiFi.cpp.obj): In function `WiFiClass::init()':
C:\Program Files\Arduino\libraries\WiFi/WiFi.cpp:22: undefined reference to `WiFiDrv::wifiDriverInit()'
example\CMakeFiles\wifi_example.dir\build.make:95: recipe for target 'example/wifi_example.elf' failed
mingw32-make[2]: *** [example/wifi_example.elf] Error 1
CMakeFiles\Makefile2:748: recipe for target 'example/CMakeFiles/wifi_example.dir/all' failed
mingw32-make[1]: *** [example/CMakeFiles/wifi_example.dir/all] Error 2
Makefile:74: recipe for target 'all' failed
mingw32-make: *** [all] Error 2

```

The problem is the Arduino.cmake because it's not linking correctly with the library WiFi, but it links with the Wire library.

Anyone knows why that warning appears and why Wire links ok but WiFi doesn't?

Thanks!

**Note**: I'm using original code which is in the repository example, I've not modified this one.

# Answer
> 4 votes
Your question actually has 2 distinct parts:

1. Why does arduino-cmake generate the warning "Policy CMP0022 is not set: INTERFACE\_LINK\_LIBRARIES..."?
2. Why does `make`, using the generated MakeFile, fail when building WiFi example?

**First off**, the arduino-cmake "**Policy CMP0022**" is just a warning, not an error. As per this cmake article, that CMP policy has been only recently introduced in **CMake 2.8.12**.

You get this warning simply because arduino-cmake has been created based on an older version of cmake and thus does not specifically support this new policy.

In order to get rid of this warning, the documentation mentions you should add the `cmake_policy(SET CMP0022 OLD)` command to your cmake configuration.

Unfortunately I tried it in the example `CMakeLists.txt` to no avail; maybe it has to be set directly in arduino-cmake files (which I have not tested).

Thus, if you want to get rid of this boring warning, it seems the only solution you are left with is to disable all warnings when launching cmake:

> cmake -G "MinGW Makefiles" -Wno-dev

This works fine and has removed all warnings..

**Your second problem** (the real one I would say) is due to to the structure of WiFi library:

Indeed, as you can see above, it has a `utility` subdirectory that contains additional source code that **cannot be found by arduino-cmake**, as by default it searches for source code files only at first level directory.

How to solve it? Just tell arduino-cmake to do a **recursive search for the WiFi library**; in your `CMakeLists.txt`, ensure you add the following line:

```
set(WiFi_RECURSE True)
generate_arduino_example(wifi_example
                     LIBRARY WiFi
                     EXAMPLE WiFiWebClient)

```

The added `set(WiFi_RECURSE True)` line just tells arduino-cmake that, for WiFi library, it should recurse through subdirectories when looking for source code.

I have checked it with "Unix Makefiles" (not "MinGW Makefiles" but I guess that won't make any difference) and it worked fine.

---
Tags: arduino-uno, compile
---


# Question
Title: What's the most efficient implementation of map(x,0,1023,50,250)?
I recently noticed how the map() function in Arduino was bulky in both terms of flash space used and time taken to execute, largely because it deals with `long` and involves a division and multiplication.

Many times you can replace maps with more basic functions i.e.

```
output = map(input,0,1023,0,255);

```

can become

```
output = input >> 2;

```

or

```
output = map(input,0,1023,1023,0);

```

can become

```
output = 1023 - input;

```

I have one line in some code that says:

```
backlight = map(LDRreading,0,1023,50,250);

```

How could this be simplified so that it is both space and time efficient?

I'll allow slight differences in output values if it results in a much better solution.

# Answer
The screenshot shows a base-2 (i.e. binary) result of calculating the constant part of a mapping. You can approximate this multiplication by a constant by a number of shifts added together. You need to break down each multiplication in the result first:

x * 0.0012 = x \>\> 3

x * 0.00012 = x \>\> 4

x * 0.00000012 = x \>\> 7

Then add these together. You are essentially breaking it down into convenient base-2 multiplies (which can always be represented by shifts) and adds - nearly always more efficient.

This doesn't get you right to 250, but pretty close:

```
>>> for i in range(0, 1024, 34):
...   print (i >> 3) + (i >> 4) + (i >> 7) + 50
...
50
56
62
   [snip]
235
241
247
>>> print (1023 >> 3) + (1023 >> 4) + (1023 >> 7) + 50
247

```

Do all your processing with a left-justified `int` (`ADLAR`=1) though, to minimize errors. The ADC returns a 10bit result, and ADLAR choses if this is aligned to the left or right of the two result registers.
> 9 votes

# Answer
How about this, mapping to 50..249?

```
output = ((input * 25) >> 7)+50;

```

Your input range was 1024 (0..1023). Output range is 200 (In the original specification, it would have been 201, which does not divide as neatly). These have a gcd of 8, so `output = (input * (200/8)) / (1024/8) + 50` will do, and the division by a power of 2 can be expressed with a shift. The nice thing is that `1024*25` still fits into a 16 bit integer, so no longs are needed.

If you want full range, you can try throwing in rounding

```
output = ((input*25+64) >> 7)+50;

```
> 4 votes

# Answer
You could approximate it quite closely using only two integer operations:

```
backlight = (LDRreading / 5) + 46;

```

That effectively maps input range 0 - 1023 onto output range 46 - 250, so it's fairly accurate. If `LDRreading` is a 2 byte integer type then it should be significantly more efficient (comparatively speaking) than anything which uses `long`.
> 2 votes

# Answer
If the input range is limited in size and you have the memory for it nothing beats a simple lookup-table.

like
unsigned char map\[1024\] = { 50, 50, \<\< more entries here \>\>, 250 } ;

You can pre-compute the content in a part of the program that isn't time-critical or just compute the entire table-content beforehand and put it verbatim in the source-code.

Doing a map is just a read of map\[\] with the original value as index.

If you input range starts with a non-zero number just decrement all inputs by the lower-bound value so you have a 0-base index for the map array. (That works for negative lower-bounds too !)

At most 1 substract (to adjust for a non-zero lower-bound) and 1 addition to calculate the array-base + index.
And a good compiler will be able to optimize it further.

You can't get more efficient than that, but you do need the space to store the table somewhere.
> 2 votes

---
Tags: map, code-optimization
---


# Question
Title: Writing First Library - Serial Stream Object
I have done quite a few projects with Arduino, but have never done more than a "Hello World" in C. I am writing my first library, and a lot of the object oriented stuff is going over my head. Anyway, my library is working as it is supposed to, I pass a float to my function and it formats it properly and sends it out over serial. However, I implemented it in a clunky way. The Arduino API Style Guide mentions a way that seems much better:

> When using serial communication, allow the user to specify any Stream object, rather than hard-coding "Serial". This will make your library compatible all serial ports on Mega and the Due, and can also use alternate interfaces like SoftwareSerial. The Stream object can be passed to your library's constructor or to a begin() function (as a reference, not a pointer). See Firmata 2.3 or XBee 0.4 for examples of each approach.

Can anybody elaborate on how to do this, or show me some code?

# Answer
> 10 votes
Here is a simple example (built and tested with a mega2560), with a class that can be passed a Stream object, and sends a Hello over this generic stream object. When constructing the object, you can pass the Stream object you want to actually communicate:

```
#include "Arduino.h"

class MyProtocol
{
public:
    MyProtocol(Stream& s):serial(s){}
    void send(){
        serial.println("Hello");
    }
private:
    Stream& serial;
};

MyProtocol p(Serial);

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

void loop() {
    delay(1000);
    p.send();
}

```

NOTE: The serial.println() is not the Serial global object, note the lower case, it is the internal Stream class variable.

If you are confused with the OO and classes, take into account (while you gain more knowledge about it) that this approach can be also used with a simple function, you can pass the serial parameter. Furthermore, it is not necessary to hardwire the Serial interface for ever, you can in fact switch in run time and use a different channel depending on some condition:

```
#include "Arduino.h"

void send(Stream& serial){
    serial.println("Hello");
}

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

void loop() {
    delay(1000);
    if(someCondition)
        send(Serial);
    else
        send(Serial1);
}

```

---
Tags: serial, c++, library
---


# Question
Title: How frequently do you need to poll UI buttons before they are perceived as laggy?
Whilst it is possible, and sometimes desirable, to use pin change interrupts to read the state of buttons, it is simpler to poll the state of buttons in `loop()`. This is a commonly used technique.

If you `loop()` executes quickly enough, then button presses are always going to be caught and the user will not be able to perceive any delay or lag.

It is possible that your loop would take so long as to cause a delay or lag to be perceived.

The question is, how long would it be, in general, before a user would see this?

# Answer
> 14 votes
The short answer is that you have **100 miliseconds** to respond to the user if you want them to feel the action occurred instantaneously.

According to Jacob Nielsen in his book Usability Engineering, from 1993, which is considered an important reference in Systems Usability and User Experience:

> * **0.1 second** is about the limit for having the user feel that the system is reacting instantaneously, meaning that no special feedback is necessary except to display the result.

He also mentions that this basic advice regarding response times has been about the same for many decades \[Miller 1968; Card et al. 1991\].

I've taken this citation from this article: Response Times: The 3 Important Limits, also writen by Jacob Nielsen.

Note that in this time you must include all time taken to read the button press and give feedback to the user.

Other response time thresholds that are important for user experience, from the same source, but that were not mentioned directly by the OP are:

> * 1.0 second is about the limit for the user's flow of thought to stay uninterrupted, even though the user will notice the delay. Normally, no special feedback is necessary during delays of more than 0.1 but less than 1.0 second, but the user does lose the feeling of operating directly on the data.
> * 10 seconds is about the limit for keeping the user's attention focused on the dialogue. For longer delays, users will want to perform other tasks while waiting for the computer to finish, so they should be given feedback indicating when the computer expects to be done. Feedback during the delay is especially important if the response time is likely to be highly variable, since users will then not know what to expect.

# Answer
> 3 votes
It's commonly known that people are unable to perceive changes when they happen underneath 10ms after their action. This responsiveness will result in an experience that has recently mostly been described as "snappy". It's noticeable but for users it's hard to put a name on it.

So if you want perfection, take about 15ms of delay. If you want really good, take 100 ms of delay. 100ms is 50ms on average, and will certainly pass for people.

The application and the expected response time is vital too. A sliding door or elevator is given very large tolerance (as the physical object will always take a lot more time) whereas ticket vending machine interfaces are not given any time at all.

The upper limit for polling would be around 1500ms. Around there people will always notice it is slow.

This data is purely personal experience as a gamer and programmer. YMMV and remember that just trying it yourself is the best way to find out how it feels. The only "scientific" answer is the \<10 milliseconds, beyond that it's about the ability to perceive the delay (which varies per person and moment) and the tolerance of the user.

As a side note, you can try fluctuating the delays in order to conserve battery or CPU time when the interface is not being used. The user-action, the faster the polling. When the application is doing it's thing, poll very slowly. Better to poll when it matters!

---
Tags: button, ui
---


# Question
Title: Changing the brightness on a Hitachi HD44780 LCD screen
I am finishing up a project- an LED game alarm clock. Seeing as this is a clock, I need to have a way to conserve power, which right now my Uno R3+ is eating up like a politician. My question is, how do I turn the screen off, or turn the back-light off using software only on a Hitachi HD44780 16x2 LCD screen? Or how do I set a sleep mode on one component? The way I plan on turning it off is with an ultrasonic range finder, if I get close it turns on the screen. If anything I say doesn't make sense, ask me to clarify, I'm in a bit of a rush.

# Answer
Place a transistor in series with a 33R resistor between the LCD pin 16 (backlight ground) and GND and switch the transistor on and off with a digital pin. That way you'll be able to turn the backlight on and off.

You can have a finer control over brightness if you put a PWM pulse on said pin. Just call `analogWrite(D3, value)` where `value` is the desired brightness.

The schematics is below. It's from Freetronics 16x2 LCD SHield.
> 8 votes

# Answer
Instead of tying the backlight directly to V+ and GND, connect it to a PWM pin (you may need to use a separate driver if the pin cannot source/sink enough current). This will allow you to control the brightness via `analogWrite()`.

Turn the LCD display off (`LiquidCrystal::noDisplay()`) when not actively in use. The contents will remain in memory but the LCD segments will not be driven.

Set the various bits in the `PRR` register to disable any peripherals not it use.

And *don't forget to sleep the CPU when it doesn't need to run*. See the "Power Management and Sleep Modes" section of the datasheet for more information about this and the `PRR` register, as well as the `<avr/sleep.h>` documentation for AVR Libc.
> 5 votes

---
Tags: arduino-uno, lcd
---


# Question
Title: How to call C functions from Arduino sketch?
I would like to know if there is a way to call functions that are contained within C files using an Arduino sketch?

My C file declares and defines a function. To save putting the messy function definition into my Arduino sketch, I'd like to call the function straight from the sketch.

Is there a standard way to do this using Arduino and C? Here is the sketch:

```
#include "crc16.h";

void setup(){

}

void loop(){

  CalculateCRC16("<09M", 4);

}

```

and this is the trimmed down C file:

```
#include <stdio.h>
#include <stdint.h>

uint16_t crctable[256] =
{
    0x0000, 0x1189,.....

uint16_t // Returns Calculated CRC value
CalculateCRC16( // Call example CalculateCRC16("<09M", 4);
    const void *c_ptr, // Pointer to byte array to perform CRC on
    size_t len)        // Number of bytes to CRC
{

    uint16_t crc = 0xFFFF // Seed for CRC calculation
    const uint8_t *c = c_ptr;

    while (len--)
        crc = (crc << 8) ^ crctable[((crc >> 8) ^ *c++)];

    return crc;
}

```

# Answer
> 11 votes
You can extern "C" #include like the following:

```
extern "C"{
#include "crc16.h"
};

void setup(){
}

void loop(){
  CalculateCRC16("<09M", 4);
}

```

And the crc16.h file could be (some minor fixes, the #pragma once, a cast):

```
#pragma once

#include <stdio.h>
#include <stdint.h>

uint16_t crctable[2] ={ 0x0000, 0x1189};

uint16_t CalculateCRC16( // Call example CalculateCRC16("<09M", 4);
    const void *c_ptr, // Pointer to byte array to perform CRC on
    size_t len)        // Number of bytes to CRC
{
    uint16_t crc = 0xFFFF; // Seed for CRC calculation
    const uint8_t *c = (const uint8_t *)c_ptr;

    while (len--)
        crc = (crc << 8) ^ crctable[((crc >> 8) ^ *c++)];

    return crc;
}

```

# Answer
> 4 votes
Your CRC function can easily be converted to C++ so that it can go into a \*.cpp file. All you need to do is use an explicit cast when you initialise your `c` pointer. Here's the 'proper' C++ way to do it:

```
const uint8_t *c = static_cast<const uint8_t*>(c_ptr);

```

However, an old C-style cast would also work:

```
const uint8_t *c = (const uint8_t*)c_ptr;

```

The problem is basically that C can be a little more permissive about letting you convert pointers implicitly between types. To do it in C++, you need to tell the compiler explicitly that the conversion is intentional.

# Answer
> 1 votes
Yes, just copy its declaration line in your sketch:

```
extern "C" {
    void myfunction(int arg);
}

```

---
Tags: arduino-uno, software, c
---


title: 'Basic electronics' resources

text:
# Question
Title: 'Basic electronics' resources
I've seen that there are many resources on programming basis for arduino for people that have some electronics basis or background. Are there similar resources on the opposite? Basics electronics for programmers? Things that cover:

* How to read schematics (different elements that appear there)
* What different pins are used for (yeah, even on a more basic level than arduino documentation)
* General idea of how a protoboard/protoshield works and how to connect components
* General common components (resitors, capacitors...) and when and how to use them...
* Safety rules, what happens when you do something wrong

# Answer
# From zero to Arduino (maybe a HOWTO someday?)

Rule zero:

* Don't overestimate the other Arduino users! They all were not born with this knowledge too.
* Never be too shy to ask!
* Making mistakes is ok as long as they trigger learning.

(-: short break :-)

You'll find lots of HOWTOs and other tutorials in the wild wild web.

I assume, the confusing thing is to read them in the wrong order.

Forget your Arduino(s) for a while and start with reading about:

* General common components (resitors, capacitors...) and when and how to use them...

This will at least partially answer:

* Safety rules, what happens when you do something wrong
* How to read schematics (different elements that appear there)

If not already done:

* Read about ANDs, ORs, NANDs, NORs, FLIPFLOPs...

This will show how their schematic symbols look like.

* ...compare them to creating the same behaviour by programming (if, and (&&), or (||), ...)
* Have a look at bit operations (&, |, ... on whole number variables.

The programming up to this point can be done on your PC.

After this, dedust your Arduino again and jump into:

* What different pins are used for (yeah, even on a more basic level than arduino documentation)

(Happy end. At least for now.)

(I make this a community wiki answer to invite others to expand this text.)
> 2 votes

# Answer
This is an extract of an introductory book that shows basic schematic components:
> 1 votes

---
Tags: hardware
---


# Question
Title: 7segment blink when the button is pressed
I have programmed an IR remote control along with an LED and an 8bit 7segment on an Arduino Uno. the segment displays the number I press via the remote, and the LED turns on and off here's my code:

```
case 16738455:
  Serial.println(0);
  if (oldvalue == results.value){
    on(num0);
    delay(1000);
    on(num00);
    delay(1000);
    oldvalue = results.value;
  }

```

oldvalue stores the last value pressed, which is the DEC value of the buttons, num0 displays the number zero, and num00 turns all the segments off. I want the 7segment to blink again when I press the same button again. Can anyone help me with this? Thanks

# Answer
> 2 votes
A simple solution would be to not worry about blinking as a piece of code, ie. remove those delays (I hate blocking code) and instead, if you are currently receiving a signal from the remote, do not display any number (or display your `num00`). Once the value is received and processed, then display that number.

This way, whilst ever the remote button is down, the display will blank out, and the number will appear as soon as the number is released. If it's the same number, then you will see the number, see a blank display, and then see the same number again. Obviously, if it's a different number, the new number would be displayed.

Since most people would only press the remote button for 100-1500ms, it should give you a nice delay anyway.

Finally, you may encounter some flashing if you process the data so quickly and the remote auto repeats. This could be handy if that number is processed multiple times by the receiving unit. The flashing would indicate that that is the case. If that is undesired, implement a simple state machine.

**edit:** your pastebin code came up whilst I was writing this answer. Having a quick look at your code, I would suggest that in the section:

```
if (irrecv.decode(&results)) {
  //receiving data? display nothing
  on(num00);
  digitalWrite(ledPin, HIGH);
  Serial.println(results.value, DEC);
  irrecv.resume();
  delay(100);
  int oldvalue = results.value;
  switch(results.value){
    case 16738455:
      Serial.println(0);
      num2display=0;      // make sure to declare this var somewhere
      //if (oldvalue == results.value){
      //  on(num0);
      //  delay(1000);
      //  on(num00);
      //  delay(1000);
      //} else {   // I think you missed an else here
      //  oldvalue = results.value;
      //}
      //on(num0);
      //delay(1000); // you don't want such large blocking delays
      irrecv.resume();
      break;
    case 16724175:
      Serial.println(1);
      num2display=1;       // add this for each section
      irrecv.resume();
      break;
      . . .
  }
}
else{
  digitalWrite(ledPin, LOW);
  on(num2display);
}

```

you only set the variable to be displayed, but display `num00`. Then in the else, you can display that number

---
Tags: arduino-uno, ir
---


title: Program stops working after a minute

text:
# Question
Title: Program stops working after a minute
I have made this small program to lighten up in sequence 8 LEDs, it starts fine, but it stops working after a minute or so and the first 2 LEDs stay permanently ON, its like the chip stoped, here is the code :

```
// Initialize an array with all 8 leds
// and give them the corresponding
// digital number.
const byte led[8] = {0,1,2,3,4,5,6,7};

// the setup routine runs once when you press reset:
void setup() {

  // initialize all 8 digital I/O pins as outputs.
  for (byte i = 0; i<9; i++) {
    pinMode(led[i], OUTPUT);
  }
  pinMode(13, OUTPUT);
}

void left (void);
void right (void);

// the loop routine runs over and over again forever:
void loop() {

  right();
  left();

}

void left (void) {
  for (byte i = 0; i<9; i++) {
    digitalWrite(led[i], HIGH);
    delay(50);
    digitalWrite(led[i], LOW);
  }
}

void right (void) {
  for (byte i = 8; i>0; i--) {
    digitalWrite(led[i], HIGH);
    delay(50);
    digitalWrite(led[i], LOW);
  }
}

```

I am using a very old arduino duemilanove.

# Answer
> 3 votes
You had several problems with your loop conditions. Arrays are 0 indexed. If we declare `const byte led[8]`, `led[0]` is the first element and `led[7]` is the 8th and last element.

Also, in `void right()`, you declared `i` as a `byte` which is an 8-bit, unsigned number from 0 to 255. While you wrote the conditional to be `i>0`, it needs to be `i>-1` or `i>=0`. So, if we change the coditional and keep `i` as a `byte` the loop would decrement `i` like 8,7,6,5,4,3,2,1,0,255,254... forever. So instead, `i` should be declared as a `char` which is an 8-bit, signed number from -128 to 127.

```
// Initialize an array with all 8 leds
// and give them the corresponding
// digital number.
const byte led[8] = {0,1,2,3,4,5,6,7};

// the setup routine runs once when you press reset:
void setup() {
  // initialize all 8 digital I/O pins as outputs.
  for (byte i = 0; i<8; i++) {
    pinMode(led[i], OUTPUT);
  }
  pinMode(13, OUTPUT);
}

void left (void);
void right (void);

// the loop routine runs over and over again forever:
void loop() {
  right();
  left();
}

void left (void) {
  for (byte i = 0; i<8; i++) {
    digitalWrite(led[i], HIGH);
    delay(50);
    digitalWrite(led[i], LOW);
  }
}

void right (void) {
  for (char i = 7; i>=0; i--) {
    digitalWrite(led[i], HIGH);
    delay(50);
    digitalWrite(led[i], LOW);
  }
}

```

# Answer
> 3 votes
Your loop conditions aren't quite right, which could be resulting in undefined behaviour. I highly doubt it would cause it to stop working spontaneously, but it's possible in theory.

In each loop that counts upwards, you basically need to stop *before* the counter reaches 8. For example:

```
for (byte i = 0; i<8; i++) ...

```

Note that it's `i<8` instead of `i<9`.

The reason is that the array is only 8 elements long, so the indices run from 0 to 7 (inclusive). Currently, your loops are going all the way up to and including 8, which means it's trying to read past the end of your array.

You'll need to fix that in `setup()` and `left()`.

The loop that goes downwards in `right()` is a little more difficult. At the moment, it runs through indices 8 to 1, meaning it has the same problem of reading past the array. However, it also never actually reaches index 0.

It's harder to fix because `byte` is an unsigned type, so you can't use `i>=0` as your condition (as it will never terminate). Personally, I would rewrite the loop to count upwards, but then reverse the index order inside the loop, so that 0 becomes 7, and so on. For example:

```
for (byte i = 0; i<8; i++) {
    digitalWrite(led[7-i], HIGH);
    delay(50);
    digitalWrite(led[7-i], LOW);
}

```

Like I said, I doubt this will actually solve your problem. It's worth trying though.

# Answer
> 1 votes
Thank you guys, its fixed now, i just dont understand why i cant use byte if i do, i\>=0, this way i never goes to 255 anyway and if does, it doesn matter, unless im missing something. Here goes the final working code :

```
/*
  Blink
  Turns on all 8 leds in sequence back and forth.

 */

// Initialize an array with all 8 leds
// and give them the corresponding
// digital number.
const char led[8] = {0,1,2,3,4,5,6,7};
#define speed 40

// the setup routine runs once when you press reset:
void setup() {

  // initialize all 8 digital I/O pins as outputs.
  for (int i = 0; i<8; i++) {
    pinMode(led[i], OUTPUT);
  }
  pinMode(13, OUTPUT);
}

void left (void);
void right (void);

// the loop routine runs over and over again forever:
void loop() {

  // Turn off the buzzer on pin 13
  digitalWrite(13, LOW);

  while(1) {
  right();
  left();
  }

}

void left (void) {
  for (int i = 0; i<8; i++) {
    digitalWrite(led[i], HIGH);
    delay(speed);
    digitalWrite(led[i], LOW);
  }
}

void right (void) {
  for (int i = 7; i>=0; i--) {
    digitalWrite(led[i], HIGH);
    delay(speed);
    digitalWrite(led[i], LOW);
  }
}

```

---
Tags: led
---