text:
Can I program a 3.3v chip on a 5v board?
I bought a Gertboard a while ago, and one of the features it has on-board is an ATMega328 (DIP). However, since the Gertboard is designed for use with the Raspberry Pi, it only operates at 3.3v, so the clock speed is limited to ~12MHz.
Programming it via the Raspberry Pi is quite cumbersome though. Instead, I'd like to transfer the chip to an Arduino Uno board so I can upload sketches from my desktop PC. I would then transfer it back to the Gertboard for normal operation.
The problem is that my Uno operates at the more typical 5v / 16MHz.
Is it safe to attempt this? Do I need to make any configuration changes in the IDE to tell it to account for a different clock speed?

avrdude over SSH not working out for you?

@IgnacioVazquez-Abrams I'm just exploring options really. I don't mind working on the command line if I have to, but I much prefer a GUI for code entry.

Samba to share the directory, and make to invoke ino to build. Messy, but it should do.

I've not seen a single ATmega328 not work at 16MHz at 3.3V before.

Sure, but that's not the question here.

@Cybergibbons The Gertboard has a 12MHz resonator built-in to provide the clock source, so unfortunately I can't change that.

I know it's not the question, which is why I didn't post it as an answer. Simplest solution, to me, would be to run both boards at 16MHz and not have to worry about anything else.

You could probably replace the avrdude executable on your machine with a script that remotes it to the pi, or better yet configure the IDE to use a different program as the programmer.  This would avoid the baud rate issue, and more importantly the constant chip transplantation that is likely to lead to bent pins or eventually worn out sockets.

The clock speed selected will affect both delay*() and millis()/micros() as well as the functions in <util/delay.h>, therefore you must use the target system's correct clock speed if you are using any of these functions. This can be easily done by editing boards.txt and copying an existing entry for the Uno and changing the value of the f_cpu parameter to match the target system (in this case, 12000000).
The difference in voltage does not matter, since the chip can run at either voltage and no connection is being made between the 5V system and the 3.3V system.

Unfortunately, the bootloader probably assumes 12 MHz.  In theory, the firmware of the 8u2/16u2 could be modified with a similar "mismatch" and likely result in the ability to utilize the bootloader with whatever odd baud rate results.  But it might be easier to improve the pi-based programming process, especially as this would avoid the constant chip transplanting.


text:
Arduino USB Power vs External Power Supply
Why is the Arduino able to accept ~5V from the USB, but requires a min of 7V when using an external power supply?

The design assumes USB provides a regulated 5v so no further regulation is necessary. The power connecter is meant to accept a wider range of voltage and regulate it to 5v, and the kind of regulators used on the Arduino board need that much higher voltage to provide regulation. If you already have a regulated +5v source you can supply it to the 5v pin. You'll bypass the on-board regulator this way, so just know that it will then be up to you to provide clean power.

Brilliant answer without getting into technical details that can confuse members that are not experienced in electronics.

Above is an AA Battery voltage curve. Many people assume that 5* 1.5V AA batterys would be enough to power the Arduino. As you can see the 1.5 is the maximum voltage and it quickly drops. Different brands have different values and sometimes this can drop below the value of the voltage regulator input. I usually tend to aim between 7 and 9 Volts for  running from batteries, ie the nominal voltage of the batteries, eg 6 x 1.5V = 9V.
For wall socket charges, Buy a cheap one and hook it up to a volt meter, Many that say 5V actually have a range of values. Raspberry Pi users often have problems with power caused by manufacturers saying its 5v and it actually delivering something like 4.85 and fluctuating beacuse of the power demand of the pi

If you want to run from batteries, using the built-in voltage regulator is a really bad idea. Best case you are dropping 2.5V when the batteries are fresh - at 0.5A this is 1.25W wasted. The regulator will start to drop out at 6V, which is 1.2V per battery. This isn't very far into the discharge at all. Bypass the regulator and design the system to deal with varying voltage, or use a good boost converter.

I've edited your text to clarify that you mean to aim for a nominal* voltage between 7 and 9V. I assume thats what you meant?

source: Stack Exchange

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

sort: votes


text:
Arduino Mega not flashable with XBee PRO S2B
I have an Arduino Mega 2560 with a libelium XBee Shield. If I have an XBee S2 mounted on it and set the two jumpers to the USB setting or remove them, I am able to flash a program onto my Arduino.
However, when I'm mounting one of my XBee PRO S2B (I have three of them available and all behave the same) on the Arduino, no matter how I set the jumpers, it is not possible to flash anything on it. I always see avrdude: stk500v2_getsync(): timeout communicating with programmer in the Arduino IDE.
Is the XBee PRO S2B incompatible with the Arduino or what might be the issue? I also tried to add an external power source additionally to the USB, but it didn't help either.
Update
After some more experimenting, I found out new details. I tried to disconnect each pin of the shield individually. While doing it, I discovered that disconnecting the reset pin from the arduino makes it possible to flash it - take a look at the XBee shield schematic, it's pin 5 from the ICSP connector; Photo:
I used a multimeter and discovered that the XBee PRO S2B CTS / DIO7 port is high, while the one from the XBee S2 is low, and so constantly resetting the arduino. I mounted the XBee PRO S2B onto the Sparkfun XBee Explorer USB and opened a serial port with PuTTY.
In contrast to the S2, the PRO S2B provides a menu with several options:
B-Bypass Mode
F-Update App
T-Timeout
V-BL Version
A-App Version
R-Reset
>

As soon as I type B, the CTS port goes low, and would prevent the arduino from resetting. Also this mode is needed to detect the module via XCTU. However, with an unmodified arduino, I wouldn't have a chance to send this letter, since the XBee is constantly resetting it. What is this menu, can it be disabled somehow?

May seem obvious, but did you compare the register settings of the XBee S2 and S2B? Such as through X-CTU. Speed, parity, etc.

See the update; since this DIO7 port seems to be an issue, I took a look at the configuration especially on this setting; on both, the S2 and the PRO S2B it says DIO7 Configuration: CTS flow control [1]. I suspect that all of these settings are irrelevant while it waits in this "bootloader thing"?

