text:
Is it advisable to reload Pro Mini with the bootloader originally designed for UNO to save 1.5 KB flash space?
In order to allow bigger user program size, is it possible and advisable to reload Pro Mini with the boot loader originally designed for UNO. This will save 1.5 KB flash space (UNO boot loader is 0.5KB, Pro Mini is 2KB).
Using a smaller boot loader is an 'intermediate' step to get more space while still enjoy the easy benefit of the Arduino IDE and many library/code example. Of course, ultimate step is to remove all boot loader (only small saving of 0.5KB if above is possible) and switch to ATmel development environment, ATmel studio, which is complex but programmer has full control of everything.
Did I miss anything in the followings?
I tend to believe that it is possible as
a) same ATMega328 chip is used in both board
b) Pro Mini is essentially cutting UNO into two halves, the MCU and the USB/Serial converter now use external USB to Serial converter
If the Pro Mini board is reloaded with UNO boot loader, how should the boards.txt file be edited to reflect the changes so that the IDE will handle it correctly?
Many thanks in advance

Wouldn't it be simpler to just pick up an ISP programmer and use that instead?

Thanks for comment. Question edited to clarify the intermediate (save 1.5KB) and ultimate (save 2KB but much more complex) steps.

No, the intermediate step is to use a programmer. Tools | Programmer, File | Upload Using Programmer

@IgnacioVazquez-Abrams - No. That is the final step.  The intermediate step (and imho the one usually worth stopping at) is to use a small bootloader and leverage the same serial interface connector for debug and loading.

@ChrisStratton: Using ISP doesn't prevent Serial and the serial monitor from working. It simply allows you to control the fuse bytes and use all of the flash and EEPROM on the chip.

Of course it doesn't prevent it, but removing the bootloader and relying on ISP does prevent you from using the serial connection for program loading.  And it's explicitly not what the poster wants to do or is asking about for this stage of their project.

If you have an ISP setup, you are in a position to find out of the Uno or other small bootloader will work, and to restore the original if it doesn't (which would likely be only for some odd quirk, such as a mutual baud rate approximation)

Thanks responders for pointing out that Arduino IDE can do both boot loader and ISP modes. The later is new information for me and helpful in choosing best approach under different stages and situations.

You can just flash the newest optiboot_atmega328-Mini.hex. That one should also be only .5k in size, as it starts writing at the same address (7E00).
If you divide 7E00 by two you get 3F00 (This is because AVRs use 16-bit words for addressing while .hex files work with bytes (8-bit)). (I figured that one out, just now)
3F00 is exactly the start of the Boot Loader Flash Section when you  have selected a 256-words Boot Size (page 291 of the datasheet). 256-words is the 0.5kb you want.
Just make sure you have the BOOTSZ1, BOOTSZ0 fuses set to 1
As for the boards.txt. I think you only need to change mini328.upload.maximum_size=28672 to mini328.upload.maximum_size=32256.


text:
Which wireless technology should I use for medium range, many to one, bidirectional communication?
Some clients, let's say 5 <= x <= 10, have to send information wirelessly to a server. Transmission does not need to be reliable (ACK).
The range would be between 50 and 100m, and may include soft obstacles like trees, cars, etc, but not major ones like whole buildings or concrete walls.
Also, as I plan to build about 20 clients, the price should be as low as possible.
Thoughts?

Packet size? Transmission interval/rate? Try looking at the NRF24L01+. These are pretty damn cheap, and will probably do what you want and more.

@Gerben Can I have multiple messages on the air at once with those?

No. Not sure if anything exists that does that, unless it's using multiple frequencies. But they have an auto-resend function. Also transmission rate is pretty fast so the chances of collisions are low.

Depends on how much data you're sending, what packet structure you want to use, whether you want to spin your own PCBs or use a plug-in module, whether you need a low-power solution, etc..
For that distance, probably a sub-1GHz solution would work best.
I've had good results with the TI range of Value Line transceivers as they offload all the packet-handling, sync-words, CRC etc. from the microcontroller.  The modules also handle addressing, and have a "listen before talking" functionality - both of which could be useful with your physical architecture.
Down sides:

You'd probably need to spin your own PCB - they have good reference
designs.
No library for Arduino... but I'd personally rather use a
transceiver that manages all the low-level comms between the modules
so I can focus on the application.

RF433 modules are about as cheap as you get. You can get a tx/rx pair(separate modules) for 1-2 USD on ebay. Just search for "433mhz module". 100m or longer range should be possible with a proper antenna - a wire of the correct length. Use wavelength / 4, for 433MHz that is ~173mm.
The modules just communicate over a serial interface and they send the data straight to the air. But for better transmission the 1's and 0's need to be balanced and a "training preamble" before a data transmit balances the receiver for better noise immunity. Use a library such as virtualwire to take care of data decoding/encoding.
The common cheap transmitters on ebay allow you to supply a higher voltage to the module for increased transmission power.

Alternatively if you want transmitter and receiver in the same module you could go for nrf24l01 based modules. I haven't yet used them myself but they are dirt cheap as well. They operate at 2.4Ghz using a proprietary protocol with retransmit etc built-in. The modules have way more pins than the cheap RF433 modules, but you can also find arduino libraries to interface with them. The cheap kind use an antenna etched straight on to the print board. According to this article the open air range is 50-80m depending in the data payload in a transmission.

You can build a mesh with e.g. 433MHz- or NRF24L01+-modules to cover bigger areas when direct communication is not possibe: http://www.airspayce.com/mikem/arduino/RadioHead/

Just connect a NRF24L01 module with amplifier to the base-station. They are like $5,- but you only need 1.

I already have some of these modules, and the range they reach is poor. After 50m I got no signal.

source: Stack Exchange

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

sort: votes


text:
Arduino Custom Function Problem
I am experiencing problems when I put parts of my code into custom functions and then have Arduino Mega 2560 run it. The code works fine when I put it all in the void loop() function, but when I create new functions then call those functions in the loop() function, it doesn't do what I want it to.
Here is the code where I put everything in the loop function
/*
Location.txt: Date/Time , Latitude (deg decimal), Longitude, Altitude (m)
Speed.txt: Date/Time, Speed (m/s), Heading (deg)
*/

#include<TinyGPS.h>
#include<SD.h>
#include<SPI.h>

int CS = 53;

long lat,lon;
unsigned long time, date;
int year,tinseconds;
byte month, day, hour, minute, second, hundredths;
unsigned long age;
char dataString[20];
TinyGPS GPS;

struct GPSstruct {
  String dateTime;
  int timeseconds;
  float C_lat;
  float C_lon;
  float C_alt;
  float heading;
  float speedmps;
};

void setup()
{
  Serial.begin(115200);
  Serial1.begin(38400);
  pinMode(CS, OUTPUT);
  if(!SD.begin(CS))
  {
    Serial.println(F("Card Failure"));
  }
}

void loop()
{
if(Serial1.available()){ // check for gps data
   if(GPS.encode(Serial1.read())){ // encode gps data
    GPS.crack_datetime(&year, &month, &day, &hour, &minute, &second, &hundredths, &age);
    GPS.get_position(&lat,&lon); // get latitude and longitude in degree decimals multiplied by 10^5
    sprintf(dataString, "%02d/%02d/%02d %02d:%02d:%02d",month,day,year,hour,minute,second);
    tinseconds = second + minute*60 + hour*3600;
    float C_lat = ((float)lat)/1000000; //to get degree decimals
    float C_lon = ((float)lon)/1000000;
    float C_alt = GPS.f_altitude();
    float heading = GPS.f_course();
    float speedmps = GPS.f_speed_mps();
    GPSstruct A = {dataString,tinseconds,C_lat,C_lon,C_alt,heading,speedmps};

//DEBUG
    Serial.println();
    Serial.print(F("Date/Time: "));Serial.println(dataString);
    Serial.print(F("Time (sec): "));Serial.println(tinseconds);
    Serial.print(F("Lat: "));Serial.println(C_lat,5);
    Serial.print(F("Lon: "));Serial.println(C_lon,5);
    Serial.print(F("Alt: "));Serial.println(C_alt);
    Serial.print(F("Heading: "));Serial.println(heading);
    Serial.print(F("Speed: "));Serial.println(speedmps);
//END of DEBUG

//add the code below makes alt = 1000000 for a long time then it fixes at some ?wierd? number
//------//
  File dataFile = SD.open("Location.txt", FILE_WRITE); //Records date/time, lat, lon, alt
    if (dataFile)
    {
      dataFile.print(A.dateTime);dataFile.print(" , ");dataFile.print(A.C_lat,5);dataFile.print(" , ");dataFile.print(A.C_lon,5);dataFile.print(" , ");dataFile.println(A.C_alt);
      dataFile.close();
    }
    else
    {
       Serial.println(F("Location.txt cannot be opened!"));
    }

   File dataFile2 = SD.open("Speed.txt",FILE_WRITE); //Records date/time, speed, heading
   if (dataFile2)
   {
     dataFile2.print(A.dateTime);dataFile2.print(" , ");dataFile2.print(A.speedmps);dataFile2.print(" , ");dataFile2.println(A.heading);
     dataFile2.close();
   }
   else
   {
     Serial.println(F("Speed.txt cannot be opened!"));
   }
//------//
   }
}
}

Here is the code where I put them into two custom functions and call them in loop()
#include<TinyGPS.h>
#include<SD.h>
#include<SPI.h>

int CS = 53;
long lat,lon;
unsigned long time, date;
int year,tinseconds;
byte month, day, hour, minute, second, hundredths;
unsigned long age;
char dataString[20];
TinyGPS GPS;

struct GPSstruct {
  char dateTime[20];
  int timeseconds;
  float C_lat;
  float C_lon;
  float C_alt;
  float heading;
  float speedmps;
};

//Function Prototypes
struct GPSstruct GPSdata(void);
void SDlogger(struct GPSstruct);

void setup()
{
  Serial.begin(115200);
  Serial1.begin(38400);
  pinMode(CS, OUTPUT);
  SD.begin(CS);
}

//GPS data function:
struct GPSstruct GPSdata(void) {
static GPSstruct A;

 if(Serial1.available()){ // check for gps data
   if(GPS.encode(Serial1.read())){ // encode gps data
    GPS.crack_datetime(&year, &month, &day, &hour, &minute, &second, &hundredths, &age);
    GPS.get_position(&lat,&lon); // get latitude and longitude in degree decimals multiplied by 10^5
    sprintf(dataString, "%02d/%02d/%02d %02d:%02d:%02d",month,day,year,hour,minute,second);
    tinseconds = second;
    float C_lat = ((float)lat)/1000000; //to get degree decimals
    float C_lon = ((float)lon)/1000000;
    float C_alt = GPS.f_altitude();
    float heading = GPS.f_course();
    float speedmps = GPS.f_speed_mps();
    strcpy(A.dateTime, dataString);
    A.C_lat = C_lat;
    A.C_lon = C_lon;
    A.C_alt = C_alt;
    A.heading = heading;
    A.speedmps = speedmps;

//DEBUG
    Serial.print(F("Date/Time: "));Serial.println(dataString);
    Serial.print(F("Time (sec): "));Serial.println(tinseconds);
    Serial.print(F("Lat: "));Serial.println(C_lat);
    Serial.print(F("Lon: "));Serial.println(C_lon);
    Serial.print(F("Alt: "));Serial.println(C_alt);
    Serial.print(F("Heading: "));Serial.println(heading);
    Serial.print(F("Speed: "));Serial.println(speedmps);
    Serial.println();
//END of DEBUG
  }
 }
 return A;
}

