text:
Why doesn't this debounce function work?
Edit 2
I made a function that works, but I'm still confused about just one thing...
I'm very confused about how variables work in C++.
In this program...
  boolean debounce(void)
{
  static boolean buttonState=LOW;
  static boolean lastButtonState;
  boolean currentState = digitalRead(4);
  static unsigned long lastDebounceTime;
  if (currentState != lastButtonState){ //if the button state has changed
    lastDebounceTime=millis();  //reset timer
    }

  if ((millis()-lastDebounceTime) > 50)  //if 50 milliseconds has passed since last bounce
  {
    buttonState = currentState;  //read value again now that bouncing is over

    }
  lastButtonState = currentState;
  return buttonState;
}

Why does changing this
lastButtonState = currentState;

To this
lastButtonState = buttonState;

Make any difference in the program?
When I try the latter line of code, the whole function stops working and I don't understand why.

What happens if 50ms haven't passed?

Using the same name for globals, locals & function parameters is just begging for confusion.

Your debounce() function is only being called every 500ms. That is probably not what you intended.

@uint128_t - Why do you say: "debounce() function is only being called every 500ms" ? I don't see that, what have I missed?

@gbulmer he edited his question

at least: static boolean buttonState;

You have declared a global 'const int buttonVal = LOW' but then using this same name to get a parameter from a function. I would suspect that the global declaration is what you are getting. At the very least, use a different variable name within the local scope of the loop function.

This probably won't answer your question completely, but here are some notes from me:
buttonState = current ;  //read value again now that bouncing is over

This won't read the value again, it just copies current into buttonValue.
What you wanted is:
buttonState = digitalRead(BUTTON); // read value again now that bouncing is over

You have multiple issues with your debounce call:

lastTimeDebounce is never used by your code, so it is always zero.
lastButtonState will be always buttonVal making the debounce function useless.

Some other tips:

Don't use the same names for parameters as for global variables:
boolean debounce(boolean lastButton, long lastDebounce, int BUTTON)
The global variable BUTTON will be shadowed by int BUTTON, essentially overriding it.
Don't use global variables (unless you have a very good reason)

EDIT
I would strongly recommend writing a function that debounces only one pin.
Because if you want a function which can debounce any pin you would need a state variable for each pin (which needs arrays hence a lot of space).
EDIT2:
Here is a debounce function that should work:
const uint8_t PIN = 13;

/*
 * Returns debounced value for `PIN`
 */
boolean debounce(void)
{
    // Current state of the pin
    boolean currentState;
    // Last state of the pin, initial value is zero
    static boolean lastCurrentState = 0;
    // Timer
    static unsigned long debounceTimer = millis();
    // Debounced value, initial value is zero
    static boolean debouncedValue = 0;

    // We first read the current state of the pin
    currentState = digitalRead(PIN);

    // Then we look if the state has changed
    if (currentState != lastCurrentState) {
        // If it has, we need to reset the debounce timer
        debounceTimer = millis();
    }

    // Then we check if the timer has expired
    if ((millis() - 50) > debounceTimer) {
        // The timer expired so we update the value
        debouncedValue = currentState;
    }

    // Save the latest state
    lastCurrentState = currentState;

    // We always return a debounced value:
    return debouncedValue;
}

But always test such things with an oscilloscope, no guarantee. FYI: this is not an ideal debounce function, but it should make the idea clear.

"buttonState = current ;
This won't read the value again, it just copies current into buttonValue." I'm not questioning that your right, but I actually copied the official arduino website when I did this. https://www.arduino.cc/en/Tutorial/Debounce

The Arduino site does not make the statement that it is actually reading the pin again.

Ok I understand now. I made my code look like yours, and my function works now. Thanks for the help. Quick question though, why does "lastCurrentState = currentState" have to go outside of the if statement?

You could add an else and add it there and it won't affect the debouncing. I just put it there for convience.

Sorry maybe I'm still a little confused... The second if statement will be executed no matter what right? ( because the program can't exit the function unless 50 millis have passed). If this is true, why can't I put "lastCurrentState = currentState" within the second if statement?

The body of the second if statement will only be executed if the button state has not changed over the last 50 milliseconds. I'm not sure what you are asking but you always want the latest state in a variable to check on it later.

Glad to hear :) no problem.

"It worked perfectly" is probably an overstatement. Yes, you saw the LED change when you pressed the button, but that doesn't mean it was getting debounced.
The problem is that you are trying to use global variables to remember the internal state of the debouncer function, and you're passing those variables into the function as parameters. In C (or C++, which is the underlying language that you're using), an assignment to a function parameter does NOT update the corresponding variable in the caller's environment. Therefore, lastDebounceTime never gets updated, and your debounce() function always just returns the current state of the button.

Beat me to it! +1 for "It worked perfectly" is probably an overstatement. Yes, you saw the LED change when you pressed the button, but that doesn't mean it was getting debounced.. A quick (possible) fix is to remove the parameters to debounce() and keep the state in global variables. A bit messy, but more useful than broken.

Thank you for your answer @Dave, I think I'm starting to understand. But quick question, what do you mean by "an assignment to a function parameter does NOT update the corresponding variable in the callers environment"? Does this mean assigning a variable to a function parameter is pointless?

No, it isn't entirely pointless, because you can use it as an additional local variable inside the function. You can think of it as the caller initializing that variable for you, but then you can update it as needed while the function executes.

@gbulmer or use static variables private to debounce()

@Jasen - Yes, that would be better. C++ classes are a bit verbose (I like to write Go) but a simple class would do, or a struct if there were several buttons to handle.

Im not an expert of C programming, but I can see lot of troubles in your programming, because you do call a function debounce(), but it is not a function that does a complete task, so you set additional variables outside of it. This is a bad practice, because you can't call the same function to compute multiple keys, that's what functons are for - make one function and call multiple times with different parameters. You should switch to pointer orented parameters for lastButtonState.
    boolean LastButton_1; // global or static variable
    long LastDebounce_1;
    int BUTTON_1;
        ... and so on

    boolean debounce(boolean *LastButton, long *LastDebounce, int BUTTON)
        {
          //your code here, where you read and write to variables located at pointer
           boolean something, new_value;
           something = *LastButton; //read value at pointer address
           *LastButton = new_value; //store the value at pointer address
        }
//now you call this
debounce(&LastButton_1, &LastDebounce_1, BUTTON_1)

Perhaps it is not correct, since I know only very basic C, but the way is the right one

If you only have one button to debounce, you can store it's state as
static variables in the debounce() function itself, like:
bool debounce()
{
    const int pin = 4;
    static bool last_state;
    static unsigned long last_change;
    unsigned long now = millis();

    if (now - last_change > 50) {
        bool state = digitalRead(pin);
        if (state != last_state) {
            last_change = now;
            last_state = state;
        }
    }
    return last_state;
}

If you may have to debounce more than one button, the cleaner way would
be to store the state inside an object, and have the debounce function
be one of its methods. That's what the
Bounce library does.

Strictly speaking, digitalRead() returns an int not a bool.


text:
Custom arduino board
Hey There Arduino Coders. I am a relatively seasoned C/C++ programmer. However, I'm still new to the Arduino Game. I'm coming here today to ask you guys a direct question that I couldn't find a direct answer for on google... here it goes:
Is it possible,(also practical) to create my own arduino board? after creating a prototype with an arduino uno and various shields?
In other words. Is it possible to shrink the arduino(make a custom arduino), and all of its shields on to one board? It seems rather large to have to lug around all of those shields and such. CHEERS!

What shields do you want? Depending on the shields you use, a better option might be to start by analysing how to reduce the shields, and then decide how to connect and control them.

Hypothetically speaking. An Ethernet shield.

It might help folks give a good answer if you update your question with the specific shields you'd like. So add Ethernet, and anything else you need.

I have a page about a breadboard Arduino which is basically an Atmega328P processor (same as in the Uno, inter alia) on a breadboard.

Also a wire-wrapped Arduino.

You can go pretty minimalistic with a ATtiny85 mounted on a button battery like this:

Is it possible to shrink the arduino(make a custom arduino), and all of its shields on to one board?

Ah there you might be asking a bit much. There are hundreds, if not thousands, of shields people have designed for it. Certainly you can make up your own board to meet a specific purpose.

Hey thanks alot Pal ... This is helpfull!!!!!!

If the shield schematics of the shields you want to use are publicly accessible and you can get the parts, you should be able to build many of the available shields on a perfboard, for example

Absolutely.  You might start with the Arduino to Breadboard Tutorial while defining your hardware requirement - for example, decide what voltage you are going to run at (and pick an appropriate regulator) and then decide if you can use the imprecise 8 MHz internal oscillator or if you need a more precise external resonator or crystal.
Once you have determined your required circuitry you can advance to making  circuit board, and possibly switch from the DIP version of the ATmega to a QFP package which is smaller and potentially ultimately easier to work with (for production you might even use a QFN, though that is a bit more challenging to solder by hand).  You may also want to look at what package technology your peripheral chips come in.
Do note though both that you can buy smaller premade Arduion-compatible PCBs, and that there are other chips which are worth considering for a permanent project, some with Arduino compatible libraries available, and some without.

Could you name some of those "other chips?" I'm curious.

Yes it is possible. It can be as simple or as complex as you wish :)
http://www.instructables.com/id/How-to-make-your-own-Arduino-board/

source: Stack Exchange

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

sort: votes


text:
sketch uploading give error?
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x30
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x0f
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x10
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x20
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x0f
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x10
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x30
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x0f
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x10
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x20

See Have I bricked my Arduino Uno? Problems with uploading to board - your "question" is very light on detail.

Most often this message indicates that you should select another board type in the Arduino IDE under Tools menu. Have you tried that?

This Instructables post has a list of potential causes for this error. Is this a new board? What board are you using? Is it a genuine Arduino board or a clone? Have you been able to upload to the board previously?

I have selected right com port. Previously i had uploaded sketches and that worked find. Now it giving me issue.

I am using clone arduino

@user3883017 What is your hardware setup? Do you have any wires connected to the RX pin?

Arduino UNO. No Just one LED to pin 13 and ground