Not a full answer - but IO/7 appears to be CTS flow control. I strongly urge you to download and use the X-CTU software (by Digi Intl.) to program them. Command line ATD7 will show current setting, ATD7=0 will disable (but use X-CTU). Why is this important? The XBee shields use CTS/RTS to signal a reboot to the Arduino (shield) - and then the bootloader will kick in and accept the data stream for flashing.

I used X-CTU to change this setting. If I disable DIO7 [0], it shows the same behaviour - as long as it is in this bootmenu, it is high. When I enter bypass mode, it goes low. If I set DIO7 to 5 (Digital Out, High), it keeps beeing high even after choosing bypass mode. So it seems like all the settings take only effect after entering bypass mode :/

Compare every setting on the working S2 with the non-working S2B thru X-CTU.

I don't have a PRO to play with, but I just looked at the datasheet and it appears that it SHOULD timeout after 60 seconds

If no serial transaction is initiated within a 60 second timeout period, the bootloader times out and returns to
  the menu. If the upload is interrupted with a power cycle or reset event, the EM250 will detect an invalid
  application image and enter bootloader mode.  (page 139)

Also, it seems that it takes a particular set of conditions to get to the bootloader, obviously these conditions are being met:

XBee modules use a modified version of Ember’s bootloader. This bootloader version supports a custom entry
  mechanism that uses module pins DIN (pin 3), DTR / SLEEP_RQ (pin 9), and RTS (pin 16). To invoke the bootloader,
  do the following:

Set DTR / SLEEP_RQ low (TTL 0V) and RTS high.
Send a serial break to the DIN pin and power cycle or reset the module.
When the module powers up, DTR / SLEEP_RQ and DIN should be low (TTL 0V) and RTS should be high.
Terminate the serial break and send a carriage return at 115200bps to the module.
If successful, the module will send the Ember bootloader menu out the DOUT pin at 115200bps.
Commands can be sent to the bootloader at 115200bps.

Note: Hardware flow control should be disabled when entering and communicating with the EM250 bootloader.

Perhaps check pins 3, 9 and 16 on boot and see if you can modify their behaviour.

I've long since closed the document, but I believe the second block quote there came from page 138

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


text:
Expected Unqualified-ID Before 'do'(and 'while')
I am getting the error "error: expected unqualified-id before 'do'" multiple times for every do{
}while(); loop I have... Any help?
Pastebin:http://pastebin.com/DubuAEUs

Perhaps you should cut down the amount of data you have (say, 3 pokemon and 7 moves) until you have working code.

I cut down the code as you said... Much easier to work with... Thanks!

From the code you posted, I would highly advise you to follow a C or C++ tutorial, as it seems quite obvious to me that you are new to C/C++ programming. There are a bunch of these on Internet.

The do whiles are outside setup or loop.

This question appears to be off-topic because it is a general C/C++ programming problem. It is not specific to Arduino at all.

Moderators, please remove this question as the code in pastebin as expired so this question is pointless now.

The do whiles are outside of the setup() or loop(), so they won't work.
I would suggest doing a simple C/C++ tutorial like this one to get up to speed with how things work.


