text:
Can I program for Arduino without having a real board?
I would like to start the development of some basic Arduino projects but I don't own an Arduino board yet. Is there a way I can write my code and emulate/test it using a desktop computer so after my board arrives I just have to upload and run my project on it?

I’m interested too, did you find one that plays well with the Arduino IDE? that is, detected by the IDE as if it was a board, with all its functionality.

I am interested in the free online Wokwi Arduino Simulator for the reasons that it runs on both windows, MAC and mobile browsers. It runs on AVR8js based engine and is also made open-source. can you review this?

There are a whole slew of Arduino simulators out there, many free, and some paid products as well.

The CodeBlocks Arduino development environment includes a free Arduino simulator, still under development but functional.
Simuino simulates the Arduino Uno and Mega pins - not a pretty-looking realistic simulator, but it works.
The Python based Arduino Simulator is another option, that plays well with the official IDE
Virtronics Simulator for Arduino looks promising, but I don't see why I would pay $14.99 for it, when I could buy one or more actual Arduino clones for that price

Many other Arduino simulators are out there if you search, and new ones are being announced, even crowdfunded, all the time.

as a note, those are not emulators but simulators, the most important difference is that it does not run the code on a AVR virtual machine (like what qemu does), but binds the Arduino functions to native code. So basically they won't be able to run native AVR stuff and register/timer behavior will not be the same as on real AVR hardware. See the difference well explained in that answer. It is, though, theoretically possible to emulate Arduino Due code with qemu.

You "don't see why [one] would pay $14.99 for it, when [one] could buy one or more actual Arduino clones for that price"? I can tell you why: because the hardware doesn't have a built-in debugger with the features that can be provided by a simulator.

The Arduino Simulator piqued my interest, but unfortunately appears to have no files related to it on the sourceforge site. Am I missing something, or has it become deprecated since you wrote your answer?

As noted in above comment, there are no files in the arduino simulator source forge site. Is there a website for it or is there another simulator that works well in mac, with official IDE?

Simuino is terrible, unprofessional and useless.  They have no clue how to code.  Arduino Simulator has no releases.  CodeBlocks is Windows only. Simulator for Arduino isn't open-source.

I like to use circuits.io aka TinkerCAD for this.
It's cloud based and has some nice features including PCB design and collaboration.
IMO the Arduino simulation and capability is impressive and intuitive.

It is very nice and clean and basic functionality is really impressive, easy to use and powerful. However many common parts (including LCD and temperature sensors) are not supported yet. I doubt you can test anything but very basic designs at this stage. I hope this will get better over time.

I gave it a quick try and found it very impressive for a free product. I don't know its limitations in terms of simulation realism, but the editor is very friendly and just placing a led into the proper slot automagically created code with the correct pin and a blinking loop!

even my choice would be 123d but my only complain about this site is they don't add new components. It would be really great if they can have some new components on their list

The electronic labs part of circuits.io site has moved to tinkercad.com, where you can find it under circuits.

The answer is outdated

I have edited it and updated the links.

free Arduino simulator is free, based on open-source AVR8js, and works on Android, iPhone, Windows and Linux. Can you please first check it out and then update your answer. This helps to reach so many Arduino users who are looking for a good arduino simulator with examples. In many aspects, it is better than Tinkercad.

Plenty of options exist in the world of electronics simulators, but circuits.io aka TinkerCAD is probably the most versatile one out there.

You can compose your circuit on a virtual breadboard which looks just like real.
You can actually watch a LED blinking or press a button during real-time simulation rather than struggling with abstract waveforms.
You can combine digital devices like a 555 timer or shift registers with (interactive) analog components like resistors and LEDs.
You can program an Arduino and simulate the microcontroller together with your analog circuit around it.
You can debug an Arduino: when the simulator reaches your breakpoint, the simulation is paused and you can easily check every variable in your code and every voltage or current in your circuit.
You can use and observe different communication protocols like UART, I2C and SPI.
You can pause the simulation in the middle of an I2C sequence by putting a breakpoint in the driver code (e.g. interrupt service routine for I2C events)
It's FREE!

This is an example circuit that has with an IR Remote and an LCD Screen.
Disclaimer: We are the makers of 123D Circuits

How does it play with the Arduino IDE? would it be available to flash, debug, etc?

Be aware that no simulator will reproduce real-life situations. There have been plenty of posts on the Arduino forum about problems with code or electronics, which turn out to be something subtle, such as:

Timing issues
Race conditions (related/dependent events not always happening in the same order)
Voltage levels, eg. floating input pins
Driving motors which drop the Arduino voltage enough that it resets
Not having decoupling capacitors
Input pins being in an "undefined" state (eg. 2.5V on a pin where 2 or less V is LOW and 3V or more is HIGH)
Problems with interrupt handlers, such as variables not being declared volatile
Voltage spikes due to not having flyback diodes on motors
The processor resetting once more than 10 LEDs are turned on because the current draw exceeds the amount the hardware can supply
Interrupt handlers taking 10 µS to process an interrupt when only 9 µS is available.

By their nature simulators can't reproduce all of this. Even if they could, would you think to toggle the "insert random noise from motors" option?

As for getting ready for the board to arrive, download the IDE and start programming. You can get libraries installed, code written and free of syntax errors, organize it neatly, and be generally ready for the big day when the hardware is in your hands.

Have fun and enjoy experimenting with your Arduino!

This is a good troubleshooting checklist for when a circuit is misbehaving seaport appearit "logically" correct.

There is one point I would like to thank you for. The bounce effect of the pushbuttons creating so many problems for beginners unless addressed. inspired b your list, I had asked to add this feature in the wokwi and now the simulator supports bounce feature in the push buttons!

Edit 2:
Please hit the like button to support free Arduino simulator
I am working with the new Wokwi Arduino Simulator. Wokwi Arduino simulator is based on AVR8js engine which is made open-source. You can find the link here
Following are the main features of the simulator
•   Supports multiple file projects
•   Supports the Arduino libraries
•   Whatever compiles on the Arduino IDE will compile on the simulator
•   Supported by all browsers
•   Compiles with latest Arduino IDE
•   Supports FastLED and many other peripherals
•   No download or installation needed
•   Easy to share the code and project with just a single click
•   Smart - Code Autocompletion, Code auto-formatting are supported
•   Provides standard library demo examples
•   Project can be compiled on RUN on Mobile browsers as well
•   Tries to be closer to real circuits – Example – Button bounce like in real hardware
•   Supports Arduino Mega, Arduino Nano, Arduino UNO, ATtiny85
•   Supports assembly instruction execution
•   Provides LED power and FPS features for FastLED projects
•   Supports a plethora of Arduino peripherals for the project – Ultrasonic sensors, Slide switches, NeoPixel matrix, Potentiometer, Servo motors, SSD1306 OLED displays, temperature and humidity sensors, rotary dialer, membrane keypad and more
•   Serial monitor is supported as well
A few Arduino Examples
Simon game using ATTiny85, buttons, buzzer, and LEDs
Project link: https://wokwi.com/arduino/projects/285525640477671948
•   Note the use of the same pins for both output and input
•   The code can be written for ATTiny85 the same way how it is written for Arduino

Slide switch demo example
Project link: https://wokwi.com/arduino/projects/292033853022798344
The slide switch can also be used as an ON-OFF switch

Simple Piano Example
Project link: https://wokwi.com/arduino/projects/291958456169005577
Plays several notes based on Arduino built-in library support

Max7219 LED dot matrix Arduino UNO project Example
Project link: https://wokwi.com/arduino/projects/290144516831183368
Supports concatenation of the Max7219 modules

HC-SR04 Ultrasonic sensor Example
Project link: https://wokwi.com/arduino/projects/290056311044833800
A very useful project to build several interesting projects (RADAR 3D mapping and more  )

Bounce feature example in Arduino Simulator
Project link: https://wokwi.com/arduino/projects/288332630964830728
Bounce is the basic problem in most beginner projects. That can create multiple input triggers, unwanted noise and makes the project to misbehave. Sometimes can be difficult to identify without proper debug or measurement tools. Knowing about the bounce in switches and tips and tricks on how to solve it is an interesting study for every beginner hobbyist.

LCD1602 display example in Wokwi Arduino Simulator
Project link: https://wokwi.com/arduino/projects/287736345015616008
LCD1602 is one of the best HMI and has been here for a long time. It helps in debugging projects during run time, we can also use it along with a keypad to make a completely practical HMI (human-machine interface). Very easy to use, and easy to learn about programming.

FastLED example with FPS and LED power
Project link: https://wokwi.com/arduino/projects/287736345015616008
Second link: https://wokwi.com/arduino/projects/281176629596652040
FastLED is a second revolution in the history of LEDs. It was never easier than now to program multiple LEDs with just one Arduino Pin. With the growing FastLED community (reddit, wokwi-Discord, and others) and FastLED examples and libraries, This is one of the most important elements in the wokwi Simulator.

Temperature and humidity sensor, Real time clock module example
Project link: https://wokwi.com/arduino/projects/287736345015616008

Serial Monitor example
Project link: https://wokwi.com/arduino/projects/286653669554782732
The serial plotter is a very useful feature when working with analog peripherals.

Adafruit SSD1306 Library Adafruit SSD1306 Library
Adafruit DHT Sensor Library
Another DHT library from GitHub
FastLED example Library
SSD1306 GitHub example
Arduino Servo Library
Task Scheduler Library
Simon Game, Electronic Safe Example
LCDGFX on Arduino Example
SSD1306 Library Examples

The Arduino simulator is free for the Arduino Community to use. We are adding more elements one after the other. It is free and we invite you to try it as well.
Please leave a comment to add more libraries or features as well

You can use Yenka (free for home use) to simulate Arduino, PIX, PIXACE and other boards with digital, analog and serial I/O. It provides a lot of components and sample projects.
Screenshot:

Can it be programed, debugged from the Arduino IDE?

Yes, you can, try using Proteus ISIS for simulating your code...
For full emulation of Arduino, there is a shareware program called VBB (Virtual BreadBoard), I tried it too and it was nice.
Edit: You can check my detailed tutorial here on how to simulate on Proteus ISIS