avrdude: Version 6.0.1, compiled on Apr 15 2015 at 19:59:58
Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
Copyright (c) 2007-2009 Joerg Wunsch
     System wide configuration file is "C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf"

     Using Port                    : COM7
     Using Programmer              : arduino
     Overriding Baud Rate          : 115200

Have you changed the atmega328 chip? If you have the new one may not have a bootloader or it may have one for a different board. Select every board option. Duemillemova maybe?
If you still have no luck, you might have over written your bootloader. Try burning the bootloader again. Instructables shows you how.

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


text:
How Atmel Studio 7 compile Arduino code?
Atmel stated in their website:

Atmel Studio 7 features seamless one-click import of projects created in the Arduino development environment. Your sketch, including any libraries it references, will be imported into Studio 7 as a C++ project. Once imported, you can leverage the full capabilities of Studio 7 to fine-tune and debug your design. Atmel Studio 7 fully supports the powerful embedded debugger on the Arduino Zero board. For other Arduino boards, shield-adapters that expose debug connectors are available, or switch to one of the many available Xplained-Mini/PRO boards to fully leverage the Atmel HW eco-system. Regardless of what you choose, you will surely make something amazing.

I wonder how they do it? Is it just a plug-in meaning that we still have to install Arduino software? Or do they have their own compiler and debugger?

I'm not sure, but best way to find out is just by trying? It appears you can easily import arduino project. I wonder how much they leave intact, or change to a more C++ like project.

The difference between code for the Arduino IDE and C++ is really just a few conveniences - adding #includes, function prototypes, setting up compile options etc. No reason this couldn't be done without requiring the Arduino software be installed. But, as @Paul suggests, why don't you just try it and see?

I tried and it ask the Arduino IDE path. I wonder why should I install Arduino IDE.

It is almost always the case that a high-level environment like an IDE provides an interface to an existing tool-chain rather than being truly an all-in-one mega-application, which would a maintenance nightmare. Atmel Studio 7 is no exception, and according to Atmel, uses and includes (quite likely by downloading it during the install process) the GCC tool-chain.

Why Atmel Studio asked about Arduino IDE path when I try to import Arduino sketch?

Probably for the Arduino libraries, which are contained within the Arduino IDE executable.

Why Atmel Studio asked about Arduino IDE path when I try to import Arduino sketch?

http://youtu.be/7WnOe00dVu0

Atmel Studio allows for the arduino .ino file to actually be compiled as a c++ project. Doing so allows true debugging, and stepping through all arduino code. It was actually insightful as it walked me through ARDUINO's main() function, which is normally tucked away nicely in a library never to be seen.
The IDE allows for highly useful features such as refactoring, find and replace, syntax highlighting and much more. I found it very useful, and a pleasant upgrade from the arduino IDE.
I often switch back and forth between the Arduino IDE and Atmel Studio, very easy to do.
Installing the Arduino software allows Atmel Studio to locate the libraries when it is installed.
By installing the Vmicro(visual Micro) toolbar, things really come together, and seem very seamless.


text:
How to have arduinos work together?
I want to have an Arduino based game you can play on a nokia 5110 screen. The problem is you cant make a medium sized game on an Arduino because the flash size is only 32k. I sit possible to have multiple Arduino's connected to each other, communicating to make it possible to have a bigger game. If it is possible how does it work?

You could store things like bitmaps, and level data in an external EEPROM.

You can. Probably the easiest solution is so make them communicate through serial connection. Or SPI. Just divide the visualization part (so all the bitmaps and the screen driver) and the input/game logic part and make them communicate. Or, if you can, follow @Gerben 's advice and use an external EEPROM for the big amount of data (even if screen libraries are quite big sometimes).

You can make quite an impressive game.

Features

Based on ATmega328P running at 16 Mhz (same as Arduino Uno).
The game has a display resolution of 104x80 with 256 colors.
Video mode is tile based and supports up to 3 sprites per scan line.
Sprites are multiplexed so there can be unlimited number of sprites vertically on the screen.
4 audio channels with triangle, pulse, sawtooth and noise waveforms.
Chiptune music playroutine and sound effects.
NES controller support.

Video of it in action:
https://www.youtube.com/watch?v=sLvgW_zb6bQ
Original post on the Arduino forum.

So, before you start wanting to connect lots of Arduinos together, investigate what can be achieved with just one. :)
The first thing to do, as others have mentioned, is to store static information into PROGMEM (see Putting constant data into program memory (PROGMEM) for more details).
If Petri Häkkinen can get his title screen, levels, sprites, music, and game logic into an Atmega328P you can too! Have fun!

Yes and no.
Yes you can make Arduinos communicate with each other and send messages to each other.
Can you use that to make a game?  Possibly.
Is it worth the effort?  No.
It would be a huge amount of work and be overly complex when you could just use a bigger Arduino, like a Mega2560 or a Due.

You can have two Arduinos communicate with each other but it is fairly complex.  See this instructable.  One process is using the I2C protocol.
A far easier option is to use a larger Arduino model.  Consider the Mega 2560 since it has 8 times the Flash memory.

Instead of I2C use serial. Much faster and more lightweight.


text:
SDA and SCL problem with MEMS
I have a simple question to ask you about SDA and SCL pins.
I have a gyro and I use these 2 pins to make it work; how can I use an accelerometer combined to a Gyro if these 2 pins are used? I should need another 2 SDA and SCL pins for the accelerometer... Tell me that I don't need to buy an IMU :D
EDIT: I'm using Gyro LG3D20H from Adafruit, reading gyro values each 10 ms.

Which gyro? Which accelerometer? Giving part numbers helps get a more specific answer.

Typically it should not be a problem to share them. Note that you can also get 6-axis sensors like the MPU6050 and similar which combine both functions in a single chip.

I2C is designed to have multiple devices connected. Assuming the gyro and accelerometer have different I2C addresses they can both be connected to the same SDA and SCL pins.
For more information see http://www.gammon.com.au/i2c
Naturally you can only "talk to" one at a time. You may need pull-up resistors on both SDA and SCL, unless the hardware already has them.

For a newbie this thing is a bit complex. Do you have a "noob" guide to link me?

As I said in my answer, you can share the SDA and SCL pins for both devices. If you have more questions please give more information.

As I said, I have a Gyro that use SDA and SCL. I'd like to buy an accelerometer and use both in the same time. I know that there are analog pins that I could use for accelerometer (or gyro, depends on which I put on SDA/SCL), but I need that both are on SDA and SCL. I'm not smart in electronics so I really don't know how to use that guide that you linked.

@Kowak, to get specific answers you need to supply more-specific information.  Please edit your question and add the model numbers or chip numbers of  your gyro, and of accelerometers you are thinking of.  Also tell how frequently you need to read them, and whether you've modified their I2C addresses

I edited with my gyro name and frequency of gyro value readings. The problem is that I don't know which accelerometer I want to buy at the moment...


text:
Arduino with multiple buttons - will power be an issue?
I have a spare Arduino Uno lying around, which I figured I could attempt to turn into a game controller. First clear issue, that immediately popped up, was that there are not enough digital input pins on the board, but I think I can get around that by using analog pins with appropriate external resistors (is that actually a possibility?).
Another one, more severe, is that I'm not sure how I would need to go around wiring microswitch buttons with the board. Assuming they short the circuit when pushed (SPST), I could simply wire one contact to an input pin, set to INPUT_PULLUP mode, and connect the other to ground. However, since I know little about how such circuits work, I'm immediately in doubt about two things. Considering the board would be used as a controller, an external power source is out of question and I'd only want to rely on the USB power. Since I want to use plenty of buttons (up to fifteen), out of caution I'm worried that shorting this many input pins to the ground at once could overload the... regulator I think?
So my question is this: is it safe to use multiple, potentially simultaneously pressed, buttons connected to input pins on an Arduino Uno board, powered solely from a USB port? Additionally, just to be clear, is it normal to connect them all to a common ground on the board?

Is the game an Arduino game, or are you planning to control something else, like a PlayStation?

@Nick, I'd like it to be a "universal" USB controller. I found the UnoJoy project that ought to cover the basics of USB communication in my case; I'll figure out if I can further modify it once I get it running. Also, thanks for moving the question over, I wasn't initially sure which domain it's considered to be specific to.

In which case I endorse Ignacio's suggestion that you consider another Arduino, for example the Leonardo. I am using one to convert button presses into boilerplate for forums, described here.

You can use V-USB (Virtual USB) instead, try searching for that.

@Nick, ah right, Leonardo does have native USB support and more digital input pins available! Since I already have an Uno to spare, I'll proceed with this one for the time being, but will certainly consider buying a Leo for future projects of similar kind. Thanks!

was that there are not enough digital input pins what? why? how? I mean... You have 20 pins. If 2 are used for the serial communication, you still have 18 pins. Connect them in a matrix, and you have 81 possible buttons. Aren't 81 buttons enough for your controller? ;)

@frarugi87, if you consider analog pins, yes, that amounts to 18! However, when I first asked the question I wasn't sure if I can utilize analog pins for this purpose; I thought I'm limited to 12 digital pins available on an Uno, hence the question. I didn't think of wiring them into a matrix though; will have to find out how to do it to allow for a maximum number of simultaneously pressed buttons, but thanks a bunch for the suggestion!

@yakcyll Well, with 12 pins you can wire up to 36 buttons. And all of them can be simultaneously pushed (you just have to use a scanning frequency larger than the responsiveness you want). Anyway this is easily achieved since usually you want the buttons to respond within tens (even 50) of milliseconds and you can scan it at more than 10 times that frequency)