text:
My DS18B20 is reading high. How can I get it to return the correct temperature?
I am working on a heating control system for my home, but having problems with the temperature sensor reading higher than I expect.
I have a 5V Arduino Mini Pro clone hooked up to a relay module, an HD47780 display and a Tiny RTC module, with a DS18B20 attached to it.
The DS18B20 is powered from the 5v Vcc applied to the Tiny RTC module rather than using parasitic power on the DQ line (as I wasn't sure if the Onewire libraries supported this mode of operation) and the DS18B20 datasheet says that Vcc may be between 3.0v and 5.5v. I measured the regulated power from the Mini Pro's  being at 5.2v.
I am comparing the temperature from the DS with the existing room thermostat (bi-metallic), an RS desktop temperature monitor with two sensors, a small 'thermo-hygrometer' and a bi-metallic fridge thermometer (in the upper quarter of its temperature range)†. The readout from the DS is always around 1-2 degrees higher than the readout from the other sensors, which are within a degree of each other.
† Not the actual one, but something similar.
Reading various forums I have heard that these sensors are quite accurate but can suffer from localised heating from components near them, so I moved the sensor onto a 20cm cable and positioned it well away from the rest of the electronics. This made no difference.
I then read that the DS can become self heating if it is supplied with too high a Vcc voltage, so I added a Red LED with 1.7v drop and measured the new voltage over the DS as 3.5v, but again, after waiting for the temperatures to stabilise once more, this made no difference.
Can anyone suggest why the DS may be reading high and what I can can do to prevent this?

How confident are you that your room thermostat isn't just reading 1-2 degrees low? You should get a third thermometer, and compare to determine where your offset is actually coming from. Since the RS thermometer likely uses the same readout electronics for both sensors, it's probably not really useful as two distinct calibration references.

I've put a lot of DS18B20 sensors in place now on various sensor nodes - maybe 50 or so. I've learnt a bit about the readings returned from them. I know you have isolated some of these as not being the cause, but it is good to confirm that they are issues.
I don't know if you are using Celsius or Fahrenheit, so the degree of the problem isn't clear.
Localised heating
I don't think of Arduino as a "hot" chip, but putting a DS18B20 in an enclosure with an Arduino and LCD caused me to see readings 2-3°C higher than expected.
Moving it outside the enclosure fixed this.
Heating from high Vcc/frequent conversions
If you supply the chip with a high Vcc and perform frequent conversions (i.e. as frequently as you can), the chip does warm up. I have seen this increase readings by 1-2°C.
I haven't seen the problem with high Vcc alone, but I operate most DS18B20 in parasitic mode and convert at most once every 10s. The ones operated in active mode generally have the powered turned off when not being used.
OneWire and DallasTemperature do support parasitic mode.
Not all temperature sensors are created equal
I had a number of temperature sensors before I started playing around with DS18B20. Almost without exception, these under-read. Most of them are based on thermistors and calibration is poor. I thought the DS18B20 were over reading, but when I used a good thermocouple and meter, I could validate that they were correct.
This was about learning to trust the DS18B20.
Heat conducted along wire
If you have the sensors on a wire, the wire conducts a surprising amount of heat. This can be an issue when running wiring along pipes.
Fake DS18B20
These sensors are very popular, and this seems to have caused fakes to appear. I have a batch of stainless steel waterproof sensors that over-read and the timings were out. They worked with the OneWire library, but not a DS2482 OneWire master. I have heard of the normal TO-92 cased ones being fake as well.

In the great wisdom of the board software, I'm not allowed to answer this question, so I'll add a comment here. As I found out the hard way on https://github.com/PaulStoffregen/OneWire/issues/91 , if you use a 3.3V chip, you need to replace the 4.7k resistor with a 2.7k resistor, or some sensors will return incorrect values.

In my case, the wiring between my uC and the sensor was too short, and was transmitting some heat. I thought that couldn't be the case at first, since another temp sensor was reporting accurate temps at the same distance. I moved it to another location on the board and voila!

Perhaps you might want to calibrate your sensor.
What does it read when immersed in boiling water (assuming sea level) ? 102.5 Celsius?  That would give you a high-temperature calibration of -2.5C.
Obviously it's better to calibrate around the temperatures you expect to me measuring.  That means trusting (or averaging?) some measuring device and calibrating to that.

I have seen offsets of several degrees C when using DS18B20 on a 3.3V bus, switching to a stable 5.0V bus and I got more reasonable values. (tested with and without parasitic power)

That's interesting, thanks, and the opposite of what some people have been reporting. I wonder if this is another fake DS18B20 issue.

I've made some experiments.
If DS18B20 was on short cable <1cm to my Arduino Pro Micro the readings was 5 degrees more than environment was. On cable lenght >10cm from arduino board and no matter where the resistor was mounted (near arduino or near DS18B20) the readings was fine.

After reading your answer, I tried moving the sensor away and my readings dropped 5 degrees to a more accurate value. Do you have any idea why? I don't think the heat of the circuit caused the difference.

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


text:
Corrupted output from HC-05 Bluetooth module
I have arduino Pro Mini 3.3V version with hc-05 module connected to 3.3V/GND and RXI/TX0 pins. I am then using my android phone to connect to the module. It shows up and pairs fine. Then I use BlueTerm app to view the output. I am seeing output that is occasionally as expected but mostly partially corrupted (characters replaced with random characters).
I am using 9600 baud rate and trasmitting the following:
void serialTransmit(int data){
  // send to raspberry pi or other device(s).
  Serial.print("Serial Transmit: ");
  Serial.println(data); // this is hard coded as "12" for testing
}

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

Does it show up as expected when using a computer? Also, I've seen some models with 38400 baud

I don't have bluetooth on any of my pc's yet, could try a tablet but should it matter if it's android or another OS? ebay listing does say 9600 baud rate but will try 38400 later.

Tablet should be fine, just to double check the reading. Could you also try setting the parity bit/etc. on BlueTerm?

Not seeing any such option in BlueTerm or other 3 apps I tried. It does seem odd that I get about 10 lines correctly at the beginning and only then it starts to corrupt.

That's weird...

It's strange that you should get anything at all in one of the  rx/tx configurations. Try changing the test string and confirm that what the few "good" transmissions really are true.

First thing to try:
Connect a 2.2k - 10k resistor from the arduino RX pin (the hc-05 tx pin) to ground.
If that didn't work, I recommend getting everything into a known state and eliminating some complexity. So, first let's remove the Android software from the equation.  And second, let's put the module into a known baud rate.
To do this wire up the arduino and module like this:
Notice that the Key pin is connected to 3.3v.  That will ensure the module is at 38400 baud on power up.
Connect the arduino to your computer with the FTDI cable.  Upload the following sketch:
/* Serial Loop */

#include <SoftwareSerial.h>

#define rxPin 8
#define txPin 9

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

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

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

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

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

With the sketch now uploaded and running, open the Arduino serial console and enter these AT commands. The serial console baud rate should be set to 9600 and line endings should be "Both NL & CR"
AT+ORGL //back to factory settings
AT+ROLE=0 //slave role - transparent serial bridge
AT+UART=9600,0,0 //default baud rate
AT+INIT //init module

You should get "OK" back from the module after each command. If you've gotten this far, we know the module is working fine and we know what baud rate it will default to now.
Hook the module back up the way you had it before.  Make sure 3.3v is disconnected from key pin and make sure you have added the pulldown resistor on the RX line. Cycle the power to the module. The module should start up running 9600 baud, slave mode. Delete the module from the Android pairing list and re-pair it.  The name probably will have changed.  Hopefully it works correctly now.
Cheers

I tried 4.7k resistor but it didn't make a noticeable difference, I assume there's no point in trying different resistor values? Also my module is bale, and has no voltage regulator, does your diagram apply to this situation since the module is rated at at 3.3V. Will need to wait until I receive my new soldering iron to change connections, clamping cables to the module is tedious :)

I think I saw 2.2k recommended, but tried it and worked with 10k.  The diagram applies except ignore the 5v line.  You take 3.3v from the mini pro vcc pin to the BT module VCC and Key pin (pin 34).

Until your soldering iron comes in, try using software serial instead of hardware serial. just move rx and tx on the arduino from 0 and 1 to some other digital pins.  See my code as an example.

If your wires are just clamped(alligator clips?) onto the module, you may just have a loose connection.

I tried software serial but couldn't get any output, will try to get it to work tomorrow. It's not even alligator clips, it's a small hand clamp that's pushing the wires against the contacts on one side :) Connections seem solid though...

Ok, so now I have a new module with breakout board. Connecting is easy now and I have tried connecting it like in your diagram. What I get as output instead of OK is some gibberish. The length seems to change depending on the input length. This is what it looks like: xÿx0þàø (input was AT+ORGL). The corruption is different now in that there is nothing discernible at all. Any ideas?

It sounds like there is a baud rate mismatch somewhere. What settings are you using where? Are you running the same sketch I posted?  Are you using the arduino serial console?

Yes, I am using latest arduino software and the Serial console that come with it. I pasted the same code you posted in a new sketch. What else could I try?

what baud rate setting are you using in BlueTerm?