I believe this website has a list of both emulators and simulators along with their price and availability.
Update:
Since some users mentioned there are broken links in that website, here's a selection of emulators I found. Note that some descriptions may have been taken from the mentioned link:

Emulino: Is an open source linux based software in early development that emulates Arduino-specific MCUs.
Emulare: is a general purpose hardware emulator. It aims to provide a central interface to build electronic simulations for embedded software development. At present emulare focuses on the ATMega line of microcontrollers (Arduino UNO has the ATMega processor).
SimAVR: is a new AVR simulator for linux, or any platform that uses avr-gcc. The simulator loads ELF files directly, and there is even a way to specify simulation parameters directly in the emulated code using an .elf section. It supports emulation of many ATMega processors and it is mentioned that it's easy to even add new ones.
Amtel Studio: This doesn't seem to mention the term emulation, but it is a sophisticated IDE to debug your code for many platforms specially Arduino. Atmel Studio 7 features seamless one-click import of projects created in the Arduino development environment. Your sketch, including any libraries it references, will be imported into Studio 7 as a C++ project. Once imported, you can leverage the full capabilities of Studio 7 to fine-tune and debug your design. Atmel Studio 7 fully supports the powerful embedded debugger on the Arduino Zero board. For other Arduino boards, shield-adapters that expose debug connectors are available, or switch to one of the many available Xplained-Mini/PRO boards to fully leverage the Atmel HW eco-system.

You can still use simulators such as EasyEDA to test your code and in most cases be able to run it on the device. But note that given the nature of electronic components, you may have to provide external resistors, capacitors etc to get the expected results.

Link only answers not a good thing here because they will be useless when the linked site goes down. Please write a summary and also make sure that your answer adds value and not just repeating the ones we already have.

I agree with @totymedli - if that link goes dead the answer becomes useless. Please summarize, at least, the emulators mentioned and the current price. You can start lines with an asterisk to make bullet points, if that helps.

Virtualbreadboard has a new VBB4Arduino 'Two Arduino's' edition which includes BOTH a JVM Arduino emulator AND a AVR Instruction set simulator with examples that cover almost all of the Arduino distribution examples and a bunch of peripheral hardware - LCD's, WS2812 Neo LEDS, Motors, Servo's, Logic Analyser and more.
http://www.virtualbreadboard.com
Disclaimer: I am the author of Virtual Breadboard

You could e.g. use my simulator.
It is especially suitable for PLC-like applications, where multitasking is achieved by cyclic evaluation of interconnected circuit-like objects: Timers, Markers, Latches, Oneshots and Registers.
You can use it to simulate your controlled system as well, as becomes clear from the examples in the download. It has modest visualisation capacities, can draw timing charts, and allows you to access and alter c.q. force all variables in real time during a running simulation. Also you can freeze time. When you're satisfied with the behavior of your control it generates the C code to be uploaded to an actual Arduino.
https://pypi.python.org/pypi/SimPyLC

a way I can write my code and emulate/test it using a desktop computer

If you mean being able to "unit test" using a desktop computer, I can offer a library I wrote called arduino_ci.
It doesn't offer emulation.  You would express your tests in code.  For example, here is a test pulled from the reference documentation that validates the data written to a port:
unittest(pin_history)
{
  GodmodeState* state = GODMODE();
  int myPin = 3;
  state->reset();            // pin will start LOW
  digitalWrite(myPin, HIGH);
  digitalWrite(myPin, LOW);
  digitalWrite(myPin, LOW);
  digitalWrite(myPin, HIGH);
  digitalWrite(myPin, HIGH);

  // pin history is queued in case we want to analyze it later.
  // we expect 6 values in that queue.
  assertEqual(6, state->digitalPin[1].size());
  bool expected[6] = {LOW, HIGH, LOW, LOW, HIGH, HIGH};
  bool actual[6];

  // convert history queue into an array so we can verify it.
  // we expect to find 6 values: the 5 we set, plus the initial LOW
  // and this is where/how we assert that
  int numMoved = state->digitalPin[myPin].toArray(actual, 6);
  assertEqual(6, numMoved);

  // verify each element
  for (int i = 0; i < 6; ++i) {
    assertEqual(expected[i], actual[i]);
  }
}

In practice, you would probably not be calling the digitalWrite functions directly -- you'd call a function in your library, then verify that the "world state" (represented here by the GODMODE construct) matches what you expected your library to do.

An alternative to simulators are services similar to online compilers like coliru, which allow users to build and run their code on a remote system. This approach has the same limitations as online compilers:

The hardware configuration and state cannot be altered remotely, except for explicitly defined interfaces.

The changes to the hardware state cannot be observed, again, except for explicitly defined interfaces.

Typically, most online compilers provide users with access to command line and process STDOUT. On Arduino, providing remote access to the serial port would provide a similar degree of control: users would be able to observe and control their running sketch through UART, but would not be able to connect/remove wires, push buttons, act on external sensors, etc.
Surprisingly, I couldn't find any such online services, so I ended up writing my own - HW Farm. If you have a web server and Arduinos you can connect to it, you can install HW Farm on it and let people access those Arduinos through a web interface. I also host such a server myself, which has a single Arduino Mega with a bunch of I2C devices connected to it. You can try it out, but don't expect it to be online and available all the time.

Yes you can, and fairly easily. There is a wonderful online simulation (completely free) called TinkerCAD. It has an excellent breadboard simulation, with parts like transistors, LEDs, ICs, and Arduino. You can program the Arduino and run it all in a live simulation that includes interactive inputs (pushbuttons, DIP switches, etc.).

[Edit: The following text refers to functionality that has been moved to Circuits.io, namely Eagle PCB]
That's not all. It also includes in a separate tab schematics for your circuit, and another tab for PCB design of your breadboard circuit! Or, you can just make your schematics from scratch and make your PCB from there.
You can have your circuit designs made and you can buy them. You can do all of this in circuits.io, and you aren't risking messing up your actual Arduino. It also has warning indicators in the simulation (for example, if you didn't use enough resistance on an LED, or an IC).


text:
How to sense snow and ice?
We are building an outdoor snow melting system for the pavement. It would be nice if it could turn on itself only when it is needed: if there is snow, ice in the surface or the pavement is wet and the temperature is below the freezing point. Is there a good way to detect if the surface of something is snowy, icy or wet?

If the pavement is black, you could detect snow by infrared reflectivity. You might detect wet by resistivity. That leaves ice. Reflectivity might work there, too, at a different threshold. You'd need to experiment.
Another possibility might be a short-range sonar. If the measured distance changes, something is there. Ice would probably read as nearer. You'd probably need to average a number of measurements to increase the measurement resolution; you care about very thin ice coatings. Snow might well read as no return - but again, experiment.
A combination of the reflectivity and sonar might be the most reliable.

I may experiment with a simple photocell used to turn lights on or off, and a light source for night time.  Mount the photocell so that its lens is upwards towards the sky, at night you'd need a light source shining on the photocell, I'm thinking a very low wattage led light to reduce power consumption, or even another photocell or astronomical time clock to turn the light source on or off, depending on how complex you'd want to make it.  When the photocell can no longer detect light you know it is covered.  You'd have to experiment with the opaqueness of the snow, and how much coverage would block out the light.  Seems like a cheap, easy, pretty much "out of the box" solution for snow anyway.

cheap video camera with snow detection software. See this article for a start

Please summarize the linked content because if it goes down your answer will loose its value.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
Change Options for the AVR Programmer via Arduino IDE
I want to program an ATtiny through the Arduino IDE. I have a somehow strange programmer. But I can upload via avrdude by

avrdude -p attiny13 -P /dev/cu.usbmodemfa131     -c stk500v2    -F -B20 -U flash:w:programm.hex

It took a while to figure out that I had to slow the baud rate via the -B20 switch. If I try to upload via the arduino 1.0.5 IDE avrdude is executed as follows.

/Applications/Adafruit Arduino 1.0.5.app/Contents/Resources/Java/hardware/tools/avr/bin/avrdude -C/Applications/Adafruit Arduino 1.0.5.app/Contents/Resources/Java/hardware/tools/avr/etc/avrdude.conf -v -v -v -v -pattiny13 -cstk500v1 -P/dev/tty.usbmodemfa131 -Uflash:w:/var/folders/9t/5jldfq752fs1x74_rhn2plz80000gn/T/build7680201613426497544.tmp/attinytest.cpp.hex:i

My question is, how can I change the preferences such that I have control over the avrdude parameters? Say I want to add a -B20 switch and change stk500v1 to stk500v2.

Short answer: I'm afraid you can't do it with Arduino IDE 1.0.5.
Long answer:
First of all, be aware that -B20 does not specify the baud rate but the bitclock period (in us); this is specific to stk500v2 programmer.
Normally, enabling your programmer should only be a matter of adding it to the list of programmers known by Arduino IDE; that list can be found in hardware/arduino/programmers.txt. You would then append the following lines at the end of this file:
strangeprogrammer.name=Somehow Strange Programmer
strangeprogrammer.communication=serial
strangeprogrammer.protocol=stk500v2
strangeprogrammer.force=true
strangeprogrammer.speed=?????

However, the problem here is that Arduino IDE does not seem to be able to use flag -B (bitclock period) but only flag -b (baud rate) which value is set to whatever you will put to strangeprogrammer.speed.
At least that's what I could find out by inspecting Arduino IDE source code: AvrdudeUploader.java never adds that flag to the avrdude command-line :-(
That means your options are:

Rebuild the Arduino IDE 1.0 on your own after modifying AvrdudeUploader.java to support -B flag; code should be quite easy (about 2 more lines of Java code).
Switch to Arduino IDE 1.5 and follow Federico's answer :-)
Use another IDE, something that deserves the IDE name. I use Eclipse with this Arduino plugin and it works fine for me. As a bonus, avrdude support seems better as you can see on the screenshot below:

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Compatibility between Arduino and Arduino clones
In a project I am using a Seeeduino v3.0 as an Arduino clone. On the seeeduino website it says that