Most of your idea is sensible. Let's go over the sensible part first, and then we'll cover the bits that need work.
Using an internal pullup and shorting the input to ground is the correct way to approach this. Note that the pins will read HIGH when off and LOW when triggered this way.
Each pullup on an AVR is between 20kohm and 50kohm. This means that the current consumption if all 15 buttons are pressed is at most about \$15 \cdot {5 \text{V} \over 20\text{k}\Omega} = 3.75\text{mA}\$. This isn't enough for the USB connection to care about.
As for using the analog connections, A0 through A5 also have digital GPIO capability, which means that you would treat them exactly the same as you would the digital pins (A6 and A7 don't have digital GPIO unless you're running a ATmegaXX8PB with a special core).
And now the bad news.
The Arduino Uno is based on the ATmega328P, which does not have native USB capability. It communicates with the host through a serial connection via a USB-UART bridge. If you're using a real (or real-enough) Uno then that bridge is a ATmega16U2 which is a MCU that does have native USB capability, so it can be reprogrammed to interpret the serial stream from the '328P and talk USB to the host.
But if you aren't then you will either need to run a piece of software on the host that translates the serial stream to HID actions, or you will have to run a software USB stack on the '328P such as V-USB which will allow you to use Low-Speed USB 1.1 directly.
My recommendation is to see if you can get an Arduino or other AVR-based board that has an ATmegaXXU4 so that you can use Mouse and Keyboard directly instead of having to faff around with HID profiles and software USB. Unless that's your thing, of course.

Ignacio, it looks like this SE doesn't support maths symbols, unfortunately.

Aye, my board is supposed to be Uno R3-compatible and apparently does have an ATmega16U2 controller on-board to handle USB communication. If I understand you right, this means that I can program it, or find suitable firmware elsewhere, to have it present itself as a common HID device, instead of writing custom firmware for it, correct?

@yakcyll: Correct, although the buttons will still need to be handled by the '328P.

@NickGammon: Nor does it support CircuitLab. Some days I wonder how we even manage to get anything done :P

I wish those that migrate would take that into consideration. I have created schematics in the EE question editor and cut'n'pasted the markup in here and it works. I don't know if the schematics get purged if there's no record of them being used in EE though. Anyone know?

Yes, it is safe to connect multiple buttons to ground. The pull-up resistors have a fairly high value - about 10 kΩ and we know from Ohm's Law that
I = V / R = 5 V / 10k = 0.5 mA

per button. Your USB power is good for about 500 mA.
Welcome to StackExchange.

Transistor, it looks like this SE doesn't support maths symbols, unfortunately. ;)

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


text:
Does anyone know a library that can emulate 3 throttles?
There is this library, but it emulates only one throttle and one rudder. The X Y Z axis don't work because they are addressed from -127 to 127 and I need 0 to 255. I just need one more throttle axis. If it helps, I'm using an ATmega328 and read analog values in the 0 to 1024 range to read Logitech g27 pedals, then dividing by about 4 to fit the read value into the 0 to 255 range.

We really want questions here to be self contained and not depend on external links for their key parts, but conversion from a -127 to 127 range to a 0-255 one should be straightforward - just add an offset.

I agree with Chris the axis ought to work if you modify the value in your code, but if there is a reason you can't use them could you not just create a private version of the library an add in the necessary for an extra throttle, pin, variable and function? (Can't see the code, can't be more specific). Maybe the author would be interested in it for joystick4.


text:
Delay function broken?
I noticed timing inconsistencies in my project, and further debugging pinpointed it to the problem below. The text should be updating every second, but the returned values are >> 1000ms.
To clarify, the text is not showing up every second.  The delays between texts vary according to fluctuating start and finish values.
I'm using a Teensy 3.2. Changing the baud rate doesn't help.
Is my timing crystal busted? Is there a serial buffering issue? I don't know how to fix either of these.

Any help would be appreciated!
Edit:
Here's the code if anyone wants to test.  I found that adding more delay functions screws the output up in completely unlinear ways.
unsigned long start, finished, elapsed;

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

void loop() {
  Serial.println("Start...");
  start = millis();
  Serial.println(start);
  delay(1000);
  finished = millis();
  Serial.println(finished);
  Serial.println("Finished");
  elapsed = finished - start;
  Serial.print(elapsed);
  Serial.println(" milliseconds elapsed");
  Serial.println();
}

Edit #2:
I thought it was worth showing everyone this screenshot.  It looks like delay(1000) just isn't functioning at all.

Edit #3:
I debugged it with an LED and it blinked at exactly 1s intervals.  It seems like delay(1000) works, so the problem must be related to the serial buffering.  I also updated my software but that didn't help.
Edit #4:
New developments from further debugging:

The problem is not reproducible on a different computer.  The Arduino serial monitor on other computers displays correctly.
Updating to the latest OSX, arduino IDE, and teensyduino did not help.
Terminal 'screen' command surprisingly prints correct serial communication.
Serial monitors from 3rd party apps, like CoolTerm and Arduino IDE do not work.

I don't know what the problem is but recommend you try grouping all the println statements together, and likewise the start=/delay/finished=/elapsed= statements, and see if that makes any difference.  If so, edit question and say so.  Also, it's a good idea to include in your question code that can be cut and pasted (so people can run tests) instead of just a picture of the code.

Yes, please edit your question and post the code into it. Indent it using Ctrl+K. I have trouble believing that 23005 - 11004 = 1000 - as shown in your screenshot.

@NickGammon, I'm having trouble believing it also.  I have no idea why this is happening.

Well, that is nothing to do with a crystal, right? 23005 - 11004 is not 1000, so that code couldn't have printed that.

In most languages statements that output data, such as print, tend to take a fair amount of time, so actually wouldn't expect finished - start = 1000. (sorry @NickGammon I know you have proved me wrong) but in general in this sort of experiment it might be better to write to variables and print at the end of the loop.  It is probably the serial buffer on your host being full causing you problems, Nick hasn't got this problem, different terminal program? Try recoding and see.

I'm not much of an expert on the Teensy internals, but on something like the Uno the serial output would be placed in a buffer, and (if not too long) would be output by an ISR during the delay(). Thus the serial printing shouldn't slow down the interval much. It would be better to get the start time, do the delay, get the end time, without any intervening serial prints, in case this wasn't true (re-order slightly).

Looks like delay just isn't functioning at all. - on what grounds? You print at the start and end of loop so you expect the end time twice, right? Which is what you get. The next time is sometimes 1000 ms later, and sometimes 2000 ms (and once 4000 ms) which is kind of weird.

What version of the IDE are you using?

Arduino 1.6.5
Teensyduino 1.25
thanks for helping :)

I don't have a 3.2 Teensy. If no-one else can help I suggest posting on the Teensy forum.

Have you tried with the code everyone is suggesting (i.e put the println all together)? If not, try with void loop() { start = millis(); delay(1000); finished = millis(); Serial.print("Start "); Serial.println(start); Serial.print("Finished "); Serial.println(finished); }

Yes, I have tried moving serials to the end.  This helps by lowering the amount of glitching serial prints, but the problem still remains.  Please look at 'Edit #4' for new info I found.

After correcting the syntax error (missing semicolon) I tried your code on my Teensy 3.0. The results look OK to me:
Start...
1250
2250
Finished
1000 milliseconds elapsed

Start...
2250
3250
Finished
1000 milliseconds elapsed

Start...
3250
4250
Finished
1000 milliseconds elapsed

Start...
4250
5250
Finished
1000 milliseconds elapsed

Start...
5250
6250
Finished
1000 milliseconds elapsed

Start...
6250
7250
Finished
1000 milliseconds elapsed

Start...
7250
8250
Finished
1000 milliseconds elapsed

Start...
8250
9250
Finished
1000 milliseconds elapsed

Since the code you posted doesn't compile, can you re-test please with your posted code, assuming you add in the semicolon, and put a space before "milliseconds elapsed".

Further down my test I see this:
Start...
153258
154258
Finished
1000 milliseconds elapsed

Start...
154259
155259
Finished
1000 milliseconds elapsed

Start...
155259
156259
Finished
1000 milliseconds elapsed

Now are you talking about the "creep" in the start time? That doesn't totally surprise me, because the rest of the code must take some time to execute.

I know this isn't an "answer" per se, but I can't post this much information into a comment.

I tested the posted code (w/ syntax correction), and got the same results.  I'm not worried about the creep, that's to be expected.

Since the subtraction's result (finished - start) displays alright, it means the right number is being stored in the variable, so it's Serial that is screwing up the task of printing it. Try reducing the baud rate to 9600 and try again.

Changing baud rates doesn't help :/

Oh, must have missed that in your post...have you tried just printing numbers (at least 6 digits) instead of millis() to see if this problem applies only to millis or to all arguments

It applies to all arguments.  I learned that the problem is independent of the hardware and must be computer related.  Check out edit #4 for more info.


text:
3.95 TFT LCD SPI or parallel interface
I would like to get one information about this TFT LCD module . This particular module works with parallel interface with arduino mega and uno.
I am trying to get rid of arduino in my project and use esp8266 itself. I have this module http://www.aliexpress.com/item/3-5-inch-TFT-Touch-LCD-Screen-Display-Module-For-Arduino-UNO-R3-HIGH-QUALITY-Free/1854595985.html
This has only the parallel interface pins mentioned which requires around more than 10 pins to make it work. Is there any possibility that there is an SPI interface supported for this one by  making use of any of the existing pins for the parallel interface.
I don't think so but still can someone confirm that. If so I need to get SPI interface ready TFT LCDs.
Thanks,

In general, no. The interface used by the chip is normally hard wired either in the connections to the Chip On Glass or in the connections of the shield (most commonly the former) and as such cannot really be changed.
You will need to either use a TFT screen that has the interface already set to SPI (and there are many) or use some form of SPI I/O expander to provide enough I/O pins to drive a parallel display.
Note that using SPI to communicate with a screen makes the screen updates considerably slower than using a parallel interface. The bigger the screen the slower it gets.


text:
Simple network protocol to communicate between N slave arduino and 1 central arduino?
i am looking to communicate text ( 40 char for each message ) between N arduino and a central one ( Communication is one way slaves to Master).I am looking for wire communication with 1 to 5 m distance.Does anyone know the best approach to do that ?
Vincent

You have quite a few options available to you as your requirements are filled by quite a few protocols, I am not going to list all. You can use things such as I2C, CAN, RS-485, RS-232.
You can find a few good examples from this EE.SE post from a search.
The CAN option is quite a good one for your application and is easy to set up and there are quite a few libraries available for the common chip MCP2525 and MCP2551. Yo can also get a 'shield' with this functionality from sparkfun.
The other options are discussed in the linked EE.SE post with regards to RS-485.
I2C can be implemented with the Wire library of arduinos and other libraries.
You can use RS-232, but I don't think it will be immune to noise at the distance you want, but you can still try. What you can do is use a multiplexer, such as this one CD74HC4067, and use it to multiplex the TX line from each node to the RX of the master.
From SFE's site:

For example, you could use it to connect the TX pins of 16 devices to one RX pin on your microcontroller. You can then select any one of those 16 devices to listen to. If you want two-way communications, you can add a second board to route your microcontroller’s TX line to 16 device’s RX lines. By using multiple boards, you can create similar arrangements for I2C, SPI, etc.

You will probably want to add some sort of checksum/CRC to the data you send over the network too.

IMHO you should first decide your network topology.
If you want a "star" network, i.e. a network when every node is directly connected to the central one, you can use any protocol. Maybe even a multiplexed serial interface.
If you want a daisy chain interface or a bus one use can or RS485.
Personally I'd avoid I2C (it's good for on-board communication, but if the device is a few meters away the noise can break it).
My suggestion: use serial over half duplex RS485: you can get very low price physical interfaces. Since it is half duplex, only one can "speak", so the master first sends an address, then puts itself in listen mode and waits. The slave whose address was told puts itself in sending mode and sends the data.
This way you will have a bus (so you can simply attach a node to another node without having to place a wire till the masater) and you'll have a simple bus logic which will prevent the information to collide. And, most important, RS485 is very strong (up to 1km if I remember well).
CAN can (sorry) be simpler to use, since the anti-collision is "embedded" in the protocol, but it's a bit more complicated to use (you'll need a transceiver and to implement the whole logic in the microcontroller instead of using a dedicated peripheral like the serial interface).

Hello,Thanks for your answer,I am looking at a star network topology ( i don't want to have the complexity of collision management).It seem more complex than i thought because RS485 will require quite some component outside the micro-controller.I may have been naive thinking i could just code something in the micro-controller and they will talk together ( like I2C ).

With a star network topology you will have to use N interfaces on the uC or a multiplexer. N interfaces are fine if N < 4-5, but if it is larger you will need a multiplexer. And if you use that, well, you will definitely need a sort of handshaking (you don't want to turn the multiplexer in the middle of a "packet"). So you will have to deal with something analogous to collisions. As for other hardware, RS485 transceiver are usually 8 pin ICs that do not require external components. And I2C is a bus network where you need handshaking (just one master and N slaves) so the problem remains


text:
connection between Arduino Uno with nRF24L01 and notebook with wireless card
My project intend to command an Arduino UNO by my notebook without cable. I thought to use a RF Nordic nRF24L01 cabled on an Arduino UNO, and to use the wireless card of my notebook to send command to it. Is it possible? Any solution?
Is this hardware solution possible?
I need to send to Arduino four analog signals to setup the light of four led.

Absolutely no. Can you connect your bluetooth headset to the wireless router? No because even if they share the same band they "speak" different protocols. So why could you do that with the nRF24L01?
If you want to communicate with your PC you have three options:

Choose nRF24L01. In this case, since the PC does not have that device, you will need to make an adapter (the easiest one could be an USB adapter). You can connect a microcontroller to a USB to serial converter and to the nRF24L01 and use it as a bridge.
Choose Wifi. Then you'll need a new transceiver for the arduino UNO you are using (maybe the ESP8266, which is around 2$) but can be a bit more complicated for just sharing data (I never used it, though, so I can be wrong).
Choose bluetooth. Usually this is my preferred way to communicate with a board. Cheap (the HC-06 module is about 2-3 $) and easy to use (the interface is a plain serial).

Good luck ;)

Might be worth trying the ESP8266 versions with USB interface. Programming them can be as easy as it is with any Arduino if you are using the Arduino IDE. I personally tend to stay away from bluetooth. Turning on bluetooth on my phone / laptop is too much effort:) WiFi is always on anyway.

@frarugi87, could you suggest a nRF24L01 module with USB adapter for my notebook? And which one for Arduino UNO?

@larzz11 But you have to implement a more complicated protocol (search for the device in the net, for instance) and I don't know if the ESP supports a direct TCP connection. The BT is much more easy to use (on the PC or phone you have a new serial interface, on the arduino... too ;) ). Anyway what you pointed out about the "turn on/off" is right :P Just one thing: why should you use the ESP USB version? It's easier to connect the arduino to it throigh the serial interface.. The PC is already connected to the wifi :P

@SPS just go on ebay and search for "nRF24L01 usb". I never used them, though, and I don't know what a "serial adapter" can do because the nRF has an SPI interface. If you want to try you can buy one and see if it works. Personally I'd design my own one using any microcontroller and writing my code...

@frarugi87 the cheapest solution? to buy another micro-controller (another Arduino??) and nRF24L01 or nRF24L01+USB? Could you provide some examples? Thanks

@SPS Some examples? go to ebay, write "nRF24L01 USB" to get these results. I think it's pretty easy..... As for the cheapest solution, probably those module work. You can give them a try... If, on the other hand, you want to spend some time on it, you can buy a board like the arduino nano, or the arduino micro + usb to serial adapter, or just any microcontroller (even an attiny where you can put the USB tiny code to get a HID device)... By the way usually when an answer is "satisfactory" you should accept it...

You could emulate BTLE with NRF24L01+ if your PC also supports it. Some amount of communication is possible I think but you would have to be quite creative.

@Avamander never knew you could "fake" BLE with a nRF24L01. Thank you! Anyway you can't receive data on the nRF, just broadcast (so you can only send data FROM arduino TO PC/mobile, and everybody with BT on will see the message). Anyway... Thank you!

@frarugi87 Is this a complete one (1 module USB for notebook + 1 module on arduino ), good for me? Or do I need another one? I'm a bit confused :-(

It looks like a good one. But again I never used them, so I don't know how they work. If you can get it to work then share your experience by just saying "Hey, it works" or "Nope, doesn't"


text:
pass class internal function as callback
I am trying to pass a class internal function as a callback function within the class. The error behavior is similar to this problem. Whatsoever, I was unable to construct working code based on that question's answer.
I try to pass over a callback function from within the class,in order to create a finite state machine, inspired by the examples I found on adafruit regarding multithreading. The idea is, that each state can call his successor. The class itself then represents the state machine and I just will call its update function.
While the following code does not resemble this utility, it resembles the problem in a minimal example (based on this larger codepiece):
class MyClass
{
  const byte theAnswer = 42;
  void (*myCallback)();

  void setCallback(void (*callback)())
  {
    myCallback = callback;
  }

  public:

  void print_info()
  {
    Serial.println(theAnswer);
  }

  void call()
  {
    myCallback();
  }

   MyClass()
  {
    setCallback(&MyClass::print_info);
  }
};

MyClass AClassOfItsOwn();

void setup()
{
  Serial.begin(9600);
  while (! Serial); // Wait until Serial is ready
}

void loop()
{
  AClassOfItsOwn.call();
  return;
}

I get the following error code returned:

...testscript.ino: In constructor 'MyClass::MyClass()':
testscript:25: error: no matching function for call to
  'MyClass::setCallback(void (MyClass::*)())'
     setCallback(&MyClass::print_info);

                                     ^

...\testscript.ino:25:41:
  note: candidate is:
...\testscript.ino:6:12:
  note: void MyClass::setCallback(void (*)())
   void setCallback(void (*callback)())

        ^

...\testscript.ino:6:12:
  note:   no known conversion for argument 1 from 'void (MyClass::)()'
  to 'void ()()'
...\testscript.ino:
  In function 'void loop()':
testscript:40: error: request for member 'call' in 'AClassOfItsOwn',
  which is of non-class type 'MyClass()'
   AClassOfItsOwn.call();

                  ^

exit status 1 no matching function for call to
  'MyClass::setCallback(void (MyClass::*)())'

fun times with polymorphism
This is code we discussed during looking for a solution. I leave it here for future reference.
I tried creating an instance of this wrapper within the actual class to hold the callback, but that did not work either.
class CallbackWrapper
{
  void (*myCallback)();
  public:

  void call()
  {
    myCallback();
  }

  void setCallback(void (*callback)())
  {
    myCallback = callback;
  }
};

class MyClass : public CallbackWrapper
{
  const byte theAnswer = 42;
  public:

  void print_info()
  {
    Serial.println(theAnswer);
  }

   MyClass()
  {
    CallbackWrapper::setCallback(&MyClass::print_info);
  }
};

trying to store the callback function in a wrapping class (also not working, '((MyClass*)this)->MyClass::CBW' does not have class type)
class CallbackWrapper
{
  void (*myCallback)();
  public:

  void call()
  { myCallback(); }

  void setCallback(void (*callback)())
  { myCallback = callback; }
};

class MyClass
{
  const byte theAnswer = 42;
  CallbackWrapper CBW();
  public:
  void print_info() { Serial.println(theAnswer); }
  void call() { CBW.call(); }
  MyClass()
  { CBW.setCallback(&MyClass::print_info); }
};

An update on why I want to change the callback function during runtime. Here I try to randomly change the callback function:
class MyClass
{
  CallbackWrapper CBW();
  public:
  void do_this() { Serial.println("doing this"); }
  void do_that() { Serial.println("doing that"); }
  void call()
  {
    CBW.call();
    if (rand() > 0.5)
    {
      CBW.setCallback(&MyClass::do_this)
    }
    else
    {
      CBW.setCallback(&MyClass::do_that)
    }
  }
   MyClass()
  {  }
};

For discussion with Michail
class CallbackWrapper
{
  public:
  void (*myCallback)();
  void call()
  { myCallback(); }

  virtual void setCallback(void (*callback)())
  {  }
};

class MyClass : public CallbackWrapper
{
  public:
  void setCallback(void (*callback)())
    { myCallback = callback; }
  void do_this() { Serial.println("doing this"); }
  void do_that() { Serial.println("doing that"); }
  void call()
  {
    CallbackWrapper::call();
    if (rand() > 0.5)
    { setCallback(&MyClass::do_this); }
    else
    { setCallback(&MyClass::do_that); }
  }
   MyClass()
  {  }
};