I tried again on a new breadboard and it worked this time, I think it was interference from another unused device connected to the same pin as serial pins. Not sure what it was last time. Thanks for your help!

I have the same problem with arduino pro mini and HC-06, only change the baud rate of your BTserial port... try diferent baud rates in my case:
Serial.begin(9600);
Serial.println("AT");

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

Works fine, it happens because the arduino try to "understand" the module, but if the module speaks other leanguage, the arduino will never understand the command.
like me... sorry for my bad english. se ya.

Add the module as software serial then add these lines to setup() these line tell us the Bluetooth to turn into data mode:
bluetooth.begin(115200);
bluetooth.print("$$$");
delay(100);
bluetooth.println("U,9600,N");
bluetooth.begin(9600);


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.

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.

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

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

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.


text:
How to connect 5V sensors to 3.3V digital input (Due)?
I'm completely new with Arduino and microcontrollers in general.
I have several 5V sensors, and need 3.3V because that's the max for the Due. Is it possible to use a resistor to connect it to the Arduino? Do I have to measure the current from the sensor and calculate the needed resistor like this?
$$\frac{5.0 - 3.3}{\text{Measured current}}$$
(5.0 - 3.3)/(Measured current)

It really depends on what you mean by sensor. An awful lot of boards can be given 3.3V instead of 5V

@Cybergibbons I'm talking about ultrasonic sensors, altimeters, accelerometers, gyroscopes, magnetometers, GPSes, bluetooth masters, SPI RF-modules and an LCD display. Wouldn't giving 3.3V to an ultrasonic sensor limit its maximum range?

I'm thinking generally anything that is connected to the Arduino Due. Some things will work with 3.3V, but is there an easy way of lowering the voltage? Being completely fresh to electronics, I can't see any other way of doing this with a cheap resistor than by measuring the current.

For bidirectional level shifting (like I2C) refer to this reply. For unidirectional level shifting you can use just a single diode with a pullup resistor, refer to the second part of this reply.

Well if you're not sure of what you're doing, you can always go with level-converters for your sensors (that does not apply to shields though)
Level-converters (sometimes called level-shifters) come in different flavors:

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

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

one-way breakout usable with 4 pairs of pins
bi-directional breakout usable with 4 pairs of pins
74HC4050 IC discussed here

I know 90% what I'm doing. There is so little power it's not dangerous. I'm not concerned about the components themselves, they can be replaced. However, I'm building an octocopter that's lifting my $2000 camera, and I don't want anything to break during flight!

Are these level-shifters simply variable resistors controlled by an IC?

Is my method of finding a suitable resistor wrong? If not, why not just use it?

No level shifter generally use active components (transistors , MOSFET, or CMOS), they are not just simple resistors.

A resistor will allow you to lower voltage from 5V to 3.3V but not to increase it. Also, there's a lot of energy waste using resistors to lower voltage, I guess power consumption is important for you if you build a copter.

So they will actually be more effective. Why do they use Arduino specific chips, instead of a general voltage lowerer? Of course the copter is short of energy, but wasting 0.03W isn't really much of a concern.

Why do you think those chips are Arduino-specific? The references I've given you are general and can be used anywhere you need 5V-3.3V shifting, i.e. almost everywhere in digital electronics where circuits are typically 5V or 3.3V.

I thought SparkFun was an Arduino only page. Thank you for your comments. The bidirectional one seems perfect!


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

You could use SPI just as you would use let's say a UART: just send the characters of the string, and terminate with whatever character you reserve for deliminating strings, for instance \n or \0.

I have never used uart and have no experience with microcontrollers. But doesn't uart have integrity checking, in contrast to SPI?

It can have a parity bit for each byte, which is a very weak form of per-byte integrity checking. Almost nobody uses it.

I believe uart uses that. I would make a library myself to do integrity checking etc. But I thought this was already common to use and easily available.

SPI is an inter-chip protocol, mainly used on a single PCB. The common assumption is that it just works, like the communication between a processor and its ROM just works. Hence adding integrity checking at that level is not commonly done. And it is both very easy and depends on what you want to transmit, so it does not lend itself to being turned into a library.

@WoutervanOoijen Okay, I didn't know. Thank you for the information. I'm just getting started with microcontrollers (Arduino in my case), and there is a lot to learn! One big problem is of course The Arduino Language vs. C++. Later on when you don't use Arduinos anymore, C++ is the better language to know. However the Arduino language is easier in the beginning. But I have a lot of programming experience in preprocessed languages, so it makes the decision easier..

What do you need that a simple for loop won't provide?

@IgnacioVazquez-Abrams I thought the transmission was too unreliable to use it without doing integrity checking. If that is not necessary, a simple function containing a for loop will do the job. Thank you everyone who has commented.

@FriendofKim - if your goal was to have a reliable transport mechanism over SPI (with some sort of error check and correction or retries) then you should edit your question to say so, as that is not a typical problem and not one would conclude from reading your question as currently stated.

Each spi peripheral has its own protocol in the sense of commands and addresses if any and data.  Spi simply makes a common ground for chip select vs clocks and clocks vs data and separate miso and mosi data lines.
So a general purpose library doesnt make sense.
Also spi certainly is not limited to a byte, many peripherals and many spi controllers allow for long sequences of data, you are also not strictly limited to multiples of 8 bits either although that is the norm.
Your arduino spi master may have its limitations but that has nothing to do with spi in general.
Integrity testing is not part of the spi protocol, you get what you get.  Ideally all of the parts are soldered down on the same board or through known connectors and the margins have been designed in.  You would need to do something outside the spi protocol, for example if it is a spi flash then after you read a chunk of data you can do a checksum and compare it with a checksum you have embedded in the data (or crc).  If it is a spi ethernet part you may choose to leave the frame checksums in the frames and re-validate each frame yourself.  If you create your own peripheral (hardware design or cpld or fpga) then certainly you can add a crc or checksum to every transfer if you wish.

So far, I saw only one SPI peripheral, which does CRC for SPI transactions.  SD cards.  A/D, D/A, I/O expanders, RTC and so on don't do CRC or checksum or any other form of integrity checking on the SPI communication.