It is based on the Duemilanove schematic, 100% compatible to its existing program, shield and IDEs.

In fact I never had any problems with shields or the IDE.
My question is now: Is the seeeduino and other clones really 100% compatible? The seeeduino board was considerable cheaper then an arduino.

Over the years I have used original Arduino boards as well as a multitude of clones of varying provenance, from the excellent InduinoX that is listed on the Arduino site as an official compatible board, to the very well-made Chinese Meduino Nano Enhancement (3.3 / 5 Volt switchable), to dirt-cheap clones from eBay that are sometimes better constructed than the official boards.
There is nothing unique or sophisticated about the Arduino board: It's basically just the microcontroller (atMEGA328, atMEGA1280, SAM3X8E or others) and its minimal support hardware. Not much that can go wrong with that little, really.
The two common elements that ensure compatibility across these boards are:

The Arduino bootloader
Support for the board within the official Arduino software distribution

The bootloader can be replaced with a better or more up-to-date version if one is available for the microcontroller on your board.
The support files can either be found online, or minor edits to the nearest similar board's files can provide the requisite support for the Arduino environment.
In short: Yes, clones typically work just as well as the original Arduino, and clones with enhanced features often work far better while retaining compatibility (e.g. InduinoX)

BTW playground.arduino.cc is a community wiki, not the official site. AFAIK, there is no list of official compatible boards.

If you closely look at the Arduino circuit diagram, You'll notice that it is little more than power supply, a USB-serial interface and the microcontroller itself.
The 'hard' part for compatibility is getting the board layout right (which connector goes where on the circuit board), and to load a compatible bootloader in the chip (which is free/open software, so why bother making your own?).
I've used several el-cheapo Arduino clones and apart from apparent physical construction (one feels a bit flimsy), they all work just like the 'real thing'. I guess the major difference between original and clone is the quality of the board, the used components and quality of assembly.

Check twice !
Most clones are exact clones with copies of the flaws that original Arduino board had. Like for example Arduino Nano not having proper RESET and TEST pin connection of FT232RL USB-serial bridge. This flaw may lead to FT232RL not responding to PC and was eventually fixed in later revisions of Arduino Nano board. Some clones were not updated.
Another "not exactly Arduino clones" example are numerous boards with CP2102 USB to serial bridge instead of FT232RL. This may pass unnoticed, but may give frustration when one clone board connects and works with your PC, but another generates system complains on missing drivers.
So again - be prepared !

I have found that most clones will do what you expect them to do, but as x4mer states in his answer, be prepared.
The most annoying issue, and even then it is quite minor, is that a lot of Chinese clones do not use an ATMega for the USB and instead use a CH340G.  These chips, while fine when connecting to a PC running Windows 7, have great difficulties with the drivers on OS X, and end up just not being recognised. It is possible to find a driver for the CH340G, but when I installed it, it immediately crashed the MacBook, upon plugging in the cloned UNO..!
I had to buy three or four clones on eBay until I got an Uno with an actual 16u2 implementing the USB interface, which would actually be recognised by the MacBook Pro, and would allow me to code using the Arduino IDE running on OS X.
Before that, I had to use a Wintel laptop.


text:
RF remote control using VirtualWire on ATtiny85 running at 8MHz on internal oscillator
I'm trying to make an RF remote control using ATtiny85 running at 8MHz on internal oscillator, this cheap RF 434MHz transmitter module (like the one below), and VirtualWire lib, but had no success so far.

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:

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

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

You know you generally need to add an antenna on the transmitter module, right? Also, maybe try reducing the bits/second in the virtualwire setup too.

@FakeName well, to be honest, I didn't even solder the RF module to the board yet, as I can't even get the MCU to send the bits to the TX pin yet. So I'm putting the scope probe to the TX pin and if I see na attempt at a transmission, then I'll solder the module in.

Ah, whoops, missed that. You definitely need to look into proper pin-mapping. The virtualwire library does claim general AVR8 support, as well as having a specific note about the ATtiny84. I am curious, though. Some of your pins are A{n}, while the transmitter pin is PB{n}. Is that the correct pin mnemonic?

I don't see PB1 defined in any of the ATtiny headers you link. Assuming that your transmitter is on PORT B, pin 1, I think you should have #define TXD_PIN  1, since port B is just accessed using the traditional digital IO mnemonic.

@FakeName After much debugging, the final Ax pin combination was the one that worked for me (except for the TXD pin, obviously). I guess you can refer to either PBx or Ax as they are macros that end up getting replaced by integers (guessing here).

The issue is that it looks like the static variables that PBx is referring to are not defined by the ATtiny libraries, so they may just kind of incidentally work. Have you verified you can controll PORT B 1 normally (e.g. with plain digitalWrite() commands? Alternatively, just swap the LED and TX pins, and use the LED pin (which you know works) for the data output.

Indeed, PBn is defined by AVR-Libc. It just so happens that arduino-tiny maps PBn to Dn, and each PBn is defined to have the value of n for use with _BV().

You mention you use Arduino IDE, have you defined a new board for your ATtiny? This can be added to ARDUINO_INSTALL_DIR/harware/arduino/boards. Otherwise, you'd have to #define VW_PLATFORM VW_PLATFORM_GENERIC_AVR and use the additional calls needed for generic AVR platforms.

@jfpoilpret The attiny-master package installs a whole bunch of new ATtiny boards on the IDE. It gives support for several combinations of ATtiny45/84/85 with 1/8/16MHz with internal and external oscillators. I'm able to program the 85 with all 3 clocks when I comment out VW.

Do you have a way to check that the frequency of the MCU is the same as the frequency F_CPU used to compile your code? Typically, when a program seems to be slower than it should it is often due to a mismatch between F_CPU and the real frequency (which is setup by fuses in your case I suppose).

Does the slowdown occur when using 3.6V by comparison to using 5V?

The slowdown occur when I include the VirtualWire includes and function calls. If I comment them out, the timing gets back to normal.

Did you try just including VirtualWire but no function call? That would remove the possibility that the includes redefine some macros.

@jfpoilpret - I comment the include AND the calls in and out altogether, back and forth, when debugging. But the calls alone won't compile without the include.

My idea was actually to keep the include but remove the calls (which should compile), then check if you experiment a slowdown or not. If yes, that would means there's something in the include that overwrites one macro like F_CPU, or a static variable (class instance) that, when constructed, changes something important.

@jfpoilpret Got it. Will give it a try before I give up on the board. I'll probably take a step back and make an ATmega328 version of it.

I have had some clock problems with the ATtiny85 myself. I once tried to attatch an LCD to one and it would never work, only a few times i was able to make out mangled text.

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);
}

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

+1 Excelent, thanks! I'll give it a try and will let you know.

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

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

Thanks for your answer. I had notice symptoms of the item 1 above: the timing got all wrong when I tried to make VirtualWire work. Item 2 seems to be good reasons for the whole thing not to work. My workaround for this problem was to stick with ATmega328 for RF stuff. I'll take a look and see if I can get back to using VW with my ATTinies.

Try the manchester library instead.
This post includes all the necessary info except wiring diagrams:
Manchester Library Won't Compile for Attiny85


text:
How many interrupt pins can an Uno handle?
I am looking at using a 7 channel RC receiver with the Arduino Uno R3. In the documentation, there are mentions of a maximum of 2 interrupt pins, whereas on certain other blogs I have seen mentions of using upto 20 pins as interrupts, with PinChangeInt library. So, how many interrupts can the Arduino handle natively? And is this different from  how many can be handled with software support such as PinChangeInt?

There are two types of "pin change" type interrupts. The external interrupts, of which there are two on the Uno. They are called 0 and 1, however they refer to digital pins 2 and 3 on the board. These can be configured to detect rising, falling, change (rising or falling) or LOW.
In addition to that are "pin change" interrupts, which detect a change to the pin state in any of the 20 pins (A0 to A5, and D0 to D13). These pin change interrupts are also hardware based so, in themselves, will be as fast as the external interrupts.
Both types are slightly fiddly to use at the register level, but the standard IDE includes attachInterrupt(n) and detachInterrupt(n) which simplifies the interface to external interrupts. You can also use the Pin Change Library to simplify the pin change interrupts.
However, steering clear of the library for a minute, we can establish that pin change interrupts can be as fast, or faster, than external interrupts. For one thing, although pin change interrupts work on batches of pins, you don't have to enable the whole batch. For example, if you want to detect changes on pin D4, this will suffice:
Example sketch:
ISR (PCINT2_vect)
 {
 // handle pin change interrupt for D0 to D7 here
 if (PIND & bit (4))  // if it was high
   PORTD |= bit (5);  // turn on D5
 else
   PORTD &= ~bit (5); // turn off D5
 }  // end of PCINT2_vect

void setup ()
  {
  // pin change interrupt (example for D4)
  PCMSK2 |= bit (PCINT20);  // want pin 4
  PCIFR  |= bit (PCIF2);    // clear any outstanding interrupts
  PCICR  |= bit (PCIE2);    // enable pin change interrupts for D0 to D7
  pinMode (4, INPUT_PULLUP);
  pinMode (5, OUTPUT);
  }  // end of setup

void loop ()
  {
  }

My testing indicates that it took 1.6 µs for the "test" pin (pin 5) to react to a change on the interrupt pin (pin 4).

Now if you take the simple (lazy?) approach and use attachInterrupt() you will find the results are slower, not faster.
Example code:
void myInterrupt ()
 {
 if (PIND & bit (2))  // if it was high
   PORTD |= bit (5);  // turn on D5
 else
   PORTD &= ~bit (5); // turn off D5
 }  // end of myInterrupt

void setup ()
  {
  attachInterrupt (0, myInterrupt, CHANGE);
  pinMode (2, INPUT_PULLUP);
  pinMode (5, OUTPUT);
  }  // end of setup

void loop ()
  {
  }

This takes 3.7 µs to change the test pin, a lot more than the 1.6 µs above. Why? Because the code the compiler has to generate for the "generic" interrupt handler has to save every conceivable register (push them) on entry to the ISR, and then restore them (pop them) before returning. Plus there is the overhead of another function call.