//SD data logging funct:
void SDlogger(struct GPSstruct A)
{
   File dataFile = SD.open("Location.txt", FILE_WRITE); //Records date/time, lat, lon, alt
    if (dataFile)
    {
      dataFile.print(A.dateTime);dataFile.print(" , ");dataFile.print(A.C_lat);dataFile.print(" , ");dataFile.print(A.C_lon);dataFile.print(" , ");dataFile.println(A.C_alt);
      dataFile.close();
    }
    else
    {
       Serial.println(F("Location.txt cannot be opened!"));
    }
   File dataFile2 = SD.open("Speed.txt",FILE_WRITE); //Records date/time, speed, heading
   if (dataFile2)
   {
     dataFile2.print(A.dateTime);dataFile2.print(" , ");dataFile2.print(A.speedmps);dataFile2.print(" , ");dataFile2.println(A.heading);
     dataFile2.close();
   }
   else
   {
     Serial.println(F("Speed.txt cannot be opened!"));
   }
}
void loop()
{
  struct GPSstruct Gdata = GPSdata();
  SDlogger(Gdata);
}

The one with all the code in the loop function prints all the serial.println commands and writes data into the micro SD card, but the one with custom functions DOESN'T print serial.println commands in GPSdata function and only prints that "Location.txt/Speed.txt cannot be opened!" and have writes 0 into the mirco SD card.
Why is this happening? Is it memory problems? (But the other one works fine)
The code here is meant to be a part of a bigger main code that uses these GPS data, so I would prefer it if I can keep the main script clean using custom functions.
Thank you.

The code in both appears to be perfectly satisfactory - stock - normal - stream file writing. Do you have an "errno" global variable available? If you do, that might shed some light on the errors you're getting. There's nothing inherent to custom functions that would make your code not work. You're absolutely sure that the SD card was plugged in & functional when you used the custom function and it failed?