At the same time a general purpose SPI library does make a modicum of sense.  I wrote a more a less generic class, which keeps track and takes care of CS# pin, SPI mode, SPI clock divider.   It still does only 1-byte read/write.  Would a multi-byte (buffer) read/write make sense?  May be...  In some situations...

@NickAlexeev There are plenty of SPI peripherals which either send CRC together with the data (example), or also require the master to send CRC of commands. Of course, many lasy library implementations simply ignore the CRC in the first case.


text:
Arduino Nano uploading gives error: avrdude: stk500_recv(): programmer is not responding
I have a Arduino Nano (Sainsmart) that I'm trying to upload a sketch to. Under the Arduino IDE, the device selected was Arduino Nano w/ ATmega328.
However uploading the sketch gives me the error
avrdude: stk500_recv(): programmer is not responding

I tried both USB ports (/dev/tty.usbserial & /dev/cu.usbserial) but the same error persist. The Arduino is connected to a Macbook Air via the USB cable, and the PWR LED indicator light on the Arduino is turned on and the L indicator LED blinks. There was no problem uploading to a Arduino Uno.
Retried after installing the latest FTDI drivers (MAC OSX, x64, v2.2.18, FTDIUSBSerialDriver_10_4_10_5_10_6_10_7.mpkg) from http://www.ftdichip.com/Drivers/VCP.htm. However that did not help.
What could have gone wrong?

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

According to the device description Features: Automatic reset during program...

Yes, but according to the comments on the Amazon page, some people who bought this got yet another clone brand, so it seems to me that a healthy dose of skepticism about any claims in the documentation is in order, especially if they can easily be verified with an experiment.

I didn't read the comments but in that case you may be right.

While hitting reset at just the right time can work (it may take several tries), with Nano clones it's almost invariably the change in bootloader serial speed by the official Arduino.cc developers that's causing the problem. This answer is more likely to produce a reliable result: Tools → Processor → ATmega328P (Old Bootloader)

Know this is old but I ran onto it during my search for Nano(V3)'s not uploading so thought might help someone else.  Problem is the bootloader - Arduino IDE BUT I Found an easy solution (right under my nose).
I realized that my nano's had been uploading just fine then I had finally updated the Arduino AVR Boards from 1.6.20 to 1.6.21.  I didn't think there was any problems because it still showed my Nano and ATmega328 etc in the board manager after the change.
But the new boards manager has a new ATmega328 processor choice for the Nano. I changed processor: In the Arduino IDE select TOOLS > PROCESSOR > pulldown menu from ATmega328P to  "ATmega328P (Old Bootloader)".
Since then, I have uploaded many programs to several different Nano's V3 (Prolofic interace Chipset) without issue.

@sa_leinad - please do not change the meaning of other's posts.  What the poster said they updated was the AVR boards package, not the IDE.  This specific version break has been reported elsewhere.

This helped solved the issue for me though!

The solution is still working, I've tested it on Arduino IDE 1.8.7 Stable, 1.8.8 Hourly Build (Nightly) 2018/11/05 23:59 GMT and 1.9 Beta Build-87 with Arduino AVR Boards 1.6.23

The change in bootloaders was made public with the release of Arduino IDE 1.8.6: https://github.com/arduino/Arduino/releases/tag/1.8.6 More infos in https://arduino.stackexchange.com/questions/51866/arduino-nano-atmega328p-bootloader-difference An ISP (or another Arduino) is required to update the bootloader: https://arduino.stackexchange.com/questions/66806/can-the-arduino-nano-bootloader-be-updated-via-itself-and-the-arduino-ide-or-i

Thanks, switching to ATmega328P (Old Bootloader) had helped me to solve stk500_recv(): programmer is not responding stk500_getsync() attempt 1 of 10: not in sync: resp=0x79 problem. Actually, I have a feeling that before I was using older version of GUI which had this option by default.

+1 worked for me

3 years later and this solution is still good. Thanks!

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

Having a similar issue with my Sainsmart Nano.
Under Preferences check "Show verbose output during [x] upload, then when uploading, you should get a red trace like this:
avrdude: Version 5.11, compiled on Sep  2 2011 at 18:52:52
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2009 Joerg Wunsch

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

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

You'll notice a little "pause" just before the first line of avrdude: Send: 0 [30]   [20]. Try uploading again and have you finger ready on the physical reset button of your Nano. Just the moment before the first avrdude: ... appears, press the reset button.
When you succeed, you'll see the screen filling with all sort of gibberish, and ending something like this after a few seconds:
[78] . [00] S [53] h [68] o [6f] u [75] l [6c] d [64]   [20] b [62] e [65]   [20] 0 [30] x [78] 4 [34] 9 [39] D [44] 4 [34] . [00] . [01] . [00] . [00] . [00] . [02] . [00] . [03] . [00] . [04] . [00] . [00] . [00] . [00] . [00] . [e6] . [06] . [b5] . [06] n [6e] . [06] w [77] . [06] . [8c] . [06] . [9d] . [06] . [00] . [00] . [00] . [00] . [02] . [0d] . [aa] . [0d] . [95] . [0c] . [c9] . [0c] . [a9] . [0c] . [f2] . [0c] . [00]
avrdude: Recv: . [10]
# | 100% 3.71s

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

avrdude done.  Thank you.

This is to say that the Arduino (or knock-off) in question does not automatically reset before uploading and you have to manually do this by pressing the button.

I recently had the same issue with 3 Nano boards I just purchased from Amazon.  I can confirm that the suggested fix (changing to "old bootloader") solved my problem.
I think the main problem is the upload speed.  The "old bootloader" version successfully uploads at 57600, but the default "new" version tries to upload at 115200 and fails.

Yes this was my problem too. Found the explanation here https://arduino.stackexchange.com/a/51874/47260

This is just a duplicate of an answer previously posted.

Did you remember to tell the IDE that the board type is a Nano?
Tools -> Board => Arduino Nano ...
This gets me every time I swap between my Nano and Uno.