Now we can work around that by avoiding attachInterrupt() and doing it ourselves:
ISR (INT0_vect)
 {
 if (PIND & bit (2))  // if it was high
   PORTD |= bit (5);  // turn on D5
 else
   PORTD &= ~bit (5); // turn off D5
 }  // end of INT0_vect

void setup ()
  {
  // activate external interrupt 0

  EICRA &= ~(bit(ISC00) | bit (ISC01));  // clear existing flags
  EICRA |=  bit (ISC00);    // set wanted flags (any change interrupt)
  EIFR   =  bit (INTF0);    // clear flag for interrupt 0
  EIMSK |=  bit (INT0);     // enable it

  pinMode (2, INPUT_PULLUP);
  pinMode (5, OUTPUT);
  }  // end of setup

void loop ()
  {
  }

That is the fastest of them all at 1.52 µs - it looks like one clock cycle got saved somewhere.

There is one caveat though, for pin-change interrupts. They are batched, so if you want to have interrupts on lots of pins, you need to test inside the interrupt which one changed. You could do that by saving the previous pin status, and comparing it to the new pin status. This is not necessarily particularly slow, but the more pins you need to check, the slower it would be.
The batches are:

A0 to A5
D0 to D7
D8 to D13

If you just want a couple more interrupt pins, you could avoid any testing by just choosing to use pins from different batches (eg. D4 and D8).

More details at http://www.gammon.com.au/interrupts

There are two types of interrupts. What the Arduino Playground said:

The processor at the heart of any Arduino has two different kinds of interrupts: “external”, and “pin change”. There are only two external interrupt pins on the ATmega168/328 (ie, in the Arduino Uno/Nano/Duemilanove), INT0 and INT1, and they are mapped to Arduino pins 2 and 3. These interrupts can be set to trigger on RISING or FALLING signal edges, or on low level. The triggers are interpreted by hardware, and the interrupt is very fast. The Arduino Mega has a few more external interrupt pins available.
On the other hand the pin change interrupts can be enabled on many more pins. For ATmega168/328-based Arduinos, they can be enabled on any or all 20 of the Arduino's signal pins; on the ATmega-based Arduinos they can be enabled on 24 pins. They are triggered equally on RISING or FALLING signal edges, so it is up to the interrupt code to set the proper pins to receive interrupts, to determine what happened (which pin? ...did the signal rise, or fall?), and to handle it properly. Furthermore, the pin change interrupts are grouped into 3 “port”s on the MCU, so there are only 3 interrupt vectors (subroutines) for the entire body of pins. This makes the job of resolving the action on a single interrupt even more complicated.

Basically, the external interrupts are extremely fast since they're all hardware based. However, there is also the pin change interrupts, but those seem to be much slower because they are mostly software based.
tl;dr: the 20 interrupt pins together are much slower. The 2 interrupt pins are the fastest and most efficient.

EDIT: I just looked at the datasheet and it says that a pin change interrupt is triggered for any of the pins selected with no indication of which pin has changed (although it is split into three interrupt vectors).

For external interrupts, it'll tell you pin 3 just changed
For pin change it'll tell you a pin changed that you were
monitoring!

As you can see, a pin change interrupt adds a lot of overhead into the ISR that you have to handle by storing previous states and seeing if it's the pin you're worried about. It might be fine for a sleep state, but it's better to use the external interrupts.


text:
Is it possible to find the time taken by millis?
The function millis would be running in the span of 100+ microseconds or less. Is there a reliable way to go about measuring the time taken by a single millis call?
One approach that comes to mind is using micros, however, a call to micros will include the time taken by the function call of micros itself as well, so depending on how long micros takes, the measurement for millis may be off.
I need to find this as an application I am working on requires accurate time measurements for every step taken in the code, including millis.

Can you clarify what you are asking here? Are you trying to get accurate times from millis() or are you trying to work out how long it takes to call the function millis()?

@Cybergibbons How long a call to miilis takes.

If you want to know exactly how long something will take, there is only one solution: Look at the disassembly!
Starting with the minimal code:
void setup(){};

volatile uint16_t x;
void loop()
{
  x = millis();

}

This code compiled and then fed into avr-objdump -S produces a documented disassembly. Here are the interesting excerpts:
void loop() produces:
000000a8 <loop>:
  a8:   0e 94 a7 00     call    0x14e   ; 0x14e <millis>
  ac:   60 93 00 01     sts 0x0100, r22
  b0:   70 93 01 01     sts 0x0101, r23
  b4:   80 93 02 01     sts 0x0102, r24
  b8:   90 93 03 01     sts 0x0103, r25
  bc:   08 95           ret

Which is a function call (call), four copies (which copy each of the bytes in the uint32_t return value of millis() (note that the arduino docs call this a long, but they are incorrect to not be explicitly specifying the variable sizes)), and finally the function return.
call requires 4 clock cycles, and each sts requires 2 clock cycles, so we have a minimum of 12 clock cycles just for function call overhead.
Now, lets look at the disassembly of the <millis> function, which is located at 0x14e:
unsigned long millis()
{
    unsigned long m;
    uint8_t oldSREG = SREG;
 14e:   8f b7           in  r24, 0x3f   ; 63

    // disable interrupts while we read timer0_millis or we might get an
    // inconsistent value (e.g. in the middle of a write to timer0_millis)
    cli();
 150:   f8 94           cli
    m = timer0_millis;
 152:   20 91 08 01     lds r18, 0x0108
 156:   30 91 09 01     lds r19, 0x0109
 15a:   40 91 0a 01     lds r20, 0x010A
 15e:   50 91 0b 01     lds r21, 0x010B
    SREG = oldSREG;
 162:   8f bf           out 0x3f, r24   ; 63

    return m;
}
 164:   b9 01           movw    r22, r18
 166:   ca 01           movw    r24, r20
 168:   08 95           ret

As you can see, the millis() function is fairly simple:

in saves the interrupt register settings (1 cycle)
cli turns off the interrupts (1 cycle)
lds copy one of the 4 bytes of the current value of the milli counter into a temporary register (2 clock cycles)
lds Byte 2 (2 clock cycles)
lds Byte 3 (2 clock cycles)
lds Byte 4 (2 clock cycles)
out restore interrupt settings (1 clock cycle)
movw shuffle registers around (1 clock cycle)
movw and again (1 clock cycle)
ret return from subroutine  (4 cycles)

So, if we add them all up, we have a total of 17 clock cycles in the millis() function itself, plus a call overhead of 12, for a total of 29 clock cycles.
Assuming a 16 Mhz clock rate (most arduinos), each clock cycle is 1 / 16e6 seconds, or 0.0000000625 seconds, which is 62.5 nanoseconds. 62.5 ns * 29 = 1.812 microseconds.
Therefore, the total execution time for a single millis() call on most Arduinos will be 1.812 microseconds.

AVR Assembly reference
As a side-note, there is space for optimization here! If you update the unsigned long millis(){} function definition to be inline unsigned long millis(){}, you would remove the call overhead (at the cost of slightly larger code size). Furthermore, it looks like the compiler is doing two unnecessary moves (the two movw calls, but I haven't looked at it that closely).
Really, considering the function call overhead is 5 instructions, and the actual contents of the millis() function is only 6 instructions, I think the millis() function should really be inline by default, but the Arduino codebase is rather poorly optimized.

Here is the full disassemby for anyone interested:
sketch_feb13a.cpp.elf:     file format elf32-avr

Disassembly of section .text:

00000000 <__vectors>:
    SREG = oldSREG;

    return m;
}