A member function does not have the prototype that you think. It has a hidden parameter for "this". A static member function could work as callback function but then it could not access member data. You should consider using virtual instead. The callback setting is then done by sub-class and implementation of the virtual member function. The C++ run-time will do the dispatch depending on the instance.

OK, I tried a bit with virtual functions, but I cannot make it run (see latest addition of code failure). Could you provide an example?

Have a look at this https://github.com/mikaelpatel/Cosa/blob/master/examples/Blink/CosaBlinkFSM/CosaBlinkFSM.ino and the FSM library https://github.com/mikaelpatel/Cosa/blob/master/cores/cosa/Cosa/FSM.hh. The state is a callback style function.

Without addressing the polymorphism part of the question, I have a post about calling an ISR from a class.

Unless you specifically limit yourself to one single class for a callback (i.e., include the class name in the function pointer specification) then you can ONLY use static member functions as callbacks.
static member functions appear as a normal function, not a member function, so don't have the implied MyClass *this as a first parameter.
If you want to allow member functions that aren't static you will have to make use of polymorphism and have a single base class that all classes which provide a callback function will inherit from.  Then you limit the callback function pointer to be members of that base class.
It is possible to do it if you are happy to limit to just one class, though the syntax is rather cryptic:
class MyClass
{
  const byte theAnswer = 42;
  void (MyClass::*myCallback)();

public:

  void call() {
    (this->*myCallback)();
  }

  void setCallback(void (MyClass::*callback)()) {
    myCallback = callback;
  }

  void print_info() {
    Serial.println(theAnswer);
  }

  MyClass() {
    setCallback(&MyClass::print_info);
  }
};

Using polymorphism you can only pass a callback function that is a member of the parent class, so it looks like that method may be out.

So, I tried creating a base class CallbackWrapper which has the callback functionality ((*myCallback)(), setCallback() and call()). I inherited MyClass from that base class. I tried to hook up my Callback using CallbackWrapper::setCallback(&MyClass::print_info()). Return is no matching function for call to 'MyClass::setCallback(void (MyClass::*)())'

I can't visualize what you are describing. Polymorphism is a tricky subject and easy to get wrong.

I abuse the edit question to post my futile try. (:

That's not abuse - that's what it's there for.  You're not using polymorphism in the right way - you need to think along the lines of an "interface" as Java has it.  I'll see about an example.

Actually, I am not sure even I can do it using polymorphism - it's incredibly tricky.  Can you have just one standard function name that will always be the callback function in a class?

I appended another code piece to explain why I want to change the callback during runtime. In my specific case, I think I could try with some tedious code refactoring I could e.g. define a class State, which will have an initialization (constructor) and an update() and an exit callback. All could be based on the same abstract base class, which I think is what you envisioned in the first place?

Callbacks with classes are an absolute nightmare to manage. If I must have one (say for an interrupt handler) it is always either static or an external wrapper function - never an instance member function. I am wondering if what you are trying to achieve is actually the best way to do what you want to do...

I think you are right; I will rethink how to do what I want to do. I could imagine I could find a better way to deal with this problem.

@Faultier I have finally found the right syntax for passing an internal member function within the same class, but you are limited to just the one class with that method.

seems almost right, but execution yields me ´request for member 'call' in 'AClassOfItsOwn', which is of non-class type 'MyClass()'´


text:
Arduino Micro blue light dimms and turns off when I plug in my circuit
I have a PING Ultrasonic Sensor, Adafruit Absolute Orientation Sensor, and a Continuous rotation servo. All pins are connected to an Arduino Micro. However because the micro only has one 5V output, I used a rail from a breadboard. I connected the + & - leads from all the devices to the rail and then plugged in two leads connecting 5V and GND from the Micro to the rail. My goal was two send power from the Arduino Micro down the rail to all three devices.
I plugged in the Micro, and instead of seeing green lights on the sensor (powered on), the blue light on the Micro turned off and the servo twitched. I have no idea why. Do I need external power for the 5V?

Sounds to me like a short or other over-current situation.

This sounds like a lot to have connected to the Micro's 5v pin. Without knowing your exact model of servo, I would still believe you are hitting the current limit. Can you try unplugging the servo and see if the circuit functions without the servo? I would power the servo externally with a 5v supply.

do you have any recommendations for the power supply? one that i can connect to a breadbooard.

would a 9v battery work?

Personally, I prefer a wall adapter. Any 5V supply that can handle the rated peak load current (plus some for padding) for your servo. I did a quick search on Amazon and I have something like this supply.I also bought some connectors like this.

I'm definitely not doing these comment hyperlinks right but I'm not sure why..so just ignore that!

but how would I connect the battery to the breadboard

Do you mean the power supply? The connector that I linked in the previous comment fits on the end of the power supply cable and will allow you to screw a pair of wires in the end. You can plug these into a breadboard.

I realized the problem I had. I switched ground and 5v by accident in the tangle of wires. Lol


text:
Corrupted files generated by Arduino with SdFat library. How to avoid that?
I got:

https://www.arduino.cc/en/Main/ArduinoBoardDuemilanove
http://wiki.iteadstudio.com/Stackable_SD_Card_shield_V3.0 (set to 5V logic)

with this sketch using SPI/SdFat+OneWire/DallasTemperature+EmonLib and no matter what I try I got corrupted files like this.
I even haven't attached my sensors yet :(
I have tried with 3 SD cards so far, each formatted with SD Memory Card Formatter and each one has this problem.
There is a separate question like that (Corrupted files generated by Arduino with SD library. How to avoid that?) but it concerns SPI confict but here SD is my only SPI device on the bus.
Any ideas?

This SD shield has CS on D4, not D10

Did this solve your problem?

yes, it did solve it

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


text:
Running light, without delay, and a potentiometer
I am just getting hands on to my Arduino Uno.
I am have finished the blinking light tutorial, managed to read a potentiometer, build a running light with delays and as well a binary counter.
Now I build a small project with 5 LEDs and a potentiometer to configure a running light and change the speed of the running light with the potentiometer.
The LEDs are connected to the pins 13 to 9 and the potentiometer is connected A0 and 5V.
I also managed to program it without a delay function, but I think it is rather ugly.
Is there a better way of doing this like I did it?
int led1 = 13;
int led2 = 12;
int led3 = 11;
int led4 = 10;
int led5 = 9;
//the delay
int pause = 1500;
//count to decide which LEDs are HIGH and which are LOW
int count = 0;
// will store last time LED was updated
unsigned long previousMillis = 0;

// the setup routine runs once when you press reset:
void setup() {
  // initialize the digital pin as an output.
  pinMode(led1, OUTPUT);
  pinMode(led2, OUTPUT);
  pinMode(led3, OUTPUT);
  pinMode(led4, OUTPUT);
  pinMode(led5, OUTPUT);

  // initialize serial communication at 9600 bits per second:
  Serial.begin(9600);
}

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

  unsigned long currentMillis = millis();

  // read the input on analog pin 0:
  pause = analogRead(A0);
  float voltage = pause * (5.0 / 1023.0);

  // print out the value and teh corresponding voltage you read:
  //Serial.println("Value: %d and Voltage: %f", pause, voltage);
  Serial.print("Value: ");
  Serial.println(pause);
  Serial.print("Volts: ");
  Serial.println(voltage);

  if (currentMillis - previousMillis >= pause) {
    // save the last time you blinked the LED
    previousMillis = currentMillis;

    if (count == 0) {
      digitalWrite(led1, HIGH);
      digitalWrite(led2, LOW);
      digitalWrite(led3, LOW);
      digitalWrite(led4, LOW);
      digitalWrite(led5, LOW);
    }
    else if (count == 1){
      digitalWrite(led2, HIGH);
    }
    else if (count == 2) {
      digitalWrite(led1, LOW);
      digitalWrite(led3, HIGH);
    }
    else if (count == 3) {
      digitalWrite(led2, LOW);
      digitalWrite(led4, HIGH);
    }
    else if (count == 4) {
      digitalWrite(led3, LOW);
      digitalWrite(led5, HIGH);
    }
    else if (count == 5) {
      digitalWrite(led4, LOW);
    }
    else if (count == 6) {
      digitalWrite(led4, HIGH);
    }
    else if (count == 7) {
      digitalWrite(led5, LOW);
      digitalWrite(led3, HIGH);
    }
    else if (count == 8) {
      digitalWrite(led4, LOW);
      digitalWrite(led2, HIGH);
    }
    else if (count == 9) {
      digitalWrite(led3, LOW);
      digitalWrite(led1, HIGH);
    }
    else if (count == 10) {
      digitalWrite(led2, LOW);
      digitalWrite(led1, HIGH);
      count = -1;
    }
    count++;
  }
}

The 'uglyness' of those repeated if/else statements can be replaced by using a switch statement.

Yes, that would be an idea, but nevertheless, it will be still a very large of code.

You can put the LED pin numbers into an array.  After each delay period, turn off the current LED, increment the count, and turn on that LED.  For example:
// Sketch re: http://arduino.stackexchange.com/questions/19605/running-light-without-delay-and-a-potentiometer

// Set constants for pins with LEDs
enum { led1 = 13, led2 = 12, led3 = 11, led4 = 10, led5 = 9};

// Make an array with the LED pin numbers
byte ledPins[] = { led1, led2, led3, led4, led5 };

// # of entries in ledPins:
enum { numLeds = sizeof(ledPins) / sizeof ledPins[0]};

//count to track which LEDs are HIGH and which are LOW
int count = numLeds-1;      // Will roll over to 0

// To store last time LED was updated
unsigned long previousMillis = 0;

void setup() {
  // initialize digital pin outputs
  for (byte i=0; i<numLeds; ++i)
    pinMode(ledPins[i], OUTPUT);

  // initialize serial communication at 9600 bits per second:
  Serial.begin(9600);
}

// loop() runs over and over again forever:
void loop() {
  unsigned long currentMillis = millis();
  // read input on analog pin 0:
  int deli = analogRead(A0);
  float voltage = deli * (5.0 / 1023.0);

  // Print out the value and corresponding voltage you read:
  // Serial.println("Value: %d and Voltage: %f", pause, voltage);
  Serial.print("Value: ");
  Serial.println(deli);
  Serial.print("Volts: ");
  Serial.println(voltage);

  if (currentMillis - previousMillis >= deli) {
    // Save the last time we blinked the LED
    previousMillis = currentMillis;

    // Turn off current LED, turn on next one
    digitalWrite(ledPins[count], LOW);
    count = (count+1) % numLeds;
    digitalWrite(ledPins[count], HIGH);
  }
}