I also had that error message. I think there are many possible causes, so I haste to specify my special case.
I have a hackintosh with OS X Yosemite 10.10.2, Arduino software 1.0.6 and Funduino UNO. Uploading the example for Serial.write() succeeded the first time. Thereafter most uploads failed. Even when the upload succeeded the serial monitor would not always show output.
This seemed to me to be due to miscommunication on the USB port. I had to repeatedly reset the funduino, unplug and replug the USB cable or even restart the system. When replugging the USB cable sometimes my system would freeze.
By googling I found a solution to "Inserting USB device causes Mavericks 10.9.1 to freeze".
Answer no 12 on tonymacx86.com basically instructs you to remove GenericUSBXHCI.kext from /System/Library/Extensions.
I am happy to report that after removing this kext I have no problems uploading the example and monitoring the output. Because I don't need to replug the USB cable I don't know whether this solves my system freeze. I'm not even sure it was a system freeze, because my system may only have become unresponsive to my USB keyboard and mouse.

Had same issue and solution was as follows:

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

The board selection does not depend on the USB interface chip, only on the processor and baud rate.

The Arduino IDE version 1.8.5 gave the same error every time I tried to connect it to my OSEPP Nano.  I tried with multiple nano boards with different versions of the IDE. I had the board set to "Arduino Nano".
The solution was: Instead of Nano choose Arduino/Genuino Uno. This worked for me.

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

That problem, ocurred to me when I upgraded the Arduino IDE. I solved it by changing the processor to "old"
Tools->Processor->"ATmega328P (old bootloader)"
thanks!!!!

This is just a duplicate of an answer previously posted

Ok. I had the same programmer is not responding error on Arduino Nano on Atmel MEGA168PA, USB chip: CH340G. Macbook Pro under macOS 10.14.2.
It hand Blink example installed and the port wasn't visible in the list.
I was trying to figured out, whats wrong and connected my Arduino Due through the programming port. After 2 attempts the sketch was uploaded... Then I connected the Nano back, the port was visible this time (actually two of them: /dev/cu.wchusbserial14120 and /dev/cu.usbserial-14120) and guess what, the upload had been successful!
Magic!


text:
Should I try to make my sketches as small as possible, even when I have enough room?
There has been a lot of talk about shrinking sketches recently, but if you don't need the room, should it be done? Will it speed up my program?
Take this code:
int led = 13;
int val;

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

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

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

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

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

  val = digitalRead(10);
}

1,396 bytes on Arduino Uno. Now let's shrink it a bit:
int led = 13;
int val;

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

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

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

1,270 bytes. A 10% decrease! It could be shrunk even more. I have the space... is it more efficient (as far as speed) to make it the most compact I can or leave it "uncompressed?" I would imagine that it would be a little more work (not much) calling blink();, therefore slowing down my code. Is this true? Are there other advantages/disadvantages of making it as small as possible (besides storage/distribution of C++ files)?

I believe that one should be fastidious about their code, but never resort to micro-optimization where unwarranted.

For me, what comes first regarding code is its readability. If it's longer it can be more difficult or it may take longer to understand properly. If a gvensize optimization makes the code clearer, then you should use it.

Generally speaking, smaller is better. However, there is a point where too small actually makes the program run slower.
My suggestion is if you are working on a sketch and it is blatantly obvious that you are repeating code over and over again, I would rip that out and put it into a function, not only does it make the program smaller, it makes it easier to read.
There is also some optimization going on behind the scenes as well during compilation, so even though the C/C++ code looks to be large, chances are the compiler/linker are determining that something are repeats and consolidating them... Or at least the AVR compiler I used previously did, cannot remember if Arduino does this.

I believe it does have some optimizations... Arduino IDE compiles with avr-gcc.

Putting repeated code into a function also makes only one piece of code providing an opportunity to make mistakes, and only one one place to have to fix it/them. Also only one place to update later when you need to change something.

You second code may be smaller in size but due to the function call overhead the max execution speed is reduced.
Does this matter in your case? No, because you have huge delays anyway, but if the code was an actual series of repeated calculations that should be executed as fast as possible then it would make a difference.
As a general rule, smaller code is not necessarily faster too.
For code optimization (either size or speed) you can refer to this application note from Atmel AVR4027: Tips and Tricks to Optimize Your C Code for 8-bit AVR Microcontrollers
I could repeat everything it says here but I don't think there is a point, you can read the original article directly.

Regarding the compiler optimization level. Arduino IDE uses the avr-gcc compiler with a setting for Os optimization.
The avr-gcc available optimization levels are (source1 source2)

O0 or no -O option
At this optimization level GCC does not perform any optimization and compiles the source code in the most straightforward way possible. Each command in the source code is converted directly to the corresponding instructions in the executable file, without rearrangement. This is the best option to use when debugging a program and is the default if no optimization level option is specified.
O1 or -O
This level turns on the most common forms of optimization that do not require any speed-space tradeoffs. With this option the resulting executables should be smaller and faster than with -O0. The more expensive optimizations, such as instruction scheduling, are not used at this level. Compiling with the option -O1 can often take less time than compiling with -O0, due to the reduced amounts of data that need to be processed after simple optimizations.
O2
This option turns on further optimizations, in addition to those used by -O1. These additional optimizations include instruction scheduling. Only optimizations that do not require any speed-space tradeoffs are used, so the executable should not increase in size. The compiler will take longer to compile programs and require more memory than with -O1. This option is generally the best choice for deployment of a program, because it provides maximum optimization without increasing the executable size. It is the default optimization level for releases of GNU packages.
O3
This option turns on more expensive optimizations, such as function inlining, in addition to all the optimizations of the lower levels -O2 and -O1. The -O3 optimization level may increase the speed of the resulting executable, but can also increase its size. Under some circumstances where these optimizations are not favorable, this option might actually make a program slower.
Os
This option selects optimizations which reduce the size of an executable. The aim of this option is to produce the smallest possible executable, for systems constrained by memory or disk space. In some cases a smaller executable will also run faster, due to better cache usage.

+1 It's better to tell the compiler to make your code bigger/faster or smaller/slower rather than doing such asinine things like needlessly unrolling loops.

Your refactor should be done simply because it's better code, not because it's smaller. The advantage is that it's easier to modify.
If making the code size smaller results in a loss of clarity (not so in your case), then you should probably view it as a premature optimization.