Admittedly, your code is somewhat hard to read without an actual editor (not your fault), but I think the issue is that in the first code (everything in one loop), the matching bracket from the initial if-statement (if(Serial1.available()) {) is located after the SD logging functions.
In the second code (decomposing the code), you have the SD logging done outside the if-statement. My guess is that Serial1.available() = false initially, so in the first piece of code, it skips everything else and loop until Serial1.available() == true. That probably doesn't take long, so you just see everything working. In the second code, you return static GPSstruct A (I'm not sure you want this to be static, but I could be wrong) which has been initialized but contains no useful data (it's uninitialized). The void loop() then takes that empty struct and passes it over to SDlogger(struct GPSstruct). That function doesn't do any error-checking to make sure that A has useful information.
An easy workaround would be to add a field to the GPSstruct for whether or not it contains data. It's a simple boolean value. The code might look something like this:
struct GPSstruct {
  boolean containsData;
  String dateTime;
  int timeseconds;
  float C_lat;
  float C_lon;
  float C_alt;
  float heading;
  float speedmps;
};

...

if(Serial1.available()){
  A.containsData = true;
  ...
} else {
  A.containsData = false;
}

...

void SDlogger(struct GPSstruct A) {
  if(A.containsData) {
    ...
  } else {
    return;
  }

Also, as I was typing this, it got migrated...

Personally, I'd put the check for available data in loop(), and if available, call the GPSdata and SDlogger functions based on that check.

That would work too. You can do it however you like; I just tried to come up with a quick example. Putting it in the loop would definitely be simpler.

Was that the problem? I don't actually see a way to mark the answer, but if you can mark a post as answering your question, you should to close it.
Glad we could help!

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


text:
How do I view Serial Output on an Android Device?
Within the Arduino IDE Serial.* output can be viewed with Tools / Serial Monitor.  How can I view Serial.* output on an Android?  As a concrete example, how can I view the output from Examples / Communication / ASCIITable?

This of course depends on the specific Arduino model generation or USB serial cable utilized.

These steps will allow your Android device to function as an Arduino Terminal.

Download a Serial Terminal app.  I'm using Android Hyperterminal, English version.
Attach an OTG ("On The Go") cable to your Android device.
Attach your Arduino to the OTG using your regular USB cable.
Make sure the terminal program is set to the same baud rate as your sketch.
Run the terminal App and select the USB port.

I didn't find that app, and ended up installing "Serial USB Terminal" by Kai Morich, it works well so far!


text:
Why are Tone.cpp and IPAddress.cpp getting built for my project?
I'm using avr-size to see the size of library objects to free up some FLASH. Why are Tone.cpp and IPAddress.cpp getting built? e.g.
$ cd /var/folders/3j/6wp3hvrj34n0xg3xzq6vjq380000gn/T/build8391693238079360471.tmp/
localhost:build8391693238079360471.tmp
$ /Applications/Arduino.app/Contents/Resources/Java/hardware/tools/avr/bin/avr-size *.o
   text    data     bss     dec     hex filename
      0       0       0       0       0 CDC.cpp.o
      0       0       0       0       0 HID.cpp.o
   1816       0     170    1986     7c2 HardwareSerial.cpp.o
    512       0       6     518     206 IPAddress.cpp.o
  10186     391     377   10954    2aca MainINOFile.cpp.o
   1872      14       0    1886     75e Print.cpp.o
   1414       1       0    1415     587 Stream.cpp.o
   1365       1      21    1387     56b Tone.cpp.o
      0       0       0       0       0 USBCore.cpp.o
    288       0       4     292     124 WInterrupts.c.o
    306       0       0     306     132 WMath.cpp.o
   4796       1       1    4798    12be WString.cpp.o
     30       0       0      30      1e main.cpp.o
    618       6       0     624     270 malloc.c.o
     56       0       0      56      38 new.cpp.o
    450       0       0     450     1c2 realloc.c.o
    588       0       9     597     255 wiring.c.o
    266       1       0     267     10b wiring_analog.c.o
    550       0       0     550     226 wiring_digital.c.o
    320       0       0     320     140 wiring_pulse.c.o
    260       0       0     260     104 wiring_shift.c.o
$ /Applications/Arduino.app/Contents/Resources/Java/hardware/tools/avr/bin/avr-size */*.o
   text    data     bss     dec     hex filename
   2790       0       0    2790     ae6 DS3231/DS3231.cpp.o
     38       0       1      39      27 EEPROM/EEPROM.cpp.o
   1444       0       0    1444     5a4 LSM303/lsm303.cpp.o
    782       0       0     782     30e Messenger/Messenger.cpp.o
    116       0       1     117      75 SPI/SPI.cpp.o
    142       0       4     146      92 SdFat/MinimumSerial.cpp.o
   2568       0       0    2568     a08 SdFat/Sd2Card.cpp.o
  10644       0       4   10648    2998 SdFat/SdBaseFile.cpp.o
   1322       2       0    1324     52c SdFat/SdFat.cpp.o
    152       0       0     152      98 SdFat/SdFatUtil.cpp.o
    233       0       0     233      e9 SdFat/SdFile.cpp.o
    736       0       0     736     2e0 SdFat/SdStream.cpp.o
   2604       0     523    3127     c37 SdFat/SdVolume.cpp.o
   3395       0       0    3395     d43 SdFat/istream.cpp.o
   1635       0       0    1635     663 SdFat/ostream.cpp.o
    754       0      86     840     348 Wire/Wire.cpp.o
$ /Applications/Arduino.app/Contents/Resources/Java/hardware/tools/avr/bin/avr-size *.elf
   text    data     bss     dec     hex filename
  29204     442    1279   30925    78cd MainINOFile.cpp.elf

The fact that source files be compiled does not mean they all will be linked together in the final exe. The linker only takes what's needed.

Might I suggest aliasing avr-size et alia? It would save quite a few keystrokes.

@IgnacioVazquez-Abrams ctrl-c ctrl-v :)  I mainly put them there for reference to future question viewers who might not know about avr-size

I was able to reproduce this building the Blink example. It explains why building a small sketch sometimes takes ages.

That's the price you pay for minimal-config development.

@Jippie, if you are on a windows machine; move the arduino directory to a path that has NO-white spaces. Any White Spaces in the path to the core lib will cause a "clean" rebuild, which is much slower. To verify turn on "output compile" in the IDE pref's. While this is a different topic. It is related. Hope it helps. (looks like 1.5.7 always does a clean build. 1.5.6r2 and prior works.)

@mpflaga who in his/hers right mind would develop on Windows?

As stated the IDE's equivalent to the make will compile anything everything it can find, in scope. But its linker has eliminate garbage enabled, hence anything not called or not static will not be linked into the EXE.
You can "avr-objdump -t" to create a map from your elf. And -d for an assembly listing. As to see exactly what is in the EXE, for your self. You need to enable show verbose output of compilation from the IDE's preferences, to display the temporary directory that contains the elf file.
example:
C:\DOCUME~1\mflaga\LOCALS~1\Temp\build6395515806682540138.tmp>C:\projects\Arduino\hardware\tools\avr\bin\avr-objdump -t MP3Shield_Library_Demo.cpp.elf > MP3Shield_Library_Demo_wo_mem.cpp.elf.map
C:\DOCUME~1\mflaga\LOCALS~1\Temp\build6395515806682540138.tmp>C:\projects\Arduino\hardware\tools\avr\bin\avr-objdump -d MP3Shield_Library_Demo.cpp.elf > MP3Shield_Library_Demo_wo_mem.cpp.elf.lst

I did the above and commented out a call to a function member of my library, between subsequent builds. To see that the code was not linked into the assembly.


text:
How to use ROHM LB202VL display (on BP-006LH-GC board) with Arduino?
I got this 8-unit, 7-segment, 2-digit display board with 24 pins and I am wondering how I can interface with this from my Arduino Uno.
The board is labeled ROHM BP-006LH-GC and it has 8 units of the LB202VL LED display. Please see these photos of the board:

I found the datasheet for the LB202VL unit and I have been trying to make an independent unit on the board to work but I haven't been successful in setting its display.
The datasheet for the LB202VL unit can be found here: http://pdf.datasheetarchive.com/datasheetsmain/Datasheets-27/DSA-525461.pdf
Can anybody help me explain how I can work with this and set the display from my Arduino? After having attempted a few times I feel a little lost with this so any help would be greatly appreciated!

https://www.google.com/search?q=arduino+multiplexed+seven+segment+display

Get a power supply of 5v or so, and a 680 ohm resistor, two lengths of wire, and probe pins until you figure it out.  You can later try a slightly smaller resistor close to the data sheet maximum, especially when you start sequencing the LEDs.

8 pins for the 7 segments and the dot (Anodes). 16 pins for the 16 digits (Cathodes). Looking at the traces I can't see any pattern in how they are connected. Just use Chris's suggestion.

A multimeter set to diode test will also work. I use it to test for working 7-segs when I shop.

I have a similar display, and I found the wiring by inspection and trial and error:
The display consist of 8 pairs of digits (LB-202VL, common cathode).
If contact points are numbered from 1 to 24 from left to right then
the common cathodes for the digits D1-D16 and the segments D.P. and 'a' - 'g' are noted below.
If you i.e. connect 1 to GND and 7 to + then segment 'c' of the first digit will be on. You have to multiplex the digits in order to use it.

D1
D2
D3
D4
D.P.
D5
c
D6
e
D7
a
D8
g
D9
d
D10
f
D11
b
D12
D13
D14
D15
D16


text:
Arduino yun as ssh client
Is it possible to set the Arduino Yun up as an ssh client? If so, how?

The Atheros chip should have enough muscle for an SSH client. The ATmega has not enough resources for that: too little RAM and too slow for reasonable use. But what do you mean by 'SSH client'? An SSH client is a program that can connect to an SSH daemon (or server). So an SSH client can initiate a connection to your PC which runs an SSH daemon. The client can send commands to the PC, the PC executes them. Is that what you mean?

Yes that is what I mean. I need the arduino yun to act as an ssh client to start an ssh session with another box and then execute some basic commands.

What do you mean that the ATmega doesn't have enough resources for an ssh client. Is this dependent on the work being done by the client or just in the setting up of the client / server

You need memory for at least the IP packets and session information as well as for the SSH keys. It would be useful if there was some memory left for regular tasks too. If you manage to squeeze that into maximum of 4kB RAM in the ATmega, then the key exchange would take ages because asymmetric key exchange is very CPU intensive.

You need to install package openssh-client: it's available in the package list. See this tutorial about how to install optional packages.
You can call ssh on the Linux side using Process from the Bridge Arduino library.
Best is when you execute single or grouped commands using a syntax as:
ssh user@your_other_host 'echo 1; echo 2'

Managing an open ssh session is possible but I think may be troublesome, so avoid it if you can.

Hi. Thanks for that answer. Im still struggling to get a fully operational ssh client. I can connect to the ssh server from the client but how do I receive data back from the server?

You can grab the output produced by the commands run on the server


text:
ArbotiX-M Problem uploading to the board
I have an ArbotiX-m Arduino board, and have followed the setup guide on Trossen robotics all the way to the 5th step. I have a Mac running OS X 10.10 and use Arduino 1.0.5. I installed the necessary drivers and copied the files to the Sketchbook directory. When I try to load the sample ArbotiXBlink program:
// Pin 0 maps to the USER LED on the ArbotiX Robocontroller.
int led = 0;

// the setup routine runs once when you press reset:
void setup() {
  // initialize the digital pin as an output.
  pinMode(led, OUTPUT);
}

// the loop routine runs over and over again forever:
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
}

It verifies just fine, but when I click upload, I get:
Binary sketch size: 1,088 bytes (of a 65,536 byte maximum)
avrdude: stk500_recv(): programmer is not responding

Any ideas?
EDIT: The board was trying to get power from the 5V instead of USB

I figured why my board wasn't responding! Apparently, the power pin was connected to the 5V supply instead of usb. Silly me!

Please add it as an edit.

No, this is proper as answers are the vehicle for solutions (even when they come from the asker), while question edits are the means of adding additional detail about the problem.


text:
SD.begin() fails second time
When I remove the SD card and try to open a file, I can detect the error properly.
But how do I detect that the card has been replaced after an error? My first thought was to call SD.begin() again but it appears that this function returns true exactly once and false thereafter.
Simplified example:
void setup() {
  SD.begin(pin); // called exactly once. Works.
}
void loop() {
  // stuff
}

But this does not:
void setup() {
  SD.begin(pin); // first time calling this function: works.
}
void loop() {
  delay(1000);
  SD.begin(pin); // always fails
}

I'd rather not reset the microcontroller just for this.

I'm looking for a SD.end() function somewhere. That is what you need, but I can't find anything in the reference.

I know this question is relatively old but still, if you wnat to run  SD.begin(chipselect); again first call if(root.isOpen()) root.close(); I added this to the library. This way SD.begin(chipselect) will return true if a card is present and false when it's not.

Are you talking about this fix?  AFAIK it's not been merged into master.  Still, a better solution than what I had before.  Thanks.

Update
A software reset, while inelegant, was much simpler to implement and debug than trying to add "retry" type functionality to SD.h. The other alternative would be to access SDFatLib.h or the other lower-level stuff (which SD.h is a wrapper for) directly, so if someone has that solution, I'll accept it instead of this one.
Original
Here is something, which is working well enough for me at the moment: does not reliably work:
bool SDState{false};
File LogFile;

bool trySDCard(void)
{
    // sanity check: maybe the SD card is actually here?
    LogFile = SD.open("test.txt", FILE_WRITE);
    delay(10);
    if (LogFile) {
        LogFile.close();
        return true;
    }
    int8_t counter{10};
    while (counter && !SDState) {
        SDState = SD.begin(TFT_CARD_CS);
        Serial.print(counter);
        Serial.print(" ");
        counter--;
        delay(100);
    }
    Serial.print("SD: ");
    Serial.println(SDState);
    return SDState;
}

void setup() {
    SDState = SD.begin(TFT_CARD_CS);
    Serial.begin(115200);
}

void loop() {
    // NB. Simplified a lot (exitMenuMessage(string) is my custom function defined elsewhere)
    switch (state) {
        case SD_RETRY:
            exitMenuMessage(trySDCard() ? "found SD card" : "no SD card");
            break;
    }
}

Seems to work Sometimes works if I insert the SD card while trySDCard() is running.


text:
Getting a random number for electronic dice
I am making a "Electronic Dice".
I have 7 LEDs to form the output, and this works fine.
My problem is getting a random result on the output.
int die_face = 1;

void loop()
{
    if (analogRead(BUTTON_PIN) == HIGH)
    {
        paintDieFace((die_face % 6) + 1);
    }

    die_face += 1;
}

The problem is, that roughly 95% of the time I get a 1.
Most of the time it's not a 1, it's a 2, or very rarely a 3.
I've tried paintDieFace() with millis()%6+1 too, but always get the same result.
When it's painted with random(1,7); I get 1, 2 or 3 100% of the time.
Is this some sort of timing issue?  I just don't get it.
Just to clarify - The paintDieFace() function is working perfectly, I'm logging the result to serial too.

This code is for a high-school student workshop, so it really needs to be kept simple.

I tested your code and I don't have this problem.

First of all, look at this line of code:
if (analogRead(BUTTON_PIN) == HIGH)

You probably want to use digitalRead(). Note that it is okay to use digitalRead() on an analog pin, just make sure to use the right pin number (A0, etc.)
From the Arduino Source:
#define HIGH 0x1
#define LOW  0x0

(Ignore the 0x, that is just specifying that it's hexadecimal. However, 0 and 1 are the same in any base)
So, really, this function is only activated when analogRead() returns 1, which could possibly cause a problem later if it doesn't check at the right time. Note: now is a good time to remind you about debouncing...
For your actual code, since you want it to be simple, I suggest you forget that code that you wrote. Arduino has a built in random library, which works unless you have some special need for a random number.
Your final code should look like something like this in the end:
void loop() {
    if (analogRead(BUTTON_PIN) == HIGH) {
        paintDieFace(random(1, 6);
    }
}

Note that you should also use this code here in your setup (make sure that analog pin is floating: nothing should be attached to it):
randomSeed(analogRead(A1));

It actually isn't random, just pseudo-random. That means it relies on an equation to generate what seem to be random numbers. Because there has to be a default value of where the equation starts (the seed), it will repeat the same numbers every time you run it.
If you're wondering how this works, know that the analog pin is affected by a ton of external factors when there is no other electric signal attached.

De...BOUNCING, not denouncing. 8)

@TDHofstetter thanks for that catch! My finger must've slipped...

Ah I didn't see the analogRead();  Of course I meant digitalRead().  Thanks for the heads-up.

for a HS project it doesn't matter, but in terms of security, randomSeed(analogRead(A1)); is terrible. random() is deterministic, and it's not hard to try all 1024 sequences. If you do that, run random() in the loop so that it's unpredictable how many times it's been called, and thus unpredictable in terms of the next result. randomSeed((analogRead(A1)+1)*millis()*micros()*(analogRead(A1)+1)) is better

@dandavis two issues with that: a) its stronger for sure, but still incredibly weak. You shouldn't be using a pseudorandom generator if it needs to be secure end of discussion. B) since seeding is traditionally at the start of the program, millis and micros are going to be very similar each time, if not the exact same. Of course, seeding when the button was first pressed may overcome this partially, but there are ways to overcome this (hold down the button before plugging it in so the first iteration of the loop reads HIGH, advanced cameras and timers, etc.)

@AnonymousPenguin: good point about the timing. i'm used to 8266s, where you can put that after the wifi connect part, which takes 1-3 seconds... a prior delay(analogRead(A0)%250) adds cheap entropy from micros(). an empty wire connected only to A0 collects noise and widens the sample range considerably, might be worth noting in the answer. "security" was probably the wrong word; i'm just suggesting  low-effort/cost ways to make a game (much) harder to cheat using an app...

@dandavis very true, although I'm sure the teacher would be pleased if the student did the work to reverse engineer the random functions and build a separate program that calculated sequences with the random seed and matched a sequence to the appropriate seed. :)

I've had better success with this version.
I did not work out the problem with the first version.  Although I did find the rear legs of the push-button were lighting up a LED - but only when pushed.  As the result is only displayed when the button is not pushed, I don't see how it could make a difference.
I believe the modulus of 6 is a problem, perhaps this does really output more ones than anything else.  Obviously looping the dice_number variable 1->6 removes the necessity for it.
#define LEDS_34_PIN 2  // Output pins used
#define LEDS_16_PIN 3
#define LEDS_25_PIN 4
#define LED_7_PIN   5

#define BUTTON_PIN  6  // Input

unsigned char dice_number  = 0;     // this is what will be shown on the die face

void setup()
{
    // Tell the Arduino we're writing to some pins
    pinMode(LEDS_34_PIN, OUTPUT);
    pinMode(LEDS_16_PIN, OUTPUT);
    pinMode(LEDS_25_PIN, OUTPUT);
    pinMode(LED_7_PIN,   OUTPUT);

    // ... and reading a button
    pinMode(BUTTON_PIN, INPUT);

    // Do a testing-dance first
    for (int i=1; i<=6; i++)
    {
        paintDieFace(i);
        delay(500);
    }
    paintDieFace(0);

}

// Show a dice-dot-style number
// based on LEDs laid out like
//    [1]     [4]
//    [2] [7] [5]
//    [3]     [6]
void paintDieFace(unsigned char number)
{
    // Turn off all LEDs
    digitalWrite(LEDS_34_PIN, LOW);
    digitalWrite(LEDS_16_PIN, LOW);
    digitalWrite(LEDS_25_PIN, LOW);
    digitalWrite(LED_7_PIN,   LOW);

    if (number == 1 || number == 3 || number == 5 || number > 6)
    {
        digitalWrite(LED_7_PIN, HIGH);
    }
    if (number >= 2)
    {
        // LEDs 3 & 4 are on for all numbers greater-than 1
        digitalWrite(LEDS_34_PIN, HIGH);
    }
    if (number >= 4)
    {
        // LEDs 1 & 6 are on for 4, 5 and 6
        digitalWrite(LEDS_16_PIN, HIGH);
    }
    if (number >= 6)
    {
        // LEDs 2 & 5 are only on for 6 (or more)
        digitalWrite(LEDS_25_PIN, HIGH);
    }
}

void loop()
{
    int button_pushed = digitalRead(BUTTON_PIN);
    if (button_pushed == HIGH)
    {
        // The user has pushed the button, change the die reading
        paintDieFace(dice_number);
        delay(20);  // flicker the LEDs if button held in
    }

    dice_number += 1;
    if (dice_number == 7)
        dice_number = 1;
}

Just as a sidenote. Remember that you need a pull-down resistor on the button pin, to get reliable data from digitalRead(BUTTON_PIN).

@Gerben: it's cheaper/easier to just set the pin mode to INPUT_PULLUP and hook button to GND...


text:
Sleep mode and months of operation on small battery
In context of getting the MCU on Pro Mini and ATMega2560 (chip is ATmega328 and ATMega 2560) to sleep and power down modes, so as to run on one set of battery for months, appreciate idea and comment.
Initially, I looked at web postings and get the following general idea. Did I miss anything?
Is sleep mode done via ATMel factory library, Arduino-level user contributed library, or the Arduino IDE? Many web posting are along the line of getting it partially working but only at half expected current reduction, etc. That is, current do reduced, but, not enough.
Are there several such library?
How are they?
Which one is better support and more functions? (no need for easy to use, can do registers programming, when needed)
Many thanks in advance

"Seems like sleep mode is done via user contributed library, instead of core 'official' IDE." Wat. The API is in avr/sleep.h, which is even more "core" than the IDE.

Followed your lead, got http://www.nongnu.org/avr-libc/user-manual/group__avr__sleep.html and look like this is one of the several lib mentioned on web postings.

Yeah, why do it the simple way when you can add 5 files and 10kB of code :/

@IgnacioVazquez-Abrams 5 files and 10kB of code?

@geometrikal: A slight exaggeration. But all the functionality required is built into AVR Libc already.

@IgnacioVazquez-Abrams In the jee lib I linked to there is a great function called loseSomeTime which falls to sleep for a set amount of time (using periodic watchdog interrupts to keep track). Also there is some code to turn off brown out detect which is not in the link from John Williams. For space saving one can simply copy the Sleepy class out into a separate file, it is only a few functions.

As an aside, the watchdog stinks for keeping track of time. If you need accuracy then use an asynchronous timer instead.

Have a read through the Jeelabs blog which documents the author's very successful attempt at making a very low power wireless sensor node that can run for months off coin cells.
http://jeelabs.org
There is also a library based on this project called Jeelib:
http://jeelabs.net/pub/docs/jeelib/
Jeelib contains a class called Sleepy that allows for easy sleeping.
Rocketscream did a thorough test of the current consumptions with the different modes here:
http://www.rocketscream.com/blog/2011/07/04/lightweight-low-power-arduino-library/
According to them, you can get the ATMega328P down to 1.7uA.
Unless you do something about the power supply on a normal Arduino board you won't be able to extend the battery life by much at all. See my answer here for some more details:
Arduino powering from 9V battery

+1 for resourceful pointers to rich sources of info. Edit the question on the power supply regulator chip. Some chip are uA rated while other are traditional higher power consumption.

You also should desolder the power-led on the boards. I prefer to skip the voltage regulator and get a battery pack that has the right voltage. E.g. three AA (3 x 1.5V = 4.5V). Most AVR chips have quite a range in acceptable voltages. Also running the chip without the crystal reduces the power use a bit I've heard. I never used crystals on my own homemade boards. Just read chapter 9 of the datasheet, especially 9.10!

I could reproduce these power requirements - main thing is to get rid of the Arduino board and start with a Bareduino or sth similar. (find a detailed description here)

Another way is to use Pro Mini board. First, de-solder the power on LED light as it takes about 3mA. Battery feeds to the 5V pin without using the regulator. The LDO voltage regulator on my board takes up about 20 micro ampere in this un-used mode (likely, different brand/model of that chip has different current consumption). De-solder if necessary.

I have a page about saving power with the Atmega328P chips (similar techniques apply to other chips): Power saving techniques for microprocessors
I made a Temperature and humidity sensor - battery powered - this runs from 3 x AA batteries, and writes to an SD card. From memory it ran for 2 years before I needed to replace the batteries.
Another project flashes an LED every second: Simple project - torch-locator. I made something similar a couple of years ago that is still running from the same button battery.

As a rule-of-thumb, you should be able to achieve 100 nA of current consumption, and still be "alive" and able to respond to external events, like button-presses (eg. a calculator or TV remote). To wake periodically (without an external event) takes more current, because you need the watch-dog timer to be active, but that can still be as low as 6 µA.


text:
MCU fuses used by Pro Mini and ATMega 2560 and power down
In context of Pro Mini and ATMega2560
Fuses, as documented in chip factory doc are complex topics (I have not really used it before), appreciate pointers and advises, to narrow down those that are needed for contexted task and left un-needed in their default modes.
Which fuses are used within context of the IDE in general, and in specific of software loading via bootloader and ISP?
Which fuses related to sleep and power down modes, in context that individual chip modules can be set to various power-saving modes via registers. Does fuses play a part in getting the power-saving effect?
Many thanks in advance

Have you looked at the datasheets yet?

Most fuse settings will work fine. The only power-saving fuse is disabling the brownout detection, but it's better to do that in software. There isn't any need to change the fuses in most cases.

The data sheets are the ultimate source. However, that may be a bit overwhelming. I find the below great resources very helpful.
1) Online Fuse Calculator There are many others.
2) avrdude-GUI
there are many others out there.
3) the .\arduino-1.5.7\hardware\arduino\avr\boards.txt
uno.bootloader.low_fuses=0xFF
uno.bootloader.high_fuses=0xDE
uno.bootloader.extended_fuses=0x05

4) I also read the fuses from any device before I stomp over them. And check into what each mean.
As for narrowing down the features the Online Calculator very helpful to start with and then read into the data sheet for ones of interest.
For the most part there have several questions and answers for low power modes, using interrupts to re-awake. Where there appears to no direct fuses to save power, outside of clock source and speed. Arguably Brown Out detect is a fuse, but that is not directly related to saving power.


text:
LCD display under power saving mode
To make LCD display, Pro Mini and ATMega2560 to run on one set of battery for months, appreciate idea and comment.
Which LCD to use?
Which LCD chip controller chip (hide inside the LCD) has better power saving mode?
Which library with functions of power saving and also can put out VERY beautiful per-programmed display, like multiple fonts, different fonts size, some graphics like circle, rectangles, color fills, gradual-color-changing background with text and graphic at 'foreground' (as in PC power point style)?
Under context of

Small Mono chrome 2 lines text display
3 inches mono chrome graphic 128 x 64 or similar
3 inches color graphic, 320 x240 or similar

Many thanks in advance

I think that is impossible. You'd have to look into only turning the lcd on when needed to save power.

So far no reply, Context 2 and 3 may be impossible, so, I re-do a new question focusing on getting a good Arduino library matching a LCD chip. Will see if conetext 1 will receive can-do reply.

Use a huge battery, or somehow re-charge the battery (solar?).

Use an eInk/ePaper style display, which uses no power while the display is not changing.  These come in monochrome greyscale, and have excellent readability.
This solves only part of your problem as you still need to power the CPU.

Agree, eInk can do. However, supply is hard to get than LCD


text:
"Hello World" program for nRF24L01+?
Where is a simple program that demonstrates unidirectional data transmission over a pair of nRF24L01+ radios?  It should have adequate output so that a beginner can determine that the transmission is working properly.

http://arduino-info.wikispaces.com/Nrf24L01-2.4GHz-HowTo

http://tmrh20.github.io/RF24 built in examples will do.

I found this site to have pretty strait forward instructions:
https://maniacbug.wordpress.com/2011/11/02/getting-started-rf24/
Main Library: https://github.com/maniacbug/RF24/
Example Sketch: https://github.com/maniacbug/RF24/blob/master/examples/pingpair/pingpair.pde

Here are several "getting started" articles that contain simple programs.
http://tmrh20.github.io/RF24
https://groups.google.com/forum/#!topic/nrf24-arduino/VaC2U5D1o_s
http://arduino-for-beginners.blogspot.com/2013/02/setup-nordic-nrf24l01-rf-modules-to.html

TMRh20 RF24 library examples work well.
Install TMRh20 RF24 library in the Arduino IDE Library Manager (“Sketch/Include Library/Manage Libraries...” and search for “RF24”). Then open the Getting Started example (“File/Examples/RF24/GettingStarted”).
You’ll need to change the “radioNumber” variable to 0 or 1 on the sending and receiving Arduino (line 13 of the code).
For the hardware I prefer to use pins 9 and 10 instead of 7 and 8 (line 16 of the code), so that all pins are connected to port B.
The nRF24 is supposed to be 5V tolerant on the data lines, but not for the power supply, so you need to connect VCC to 3.3 V. In my experience, it works best if you use it with a full 3.3 V board (ESP8266 or Arduino Pro Mini).
You absolutely need to add a strong capacitor between VCC and ground. I use a 2200 µF capacitor, but 10 µF may be enough (http://arduino-info.wikispaces.com/Nrf24L01-2.4GHz-HowTo).
I also wrote a small article about the nRF24L01+.


text:
Mega 2560 powered with 7V don't work correctly
I have an Arduino Mega 2560  with a GPRS seeedstudio shield and an USB Host CircuitsAtHome shield which work fine when powered with USB or with an adjustable voltage regulator set at 8V.
When I set this voltage regulator at 7V (minimum voltage from the spec to get the better efficiency) I am still reading 5V and 3.3V on the pins of the Arduino and all the leds of the Arduino and the GPRS shield seems fine but the USB Host CircuitsAtHome shield seems to not work properly.
I cannot debug it using the console because if I plug the USB cable, everything works fine...
Why 7V fail while 8V is ok?
The adjustable voltage regulator can provide up to 5A which is plenty.

7v is the minimum voltage from which spec? Can you provide links to all the components of the circuit?

From this page : http://arduino.cc/en/Main/arduinoBoardMega2560 "input voltage (recommended)"

The Voltage-Regulator has a dropout-voltage of 1,2V, but in line to the regulator is a diode, which adds another minimum 0,7V (dont know the exact part number, so i guessed the voltage of a Si-diode at ~1A). So you have to supply at least 5 + 1,2 + 0,7 = 6,9V. I presume the circuit doesnt draw a constant current all the time, so from time to time the regulator cant supply the 5V because you sink under the necessary dropout-voltage of the rehulator/diode-combination.
-> Use 8V  or bypass the Diode D1 (with a solder-bridge) and use 7V if its a must and you are sure the input-polarity is always correct.
Arduino-Mega-2560-schematic: http://arduino.cc/en/uploads/Main/arduino-mega2560_R3-sch.pdf

You need to be clear about how you are hooking this up. Are you feeding 7V into the Vin on the Arduino? If so, then the voltage regulator on the Arduino is attempting to regulate 7V down to 5V. As Echo says, 7V isn't quite enough for the built-in voltage regulator.
If your voltage regulator outputs clean, noise and ripple free regulated voltage, you could set it to 5.0 volts and feed it directly into the Arduino's 5V line, bypassing the regulator on the Arduino completely. If you do this you need to make absolutely sure that you give it exactly +5V though, as you will likely destroy the board if you go much over 5V or wire it backwards.
If it's a switching regulator then you might need to add a choke to the output of the regulator to get rid of high frequency noise on its output.

I am currently feeding the board using the 2.1mm jack plug of the board. Will it be safe to power the board at 5V  (directly to the 5V pin of the board) with this converter : http://www.seeedstudio.com/depot/Adjustable-StepDown-DCDC-Converter-10V-17V18A-p-1717.html?cPath=1 . Is it outputs clean, noise and ripple free regulated voltage? Thanks!


text:
Parse data from sensor without delimeters
Im using a variant of Arduino Due embedded on a ARM (Udoo). And I have connected a Medlab SPO2 Pearl 200 sensor to Serial1.
Im just trying to parse input from Serial1 to Serial, in a human-readable format (Hexadecimal).
The protocol is described in this image:

And using this Arduino code I reveice two times the "no finger detected line"
int lineLength = 16;
int spo2read[16];
int readed = 0;
 if (Serial1.available()) {
    int inByte = Serial1.read();
    if (readed < lineLength) {
      spo2read[readed] = inByte;
    }
    readed++;
    if (readed == lineLength) {
      Serial.print("SPO2: ");
      for (int i = 0; i <= lineLength; i++) {
        Serial.print(spo2read[i], HEX);
        Serial.print( delimeter);
      }
      Serial.println("");

      readed = 0;
    }

  }

Output with no finger is:
SPO2: A,FB,2,F9,0,FA,0,FC,A,FB,2,F9,0,FA,0,FC,0,

Buf if I put my finger, all is messed up:
SPO2: 7C,74,6B,62,5A,51,4A,42,3B,34,30,2E,2F,30,31,33,0,
SPO2: 36,38,3B,3E,3D,3C,3C,3B,3B,38,34,2F,2C,2B,2B,29,0,
SPO2: 24,21,1E,1D,1E,1E,1F,20,22,24,26,28,2B,2D,30,32,0,
SPO2: 35,37,39,3C,3E,40,42,44,45,4A,4F,53,55,57,59,5C,0,
SPO2: 5E,60,61,F9,0,FA,0,FC,1A,FB,0,F8,62,62,62,63,0,

Sensor doesn't sends a \n or \r so I don't know exactly how to parse the data

It says there is a marker byte. You have to look for the marker byte to know when the message has ended.

as per http://www.medlab-gmbh.de/english/downloads/pearl100_144.pdf page 13 marker bytes and example C code page 16 are values greater than or equal than F0

I have used the source code available on the Medlab web, and do some "modifications" to be Arduino compatible.
I dont wanna the waveform data, because my final program will do the waveforms acording the data received, so I don't "listen" to the waveform packet
boolean startbyte = false;
byte buf = 0;

  while (Serial1.available() > 3)
  {
    buf = Serial1.read();
    if (buf > 0xfc)
    {
      buf = Serial1.read();
    }

    if ((startbyte == true) && buf > 0xF7)
    {
      startbyte = false;
    }

    if (buf > 0xf7 && startbyte == false)
    {
      //startbyte = true;
      if (buf == 0xf8)
      {
        startbyte = true;
      }

      if (buf > 0xf8)
      {
        byte RX = buf;
        buf = Serial1.read();
        if (buf > 0xfc)
        {
          buf = Serial1.read();
        }

        if (RX == 0xf9)
        {
          //SPO = buf;
          Serial.print("SV:");
          Serial.print(buf, DEC);
          Serial.println();
        }

        else if (RX == 0xfa)
        {
          //Pulse = buf;
          Serial.print("SPV:");
          Serial.print(buf, DEC);
          Serial.println();
        }
        else if (RX == 0xfb)
        {
          //Status = buf;
          Serial.print("StV:");
          Serial.print(buf, DEC);
          Serial.println();
        }

        else if (RX == 0xfc)
        {
          //quality = buf;
          Serial.print("QV:");
          Serial.print(buf, DEC);
          Serial.println();
          Serial.println();
        }
        else { }
      }

    }
    else if (startbyte == true)
    {
     //Waveform data
    }
  }

actually I don't think it is all mixed up
as per geometrikal use the markers to parse the data stream
I believe your above sample data started mid-stream during the 0xF8 of the wave form.
F8,...
...,7C,74,6B,62,5A,51,4A,42,3B,34,30,2E,2F,30,31,33,0,36,38,3B,3E,3D,3C,3C,3B,3B,38,34,2F,2C,2B,2B,29,0,24,21,1E,1D,1E,1E,1F,20,22,24,26,28,2B,2D,30,32,0,35,37,39,3C,3E,40,42,44,45,4A,4F,53,55,57,59,5C,0,5E,60,61
F9,0
FA,0
FC,1A
FB,0
F8,62,62,62,63,0,...

I believe reading this as a finite length does not portray the data for easy interpetation. Given that 0xF8 is a variable length protocol.
Where the reparse of your data initially appears to be legitimate parse.
That said I do read the SPO2, Pulse as zero. Where it may be likely the sensor has not finished its reading and auto gain cycles.


text:
How do I specify a working directory when saving to SD card?
I'm trying to datalog to a EyeFi SD card by writing to a file with a jpg extension. Here's that portion of my code so far:
// see if the directory exists, create it if not.
if( !SD.exists("/DCIM/100NIKON") )
{
  if( SD.mkdir("/DCIM/100NIKON") )
  {
    Serial.print("File directory created: ");
  }
  else {
    error("File directory not created");
  }
}
else
{
  Serial.print("File directory exists: ");
}

// Test file
char filename[] = "DSCN0000.JPG";

if (! SD.exists(filename))
{
  logfile = SD.open(filename, FILE_WRITE); // only open a new file if it doesn't exist
}

if (! logfile)
{
  error("Couldnt create file");
}

The Arduino creates the directory, but the file is still saved to the root.  I would love some help or tips on this.

You're creating a directory, and then not writing the file into it.
You need to change the filename to /DCIM/100NIKON/DSCN0000.JPG";
Note that SD.open() takes the full filepath to the file, not just the file*name*.
From the Arduino Docs:

The file names passed to the SD library functions can include paths
  separated by forward-slashes, /, e.g. "directory/filename.txt".
  Because the working directory is always the root of the SD card, a
  name refers to the same file whether or not it includes a leading
  slash (e.g. "/file.txt" is equivalent to "file.txt"). As of version
  1.0, the library supports opening multiple files.

(emphasis mine)

Oooh, I was thinking that after creating a directory with mkdir, the directory will automatically become the working directory.  Thanks a lot!

@user2218339 - Nope, and as far as I can tell, there isn't even a way to change the working directory at all. It's basically hard-wired to /.


text:
Calling a function that is outside of a class from inside
I have an Arduino sketch with a timer interrupt class and would like to place the TIMER2Services() function in the TimerTwoTest.ino file for easy access. On compile I get a multiple definition of tmb2 error in the .ino TIMER2Services() function. I have tried all the variations I can think of but no luck. Is there a way to do this?
TimerTwoTest.cpp.o: In function `TIMER2Services()':
D:\Arduino157/TimerTwoTest.ino:41: multiple definition of `tmb2'
TimerTwo.cpp.o:C:\Users\...\build8577138580185682113.tmp/TimerTwo.cpp:10: first defined here

collect2.exe:
TimerTwo.h:
class Tmb2
{
  public:
  void initTIMER2(unsigned int Hz, unsigned int ulPeriod);
  void resetTIMER2(unsigned int Hz, unsigned int ulPeriod);
  TIMER2_TYPE getPeriodTIMER2(void);
  void activeTIMER2 (void);
  private:
}tmb2;

TimerTwo.cpp:
extern void TIMER2Services(void);

[this function is line 10 for the error]
void Tmb2::initTIMER2(unsigned int Hz, unsigned int ulPeriod){  //setperiod and enable interrupt
  if (Hz){
    ulPeriod = 1000/Hz;    //if Hz > 0 use frequency microseconds
  }
  Timer2.attachInterrupt(TIMER2Services).setPeriod(ulPeriod).start();
}

TimerTwoTest.ino:
volatile unsigned long burpCount = 0;

//This routine services the interrupt
void TIMER2Services(void){
  burpCount++;
}

Which file(s) are you including, and where? Also: it looks like you're using an external library: is this correct?

The problem is your definition of tmb2.  You're declaring the variable in the header file, and not the C(++) file.
Please try this:
TimerTwo.h
#ifndef __TIMER_TWO_H__
#define __TIMER_TWO_H__

extern void TIMER2Services(void);

class Tmb2
{
    public:
        void initTIMER2(unsigned int Hz, unsigned int ulPeriod);
        void resetTIMER2(unsigned int Hz, unsigned int ulPeriod);
        TIMER2_TYPE getPeriodTIMER2(void);
        void activeTIMER2 (void);
    private:
};

#endif // #ifndef __TIMER_TWO_H__

The #ifndef TIMER stuff saves you getting multiple definitions from header files if they're included more than once.  There's other ways to do this, but this is simple and well-known.
TimerTwo.cpp
#include "TimerTwo.h"

void Tmb2::initTIMER2(unsigned int Hz, unsigned int ulPeriod)
{
    //setperiod and enable interrupt
    if (Hz)
    {
        ulPeriod = 1000/Hz;    //if Hz > 0 use frequency microseconds
    }
    Timer2.attachInterrupt(TIMER2Services).setPeriod(ulPeriod).start();
}

TimerTwoTest.ino
#include "TimerTwo.h"

Tmb2 tmb2;
volatile unsigned long burpCount = 0;

// This routine services the interrupt
void TIMER2Services(void)
{
    burpCount++;
}

void setup()
{
    tmb2.initTIMER2(blah1,blah2);
}

For the sake of neatness, I'd move TIMER2Services into class Tmb2 as a static function... if possible.

Shouldn't TimerTwo tmb2; be Tmb2 tmb2;?

Yeah, you're right Gerben.  I've just edited it

I would also re-think the closeness of the class name and instantiation name: Tmb2 looks very much like tmb2, and could lead to errors of mistaken identity. It's certainly a personal 'good practice' for me, but there are no rules for either opinions.


text:
Wrong Mouse.move() output in Arduino Leonardo
I'm using my Arduino Leonardo as a Mouse but I'm experimenting a strange behaviour.
I put my mouse at (-1, -1) (absolute) coordinates and then I execute this code:
Move.move(com[curr_cmd_id].x, com[curr_cmd_id].y, 0);

where that point is (334, 180) (relative coords) (and I checked it through Serial console)
Now, the pointer is actually moving to the right but then it stops. Let's say it reaches the point (334, 0).
Then I tried:
Mouse.move(com[curr_cmd_id].x, 0, 0);
delay(500);
Mouse.move(0, com[curr_cmd_id].y, 0);

but still the same behaviour.
Then finally I tried this one (which it actually solves my problem but it's a dirty solution):
int i;
for(i=0; i<com[curr_cmd_id].x; i++){
  Mouse.move(1,0,0);
  delay(1);
}
for(i=0; i<com[curr_cmd_id].y; i++){
  Mouse.move(0,1,0);
  delay(1);
}

Could anybody help me in understanding what's going on here? How can I achieve a simple and direct relative movement for my pointer?
Thanks you in advance!!

So it's only moving to the right, and not up?

Only on the right and not down (considering the coordinates I expect to go down with positive y)

It looks like maybe there's something filtering a maximum "jump" in the mouse position.  What happens if your increment your for loop by more than 1 - can you experimentally discover a limit?

why result is so diffrent between : moveMouse(127, 0, 0); and for (i=1; i<= 127; i++) { moveMouse(1, 0, 0);} ?

I struggled with this too until I realized this

Parameters
xVal: amount to move along the x-axis - signed char
yVal: amount to move along the y-axis - signed char
wheel: amount to move scroll wheel - signed char

Note it says signed char.
That means the value you pass to the Mouse.move is a signed 8-bit. (-128 to 127)
My work around is this below:
void moveMouse(int x, int y, int w){
  x = (int)x / 1.59; //Adjust these two values accordingly. I found out that 100, 100 does
  y = (int)y / 1.58; //not move 100, 100. It moves 159, 158 for me.

  while(x!=0 || y!=0 || w!=0){
    int moveX, moveY, moveW;
    if(x > 0){
      if(x >= 100){
        moveX = 100;
      }else{
        moveX = x;
      }
    }else if (x < 0){
      if(x <= -100){
        moveX = -100;
      }else{
        moveX = x;
      }
    }else{
      moveX = 0;
    }

    if(y > 0){
      if(y >= 100){
        moveY = 100;
      }else{
        moveY = y;
      }
    }else if (y < 0){
      if(y <= -100){
        moveY = -100;
      }else{
        moveY = y;
      }
    }else{
      moveY = 0;
    }

    if(w > 0){
      if(w >= 127){
        moveW = 127;
      }else{
        moveW = w;
      }
    }else if (w < 0){
      if(w <= -128){
        moveW = -128;
      }else{
        moveW = w;
      }
    }else{
      moveW = 0;
    }

    x = x - moveX;
    y = y - moveY;
    w = w - moveW;

    Mouse.move(moveX, moveY, moveW);
  }

Same answer in 5 lines: void MouseMove(int x, int y) {   for(int i=0; (x>0)?(i<x/100):(i>x/100); (x>0)?(i++):(i--))      Mouse.move((x>0)?(100):(-100), 0);   for(int j=0; (y>0)?(j<y/100):(j>y/100); (y>0)?(j++):(j--))      Mouse.move(0, (y>0)?(100):(-100));   Mouse.move(x%100, y%100); }


text:
Very long delay() possible?
I'm trying to make an opening and closing little door that should open or close every 12 hours. I was wondering if I could just make a small looping script with a delay() for 12 hours, delay(43 200 000 000); I guess? However, I have no idea if that's possible and/or recommendable. Some feedback/alternatives(if needed) would be nice :)

ok, i think delay has a max of 65535 µs, but now i need an alternative...

Timing in more mature, MCU-alone systems is usually done by programming a hardware timer channel of the MCU to fire an interrupt periodically, and then counting these - that lets the processor do other things in the meantime, and is cumulatively as accurate as the clock crystal.

Using delay will magnify an ever so slight overhead error. It is better to use an interrupt to time a known good period and then count from there. Here is a proof of concept on my personal website: http://blog.linformatronics.nl/213/electronics/timed-1-millisecond-interrupt-routine-for-arduino

If it doesn't have to be perfectly timed, you can use unconventional things, like a light sensor to sense morning and evening.

yes, I thought about that, however I only have a little light detector part and I'm not sure how to protect it from the weather (the little door is outside)

@FredPannekoek. Put the detector under a roof. You don't need to put it directly under the sky.

I want 20 minutes low and 3 minutes high program structure. I have arduino uno board

The real time clock method is the most accurate way but otherwise use millis
unsigned long startMillis = millis();
while (millis() - startMillis < LONG_DELAY_MS);

This will delay up to approx. 4294967295ms (2^32-1) or 49 days, after which the timer will catch up to the value of startMillis

What is wrong with just using delay(LONG_DELAY_MS)? The arduino implementation accepts unsigned longs. I'm also not entirely sure you code works correct when millis() wraps around, and is smaller than startMillis

Delay makes your arduino completely inactive while waiting if I'm correct. I don't know how this will act when millis is back to 0.

@Gerben good stuff, put it as an answer!

@FredPannekoek overflow will work fine, so long as unsigned long is used.

So, you want to have interrupts every ms, for 12h? Why just not putting the controller in sleep mode for 12h?

@23ars How are you going to wake up the controller after 12 hours exactly? Most elegant solution is an external RTC with 12 hour alarm.

take look at the Ricardo's answer. Or if you don't want the watchdog and sleep mode, a solution could be to set the timers to genererate an interrupt every second  (TIMERX_COMPA) and count second, not millis. with millis you generate every ms an interrupt and that's not quite ok. Even if it's Arduino, I'm, somehow, against using functions from libraries, like millis and others.

@23ars The main reason Arduino is so successful is its easy-to-use hardware abstraction library, if you are against functions from libraries you are limiting yourself somewhat. Anyway, the function of comments is to improve the answer, if you have a better solution, write your own answer.  ;)

@Gerben: Why do you say that the Arduino implementation accepts unsigned longs? Arduino Reference states that the argument for delay() has to be an unsigned int. (Your link to 'arduino implementation' is now dead).

@PimV updated link: https://github.com/arduino/ArduinoCore-avr/blob/master/cores/arduino/wiring.c#L106 . The Arduino reference website also says delay accepts an unsigned long. So I'm not sure which reference you are referring to, that says it has to be an unsigned int.

@Gerben: Thank you. I apologize, you are right. Can't find it back, probably looked with my nose.

delay() has its uses, but for long delays it's no good. It simply tells the microcontroller to do nothing for x clock cycles. During that time, your Arduino can't do anything else.
Your best bet would be to use a thing called a Real Time Clock (RTC). These chips are specifically made to keep track of time, and you can connect them to your Arduino with ease. Here's an example of how you could do that.

+1 - The RTC solution is specially good if you want more accuracy than the MCU can give you.

@Ricardo - an RTC is not likely to be any more accurate than an MCU with a clock crystal using one of its hardware timers to fire a periodic interrupt; what it does usually get you is tracking across power loss, and perhaps some knowledge of calendar schemes.

Afaik uno does not use a quartz bit a ceramic resonator for its clock, thus with much less accuracy than an rtc.

@ChrisStratton - Right. Point taken. The RTC will be much better option if the OP has to open or close the door at a given time of day.

You could use the watchdog interrupt and have your MCU sleep while waiting and save power.
But notice that you'll only save power if your board also saves it. That means you have to have a low quiescent voltage regulator instead of the usual regulators that equip the most common Arduino boards, such as the Uno. Otherwise, it doesn't matter whether your MCU saves energy if your board doesn't.
Here's the code (untested):
#include <avr/sleep.h>
// This variable is made volatile because it is changed inside an interrupt function
volatile int sleep_count = 0; // Keep track of how many sleep cycles have been completed.
const int interval = 720; // Interval in minutes between waking and doing tasks.
const int sleep_total = (interval*60)/8; // Approximate number of sleep cycles
// needed before the interval defined above elapses. Not that this does integer math.

void setup(void) {
    watchdogOn(); // Turn on the watch dog timer.
    // Disable the ADC by setting the ADEN bit (bit 7) to zero.
    ADCSRA = ADCSRA & B01111111;
    // Disable the analog comparator by setting the ACD bit (bit 7) to one.
    ACSR = B10000000;
    // Disable digital input buffers on all analog input pins by setting bits 0-5 to one.
    DIDR0 = DIDR0 | B00111111;
}

void loop(void) {
    goToSleep(); // ATmega328 goes to sleep for about 8 seconds
    // and continues to execute code when it wakes up
    if (sleep_count == sleep_total) {
        // CODE TO BE EXECUTED PERIODICALLY
    }
}

void goToSleep() {
    set_sleep_mode(SLEEP_MODE_PWR_DOWN); // Set sleep mode.
    sleep_enable(); // Enable sleep mode.
    sleep_mode(); // Enter sleep mode.
    // After waking from watchdog interrupt the code continues
    // to execute from this point.
    sleep_disable(); // Disable sleep mode after waking.
}

void watchdogOn() {
    // Clear the reset flag, the WDRF bit (bit 3) of MCUSR.
    MCUSR = MCUSR & B11110111;
    // Set the WDCE bit (bit 4) and the WDE bit (bit 3) of WDTCSR.
    WDTCSR = WDTCSR | B00011000;
    // Set the watchdog timeout prescaler value to 1024 K
    // which will yeild a time-out interval of about 8.0 s.
    WDTCSR = B00100001;
    // Enable the watchdog timer interupt.
    WDTCSR = WDTCSR | B01000000;
    MCUSR = MCUSR & B11110111;
}

ISR(WDT_vect)
{
    sleep_count ++; // keep track of how many sleep cycles have been completed.
}

The code I copied is from this page: Low-Power Arduino Using the Watchdog Timer.

Do you have a sleep(unsigned int seconds) available?
If not, this would allow you to delay() a very long time:
for (unsigned int bigloop=0; bigloop<65535; bigloop++)
{
   for (unsigned int smallloop=0; smallloop<65535; smallloop++)
   {
      for (unsigned int tinyloop=0; tinyloop<65535; tinyloop++)
      {
         delay(65535);
      }
   }
}

I could try this if I don't manage to get an rtc like Tom said. Thanks for helping!

This will work:
longDelayInSeconds = 120; //two minutes;
while (p < longDelayInSeconds) {

        delay(1000);
        p++;

}

not the best solution and the OP asked for 12 hours, not 2 minutes.

I just use for loops when I don't want to do stuff in between:
for (int Hours = 0; Hours < 12; Hours++) {            //Creates 12 hours
  for (int Minutes = 0; Minutes < 60; Minutes++) {    //Creates 1 hour
    for (int Seconds = 0; Seconds < 60; Seconds++) {  //Creates 1 minute
      delay(1000);                                    //Creates 1 second
    }
  }
}

Explaing how this is better than a simple delay(43200000).

Well for starter it would be easier to modify how long you want to wait. Just change the number for each hour, minutes and seconds without needing to convert into miliseconds.


text:
SD datalogger sometimes skips readings
I'm using the Adafruit SD shield with a Mega board and wrote a simple program to log data.  I am outputting a constant stream of data at 115200 baudrate from another Arduino to the Mega.  The data output is mostly good, but there are places where some data are skipped.  These skipped data usually occurs around a file flush.  I've tried playing around with the flush frequency and the soft buffer size, but to no avail.  I'm not sure what these hiccups are caused by and would like some help.
void loop(void)
{
  while (Serial1.available())
  {
    softBuffer[i] = Serial1.read();
    i++;
  }

  if (i >= SOFT_BUFFER_SIZE)
  {
    for (x = 0; x < SOFT_BUFFER_SIZE; x++)
    {
      logfile.print(softBuffer[x]);
    }

    logfile.flush();

    i = 0;
  }
}

The amount of time an SD card can take to actually commit data is relatively unbounded.  If your buffer cannot handle the data delivered for a fair fraction of a second, you may have problems with some cards.  How much data is delivered in a second?  115200 baud can potentially bring as much as 11520 bytes, while a Mega 2560 only has 8192 bytes of RAM in total.

But if you are not up against that limit, you could still be against another based on the architecture of your code.  A different scheme would use two buffers, one being filled directly by the serial interrupt (no Arduino Serial class), while the other is flushed to the card, then swap.  Or use a non-blocking SD library which can do other things while periodically polling the card to see if it is done.

@ChrisStratton I don't really understand the dual buffer suggestion.  With two buffers, aren't they still printing and flushing to the same file?  or do you mean doing something like alternating between logfile1.print and logfile2.print?

I mean continuing to fill one buffer while waiting for the SD card to flush the other, presumably to a single file.  Your current code does not appear to be able to continue accept new data while it is waiting for the card to finish flushing old data.  But depending on your data rate, you may not have enough memory on board to cover for the longest possible card delay anyway.

@ChrisStratton IIRC the Arduino internal serial buffer is only 16 bytes long, increasing that might be an elegant solution.

Correction, 64 bytes if RAMEND > 1000.. I don't know what RAMEND is though. https://github.com/arduino/Arduino/blob/master/hardware/arduino/cores/arduino/HardwareSerial.cpp

Probably not as that would lead to double buffering  - it would be better to skip the serial class entirely and receive durectly to one of the ping-pong card buffers.  Or else write to the card directly from the serial buffer.  This is a case where if you want nice abstraction, you need a system with more buffer memory.

The SD card library works by filling up a 512 byte buffer. Once full, the data is written to disk.
The flush command updates the directory listing with the correct size for the file and also updates the file allocation table. It only needs to be done once, just before you pull the card out.
While flush is doing its thing, the internal serial buffer of the Arduino is filling up with new bytes. The internal buffer is 64 bytes long so if flush takes too long, the internal buffer fills up and you lose characters. You could edit HardwareSerial.cpp in the Arduino program directory to make it say 256 bytes.
Because of this softBuffer is not needed. Simply write straight to the card and let the internal buffer handle the buffering. See https://github.com/arduino/Arduino/blob/master/hardware/arduino/cores/arduino/HardwareSerial.cpp for the Serial code.
unsigned long bytesWritten = 0;
void loop(void)
{
  while (Serial1.available())
  {
    logfile.write(Serial1.read());
    bytesWritten++;
    if(bytesWritten > BYTES_PER_FLUSH) logfile.flush();
  }
}

I tried that, but data is still being skipped.  I think I might have to try a different SD card library.  Is using a baud rate of 115200 testing the limits of the Mega?

@user2218339 What did you change the buffer in HardwareSerial.cpp to? It is not really the baud rate, but how much data is being transmitted

Sorry, I must have read too fast, I didn't see the part where you suggested to change the hardware buffer size. I will give it a try today.

I got a chance to try it out, and that was definitely the solution!  Thanks geometrikal!

@user2218339 glad it worked - i learnt something too!


text:
Programming Arduino Pro mini 328 with Arduino Uno SMD
I apologize in advance, because there is a lot of tutorials out there about programming arduinos with another arduino, however I can't find really simple one I could understand.
I have Arduino Uno SMD version and Arduino Pro mini 328. I want to upload sketch to Arduino Pro mini using Arduino Uno in ISP mode (I guess).
I want to know EXACTLY which pins need to be connected and if all I need is Arduino IDE to upload my sketch to Pro mini ?
Thank you for your help.

For  upload sketch to Arduino Pro mini, unless your code size is really big and run out of space, many people use FTDI style USB to serial board (6 finger nails sized) to download via bootloader. There are tons of tutorial with good diagram. Try search by these keyword. Sparkfun and arduino.cc should have needed info for you

@JohnWilliams Thanks for comment. However, I don't want to buy another board. I just want to use my 2 existing ones.

How exactly have existing guides and tutorials failed you?

@IgnacioVazquez-Abrams Well, I haven't actually found any which would cover exactly my scenario - meaning Arduino Uno SMD and Pro mini 328.

ISP via the Arduino is still done the same way regardless.

You should be able to take the Uno-as-target instructions and use them with the mini simply by connecting to the same (Arduino) pin names - digital 10 through 13 and RST (reset).

@ChrisStratton Ok, but what bothers me are advices about removing Atmel chip from its socket in Arduino Uno. But I have SMD version, so it's not possible. This really confuses me.

The ISP instructions do not involve doing that.  You might be thinking of instructions for using an Arduino with it's main processor removed as a USB-serial interface to talk to the bootloader of one without its own USB interface; but you said you wanted to use ISP programming rather than bootloader programming.

OK and could you point me to some comprehensive tutorial ? I am looking at http://arduino.cc/en/Tutorial/ArduinoISP but it's not about Arduino Pro mini - I don't know if there is something special involved or I can wire it as in first diagram. This tutorial talks about burning bootloader, but I want to upload my sketch, I am really confused here.

@Frodik, two different things. ISP programming is used to program the boot loader, which is a small program that runs on startup and allows for larger programs to be uploaded using serial. You need a USB to serial converter. It has a USB port and a female header that connect to the 6 pins on the arduino pro.

@geometrikal I apology for my confusion. Now your comment makes sense. So please, what do I do if I want to just upload my sketch ? I am pretty sure that my Pro mini already has Arduino bootloader.

You use the same setup you would as for burning a bootloader, only in the software you select something like upload using programmer and select arduino as ISP as the programmer.  Long term you are going to want that logic-level USB serial cable anyway, as it enables you to get debug output from your sketch.

check this tutorial:

http://www.instructables.com/id/Arduino-Examples-2-Use-an-Arduino-as-a-FTDI-Progr/

Works fine for me (I have a redboard, also with SMD microcontroller). In short this is the pinMap:
UNO BOARD (SMD)    Pro Mini 5V
       GND             GND
       5V              VCC
       RX              RX1
       TX              TX1
       Reset           GRN

Just to be sure, RX and TX on Uno board are digital pins 1 and 2, right ? But that would mean, that if I wanted to upload sketch to finished project which would have soldered all the digital pins to other modules, I couldn't use those 2 pins (RX,TX). That was the reason why I wanted to use ISP so I wouldn't have to sacrifice 2 pins.

@Frodik - ISP requires 3 pins plus reset, bootloader requires 2 plus reset.  That doesn't mean you have to reserve the pins, but it does mean you can't use them for things which conflict.  For example, you can use them as outputs from the ATmega to peripherals, as long as spurious operation of the peripherals during programming is not problematic.  But you shouldn't use them to read from peripherals which might problematically drive signals onto those pins during the programming.

@ChrisStratton But if I understand it correctly, ISP requires different pins than digital 1-13, right ?

@Frodik As Chris mentioned, 3 pins are used, these pins are D11, D12, D13. The arduino website shows this http://arduino.cc/en/Tutorial/ArduinoISP. Remember that a Pro Mini is literally an Uno that got shrunk.

Please check this tutorial if you want to upload sketches to Pro mini with Arduino UNO with SDM chip
http://www.instructables.com/id/Uploading-sketches-to-Pro-Mini-using-Arduino-UNO-b

It is preferable to answer questions directly rather than simply linking to external sites. Adding a summary of the Instructable text, specifically address the question asked by the OP about which pins are involved, would go a long way to helping the the OP, other people with the same problem, and getting your answer accepted.

Following the tutorial on http://www.instructables.com/id/Arduino-Examples-2-Use-an-Arduino-as-a-FTDI-Progr/ I was able to upload the blink sketch to the Pro Mini 5V version with an Arduino Nano. After I tried uploading the sketch that I really wanted to use but got many errors in the IDE I tried a couple more with no luck. I had stumble on another article earlier about using the Arduino Nano to program the Pro Mini http://www.electronicsmayhem.com/?p=31. I had tried that method but with no luck but using the first tutorial & only changing one thing from it with info from the article i mentioned I was able to upload the sketch without any errors. The only thing I changed was I didn't connect the TX from the Nano to the TXI of the Mini.
   Arduino Nano     Pro Mini 5V
       GND-------------GND
       5V--------------VCC
       RX--------------RX1
       Reset-----------GRN(DTR)


text:
Motor shield and wireless transceiver compete for same pins
I would like to use these 2 components with an Arduino Uno:

Arduino Motor Shield R3
nRF24L01 2.4GHz Wireless Transceiver

I use Stepper for the motor shield, and SPI + RF24 for the wireless transceiver.
I could write 2 sketches that work perfectly, but how can I combine them together?
My issue is that they both require access to pins 11, 12 and 13.
Any help is greatly appreciated!

You can't really. You could use Channel A, if you disable the motor (keep D3 low), while performing your SPI communication. I think, but am not sure, you can use both channels if you enable the break (D9 and D8) while using SPI. But you can't have any motors running while using SPI. (BTW the person that designed that shield should be fired for using the SPI pins. That's just bonkers)

For prototyping, use male to female jumper wires to connect the Arduino Uno to the robot shield. It is a bit of a pain, but it makes it easy to free the conflicting pins for the wireless transceiver.
For a more permanent solution, look at Chris K's answer.

This is the core of embedded design and "hacking" and highlights one of my peeves about Arduino design: too much focus on the pin numbers and physical location on the PCBs, rather than the actual functions on those pins.
So? Physically move the pins on the Motor Shield. Here are 3 options in order of the most hack-ish to most-clean:
1) Use an edge cutter to cut the bottom of the pins off the motor shield then solder jumpers to the nub to other pins that are free.
2) Use a hot air station to desolder that header row, solder in your jumpers, and put back only the pins you want. Board designs with such limited foresight (like your situation) is what led me to buy my hot air station. And now I pretty much use sensor shields for my interfacing outside the stack or proto shields to be intermediate layers to translate pins.
3) Cut the trace on the motor shield PCB itself to free the SPI pins. Then find pins that have your function (pwm?) and also are NOT used by any other shields in your "stack". Solder a jumper from the exposed trace on SPI pins to your free "new" pins.
If you stalk through my answers there are write-ups on two test benches I made and you can get ideas from the various work-arounds I have employed to get my hardware working.


text:
In Linux, how do I get this Arduino library to work
In Linux Fedora 20 Arduino I want to use the Timer library from here, from which  I have downloaded the folder Timer-master.zip, but, when I try to import it, I get the Arduino message that it cannot be imported because its name includes characters other than plain ACSII letters and numbers. I have tried copying the file to Timermaster.zip and importing that instead, but still got exactly the same failure message.
Please, how do I get out of this impasse?

What's causing the problem is that the folder name inside the zip has a hyphen in it, just extract the folder from this zip and rename it to timer instead of timer-master. I just imported it on Fedora 20.

#'itchyzombie, Thanks for that prompt and excellent answer. I have done that and, as you say, it works. A day wasted in frustrating floundering, but a nice end result


text:
perform an action maximum x times per hour
is it possible to perform an action maximum x times per hour on the arduino?
I made a automatic water sprinkler that sprays when the humidity is lower than 50%. but if the sprayer performs this "spray" more than 4 times an hour the humidity wil be to high and wil rise to fast.so is there a way to restrict the amount of times an action is performed per hour,and then if the next hour comes the sprayer can perform his "sprays" 4 times before it stops again
sorry for bad english, this is not the language I speak (and type) mutch

Humidity rising too quickly indicates a lack of proper feedback.

Sure it's possible. It would be better if you had a real time clock module. Then you could use time-of-day.
You need to define your problem a little better. Would it be ok to run the sprinkler every 5 minutes, then not again for 40 minutes, for a total of 4 sprays in an hour, but clustered together? Do you want to prevent 4 sprays in a clock hour, or not go over an average of 4 sprays per hour?
Without a realtime clock module, I guess here's what I would do:
After a spray, record the time (in millis). Then in your loop, don't spray again for 15 minutes (15*1000*3600 milliseconds.)
The code would look something like this: (not real code, more like pseudocode)
const unsigned long fifteenMinutes = 15*1000*3600;
unsigned long nextSprayTime = 0;

loop()
{
  if (millis() >= nextSprayTime)
  {
    if (humidity < 50)
    {
      spray();
      nextSprayTime = millis() + fifteenMinutes;
    }
  }
}

Edit: You said, in comments:

i want it not to go over 4 sprays an hour,i have the ds1307 rtc
  module. situation: ist an automatic egg incubator and the humidity
  must be between 50% and 60%.i control the sprayer whit a dht11 sensor
  an a servo connected to an spray bottle. if the humidity is below 50 %
  the servo starts whit spraying.the servo keeps on spraying every
  second until that 60% mark is reached and then shuts of.so the amount
  of water in the box is way to much and so the humidity keeps on
  climbing until the 100% mark whit is deadly for the eggs

Ok, that gives your readers a clearer picture.
You're dealing with a process control problem, not just a hardware or software problem.
When you spray water, it will likely take several minutes for the change in humidity to stabilize and be detected by your sensor.
Your current approach sounds wrong because you dump far too much water into the system, and don't give it time to reach a new equilibrium before adding more water.
You need to collect some data.
There is going to be a significant lag between putting a spray into the incubator and sensing the increase in humidity, and when the increase reaches it's max.
You need to measure that lag.
You also need to know how much a single spray increases the humidity.
You should probably **ALSO* figure out how many sprays at a time you can spray before water droplets form on the walls of your incubator and on your eggs, since I assume that is very bad and to be avoided at all costs. Thus I would add a moisture detector to your system (A small piece of cloth with electrodes on it at 2 locations a couple of CM apart, and a sensitive conductivity sensor that detects the change from insulator to weak conductor that takes place when the cloth becomes saturated with water.)
You should also figure out how fast the humidity in your incubator drops if you don't add any water, for a variety of different conditions. (Likely affected by current humidity, outside temp and outside relative humidity, so you probably want 2 humidity sensors, one inside and one outside the incubator, and to record all the variables and graph them.)
I would suggest writing a data collection program. You might want to run it with the serial cable connected to a PC constantly, or install an SD card and save your data there.
In all your tests, you probably want to wait a significant time (15 minutes? 1/2 hour? 1 hour?) for the incubator to reach equilibrium before beginning your test.
You want the conditions of your incubator to be as close to your real-world conditions as possible. You might want to put eggs (dummy eggs, grocery store eggs at room temp, or something like that) in the incubator during the test to allow for the amount of water they absorb. You want the outside temp to be as close to your real-world temp as possible. If the incubator will be exposed to direct sunlight, air vents, wind, etc, then you want those same conditions.
At each step in every test you should record the current time, the current outside temp and humidity, and the current incubator temp and humidity, and the time of each spray you trigger.
Add your condensation detector at the beginning, and any time it detects condensation you should sound an alarm, record the time that it trips, and abort the current test. If you get liquid condensation you've done something wrong and need to adjust.
Write a program for your computer that graphs all your data points over time. Every time you run a test (other than the very first test) graph all the data and look at it. Patterns will probably jump out at you.
Test 1:
Record the time and the current humidity. Add one spray of water, and then record the humidity for 15 minutes. Look for an increase in humidity and when it peaks. The time from adding a spray to the peak increase in humidity is what you want.
Test 2:
Then modify your program to log the spray-to-peak-humidity-increase time, and each time it detects the humidity starting to drop again, spray once more, log the current outside temp and humidity, the inside humidity and outside time of the spray, and repeat.
This will give you spray-to-peak-humitity lag times over a range of humidity values. Graph that data with starting relative humidity on the x axis and the lag time on the y axis and look at it. Is it a constant value? A straight line? Is it a geometric curve? Exponential? Come up with a curve that fits the data fairly well.
Test 3:
A test that uses an increasing number of sprays, looking for how many sprays you can do at once before you cause condensation.
Start with 2 sprays.
Look for the peak increase in humidity, and once the humidity starts to drop, increment your spray counter to 3, spray that many times, and repeat. When the condensation alarm trips, stop the test.
Note that the number of consecutive sprays you can do before the moisture alarm trips will probably change for different starting humidity levels. My guess is that the max number of sprays you can add without triggering condensation will be highest at your lowest humidity level, and as the humidity increases, you'll get condensation with less and less sprays.
Test 4:
Figure out how to measure the max number of sprays that trigger condensation when you start at less than your minimum humidity, at your minimum humidity, at halfway between min and max, and at max. (This experiment will take some thought since it's not easy to get to a given humidity level, and once you trigger condensation you'll have to stop, dry everything out, and start again.)
Test 5:
Get your incubator as close to the maximum acceptable humidity (60%) as you can at the beginning of the test, or even a little above. Simply record the humidity every minute until it drops to the lowest acceptable level (50%). Graph the data. That will show you how fast the humidity drops if you do nothing.
Test 6:
Repeat test 5 for the range of outside conditions you might find in your production environment. (If you're in a climate-controlled space, do you have summer and winter thermostat settings? Test for those upper and lower ranges. How much does your indoor humidity level vary?)
Now what?
Now you have lots and lots of data.
More than likely you have an idea of how many sprays you can add at a time without triggering condensation over your humidity range. This should be fairly simple: (for example, at humidity < 50% to 52%, you can use 3 sprays.  AT 53-55%, 2 sprays. Above 55%, 1 spray.) You should also have a rough idea how much increase you'll get in humidity for a given number of sprays.
You have an idea of how fast the humidity drops if you don't add water.
You have an idea how long it takes for a spray set of sprays to cause a peak in the humidity level.
Write a program that strives to keep the incubator in the middle of your desired range. If 50% is your absolute minimum humidity level and 60% is your max, then trigger sprays at 52%, not 50%. Spray as many sprays as you can without causing condensation (or overshooting your max humidity), then lock out sprays for the time period you calculated as the time it takes for your sprays to cause the maximum increase in humidity.
If you've found that the max number of sprays you can do at a time is different for different humidity levels, use code that comes up with a number of sprays that stays below that limit. Also try to estimate how much increase in humidity you get per spray, and each time you trigger a series of sprays, stay below the number of sprays that reaches your max humidity.
If you've found that the conditions outside the incubator have a big effect on your system, adjust your code to compensate for those changing conditions.
You want a system that uses small adjustments over time to keep a system at near equilibrium. Big adjustments will likely cause wild variations in conditions that go outside of the acceptable range.
Other considerations:
Do you need to open the incubator at regular intervals to check on the eggs or turn them, or do you have an egg turner? If you do need to open the incubator, you will need to figure out the effect this has on your temp and humidity levels for the range of outside conditions you face. You can probably build your system with a door sensor that detects you opening the door, the outside temp and humidity, and how long the door is open. Once you close the door, it would note the new inside temp and humidity and make an educated guess as to how much the humidity will drop after being open, and add water accordingly.

i want it not to go over 4 sprays an hour,i have the ds1307 rtc module.
situation: ist an automatic egg incubator and the humidity must be between 50% and 60%.i control the sprayer whit a dht11 sensor an a servo connected to an spray bottle. if the humidity is below 50 % the servo starts whit spraying.the servo keeps on spraying every second until that 60% mark is reached and then shuts of.so the amount of water in the box is way to much and so the humidity keeps on climbing until the 100% mark whit is deadly for the eggs

@BrianLaebens, see my edits.

Nice and thorough answer, but note that: 1) fifteenMinutes = 15*1000*3600 triggers an integer overflow. You should add the suffix UL to at least one of the factors. 2) if (millis() >= nextSprayTime) will not work as expected when millis() rolls over, whereas if (millis() - lastSprayTime >= fifteenMinutes) is rollover-safe.

You might be spraying faster than the sensor or the environment can respond, causing your humidity overshoot your goal. Try spraying way less often, experimenting with the interval until you understand more about the dynamics of the humidity.
My first guess would be to try once per minute and see whether that still overshoots or if it fails to maintain the humidity. That will tell you whether to increase the interval more or to decrease it. Writing the time and humidity readings to the terminal and plotting those may help you understand your system behavior better.


text:
Arduino Digitalwrite for while loop set
My question is simple. Does Arduino set the digitalwrite() the moment it is called or at the end of the while loop. E.G.
int ledPin = 13;
void setup()
{
  pinMode(ledPin, OUTPUT);
}

void loop()
{for(int i=0; i<10; i++){
if(i%2==0){
  digitalWrite(ledPin, HIGH);
  delay(1000);}else{
  digitalWrite(ledPin, LOW);
  delay(1000);      }
}

A key point of the Arduino 'language' is every statement is completed before the next one can begin.
A simple statement has a ';' at the end of it.
Or followed by ')' instead of ';' in for (...; ...; statement) loop.
So digitalWrite() will set the pin, HIGH or LOW, before it completes and allows the next statement, delay(...) to begin.
Side note:
Actually digitalWrite() takes a small amount of time to do its work, so it is not exactly 'the moment' it is called. digitalWrite() is pretty quick, a few millionths of a second, which is usually near enough to be practically 'the moment' for most applications.

Arduino 'language' a.k.a. C++ (would add it in brackets to the answer but too short for edit)

Arduino sets the pin at the moment digitalWrite() is called.

To be extremely pedantic, it sets the IO pin state a short time into the processing time of the function call, which can be important if you're trying to run things very fast (digitalWrite() is actually quite slow, in comparison to writing pin control registers directly). It still sets the pin within the execution of the digitalWrite() function call, in any event.

The condition
if(i%2==0)

will be checked immediately upon entering the "for" loop, and again on every iteration of that loop. It will be the first code executed on each iteration. One form or another of the digitalWrite() will be called next, followed by the delay().


text:
How do I write an Arduino program to an AVR chip without the Arduino bootloader?
Is it possible to write an Arduino program to an AVR chip that does not have teh Arduino bootloader installed?  What is the process to do so?

Step 1: Get yourself a programmer.
This can be anything from a USBasp to an Arduino programmed for ISP all the way to an AVR ONE!. Some can be used from the IDE, and some cannot.
Step 2: Set up the chip as expected from the entry in boards.txt and from the datasheet.
Add a crystal, decoupling caps, whatever. Don't connect power yet.
Step 3: Connect the programmer.
If using ISP, connect the ISP pins. If using JTAG, connect the JTAG pins. If using something else, see the programmer and chip documentation for connection details. You may want to connect power at this point for the next step.
Step 4: Program fuses.
Program the oscillator, BOR, CKDIV8, EESAVE fuses as desired/required. Fuse calculator.
Step 5: Compile the program and write it to the chip.
If using the IDE, select the programmer in Tools | Programmer and then hold shift when clicking the Upload button (or press Ctrl-Shift-U). If your programmer is not supported by the IDE then compile the program (Sketch | Verify/Compile or Ctrl-R), locate the temporary directory it has been built in, and use avrdude or your JTAG program to upload it to the programmer.
Step 6: There is no step 6. You're done.
I just wanted to see if you would read this far.

Step 7: Write a comment acknowledging the fact that you read step 6...

If there are no memory restrictions (too large program) which eliminates this option, I'd try to write the Arduino bootloader first and then continue normally. This has the advantage of simple reprogramming if required.


text:
Teensy 3.1 no overclock option for 168 MHz
I'm sorry if this isn't the right area. Teensy uses the arduino ide.
I've seen some people show off the 144 mhz and 168 mhz option in their ide. I read in the Teensyduino 1.19 release notes that the options were added but not enabled. I would like to know how to enable it or if I somehow downloaded an older version.
P.S I get the 96 mhz option.
Thanks ahead of time!

Did you look in boards.txt yet?

yes I see this:
teensy31.menu.speed.168.build.f_cpu=168000000
teensy31.menu.speed.144.build.f_cpu=144000000
teensy31.menu.speed.120.build.f_cpu=120000000
teensy31.menu.speed.96.build.f_cpu=96000000
teensy31.menu.speed.72.build.f_cpu=72000000
teensy31.menu.speed.48.build.f_cpu=48000000
teensy31.menu.speed.24.build.f_cpu=24000000
teensy31.menu.speed.16nousb.build.f_cpu=16000000
teensy31.menu.speed.8nousb.build.f_cpu=8000000
teensy31.menu.speed.4nousb.build.f_cpu=4000000
teensy31.menu.speed.2nousb.build.f_cpu=2000000

Using the latest Teensyduino distribution as of this writing, 1.25, you have to uncomment the higher overclocking options in the boards.txt file, located here in my install-
/hardware/teensy/avr/boards.txt
The options look like this, just remove the # symbol-
#uncomment these if you want to try faster overclocking
#teensy31.menu.speed.168opt=168 MHz optimized (overclock)
#teensy31.menu.speed.144opt=144 MHz optimized (overclock)
#teensy31.menu.speed.120opt=120 MHz optimized (overclock)`