unsigned long micros() {
   0:   0c 94 34 00     jmp 0x68    ; 0x68 <__ctors_end>
   4:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
   8:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
   c:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
  10:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
  14:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
  18:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
  1c:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
  20:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
  24:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
  28:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
  2c:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
  30:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
  34:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
  38:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
  3c:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
  40:   0c 94 5f 00     jmp 0xbe    ; 0xbe <__vector_16>
  44:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
  48:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
  4c:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
  50:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
  54:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
  58:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
  5c:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
  60:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
  64:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>

00000068 <__ctors_end>:
  68:   11 24           eor r1, r1
  6a:   1f be           out 0x3f, r1    ; 63
  6c:   cf ef           ldi r28, 0xFF   ; 255
  6e:   d8 e0           ldi r29, 0x08   ; 8
  70:   de bf           out 0x3e, r29   ; 62
  72:   cd bf           out 0x3d, r28   ; 61

00000074 <__do_copy_data>:
  74:   11 e0           ldi r17, 0x01   ; 1
  76:   a0 e0           ldi r26, 0x00   ; 0
  78:   b1 e0           ldi r27, 0x01   ; 1
  7a:   e2 e0           ldi r30, 0x02   ; 2
  7c:   f2 e0           ldi r31, 0x02   ; 2
  7e:   02 c0           rjmp    .+4         ; 0x84 <.do_copy_data_start>

00000080 <.do_copy_data_loop>:
  80:   05 90           lpm r0, Z+
  82:   0d 92           st  X+, r0

00000084 <.do_copy_data_start>:
  84:   a0 30           cpi r26, 0x00   ; 0
  86:   b1 07           cpc r27, r17
  88:   d9 f7           brne    .-10        ; 0x80 <.do_copy_data_loop>

0000008a <__do_clear_bss>:
  8a:   11 e0           ldi r17, 0x01   ; 1
  8c:   a0 e0           ldi r26, 0x00   ; 0
  8e:   b1 e0           ldi r27, 0x01   ; 1
  90:   01 c0           rjmp    .+2         ; 0x94 <.do_clear_bss_start>

00000092 <.do_clear_bss_loop>:
  92:   1d 92           st  X+, r1

00000094 <.do_clear_bss_start>:
  94:   ad 30           cpi r26, 0x0D   ; 13
  96:   b1 07           cpc r27, r17
  98:   e1 f7           brne    .-8         ; 0x92 <.do_clear_bss_loop>
  9a:   0e 94 f0 00     call    0x1e0   ; 0x1e0 <main>
  9e:   0c 94 ff 00     jmp 0x1fe   ; 0x1fe <_exit>

000000a2 <__bad_interrupt>:
  a2:   0c 94 00 00     jmp 0   ; 0x0 <__vectors>

000000a6 <setup>:
  a6:   08 95           ret

000000a8 <loop>:
  a8:   0e 94 a7 00     call    0x14e   ; 0x14e <millis>
  ac:   60 93 00 01     sts 0x0100, r22
  b0:   70 93 01 01     sts 0x0101, r23
  b4:   80 93 02 01     sts 0x0102, r24
  b8:   90 93 03 01     sts 0x0103, r25
  bc:   08 95           ret

000000be <__vector_16>:
#if defined(__AVR_ATtiny24__) || defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__)
ISR(TIM0_OVF_vect)
#else
ISR(TIMER0_OVF_vect)
#endif
{
  be:   1f 92           push    r1
  c0:   0f 92           push    r0
  c2:   0f b6           in  r0, 0x3f    ; 63
  c4:   0f 92           push    r0
  c6:   11 24           eor r1, r1
  c8:   2f 93           push    r18
  ca:   3f 93           push    r19
  cc:   8f 93           push    r24
  ce:   9f 93           push    r25
  d0:   af 93           push    r26
  d2:   bf 93           push    r27
    // copy these to local variables so they can be stored in registers
    // (volatile variables must be read from memory on every access)
    unsigned long m = timer0_millis;
  d4:   80 91 08 01     lds r24, 0x0108
  d8:   90 91 09 01     lds r25, 0x0109
  dc:   a0 91 0a 01     lds r26, 0x010A
  e0:   b0 91 0b 01     lds r27, 0x010B
    unsigned char f = timer0_fract;
  e4:   30 91 0c 01     lds r19, 0x010C

    m += MILLIS_INC;
  e8:   01 96           adiw    r24, 0x01   ; 1
  ea:   a1 1d           adc r26, r1
  ec:   b1 1d           adc r27, r1
    f += FRACT_INC;
  ee:   23 2f           mov r18, r19
  f0:   2d 5f           subi    r18, 0xFD   ; 253
    if (f >= FRACT_MAX) {
  f2:   2d 37           cpi r18, 0x7D   ; 125
  f4:   20 f0           brcs    .+8         ; 0xfe <__vector_16+0x40>
        f -= FRACT_MAX;
  f6:   2d 57           subi    r18, 0x7D   ; 125
        m += 1;
  f8:   01 96           adiw    r24, 0x01   ; 1
  fa:   a1 1d           adc r26, r1
  fc:   b1 1d           adc r27, r1
    }

    timer0_fract = f;
  fe:   20 93 0c 01     sts 0x010C, r18
    timer0_millis = m;
 102:   80 93 08 01     sts 0x0108, r24
 106:   90 93 09 01     sts 0x0109, r25
 10a:   a0 93 0a 01     sts 0x010A, r26
 10e:   b0 93 0b 01     sts 0x010B, r27
    timer0_overflow_count++;
 112:   80 91 04 01     lds r24, 0x0104
 116:   90 91 05 01     lds r25, 0x0105
 11a:   a0 91 06 01     lds r26, 0x0106
 11e:   b0 91 07 01     lds r27, 0x0107
 122:   01 96           adiw    r24, 0x01   ; 1
 124:   a1 1d           adc r26, r1
 126:   b1 1d           adc r27, r1
 128:   80 93 04 01     sts 0x0104, r24
 12c:   90 93 05 01     sts 0x0105, r25
 130:   a0 93 06 01     sts 0x0106, r26
 134:   b0 93 07 01     sts 0x0107, r27
}
 138:   bf 91           pop r27
 13a:   af 91           pop r26
 13c:   9f 91           pop r25
 13e:   8f 91           pop r24
 140:   3f 91           pop r19
 142:   2f 91           pop r18
 144:   0f 90           pop r0
 146:   0f be           out 0x3f, r0    ; 63
 148:   0f 90           pop r0
 14a:   1f 90           pop r1
 14c:   18 95           reti

0000014e <millis>:

unsigned long millis()
{
    unsigned long m;
    uint8_t oldSREG = SREG;
 14e:   8f b7           in  r24, 0x3f   ; 63

    // disable interrupts while we read timer0_millis or we might get an
    // inconsistent value (e.g. in the middle of a write to timer0_millis)
    cli();
 150:   f8 94           cli
    m = timer0_millis;
 152:   20 91 08 01     lds r18, 0x0108
 156:   30 91 09 01     lds r19, 0x0109
 15a:   40 91 0a 01     lds r20, 0x010A
 15e:   50 91 0b 01     lds r21, 0x010B
    SREG = oldSREG;
 162:   8f bf           out 0x3f, r24   ; 63

    return m;
}
 164:   b9 01           movw    r22, r18
 166:   ca 01           movw    r24, r20
 168:   08 95           ret

0000016a <init>:

void init()
{
    // this needs to be called before setup() or some functions won't
    // work there
    sei();
 16a:   78 94           sei

    // on the ATmega168, timer 0 is also used for fast hardware pwm
    // (using phase-correct PWM would mean that timer 0 overflowed half as often
    // resulting in different millis() behavior on the ATmega8 and ATmega168)
#if defined(TCCR0A) && defined(WGM01)
    sbi(TCCR0A, WGM01);
 16c:   84 b5           in  r24, 0x24   ; 36
 16e:   82 60           ori r24, 0x02   ; 2
 170:   84 bd           out 0x24, r24   ; 36
    sbi(TCCR0A, WGM00);
 172:   84 b5           in  r24, 0x24   ; 36
 174:   81 60           ori r24, 0x01   ; 1
 176:   84 bd           out 0x24, r24   ; 36
    // this combination is for the standard atmega8
    sbi(TCCR0, CS01);
    sbi(TCCR0, CS00);
#elif defined(TCCR0B) && defined(CS01) && defined(CS00)
    // this combination is for the standard 168/328/1280/2560
    sbi(TCCR0B, CS01);
 178:   85 b5           in  r24, 0x25   ; 37
 17a:   82 60           ori r24, 0x02   ; 2
 17c:   85 bd           out 0x25, r24   ; 37
    sbi(TCCR0B, CS00);
 17e:   85 b5           in  r24, 0x25   ; 37
 180:   81 60           ori r24, 0x01   ; 1
 182:   85 bd           out 0x25, r24   ; 37

    // enable timer 0 overflow interrupt
#if defined(TIMSK) && defined(TOIE0)
    sbi(TIMSK, TOIE0);
#elif defined(TIMSK0) && defined(TOIE0)
    sbi(TIMSK0, TOIE0);
 184:   ee e6           ldi r30, 0x6E   ; 110
 186:   f0 e0           ldi r31, 0x00   ; 0
 188:   80 81           ld  r24, Z
 18a:   81 60           ori r24, 0x01   ; 1
 18c:   80 83           st  Z, r24
    // this is better for motors as it ensures an even waveform
    // note, however, that fast pwm mode can achieve a frequency of up
    // 8 MHz (with a 16 MHz clock) at 50% duty cycle

#if defined(TCCR1B) && defined(CS11) && defined(CS10)
    TCCR1B = 0;
 18e:   e1 e8           ldi r30, 0x81   ; 129
 190:   f0 e0           ldi r31, 0x00   ; 0
 192:   10 82           st  Z, r1

    // set timer 1 prescale factor to 64
    sbi(TCCR1B, CS11);
 194:   80 81           ld  r24, Z
 196:   82 60           ori r24, 0x02   ; 2
 198:   80 83           st  Z, r24
#if F_CPU >= 8000000L
    sbi(TCCR1B, CS10);
 19a:   80 81           ld  r24, Z
 19c:   81 60           ori r24, 0x01   ; 1
 19e:   80 83           st  Z, r24
    sbi(TCCR1, CS10);
#endif
#endif
    // put timer 1 in 8-bit phase correct pwm mode
#if defined(TCCR1A) && defined(WGM10)
    sbi(TCCR1A, WGM10);
 1a0:   e0 e8           ldi r30, 0x80   ; 128
 1a2:   f0 e0           ldi r31, 0x00   ; 0
 1a4:   80 81           ld  r24, Z
 1a6:   81 60           ori r24, 0x01   ; 1
 1a8:   80 83           st  Z, r24

    // set timer 2 prescale factor to 64
#if defined(TCCR2) && defined(CS22)
    sbi(TCCR2, CS22);
#elif defined(TCCR2B) && defined(CS22)
    sbi(TCCR2B, CS22);
 1aa:   e1 eb           ldi r30, 0xB1   ; 177
 1ac:   f0 e0           ldi r31, 0x00   ; 0
 1ae:   80 81           ld  r24, Z
 1b0:   84 60           ori r24, 0x04   ; 4
 1b2:   80 83           st  Z, r24

    // 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);
 1b4:   e0 eb           ldi r30, 0xB0   ; 176
 1b6:   f0 e0           ldi r31, 0x00   ; 0
 1b8:   80 81           ld  r24, Z
 1ba:   81 60           ori r24, 0x01   ; 1
 1bc:   80 83           st  Z, r24
#if defined(ADCSRA)
    // set a2d prescale factor to 128
    // 16 MHz / 128 = 125 KHz, inside the desired 50-200 KHz range.
    // XXX: this will not work properly for other clock speeds, and
    // this code should use F_CPU to determine the prescale factor.
    sbi(ADCSRA, ADPS2);
 1be:   ea e7           ldi r30, 0x7A   ; 122
 1c0:   f0 e0           ldi r31, 0x00   ; 0
 1c2:   80 81           ld  r24, Z
 1c4:   84 60           ori r24, 0x04   ; 4
 1c6:   80 83           st  Z, r24
    sbi(ADCSRA, ADPS1);
 1c8:   80 81           ld  r24, Z
 1ca:   82 60           ori r24, 0x02   ; 2
 1cc:   80 83           st  Z, r24
    sbi(ADCSRA, ADPS0);
 1ce:   80 81           ld  r24, Z
 1d0:   81 60           ori r24, 0x01   ; 1
 1d2:   80 83           st  Z, r24

    // enable a2d conversions
    sbi(ADCSRA, ADEN);
 1d4:   80 81           ld  r24, Z
 1d6:   80 68           ori r24, 0x80   ; 128
 1d8:   80 83           st  Z, r24
    // here so they can be used as normal digital i/o; they will be
    // reconnected in Serial.begin()
#if defined(UCSRB)
    UCSRB = 0;
#elif defined(UCSR0B)
    UCSR0B = 0;
 1da:   10 92 c1 00     sts 0x00C1, r1
#endif
}
 1de:   08 95           ret

000001e0 <main>:
#include <Arduino.h>

int main(void)
 1e0:   cf 93           push    r28
 1e2:   df 93           push    r29
{
    init();
 1e4:   0e 94 b5 00     call    0x16a   ; 0x16a <init>

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

    setup();
 1e8:   0e 94 53 00     call    0xa6    ; 0xa6 <setup>

    for (;;) {
        loop();
        if (serialEventRun) serialEventRun();
 1ec:   c0 e0           ldi r28, 0x00   ; 0
 1ee:   d0 e0           ldi r29, 0x00   ; 0
#endif

    setup();

    for (;;) {
        loop();
 1f0:   0e 94 54 00     call    0xa8    ; 0xa8 <loop>
        if (serialEventRun) serialEventRun();
 1f4:   20 97           sbiw    r28, 0x00   ; 0
 1f6:   e1 f3           breq    .-8         ; 0x1f0 <main+0x10>
 1f8:   0e 94 00 00     call    0   ; 0x0 <__vectors>
 1fc:   f9 cf           rjmp    .-14        ; 0x1f0 <main+0x10>

000001fe <_exit>:
 1fe:   f8 94           cli

00000200 <__stop_program>:
 200:   ff cf           rjmp    .-2         ; 0x200 <__stop_program>

Wow, great answer! +1

1) The four sts should not be counted as call overhead: this is the cost of storing the result in a volatile variable, which you would normally not do. 2) On my system (Arduino 1.0.5, gcc 4.8.2), I don't have the movws. Then the cost of calling millis() is: 4 cycles of call overhead + 15 cycles in millis() itself = 19 cycles total (≈ 1.188 µs @ 16 MHz).

@EdgarBonet - That doesn't make sense, x is a uint16_t. It should be 2 copies at most if that is the cause. Anyways, the question is how long does millis() take when used, not when called while ignoring the result. Since any practical use is going to involve doing something with the result, I forced the result to be stored via volatile. Normally, the same effect would be achieved by the later use of the variable that is set to the return value of the call, but I didn't want to have that extra call taking up space in the answer.

This uint16_t in the source does not match the assembly (4 bytes stored into RAM). You probably posted the source and disassembly of two different versions.

@ConnorWolf Amazing answer and explanation. Thank you!

Write a sketch that millis 1000 times, not by making a loop, but by copy and paste. Measure that and compare it to the actual expected time. Mind you that that the results may vary with different versions of the IDE (and its compiler in particular).
Another option is to toggle an IO pin before and after the millis call, then measure the time for a very small value and a somewhat larger value. Compare the measured timings and calculate the overhead.
The most accurate way is to take a look at the disassembly listing, the generated code. But that is not for the faint of heart. You'll have to carefully study the datasheet how long each instruction cycle takes.

How would you measure the time taken by 1000 millis() calls?

You do know millis() is supplied by an interrupt on timer0 that increments an internal variable every tick?

@TheDoctor I mixed up with delay, you are right. But the idea stays the same, you can time a large number of calls and average them. Turning off the interrupts globally may not be a very good idea though ;o)

Make sure your data set is large enough as printing characters to the Serial take a few milliseconds themselves. I don't remember the exact time, but I think it's something like ~0.6ms per character sent to Serial.

@Steven10172 you can time an empty string against a 1000-times string (or more), then you know the delta and the measurement is more accurate.

I second calling millis repeatedly and then comparing actual vs. expected.
There will be some minimal overhead, but it will diminish in significance the more times you call millis().
If you look at
C:\Program Files (x86)\Arduino\Arduino ERW 1.0.5\hardware\arduino\cores\arduino\wiring.c

You can see that millis() is very tiny at only 4 instructions (cli is simply # define cli()  \__asm__ \__volatile__ ("cli" ::)) and a return.
I'd call it about 10 million times using a FOR loop which has a volatile as the conditional. The volatile keyword will prevent the compiler from attempting any optimization on the loop itself.
I don't guarantee the following to be syntactically perfect..
int temp1,temp2;
temp1=millis();
for (volatile unsigned int j=0;j<1000000;++j){
temp2=millis();}
Serial.print("Execution time = ");
Serial.print((temp2-temp1,DEC);
Serial.print("ms");

my guess is that takes ~900ms or about 56us per call to millis. ( I don't have an aruduino handy ATM.

You should change int temp1,temp2; to volatile int temp1,temp2; to prevent the compiler from potentially optimizing them away.

Good call on the volatile. I definitely meant to put that in and then didn't.
I should have also mentioned that the way to do a more proper benchmark is to run an empty loop, record that execution time, then run the loop again while doing work. Subtract the difference, divide by the number of iterations, and there is your highly accurate execution time.

That kind of benchmark only works on a system that does not ever pre-empt your code execution. The arduino environment by default has periodic interrupts that will execute periodically. A better solution would be to toggle a pin on every execution, and use a high-resolution timer of some sort to measure the toggle rate when running and not running the code in question, take the minimum execution time over a number of samples for each, subtract the baseline, and treat that as your execution time. Assuming your execution time is shorter then the minimum time-between interrupts.


text:
How do I figure out if my board is approaching end of life?
I have a uno that I have been using for 3 years now. I will be using it again in a rather critical project in which failure on the part of the board could be rather expensive and dangerous. So, I would like to be sure that the board is not approaching end of life or going to fail anytime soon. Is there any reliable way to figure out how long the board will function without failing or reduction in performance?

"failure on the part of the board could be rather expensive and dangerous". Define expensive and define dangerous. Maybe an Arduino is not the best fit for your application, maybe you need to design in a fail safe mechanism.

@jippie Think small UAVs and/or other small to medium robots.

Unfortunately, there isn't much way to really determine "wear" in the context of solid-state electronics.
Probably the things that are most likely to fail are the electrolytic capacitors and the connectors.

First, if you're using an ATmega CPU for something that could possibly injure someone CONTACT ATMEL AND TALK ABOUT SAFETY PRECAUTIONS. The ATmega CPU used in most of the arduino models is not rated for use in such situations.
In EVERY datasheet:

Atmel products are not intended, authorized, or warranted for use as components in applications intended to support or sustain life.

Now, realistically, this is probably mostly lawyer repellent, but you should still take appropriate precautions.
Really, while there isn't anything on a common arduino board that really wears out except the connectors, why are you trying to save $30 at a potential huge cost? Just buy a new board.
I'd also strongly reccomend you chose a board with a SMT ATmega328P, since that removes the IC socket contacts from the list of concerns. If possible, also remove the pin-headers, and solder wires to the board directly. Try to minimize connectors, since they are frequent points of failure.

One of the sections of the Arduino that is likely to become unreliable over time is its memory. There are three pools of memory in the microcontroller used on avr-based Arduino boards:

Flash memory (program space), is where the Arduino sketch is stored.
SRAM (static random access memory) is where the sketch creates and manipulates variables when it runs.
EEPROM is memory space that programmers can use to store long-term information.

The memory is one part of the board that can be checked and verified, and thus evaluated for reliability/health. A very basic way to check memory would be to write a certain 8-bit pattern (byte character) over every address in the memory and then read the value present from every address. If the value that was written matches the value that is read, then that specific 8 bit block in memory is functioning correctly at the present moment.
Wear in ROM memory usually occurs in a blockwise pattern i.e. n*8-bit blocks become degraded over time. So, for a 2K byte ROM chip, the health of the chip can be estimated by writing and reading from every byte on the chip, and calculating the percentage of correctly functioning blocks. If the percentage of failed blocks is significant (15%-20%), that means that the memory is likely to fail soon.
The test code can be written using separate methods for each of the memory sections.
SRAM
Any variables declared statically or dynamically are allocated on the SRAM. So, we could declare a large character array (~2000) and fill every element with 255 (all bits 1). Then, we could attempt to read each of those elements and see if the value being read is indeed 255.
EEPROM
The EEPROM can be manipulated using the EEPROM library. The library provides functions to read and write from specific locations in the EEPROM. So, all memory addresses can be tested by simply looping over the entire memory
space. This operation will require 500 writes and reads.
Depending on the board usage, EEPROM is most likely to fail first but is not critical to board operation.
Flash
Data can be stored on the flash memory using the PROGMEM directive. Similar to SRAM, a large array can be declared and initialized here. Then, values can be read and checked.

This concentrates just on the microcontroller, which is highly unlikely to be the least reliable bit on the board. The flash is rated to 10k cycles - this is very hard to achieve. Also the test would only prove that it is working now, not when put into the application. It's much easier surely to just validate the program memory once programmed, or the EEPROM?

I'd question the phrase "One of the sections of the Arduino that is likely to become unreliable over time is its memory." - the flash can do 10k cycles, the EEPROM 100k cycles. That's a lot of writing.

@Cybergibbons Memory intensive applications can end up doing 100+ writes per minute. Not common, but possible when using a large number of sensors. The test would give us a percentage of the memory that is working correctly. I dont have specific knowledge of the ROM chips on the Arduino, but many ROMs have the ability of spreading read and write cycles across the chip. The effect of this is that when even some memory locations degrade, it is a sign that the entire chip will degrade soon. Even if the R/W cycles are not spread, even then, if certain areas start to fail, then it is a sign that..

atleast parts of the chip have undergone significant wear making the chip partly unreliable. In either case, evaluating the entire range of memory available is quite a reliable method to figure out current state of the chip, which can give an indication of failure in the near future. Yes, this will not tell  me if the chip will fail in the next project, but in the case of a dangerous or expensive application, I certainly would not put a chip to work that has an increased likelihood of failure.

If you are writing to EEPROM or flash hundreds of times a minute, you are looking at a lifetime of under a day though. That's just inappropriate use. There is no wear levelling in an ATmega.


text:
How do I burn the bootloader?
I was instructed to "burn the bootloader" to my Arduino to fix an error I was getting. How can I do this? (And what exactly is the bootloader?)

It is pretty easy to burn bootloader to arduino provided you follow right steps. This video might help you: YouTube - How To Burn Bootloader Onto ATMEGA328P-AU(SMD) | Homemade ARDUINO MINI

The bootloader is a small program that is (almost) always on an Arduino. It manages uploading and starting the sketches you make, and blinks the pin 13 LED whenever the board resets.

To burn the bootloader:

Obtain an AVR ISP, USBtinyISP, ParallelProgrammer, or similar; or use another Arduino board. This will be your ISP.
Unless otherwise instructed, connect the ISP to the ICSP pins on your board.
Power your board with either a USB cable or an external power supply.
Open up the Arduino IDE.
Make sure you selected the correct board that you are burning to at Tools ► Board ► in the IDE. Double-check this even if you could upload programs correctly; uploading doesn't always require the right board.
Select the appropriate programmer at Tools ► Programmer ►.
Click Tools ► Burn Bootloader, and wait. It shouldn't take more than a minute, and often takes only a few seconds.

Sources:

http://arduino.cc/en/Hacking/Bootloader
http://arduino.cc/en/Guide/Environment

The AVRISP is pretty much EOL (end-of-life) at this point. At minimum, you want a AVRISPmk2. There are also lots of other, fancier tools (AVR One! for example). You should probably just say {line 1} or other dedicated ISP programmer.

On boards like the Arduino Yun, each time you "upload via wifi", you're burning the bootloader merged with your sketch. This thanks to the fact that the Linux CPU is connected to the AVR MCU through SPI, so that you can mimic an ISP with software.

@FedericoFissore - is that why it take so long?

Yes, that and the fact that GPIO bitbanging is slower. There is an ongoing effort to speed it up.

What is a bootloader?

And what exactly is the bootloader?

The bootloader is a small piece of code residing in the "high" part of program memory. Normally it is not erased when you upload new sketches. Its purpose it to be activated immediately after a reset (the fuses are configured to commence code at the bootloader address rather than address 0x0000). The bootloader will wait a short time (such as one second) to see if "programming" data is arriving on the serial port.

If so, it reads that data, and decodes it to reprogram the rest of the flash memory. Working in conjunction with the uploading program (normally avrdude) the new sketch is sent via the serial port. The bootloader erases pages of flash memory, and replaces them with the new code. Once done, it executes the new code.
If no instructions arrive, the bootloader jumps to address 0x0000 to execute the existing sketch on the board.

How to replace the bootloader
An alternative method to program a bootloader is to use a sketch I wrote a while ago which runs on a:

Uno (or similar, such as Duemilanove)
Leonardo
Mega2560

The "programming" board runs the sketch which has bootloaders for a number of boards hard-coded into it. You connect the programming board to the target board (the board wanting the bootloader) with 6 hook-up wires as shown.

That particular photo illustrates one Uno programming another one.
You run the sketch (operating via the Serial Monitor to give it commands). First it identifies the target chip:
Atmega chip programmer.
Written by Nick Gammon.
Entered programming mode OK.
Signature = 0x1E 0x95 0x0F
Processor = ATmega328P
Flash memory size = 32768 bytes.
LFuse = 0xFF
HFuse = 0xDE
EFuse = 0xFD
Lock byte = 0xCF
Bootloader address = 0x7E00
Bootloader length = 512 bytes.
Type 'L' to use Lilypad (8 MHz) loader, or 'U' for Uno (16 MHz) loader ...
Type 'G' to program the chip with the bootloader ...

The you  press G to program it.
Erasing chip ...
Writing bootloader ...
Committing page starting at 0x7E00
Committing page starting at 0x7E80
Committing page starting at 0x7F00
Committing page starting at 0x7F80
Written.
Verifying ...
No errors found.
Writing fuses ...
LFuse = 0xFF
HFuse = 0xDE
EFuse = 0xFD
Lock byte = 0xCF
Done.
Type 'C' when ready to continue with another chip ...

For a Uno this takes one second. To program a Mega2560 takes 3 seconds.
Detailed instructions at Atmega bootloader programmer
Code can be downloaded from Github: nickgammon/arduino_sketches

Do you have to select the type of chip your are burning to (Tools->Board..)? What board do I select when I am burning the bootloader to stand alone chip?

You select the type of board you are using to burn the bootloader in the IDE. The bootloader sketch auto-detects the target board type.


text:
Can a PC connect to an Arduino for serial communication without installing the entire dev kit?
I'd like to send a prototype board to a friend pre-programmed and wired. Ideally they should just need to plug in the USB and connect to it over a serial COM port.
With another laptop I used for testing I had to install the full dev kit, sketch editor and all to get it working.
Can I somehow send just the portion of the kit that provides the COM drivers and not the rest? Is there a prebuilt install for just that portion?

On Windows in C:\Program Files\Arduino there is a folder called drivers, which contains all the drivers for the Arduino boards. I think that's what you are looking for.

And for OSX and Linux the driver is typically shipped with the OS already (though older FTDI boards may require a driver on OSX?  Anyone remember?)


text:
How do send sketch updates to devices without the editor?
I'd like to update the sketch of a device that a friend out of state is testing. I could have them install the full editor and send the source code but I'd rather not require them to do something so technical.
Is there a way to compile the firmware binary and push that out to a device over the COM port more directly?

In general, yes.
The compile routine creates a .hex file in a temporary directory that contains the flash image for the device. One can use AVRDUDE to upload this .hex file to the Arduino from the command line. It is simply a matter of getting the command arguments correct in order to tell it where and how to upload the image. Enabling verbose output in the IDE will tell you both exactly where the .hex file is located and what arguments are required for the board selected.

As a side note, latest openwrt version for the yun bundles reflash through http upload: you enter yun's webpanel, select the .hex to upload and click


text:
Measuring voltage on an analog pin - What do I need to know about amperage?
I'd like to measure the voltage at a test point on a stepper motor driver chip with an arduino. The voltage at this point controls the amperages to the phase coils and is adjusted to trim the driver.
I have a common ground with the driver already, I'd like to wire the drivers v-ref point to an analog input to drive an LCD showing the output amp number so I can adjust the driver.
The issue I am worried about is that with the hardware I have to test with a properly trimmed driver is pushing 0.84A.
Is this safe to do without killing the arduino board?

Yes. The only thing you need to be concerned about is the voltage. It needs to be less than the Arduino Vcc.
The voltage sense circuit (analog inputs) typically have a high impedance and should draw a negligible current from the circuit being sensed. I didn't have much luck finding the actual spec for any of the AVR chips, but I did find this answer to the question on Electronics.StackExchange – where they say "hard to tell, the specs are incomplete, but 10 KΩ seems like a reasonable guesstimate/assumption" (I paraphrase). The reasoning is interesting and worth a read.

Awesome thank you, I'll give it a try tonight.


text:
Can I run a Mega 2560 on 14v?
I have a Mega 2560 with a ramps 1.4 shield. I noticed when I turn on the 14v power supply the mega would also power up and run.
Am I damaging it running it at 14v? If not is there a solder or jumper somewhere that I can set it to only run the mega/logic on the usb power? The 14v is just for the stepper motors.

Input Voltage (limit)  6-20V

http://reprap.org/wiki/RAMPS_1.4#Power_Supply

Where is the 14v being supplied to? You Seem surprised that it's receiving power this way, so I assume it's not through the 'usual' channels. I'm not familiar with the board, but as above, it will run on 14V, just make sure they are going into the correct hole!

@MikaelPatel If your board does not have this diode soldered in (or if you cut it), you will need to power the Mega through the USB connector or through a separate 5v line I read that page but missed this sentence! I'll always have usb power (To push gcode) so that looks like the answer.

You can, but you shouldn't, because the the board will heat excessively, as you're out of the recommended range for the input voltage on vin (7-12V).
Unless you have a switching regulator (the one on the board is linear), then you shouldn't' have too much of a difference between the operating voltage and vin as an operating principle because of efficiency (and thus heat) issues.

Thanks! It looks like I can remove a diode on the ramps board to stop it from supplying power to the mega and that will solve the problem completely.

Incidentally, most of the cheap barrel jack sockets you can get, like the one on the Arduino boards, are only rated for 12V maximum. That, more than the regulator's heat dissipation, is the limiting factor.


text:
How can I check if my thermostat is on?
I'm working on a project to better understand how my home cooling system behaves. I'd like to produce graphs of temperature in various areas, overlaid with when my existing thermostat turns the A/C compressor and fan on.
Connecting up a few ESP8266's with temperature sensors reporting over WiFi is straightforward enough; I'm comfortable doing that. But I'm struggling with how to detect when my thermostat is calling for A/C cooling.
My (battery-powered) thermostat has red, white, yellow, and green wires:

Red has ~28Vac
White enables the heating system
Green enables the fan
Yellow enables the A/C compressor

With a multimeter, I easily determined that the thermostat simply closes a relay (I can hear it; that was a dead giveaway) and there's no resistance. So if A/C is called for, it closes relays connected Red to Yellow (and Green).
I don't really want to mess with drawing power from the 28Vac; it's easy enough to power an 8266 with 5V from a wall wart and that's sufficient for this project. Ugly, but acceptable.
I want to detect when the thermostat relay is closed and turning on the air conditioner. Clearly I'm not an EE by trade, and I'm struggling with the right search terms to communicate "detect whether two outside pins are electrically connected". I think something that emulates a multimeter's continuity function would work.
I did find references to the LM*39 series, but (1) I'm not sure it would like being exposed to AC power, and (2) the 'offset voltage' is usually measured in mV, which suggests to me that I'm barking up the wrong tree.

If there are 3 relays, and you know that the relays control the 3 'systems', then you could wire up your 8266 through the "NC" (not connected) pin then you know that when voltage goes through the NC pin the relay is not on

The easiest way probably is to connect to the 28V signal and measure it. 28V is not high enough to be dangerous to humans, but it is dangerous to your ESP8266, but it's very simple to decrease the voltage to a level where your ESP8266 can safely detect it.

Welcome! I used bidirectional optocouplers. The input has a resistor I believe 27K and the output is a NPN transistor with a pull up to +5. The emitter goes to electronic ground. I connected these across the relay coils. They have not given me any problems since installed about 15 years ago. Nice thing they are not polarity sensitive.

heh i guess opto couplers are the way to go if you don't already have a bunch of op amps.  +1 to that

I used them because of the electronics in the HVAC system is AC and needed to stay isolated from the rest of the world. Thanks Able

Thank you! I’ll try this.

You are welcome, let us know how it works out.

Most straight forward method should be to slap an op amp on the leg of the wire that the relay activates and deactivates by connecting to it.  The key is to power the op amp with low voltage so your esp gets that as input.  The signal legs can handle whatever the relay gives, and the ac, fan, and heater will handle the pull signal for the not connected state.
That only goes so far as to protect the esp by having the op amp take the high voltage and output low.  To turn a potentially AC low voltage signal into a nice dc one, use a diode, capacitor, and resistor (trim pot).  Remember that this is going to be discharging that cap through your resistor so figure out a minimum and check the pot before powering the device (or add a regular resistor in series).

Sending a high voltage input to an op-amp powered by a lower voltage isn't necessarily safe for the op-amp. You'd have to check the datasheet for the specific op-amp. Better to use a voltage divider to reduce the voltage.

remember to check specs regardless of what components.  if you are using a voltage divider- figure out acceptable current losses and the wattage requirements for your resistors.

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Drum game controller - Problem with Piezo inputs
I currently try to build some Drums for the game Clone Hero. The problem that I have is that I can't use both of my Piezo inputs that I have hooked up at the same time.
I have a Arduino Pro Micro and use this Library. This is my code that I have so far. I'm pretty new to this Arduino stuff, so I don't understand a ton yet.
Anyway, thanks in Advance. :)
#include <Joystick.h>

const int drum1 = A0;
const int drum2 = A1;
const int drum3 = A2;
const int drum4 = A3;

const int threshold = 100;

int sensorReading = 0;

Joystick_ Joystick;

void setup() {

  // Initialize Joystick Library
  Joystick.begin();
}

// Last state of the button
int lastButtonState = 0;

void loop() {

  sensorReading = analogRead(drum1);

  if (sensorReading >= threshold)
  {
    Joystick.pressButton(0);
    Joystick.releaseButton(0);
  }

  sensorReading = analogRead(drum2);

  if (sensorReading >= threshold)
  {
    Joystick.pressButton(1);
    Joystick.releaseButton(1);

  }
}

@Juraj I can use both, but not at the same time.

they don't activate at the same time. they activate one after another. here is a video that shows it. https://imgur.com/a/a6quH5d

I think, from your description, that your problem is with your methodology and what you think your code can achieve. Code executes strictly sequentially. If you have simple "if this then that" constructs then yes, things will happen separately, no matter how close you think they are in time. It sounds like you need to introduce the concept of "time slices" and "events" into your design. If these two events happen both within this predefined period of time then activate both buttons.

An alternative is to separate out the pressing of the buttons from the releasing of the buttons. When the drum is struck press the button, and set a timer running (store a timestamp). When that timer expires (millis() - drum1Time >= 100, for example) then release the button. That way you can have one button being pressed, followed by a second button being pressed, and eventually both buttons being released.

For that it may be useful to encapsulate all the logic and variables for one drum in a class, then simply instantiate multiple instances with different parameters for each drum pad and joystick button.

From my interpretation of your problem it seems like you want to be able to press two (or more) joystick buttons at once by striking multiple drum pads.  As it stands your code will never be able to do that since you press, then immediately release, each button sequentially.
The simplest way around this is to only press the button when you strike the drum, then release the button at a later time, which gives a chance for another button to be pressed in the meantime.  What that "later time" is would be for you to decide.
The simplest thing to do is maintain a "this drum has been struck" flag along with a "this drum was struck at" timestamp (it's possible to combine the two), both of which are set at the moment of striking the drum. Then later in your code you check that timestamp and flag and release the button (and disable the flag) if the required time has expired.
To prevent duplicate code it can be good to encapsulate the logic and state variables for a single drum into a class and then instantiate multiple instances, one for each drum pad. For example, here's some untested code that may or may not work:
class Drum {
    private:
        uint32_t _timestamp;
        uint8_t _button;
        uint8_t _channel;
        int16_t _threshold;

    public:
        Drum(uint8_t channel, uint8_t button, int16_t threshold = 100) {
            _channel = channel;
            _button = button;
            _threshold = threshold;
            _timestamp = 0;
        }

        void process() {
            if (_timestamp > 0) { // Has been struck
                if (millis() - _timestamp >= 100) { // 100ms window - adjust as needed
                    Joystick.releaseButton(_button); // Release the button
                    _timestamp = 0; // Set it as not struck
                }
            }

            if (analogRead(_channel) > _threshold) {
                _timestamp = millis(); // Set it as struck now
                Joystick.pressButton(_button); // Press the button
            }
        }
};

Then you can instantiate multiple drums:
Drum drum1(A0, 0);
Drum drum2(A1, 1);

Then in your loop simply:
void loop() {
    drum1.process();
    drum2.process();
}

Again I reiterate: this code is untested, I don't even know if it compiles.


text:
How do I connect my ESP32 cam to my old modem without using Wi-Fi?
I have an Arduino ESP32 cam that I want to use as a bird cam. I want to use my old Orcon wireless modem to connect with this cam. I will connect with cable from my computer to this modem. As my existing Wi-Fi is running on 5Ghz, I cannot connect to it with this cam. So I need some pointers on how to do. Thanks.

please draw a diagram of how you want everything connected ... right now, all we know is that the computer and modem are connected together by some type of cable

You want to connect the ESP32 to the "modem" over the modem's wireless, then the modem to the computer over an Ethernet cable? Then you need to configure the "modem" appropriately. We can't help you with that.

Use an FTDI programmer and communicate with a serial protocol like UART.
The connection schematic can be found here.
https://randomnerdtutorials.com/program-upload-code-esp32-cam/
However you would have to do some extra research work on making the serial communication with the ESP32.
So a nice way would be to buy a wifi module for your old computer and use it to connect to the wifi and program the ESP32 accordingly.


text:
WiFi.h library, Issues with client.print()
I have an esp32 development board that I am trying to use to get Bitcoin price data using the Coinbase api.
On the Coinbase developers website, they give this example Curl command to get Bitcoin price data:
curl https://api.coinbase.com/v2/prices/spot?currency=USD

I put this into a command prompt on my computer and it works as expected. So I used this as a template for my HTTP get statement in my Arduino sketch.
if (!client.connect("api.coinbase.com",80)) {
  Serial.println("Connection failed.");
}
delay(100);
client.print("GET /v2/prices/spot?currency=USD HTTP/1.1\r\nHost: api.coinbase.com\r\n\n");

However, when sent from my esp32, I get a "301 Moved Permanently" error. But the new Location specified in the response is exactly where I was accessing in the first place!
HTTP/1.1 301 Moved Permanently
Date: Sun, 22 Aug 2021 22:15:50 GMT
Transfer-Encoding: chunked
Connection: keep-alive
Cache-Control: max-age=3600
Expires: Sun, 22 Aug 2021 23:15:50 GMT
Location: https://api.coinbase.com/v2/prices/spot?currency=USD
Set-Cookie: __cf_bm=ea2a2031c3fa42b910632c627d2ed4c48824323d-1629670550-1800-ARKBVsdI9BWVOOTWmKXp+cMv0hcxMU4YAOR1JyHtH2Q49TEBkGuGNXLxSMIanzC7W8Ga9uXBCtdo+Th7Fgir8Jc=; path=/; expires=Sun, 22-Aug-21 22:45:50 GMT; domain=.coinbase.com; HttpOnly
X-Content-Type-Options: nosniff
Server: cloudflare
CF-RAY: 682f764a88f3a3eb-PIT

Why does this HTTP request work with Curl, but not when sent from the esp32?

HTTP != HTTPS...

It's not an error, it's an HTTP redirect.
The HTTP request worked as expected on the ESP32. Curl automatically handles the redirect. Your homegrown HTTP implementation does not.
The Coinbase API requires you to use HTTPS and does not allow HTTP. This protects private information, like API keys and information the API may return. It also verifies that you're talking to the real Coinbase API server and not an impersonator.
You'll need to use port 443 and the WiFiClientSecure library instead of WiFiClient library. Or even better, you could use an HTTP client that already implements the HTTP protocol, like HTTPClient.


text:
configuring characteristics to communicate data on the Arduino bluetooth low enegy module
I have the HM-10 Arduino BLE module. I am also building an app to send and read characteristics on the BLE module. On the Arduino BLE side of things though, how do I set up which characteristic listens for which kind of data?
So, if the BLE module has 1 service containing two characteristics the first one being read-only and the second one being write-only. On my android app, I can find the UUIDs of these two characteristics and perform read and write operations on the corresponding characteristics. But how would I go about initializing which characteristic on the BLE module should expect which kind of operation?
All I see other people do is they perform BLE.read and BLE.write functions to accomplish this. But if you have multiple characteristics and some that can do both kinds of operations, how do you distinguish between them in the code? Does the BLE module only think of the characteristics as one entity that can either be read to or written to, whereas the android app needs to know which is which? The HM-10 documentation talks about setting up the characteristic UUID but talks about pins on the chip to control things, which is weird because the arduino already has pins that you can use.
Worst case scenario, I guess I could just look at ArduinoBlue or Dabble's arduino source code.