When considering optimization, think carefully about what resource is most valuable.
You can optimize for code size; this will let you put more code onto your processor. What will the rest of the space be used for? If your code doesn't fit onto your arduino, and your alternative is buying a larger chip, then this is worth the effort.
You can optimize for speed - you can run more code in the same amount of time. If you are sampling data once per second, and sleeping the rest of the time, then this won't help.
You can optimize for power usage - very important if you're on a battery, less important if you are on mains. This might also not just be power consumed by the arduino, but also sensors & motors - can they be turned off for a while?
There are two optimizations that a lot of programmers forget - optimizing for development time, and optimizing for readability.
Any optimization for one thing will tend to de-optimize for at least one (often several) other things. If you don't know which optimization is going to be most useful, then go for readability, then development time (because today's readability = tomorrow's development time x 10!)
Usually, the most expensive thing is the development time (i.e. YOUR time, especially if you are on the clock for a customer). Most other optimization has a threshold - so long as you are over (under?) a specific threshold, further optimization doesn't help. Code size and execution speed (except when shared between competing tasks) are like this - if your code fits on the chip, then it is small enough. If it needs to do something else later, you can optimize it then. If your program can do all it needs to (assuming it is real-time; calculating Pi is a different case), then that's as fast as it needs to be.

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


text:
What are some steps to attach an Arduino to an electric heater?
I have the below portable electric heater, but I would love to control it's start AND stop time using an Arduino. As-is, it does not come with a stop feature. SO, I have a burning question. How can I get an Arduino to start and stop this heater at specific times of the day?
As you can see, it does have a start time, but it does not have a stop time.
The power button is a simple push button. I suspect I would need to 'interject' into that and the board by using a switch? Apologies if the terminology is off, but I'm very green.
Where would a noob begin?
-EDIT-
The unit is always off when it's plugged back in. That likely means I cannot put a timer on the power cord.

One important point to clarify: if you plug it out then plug it in again to main power (with the power cord), in which state is it, on (heating) or off (waiting for someone to push the on button)?

A lot of newer devices with soft switches like this, unfortunately, don't work when turned on. A step backwards.

@jfpoilpret The unit is always off when plugged back in. I've update the question.

Off when power returns is a failure mode with safety in mind. It would be wise to make sure your timer device replicates this behavior.

Easiest: External relay or solid state relay. Relay defaults on. A' (Arduino cct can detect current draw, turn relay off/on, be programmed to either stop time or run time). ||  Set external A' timer to desired time. A' sets relay ON. | Set heater to desired start time. When heater start A' sees current and starts timing, or in time of day mode just turns off power at correct time. || This keeps all circuitry external.

Would or should begin? Don't fiddle with the internals of the heater.
Set its switch to the always on position and control switching on and off with an external relay. Make a box that has plenty of room (you can reduce size at a later moment), a power cord, a mains adapter for your Arduino and a mains outlet in which you can plug your heater.
Use:

an RTC (real time clock) breakout to keep accurate time
optionally a 7 segment display to display date/time. Just make sure it has a driver chip on it so you don't need your Arduino to multiplex the individual LEDs
couple push buttons to configure the device
a relay rated for the maximum power of the heater to turn it on/off, that can be driven from 5V. Possibly needs a transistor and flyback diode to be controlled from an Arduino GPIO line.

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

The unit is always off when plugged back in. This is likely why a timer on the outlet won't work. I've updated the question.

Opto coupled relay would be safer. Or use something like this from spark fun https://www.sparkfun.com/products/10747

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