That is realy a nice piece of code. THX a lot. I will try to midify it a little bit, so that the running light will run from "left to right" and then back from "right to left"

done, awesome, that was fun.

Your Serial.print()s will print on every iteration of loop() even if that iteration doesn't operate on the LEDs. You'll be swamped with output on the terminal.
One improvement I'd make would be to get rid of the counter and the if/else if/.../else if segment. Rotate a bit through a byte variable for as many bit-positions as you have LEDs. Then call a function with that byte, that will set each LED on or off according to the state of its respective bit.
One more improvement can be had if you rotate the bits through bit positions 1 to 5 (in this case) of your byte variable, because you made the fortunate or perhaps intentional assignment of LED's to digital I/Os that are adjacent bits in PORT-B! One single PORTB = [your byte]; statement could set all 5 LEDS simultaneously.
Update:
PORTB is a register in the UNO's Atmega328p MCU, one of three (PORTB, PORTC, and PORTD) that connect to all of the I/Os on the UNO (or any other '328 based MCU board). By setting the (up to) 8 bits in one port, a single assembly-language instruction can set that many I/Os simultaneously. It is incredibly efficient. The downside of doing that instead of calling digitalWrite() is that the sketch is then tailored to that particular processor. digitalWrite() uses more program memory and execution time (by a lot, especially when setting multiple I/Os), but keeps your sketch processor independent; digitalWrite() knows which processor it was compiled for and how to translate a Digital I/O number to a physical external pin on that processor, so you don't have to.
For those interested in the low level details of the hardware, they are in the processor's datasheet.

The part with the "if/else if" is indeed very ugly. jwpat7 shows a solution wich looks what you have described. Could you please explain what ypu mean with "PORT-B"?

Completed now.
@all: Thank you very much.
@JRobert: Thanks a lot for the very good explanation
@jwpat7: Thanks for the code, it helped me a lot.
// Sketch re: http://arduino.stackexchange.com/questions/19605/running-light-without-delay-and-a-potentiometer

// Set constants for pins with LEDs
enum {
  led1 = 13, led2 = 12, led3 = 11, led4 = 10, led5 = 9};

// Make an array with the LED pin numbers
byte ledPins[] = {
  led1, led2, led3, led4, led5 };

// # of entries in ledPins:
enum {
  numLeds = sizeof(ledPins) / sizeof ledPins[0]};

//count to track which LEDs are HIGH and which are LOW
int count = numLeds-1;      // Will roll over to 0

// To store last time LED was updated
unsigned long previousMillis = 0;

//direction forward
boolean forward = true;

void setup() {
  // initialize digital pin outputs
  for (byte i=0; i<numLeds; ++i)
    pinMode(ledPins[i], OUTPUT);

  // initialize serial communication at 9600 bits per second:
  Serial.begin(9600);
}

// loop() runs over and over again forever:
void loop() {
  unsigned long currentMillis = millis();
  // read input on analog pin 0:
  int deli = analogRead(A0);
  float voltage = deli * (5.0 / 1023.0);

  // Print out the value and corresponding voltage you read:
  // Serial.println("Value: %d and Voltage: %f", pause, voltage);
  // Serial.print("Value: ");
  // Serial.println(deli);
  // Serial.print("Volts: ");
  // Serial.println(voltage);

  if (currentMillis - previousMillis >= deli) {
    // Save the last time we blinked the LED
    previousMillis = currentMillis;

    if(forward){
      // Turn off current LED, turn on next one
      digitalWrite(ledPins[count], LOW);
      count = (count+1) % numLeds;
      digitalWrite(ledPins[count], HIGH);

      if(count == numLeds-1 ){
        forward = false;
        count = 0;
      }
    }
    else {
      digitalWrite(ledPins[count + numLeds-1], LOW);
      count = (count - 1) % numLeds;
      digitalWrite(ledPins[count + numLeds-1], HIGH);

      if(count + numLeds-1 == 0){
        forward = true;
        count = 0;
      }
    }
  }
}

You might not realize, but your code still has a "delay" or well, the analogRead function. The function starts the ADC, waits for it to complete and then continues. (This is far below microseconds, but might be crucial) @NickGammon has made an very interesting post about it: http://www.gammon.com.au/adc
But, you shouldn't care, unless you really want to go beyond the scope of Arduino.
Also, you could use a timer + interrupt to change the LED's.
Combine these two things, and your program is running at full efficiency, and you could even run other things at the same time, with a minimal delay.


text:
Arduino cluster functionality - feasibility advice for arduinos to communicate using variable-length long strings?
My apologies. This is my first time on this site and I wasn't even aware that it wasn't some sort of discussion forum until receiving the automated response message to my already submitted vague and open-ended question.
Thank you Nick Gammon for pointing out Wanago's very interesting project, and I am sorry I did not provide enough information to show the difference in requirements. His solution is quite strictly structured and rigid (not just physically). But I wish to provide a solution that might allow anyone to fairly easily create an ad-hoc collection of any available arduino compatible hardware - which could also allow use of ESP devices for additional functionality if wished, but would not require ESPs as a means of connecting nodes. There may be a better solution than your RS485 Rolling Master for connecting nodes, but yours is the best solution I have yet seen so far, and not least because of the minimal resources required.
Thank you JBulmer for your clear overview and assessment, which does now give me a point of focus. In order to pursue this, I must try to aquire sufficient skills to add some form of multiple-chunk protocol layer on top of Nick Gammons Rolling Master protocol. I don't know if I'll manage it because I'm a hacker not a programmer, therefore I would appreciate  if I could give my reasons for trying, because I would very much value your opinion as to whether you think it would be worth my efforts or not.
Nicks protocol already provides auto-negotiating of nodes and takes care of most fault-tolerance type issues. I believe it auto-detects nodes and assigns them IDs which are stored in each individuals EEPROM, so he has already taken care of most of the connectivity side of things.
And I think the main reason for him using a defined message length was in order for all nodes to be able to poll in timeslot sequence for opportunity to transmit as master, which means it ought to be possible to somehow sync up re-constitution of split message blocks.
So apart from the protocol extension for handling of long strings, I don't see any other major obstacles which I can't imagine a solution for in principle even if not yet aware of how. I hasten to add that I am pushing myself way out of my comfort zone to try to achieve this because I think (though perhaps wrongly) that it might offer much benefit to ordinary arduino amateurs (such as myself) who I feel arduino is mainly aimed at. So the following example is not any specific requirement of mine, just something to illustrate some of the potential that could be offered to non-professionals - hopefully after the initial scene-setting, things can become more apparent...
The majority of arduino project examples use the serial monitor as a quick and easy way for user interaction, which can then be expected to need customising for more practical methods of input and output - but clustered nodes communicating serially might allow many project examples to be used almost as is.
An Infra-Red sender makes a good starting point. The IRremote library IRsendDemo.ino monitors the serial port for a keypress then calls a send routine, eg: irsend.sendSony. The incoming serial trigger could be made to be anything the user wished to use as a command, such as MyIRblaster, and could also include an equivalent text string of any required parameters for appropriate data conversion before use, ie:  MyIRblaster Sony(0xa90, 12)
All this can be developed and tested in independent isolation using the serial monitor, then when happy, add a 'common' block of RS485-based cluster-talk code, allowing any other node the ability to then send it a MyIRblaster command and parameter to action when needed.
As the IR arduino is using the IRremote library anyway, we may as well also give it an IRread capability, which wouldn't even require any associated trigger command.
It would be an advantage to be able to save IR signals somewhere though, but trying to squeeze on additional SD and FAT libraries as well as IRremote might be a step too far, so perhaps better just to add a separate SD node for storage. The SD node could have a file of saved IR codes, perhaps each with an asscociated corresponding simple text description such as TVmute, and have a suitable command+parameter capability added such as "SendBlaster (name)". This would allow any node to issue eg: "SendBlaster TVmute" to the SD node which in turn could issue a corresponding MyIRblaster Sony(0xa90, 12) command to the IR node.
And similarly to action any other types of node functionality for that matter - it would be relatively trivial to add some relays to the IR node if wished, and make the node recognise a "Relay (name)" command+parameter for instructing it to control any relay as required.
But it would also be just as easy (if not easier from a software point of view) to add a separate Relay node if wished. And similarly, even a Trigger node perhaps offering 64 channels of interupt-driven inputs - which also wouldn't need to recognise any incoming command, just simply be able to issue perhaps a 'Triggered' command plus appropriate triggered channel number as a lookup instruction to the SD node. Every trigger input could be assigned its own corresponding list of responses in its config file entry, which could include any of the functionality that any of the nodes could respond to.
Adding new functionality to the cluster would be as simple as adding another command keyword to a relevent nodes list of commands to be parsed for, which when matched would branch to an appropriate internal function.
So adding a "WriteLOG" command to the SD node (and having it parse for an accompanying "Details" parameter) could provide a facility for every node to be able to record events to an event log just by sending the serial command "WriteLOG (details)"to the SD node.
Commands don't have to be external, they could include any locally recognised macro-type commands for accessing any of the internal capability. So for instance the SD node could recognise a "Pause (duration)" instruction to invoke a non-blocking delay if wished. This could allow the SD node to send multiple IR code commands with pauses between each transmission. It might also recognise a 'No_Retrigger (duration)' timer to prevent unwanted repeat triggering of PIRs etc.
To better appreciate the potential now, we could create a config file on SD that contains an appropriate channel entry # for every trigger input we might wish, be it IR receives, PIRs, switch contacts or whatever.
The channel #3 doorbell entry could be something like this...
3  Doorbell,  No_Retrigger (3mins),  MyIRblaster (TVmute),  Relay (Porchlight) (ON),  Relay (Doorbell) (ON),  Pause (3secs),  Relay (Doorbell) (OFF),   MyIRblaster (TVun_mute),  Pause (5mins), Relay (Porchlight) (OFF).
If the SD node receives a 'Triggered Doorbell' instruction it simply parses the corresponding #3 entry and sends any extracted commands out for the other nodes to action as appropriate. In this case it would ignore subsequent PIR retriggering for 3 minutes, send commands to mute the TV, turn on the porch light, ring the doorbell for 3 seconds, unmute the TV, then turn the porch light off after 5 minutes.
It could also easily include simple local conditional logic to only turn the Porchlight when dark etc, which could allow option for appropriate qualifiers to a commands parameters, ie: Porchlight (ON) (IF_dark).
PIR sensors could select CCTV cameras, or even send IR commands to point a PTZ cam to preset positions, and all using just the same cluster functionality being used above.
A voice node might be added to givie an "Announce (message)" command, then add appropriate config entries to provide appropriate voice announcements for any triggered events.
Even amateurs could evolve quite sophisticated flexible ad-hoc systems without needing any rocket science, and without hardware constraints other than needing cheap RS485 adapters and sufficient memory for running the protocol and parsing out any commands plus conversion of any parameters.
Although the SD node in the example above is tending towards becoming a systems co-ordinator, it is still just essentially another cluster peer node. But perhaps there could be good grounds for trying to modify Nicks Rolling Master to take advantage of what benefits an SD intelligent controller might offer, such as newly connecting nodes automatically obtaining assigned IDs plus other 'characteristics' and 'behaviour' from the centrally managed SD config file.
I'm willing to roll up my sleeves and prepare for the long slog if the concept is considered realistic and worthwhile, but I would certainly welcome informed opinion as to whether it might be or not.
-------Original---------
I am looking into the feasibility of linking multiple Arduinos together to form a cluster of Arduino and ESP8266 nodes capable of sending sequences of plain text commands plus optional parameters to each other.
This could offer a mechanism for any node to be able to access the functionality of any other node without having local burden of that functionality.
For instance, only the SDcard node would require the libraries and overheads for accessing a centralised config file on SD card, but any of the other nodes could request appropriate entries from the config file whenever needed, or have ability to write event entries to a log file.
Similarly for an InfraRed node and its IR libraries, allowing any other node to send it plain text commands and parameters to transmit any required IR code even though the other nodes don't have local IR functionality themselves.
Basically, each individual arduino might just be considered a black box that does something useful and can be programmed to respond to certain external text commands (so in fact any other platforms with similar blackbox functionality could also easily be integrated to the cluster if wished).
Each node would parse an incoming string for a command that matched any of it's own local list of recognisable commands (ie: IRsend [code]) then branch as appropriate with any extracted accompanying parameters.
A cluster could be built up to include any and all required arduino functionality even though all of that functionality could never be squeezed onto any single arduino.
So an automation cluster could include things like voice announcements, web access, X-10 firecracker control etc just by including the appropriate nodes. Then tomorrow a voice recognition node might be easily added - needing to do nothing more than just issue appropriate text commands to also invoke any already existing functionality.
In principle, anyone could have the capability for doing almost anything they might wish, so although I don't know if this cluster functionality idea can be practically achieved or not, but the possible potential offers much incentive for trying.
And Nick Gammons excellent RS485 Rolling Master article brings the possibility so tantalisingly close... but it uses fixed-length messages to achieve it's clever self-negotiating fault-tolerance, and I'm afraid I don't know enough to be able to merge variable-length long string capability with his enticing communications system.
So I would appreciate any suggestions, even just informed advice telling me to forget it because it cannot be done (cos at least then I'd be able to get some sleep!).
Thanks,
Robin Baker.

Someone (Wanago) has done a similar project here. However instead of ESP8266 he used I2C which sounds more practical to me.
See images:

He had the same basic idea - each board has a specific task, and the work is shared between them.

Many communication systems use fixed-length, or limited-length, data exchange at the lower levels. For example, the ethernet network, under TCP/IP, has a maximum package size of 1526 bytes.
However, that doesn't prevent us moving large chunks of data, e.g. a DVD across the Internet.
A common approach is to use a layered protocol suite. Each layer is responsible for providing a service to the higher layer by using the service of the lower layers.
We talk about layered protocols because it provides a powerful, yet simplified way of thinking about communication problems. Rather than get bogged down in lots of detailed issues which need to be solved to work, we try to organise the problem into simpler and simpler solutions. Eventually things which we can implement without too much difficulty can be built, then higher layers are built from the simpler capabilities of lower layers.
The highest level of your protocol would provide the sort of service you need. In this case, you want to be able to send long-ish string messages, so the highest level would do that by using a mid-level fixed-length service.
In its turn the mid-level fixed-length service might provide error-free fixed-length messages using a still-lower-level service which can move fixed-length messages, but can't correct some types of errors.
(This is just an illustration of the idea, please don't take this as a concrete suggestion on how to implement anything.)
So, don't think "I don't know enough to be able to merge variable-length long string capability with his enticing communications system"
Instead, ask the simpler question, "how could I use that existing fixed-length communication system to send variable length strings?"
The answer might be pretty simple if the underlying system guarantees the order that messages are received. For example, send a count of the message length (in one or more messages) then send that number of bytes. The receiver knows how much to expect, and needn't act to interpret the data until it is received.
Then how to tell the difference between the command and its parameters? The command might be the first 'parameter' in the string, and parameters come after it.
The way I interpret your question, there may be several problems beyond sending variable length strings. There are potential problems like: adding or removing nodes, nodes failing, allocating 'names' to services on nodes (so commands can be sent to the appropriate node), etc.
However, the fundamental problem of sending long strings over a fixed-length communication channel is straightforward, and can be solved in a few different ways (I mentioned one, above).


text:
Visual Micro without .ino files
I am using the visual micro extension for Visual Studio 2015.  I would like to not use any .ino files since I'm trying to setup cppcheck which doesn't recogonize .cpp files, and its just what I'm used to.  However when I change my project.ino file to project.cpp the compile option is no longer available (I assume its looking for a .ino file).  Is there a project setting I can change to fix this?

Make a new tab in the IDE (top RH corner) with a xxx.cpp file name. Put your code in that. Leave the .ino file blank. Then it will compile. You need to add:
#include <Arduino.h>

... to the start of the .cpp file.
More information: How to avoid the quirks of the IDE sketch file pre-preprocessing

To clarify the question about libraries ...
You do need to put into the .ino file an include for any libraries used in the project. For example:
#include <Wire.h>
#include <SPI.h>
#include <EEPROM.h>

This effectively triggers the Arduino build process to link those libraries into the final executable file.
Related, my reply in this thread: Classes and objects: how many and which file types do I actually need to use them?

Thanks, that seems to be working in the Arduino IDE, but where I really need it to work is using the Visual Micro visual studio addin.  When I compile the project there I get #fatal error: SPI.h: No such file or directory so it doesn't seem to be handling the library paths correctly.

Nvm, the link you posted addresses this.

As you have found, Visual Micro will not consider the project to be an Arduino project if you do not have a "project_name.ino" included in the project
A cheat is to create a "project_name.cpp" and include it in the project. This will cause the .ino to be ignored during compilation.
EDIT: The project_name.cpp takes priority during compile, therefore the .ino just becomes a dummy. However the .ino will still be used for intellisense. The cpp should be #included in the .ino along with any libraries you want discovered by intellisense.
The Visual Micro release yesterday includes automatic "library in library" discovery which means you would no longer need to put all lib #include's in the project_name.ino. (tip: you can switch the "deep search" feature off for each project via the Visual Micro menu. It slows the compile down with large libraries)

Just to clarify, if "deep search" is off would the #includes still need to be in the .ino files?

Yes. With "Deep Search Off" all possible library includes need to be in the master .ino file. Then deep search is pointless :)


text:
How do I install Arduino drivers?
I need to install my Arduino drivers, but Windows 8.1 doesn't seem to like Arduino, and it greys out the update driver button. Therefore I can't select the drivers from the drivers folder in my Arduino IDE folder.
There are drivers that need to be installed. But Windows 8.1 greys out the update driver software button. Also, it refers to Arduino Uno as an unknown device. How do I install the Arduino drivers and make Windows let me install the drivers?

Are the drivers signed?

What do you mean?

Try right-clicking on the .inf file and selecting "install".

Have you tried following the Windows 8 instructions at https://learn.sparkfun.com/tutorials/installing-arduino-ide/windows ?

Have you tried following the Windows 8 instructions at http://dawdevel.blogspot.com/2012/12/arduino-uno-on-windows-8-without.html ?

Which .inf file Majenko?

What Arduino is it?  Is it a genuine one, a clone or a fake? Where did you get the drivers from?  Do you know what version they are?  Are they on CD/DVD or downloaded?

I've fixed the problem now :). The drivers needed administrator rights for modification and I'm not admin so I asked my admin to allow me to update the drivers

The IDE package usually ships with the driver(at-least the latest one).
Go to Program Files in C: and find the Arduino folder and you should find a folder named Drivers. Inside you will find an application named dpinst-x86. Run it and you should be good to go!

Often reinstall the latest arduino IDE with Windows Administrator rights helps (use right click execute as administrator).

If the arduino is undetected in PC go to control panel-device manager - connect the arduino and some COM port will appear click it and troubleshoot make sure your PC is connected to internet and then you will be able to see your com port in arduino ide.


text:
Due : DMAC BTSIZE trimmed modulo 8192?
On Arduino Due, I set-up DMA transfers using direct control of memory mapped hardware registers.
There is a 16-bit BTSIZE field in CTRLA which indicates the number of (width sized) transfers.  If I specify larger than 8191, the value of btcount is trimmed to 13 bits after the DMA channel is enabled.  I set chunk size src/dest to 1.
The ATMEL data sheet for the sam3x (linked from the due page) does not mention this 'limitation' (section 22.7.16), or possibly I'm using it wrong.
What reference is canonical and correct for the DMAC (dma controller)?

As noted in the links in the comments, multi-buffer transfer can work around this, but since I don't know why it works or fails, it's hard to decide if that solution will work in all cases.

Please post the code that does this transfer.

This looks relevant: http://community.atmel.com/forum/synchronous-serial-controller-ssc-or-i2s-using-dma-controller-sam3x8e-incomplete-data-transfer

Thanks for the link, I moved to multi buffer continuous transfer too, which works around the issue, but doesn't really answer the question:where can I get good/correct documentation for the Dmac.  Note that there are other problems with the datasheet Dmac documentation relating to multi buffer transfer.

I have made two or three bug reports direct to Atmel about their documentation. In each case they acknowledged it was wrong and said they would fix it. Possibly there is no good/correct documentation on this point. Contacting Atmel and submitting a ticket might help correct this situation.

Thanks for your help, hopefully this will help the next person.  I'll add more working Dmac code in this and other questions when I get some time.

It is probably a nightmare for them to keep the documentation exactly and precisely synchronized to what the chip actually does. If people don't report things, little errors are likely to stay there.

By the way, 2^12 is 4096, not 8192.

I'll quote the answer given in this link to help make this question more useful for future people who search this problem.

The dmac.h file in asf library has a macro named DMA_MAX_LENGTH set to 0xFFF = 4095. We tried changing it to higher values but still Buffer Transfer size (BTSIZE) register was showing only values till 4095. This seemed to us to a hardware limitation of the DMAC in Atmel SAM3x8E (which we did'nt see mentioned in the datasheet). So this closed the option of single buffer transfer for us and we moved to multi-buffer transfer
It was a simple way out (even though I took some time to figure it out :P ) - Use multi-buffer transfer with contiguous source address! (see table 22.4 Row 3)


text:
RF24 Stalls Arduino Program with powerDown
I have an ATtiny85 and an Arduino Uno both using NRF24L01 chips to communicate with one another. The ATtiny85 is powered by a CR2032 coin cell. I am using tmrh20's fork of the RF24 library which can be found here. Here's the problem I'm encountering:
Under the current code posted, the Uno will receive about 80 packets of data (80 packets times 2 seconds per packet is about 160 seconds of time) before the ATtiny will simply stop sending, and the Uno receives no more data. I can tell that it's the ATtiny, because I've got a DMM hooked up to it. Normally, my DMM tells me that the ATtiny is drawing less than 0.005mA of current, but at the instance of the stall the DMM reads approximately 1.4 mA of current draw, which makes sense because under normal conditions with no sleep the ATtiny draws about 1mA, and the radio not in power down mode and not transmitting draws 0.4mA.
I've spent quite some time trying everything from setting the clock speed to a different value (it's at 1MHz) to changing the power amplifier value. The only thing I've tried that makes an impact is getting rid of the powerUp and powerDown function calls. Once these are removed everything works perfectly transmission-wise, except the only issue is that the whole system is drawing 0.4mA constantly, which is too much.
I don't think the coin cell is a problem considering the system works when the powerUp and powerDown calls are removed. Here's my code:
Reciever:
#define CE_PIN 7
#define CSN_PIN 8

#include <SPI.h>
#include "RF24.h"

RF24 radio(CE_PIN, CSN_PIN);

byte address[11] = "SimpleNode";
unsigned long payload = 0;

void setup() {
  while (!Serial);
  Serial.begin(115200);
  radio.begin(); // Start up the radio
  radio.setAutoAck(1); // Ensure autoACK is enabled
  radio.setRetries(15,15); // Max delay between retries & number of retries
  radio.openReadingPipe(1, address); // Write to device address 'SimpleNode'
  radio.startListening();
  Serial.println("Did Setup");

}

long counter = 0;

void loop(void){
  if (radio.available()) {

    radio.read( &payload, sizeof(unsigned long) );
    if(payload != 0){
        Serial.print("Got Payload ");
        Serial.print(payload);
        Serial.print(" - ");
        Serial.println(counter);
        counter++;
    }
  }

}

Transmitter:
//Sleep
#include <avr/sleep.h>

const int sleepSecs = 2;

//Radio
#define CE_PIN 3
#define CSN_PIN 3 //Since we are using 3 pin configuration we will use same pin for both CE and CSN
#include "RF24.h"
RF24 radio(CE_PIN, CSN_PIN);
byte address[11] = "SimpleNode";
unsigned long payload = 0;

void setup() {
  //Setup radio
  radio.begin(); // Start up the radio
  radio.setAutoAck(1); // Ensure autoACK is enabled
  radio.setRetries(15,15); // Max delay between retries & number of retries
  //RF24_PA_MIN, RF24_PA_LOW, RF24_PA_HIGH and RF24_PA_MAX
  radio.setPALevel(RF24_PA_HIGH);
  radio.openWritingPipe(address); // Write to device address 'SimpleNode'

  //Setup sleep
  setup_watchdog(6);
  set_sleep_mode(SLEEP_MODE_PWR_DOWN); //Power down everything, wake up from WDT
  sleep_enable();
}

volatile int watchdog_counter = 0;

ISR(WDT_vect) {
  watchdog_counter++;
}

void loop() {
  sleep_mode(); //Go to sleep!

  if(watchdog_counter >= sleepSecs)
  {
    ADCSRA |= (1<<ADEN);
    radio.powerUp();
    watchdog_counter = 0;

    payload = 123456;
    radio.write(&payload, sizeof(unsigned long) ); //Send data to 'Receiver' every second

    radio.powerDown();
    ADCSRA &= ~(1<<ADEN); //Disable ADC, saves ~230uA
  }
}

//Sets the watchdog timer to wake us up, but not reset
//0=16ms, 1=32ms, 2=64ms, 3=128ms, 4=250ms, 5=500ms
//6=1sec, 7=2sec, 8=4sec, 9=8sec
//From: http://interface.khm.de/index.php/lab/experiments/sleep_watchdog_battery/
void setup_watchdog(int timerPrescaler) {

  if (timerPrescaler > 9 ) timerPrescaler = 9; //Limit incoming amount to legal settings

  byte bb = timerPrescaler & 7;
  if (timerPrescaler > 7) bb |= (1<<5); //Set the special 5th bit if necessary

  //This order of commands is important and cannot be combined
  MCUSR &= ~(1<<WDRF); //Clear the watch dog reset
  WDTCR |= (1<<WDCE) | (1<<WDE); //Set WD_change enable, set WD enable
  WDTCR = bb; //Set new watchdog timeout value
  WDTCR |= _BV(WDIE); //Set the interrupt enable, this will keep unit from resetting after each int
}

Try resetting the nrfs with the below answer: https://arduino.stackexchange.com/a/54604/35167

A delay after the powerUp() made the program work for longer, but it still stalled. More delays after write() only exacerbated the issue. The only thing that I've done to get this to work is to put the sending code in the watchdog ISR itself. However, this is limited to only around 4 seconds max per sent packet because this is the watchdog's max value, but that's OK for my application.
This leads me to believe that somehow the watchdog is interfering with sending, so possibly disabling it and reenabling after sending could have some effect if anyone else is having this problem.

After looking at the RF24 header file, I suggest you call radio.stopListening() right before you call write(). Also add a delay of 5 ms after write(). It would be nice to know the exact point at which the program got stuck; add digitalWrite(13, HIGH) inside the IF block, after powerDown() and again outside the block, immediately after sleep_mode(), but with a LOW argument instead, so you can know if the problem is that the AVR stops waking up at some point or if its the radio methods that is blocking, for some reason.

an additional 5 ms after powerup?

Yeah...the header file says it should be included for maximum compatibility.

Oops...just checked your link...i didnt look at the source before...i guess i should change that

One more thing: do I need to call startListening again after writing and delaying?

No...theres no need to listen at all since you are only transmitting...

@AlexWulff I've edited my answer concerning the delay and the position of the digitalWrites.


text:
How to install Arduino IDE on Raspberry Pi
How do you install the Arduino IDE on the Raspberry Pi running an ARM version of Ubuntu or Raspbian? There doesn't seem to be any official ARM release. Both distros have an "arduino" package in their standard repos, but it only includes an ancient 1.0 version that's missing a lot of features.

have you tried downloading the linux 32 bit version it from arduino.cc? what happens?

Yes, I thought that might work too, but it's compiled for the i386 architecture so it gives me an error when I try to run it on the RPi. Apparently, i386 and 32-bit ARM are not compatible.

The IDE is java, so you might just need to replace the avr-gcc stuff with its arm version

The IDE is indeed written in Java, but build with Ant, which results in a not cross-platform startup file. I do think it should be possible compiling Arduino yourself on the rpi. Lookup a tutorial on ant builds on the rpi and clone the sources from the github repository.

Not sure if this will help, but I have it sort of running on Fedora on a Pi, see Arduino IDE on Fedora. I've had a few (path) issues, to which my post will attest, which I am sure are surmountable.

It's included in raspbian. Also in lemakers raspbian for bananapi.

Arduino at http://playground.arduino.cc/Linux/Raspbian recommends:
sudo apt-get update && sudo apt-get install arduino

but indeed warns that the version is old:

Note: This will install an old version of Arduino, and may not support
  some of the newer boards. You can not download a newer version from
  the website, because there is no ARM version. -- Arduino wiki on Raspbian

Looking at the raspbian respository at http://archive.raspbian.org/raspbian/pool/main/a/arduino/ currently lists 1.0.5
There are folks working newer versions of Arduino for ARM at https://github.com/arduino/Arduino/issues/3334 but it isn't finished yet.

why on earth would you like to run on the Pi? It's hideously slow. A ten-year-old intel machine is faster.


text:
Trying to understand compilation error message
C:\Users\Field\Documents\Arduino\Adafruit_TCS34725-master\examples\tcs34725autorange\tcs34725autorange.ino:2:31: fatal error: Adafruit_TCS34725.h: No such file or directory

 #include "Adafruit_TCS34725.h"

                               ^

compilation terminated.

exit status 1
Error compiling.

Did you try installing the library?

I got it, I goofed on installing the library.

You are trying to use a library, but it is either not installed, or is installed in the wrong location. A library, in this context, is code that supports a sensor or some other hardware or that accomplishes a task. We call them libraries because we can share and reuse them – like borrowing a book from a library.
It looks like you're trying to get the Adafruit TCS34725 color sensor going. The official source of the library is in the Adafruit's GitHub repository for the TCS34725 and there is a link at the bottom of the README for how to install a library. I'll bet that will get you back on track.

I got it, messed up on installing the library