(From http://keshavsaharia.com/2012/12/01/coffeeduino/)
Basically here's what you do:

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

In code, you can just turn the relay on for a quarter of a second or so. Then, the IC on the heater will react like you pushed the button.
Make sure to seal all of this up and make sure you don't accidentally short out any of the wires. I would say to also isolate the Arduino and relay to make sure that you don't electrocute yourself at all if something goes wrong.

+1 This is (probably) a good solution if you are competent at delving inside mains powered gear. It may void your home insurance :-(.

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

Thought about this, but this particular heater does not remember it was left ON. Therefore, each time it gets unplugged I even have to reset the clock (since it has time based turning off/on).

To be safe use a device like the power tail from spark fun(basically a sealed relay unit, ready for you to connect to the arduino)
Much easier and safer if you don't have any experience working with 120V/240V
uses a 3-12 input to switch 120v up to 15A
https://www.sparkfun.com/products/10747

Thanks. I did consider this as well and would be a good solution in some cases. With this particular heater, it always starts as OFF when its plugged in, regardless if it was ON before power was cut. Therefore, the Power Tail would not work here. It is a good product and I am considering it for other projects. Thanks for the recommendation!

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

Power it down at a preselected time of day, provided the Arduino is able to keep track of time, or
The Arduino will turn it off a set period after it has started to heat.

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

Able to sense current drawn by heater.
Able to turn a heater control relay on/off
Able to set or select a time delay on Arduino.

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

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

Equipment:
Arduino controlled external relay or solid state relay.
Some means of detecting that heater is drawing current - timer mode only.
Arduino.

Arduino cct can:

Detect current draw.
Turn relay off/on
Be programmed to either stop time or run time.
Drives external relay or solid state relay.
Optional: Relay defaults on.

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


text:
Most compact method of powering Arduino from wall socket
There are a lot of methods to power an Arduino from a large range of voltages:

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

What I can't seem to find is a small 220V-5V converter. I'd like to put an Arduino in the wall, under a light switch, so size matters.
The last resort option is to open a 5V phone charger and replace the metal prongs that go in a socket with two wires, and replace the USB socket with another pair of wires that go the Arduino board, but still, an Arduino Pro Mini or an Arduino Nano is smaller than the phone charger.

Check your insurance if you are covered in case of fire caused by your construction.

@Josef  Your comment looks like a question. If you have a new question please post it as such.

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

You will probably have to do something like that.

Because of the nature of conversion between AC and DC, there has to be some large parts.* I'm not going to go into the specifics here. There is usually a diode bridge (because AC waveforms reverse the current ~60 times a second) and a transformer (to lower the voltage for the diode bridge). They almost always include a regulator and a capacitor to make sure voltage is exact and it outputs a "clean" power supply.
*Switching power supplies, although considerably more expensive, are a lot smaller and more power efficient.
This adapter seems to be the most compact adapter I can find for 220V. You'll never get something near the size you are desiring, even with a switching power supply. I don't know the size of the Amazon adapter I gave a link for, but in the US (120V), iPhone chargers are very small and they should fit in a standard depth outlet box (with a little room left over for relays and such). If you really need to get everything smaller, I recommend using a ATtiny chip.
How I recommend connecting this:
I would avoid ripping this apart at all costs from a safety perspective. It would be really easy to send 220V to your Arduino if you're not careful. If you absolutely have to, you might want to coat it with some non-conductive epoxy or other coding. Note: this may act as a thermal insulator, therefore reducing the lifespan of the part. You should just coil some wire around the prongs, and then melt a little solder onto each of the terminals. Then, cover that with electrical tape and pigtail (with a wire nut) into a source power line. Note: you probably are doing wiring that could be illegal in your area. Check your local building codes before attempting this.
After that, attach a USB cord to the socket and to the Arduino or the ATtiny/ATmega328 chip 5V/GND input (of coarse, after cutting and stripping one end of the USB cord). I would also, after finalizing all the code and circuitry, seal that with some epoxy or somehow add it to an enclosure to make sure you don't fry your Arduino if a loose wire touches the Arduino circuitry.
If you don't feel safe doing any of the above, don't do it. You can live without a Arduino light switch.
That being said, happy hacking! :P

I don't think you can get much smaller than this for a mains -> 5V converter that is isolated from the mains. There are tricks to get non-isolated low voltages, but they are not generally safe.

Thank you, I will order a few of these adapters and post here with the results.

@Vladb If you haven't ordered them already I would suggest asking a question on Amazon for the dimensions. Editing my post to suggest how to connect those to the wiring and your Arduino.

@Vlad Updated post.

No. This is big because it is a linear power supply where the transformer operates at line frequency and so must by physically larger.  It's also unregulated and poorly filtered.  Switching power supplies as have largely taken over in the past few years are much smaller, because their transformers are operated at the higher switching frequency.

@Chris I forgot about switching power supplies... I'm updating my post now. In my opinion, switching power supplies are still somewhat bulky, but nowhere near as big as a linear supply.

I can suggest you to try this : AC DC Step Down Converter
It is as small as the Apple's tiny cube, and it can be placed inside of a wall easily. (I'm personally using this with an arduino micro)

Thank you for the information, i have ordered a few of these too.

Im not quite about things that go to the mains from aliexpress. Anyone used that thing?

Nowadays, most smartphones come with a charger that is linked to the USB plug of the phone.
The charger for my HTC says: 5V, 1A, I guess this voltage must be regulated (but I haven't checked it has the charger is sealed).

The charger itself has a female USB socket on which you can plug any USB cord to link to your Arduino.
IMPORTANT! I have never tried it myself! I would not bet my life on it! It would be wise to check the output voltage is well regulated.

It's regulated. I've cracked those units open to use the circuit inside in other projects. It's amazingly compact.

Simplest and cheapest solution...if it's good enough for Samsung et al then it's...

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

Using this, following safety tips at https://skippy.org.uk/quick-look-at-the-hlk-pm01/

It's 34mm x 20mm x 15mm, which is very small.

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

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

The website says it only works for 120VAC, but the OP says they want a 220V adapter. I guess the title is a little misleading... and there might be another model for 220V.

true. i don't know how much power OP needs but one of these similar ones might work. http://www.digikey.com/product-detail/en/BP5041A5/BP5041A5-ND/658559 , http://www.digikey.com/product-detail/en/PBK-3-5/102-3106-ND/4332643 , http://www.digikey.com/product-detail/en/PBK-1-5/102-3101-ND/4332638

Any good idea is worth investigating. It might be for 110V but now I can look for the 220 version, if there is such a thing. Thank You! DrewTM - you posted right before I did. Thank you again for the links!

An obvious answer has been omitted which is: transformerless power supply.
If your average power requirements are low (<10mA) then this is the most compact way to achieve the desired voltage.
For an in-depth study see: http://ww1.microchip.com/downloads/en/AppNotes/00954A.pdf
Another solution: jeelabs.org /2011/11/27/ultra-low-power-supply/
Some limitations:

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

Best answer, much smaller than other options.

wanted to do a similar thing and I found and just ordered these:
http://uk.farnell.com/recom-power/rac03-05scr-277/conv-ac-dc-3w-90-305v-in-5v-out/dp/2289701
A fully sealed power supply, disk-shaped, 5cm diameter and 11mm thick. THey are available in 3.3V, 5V, and 12V. They are designed to be put inside walls or behind switches.

That's pretty neat. The product is discontinued anyway. Is there a version around that can output 2A instead of 600ma?

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

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

This one is 51 x 30 x 17.5mm

What if you replace the nearest outlet with some kind of USB Wall Socket and attach to that (either through a standard USB plug, or inside the wall) ?

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

It would be helpful if you mentioned some of the details of that converter in your answer.

Ordered a few of these, will add comment with the results when I get them.

Nov 2016
Here is a list of compact PCB mounted power supplies that are small (~50mmx25mmx20mm) from Mouser:
http://www.mouser.com/Power/Power-Supplies/AC-DC-Power-Modules/_/N-dv0g5?Ns=Output+Current-Channel+1%7c0&No=25&P=1yxt7eu
These all take in 120-240VAC and provide outputs in the range of 3 - 5 vdc with varying options for current.
The 5V 1A from Meanwell (IRM-05-5) looks like a good deal at $8.52 each.
http://www.mouser.com/ProductDetail/Mean-Well/IRM-05-5/?qs=sGAEpiMZZMuWiaalG5TUgH52QN1%252bIKAVmGC9ENLDVf688EuOMfqROg%3d%3d
Paul.

Wow, that's a nice one. Does it have output galvanically isolated from input (i.e. "can I touch the board powered by this thingie")? The datasheet mentions resistance between input and output and also has a couple of coils on schematics, but I'm still not sure.

The datasheet quotes "Isolation Class II".
See: https://en.wikipedia.org/wiki/Appliance_classes#Class_II

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