text:
ESP8266 RTC memory (for bootcount)
I'm using an ESP8266 with deep sleep + wake up when RST pin goes low.
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266HTTPClient.h>
WiFiClient client;
HTTPClient http;
RTC_DATA_ATTR int bootcount = 0;

void setup() {
    bootcount ++;
    WiFi.begin("MySSID", "password");
    while (WiFi.status() != WL_CONNECTED) {
        delay(20);
    }
    // here I send "bootcount" with HTTP request
    ESP.deepSleep(0);
}
void loop() {
}

Here RTC_DATA_ATTR int bootcount = 0; fails with RTC_DATA_ATTR unknown.
How to get the number of times the ESP8266 has woke up from deep sleep?

RTC_DATA_ATTR is for esp32

Thanks @Juraj, you're right, I think you can post this as an answer. Does this mean it's not possible to count the number of times the ESP8266 has resumed/rebooted from deep sleep? How to save/restore a number in RTC memory?

The ESP8266 RTC has 512 bytes of RAM that persist across restarts but not during power outages. While this RAM isn't persistent across power outages it also doesn't have the write limitations that flash memory has, making it appropriate for frequent writes which don't need to survive power loss.
The ESP32's compiler and software framework make it easy to access similar memory on it using the RTC_DATA_ATTR attribute; unfortunately as you found and @Juraj pointed out, the ESP8266's doesn't.
Thankfully the Arduino core for the ESP8266 includes support for reading and writing this area of memory using methods in the ESP object.
ESP.rtcUserMemoryRead() reads RTC memory and ESP.rtcUserMemoryWrite() writes RTC memory. In your case you could do something like this:
void setup() {
  uint32_t bootcount;

  if(!ESP.rtcUserMemoryRead(0, &bootcount, sizeof(bootcount))) {
    Serial.println("RTC read failed!");
    while(1)
      yield();
  }

  bootcount++;

  if(!ESP.rtcUserMemoryWrite(0, &bootcount, sizeof(bootcount))) {
    Serial.println("RTC write failed!");
    while(1)
      yield();
  }

  Serial.begin(115200);
  Serial.print("boot count is ");
  Serial.println(bootcount);
}

void loop() {
}

Not quite as convenient as the RTC_DATA_ATTR attribute but it still gets the job done.
I changed the type of bootcount from your example to uint32_t because it should never be negative, and the size of uint32_t is independent of the size of int.
Because the Arduino core is open source, you can read the implementation of these functions if you want to know how they work.


text:
Radio receiver: deep sleep when no byte arrives, and wake up when a byte arrives?
This code works to listen for bytes via radio (with a 433 Mhz receiver module) with the Manchester library and Manchester code, and do an action when certain bytes are received:
#include "Manchester.h"

void setup() {
  pinMode(3, INPUT);
  man.setupReceive(3, MAN_1200);
  man.beginReceive();
}

void loop() {
  if (man.receiveComplete()) {
    uint16_t m = man.getMessage();
    man.beginReceive();   // start listening for next message
    // do something with m
  }
}

But it requires to have the Arduino / ATtiny / ATmega / MCU constantly running.
Question: is there a way to put the ATtiny on deep sleep mode (to get < 1 uA consumption) and wake-up only when a byte arrives via radio?
I know how to do this with an interrupt or "pin change interrupt", but here with radio library Manchester, it's probably more complicated. How to do it?
In this case it's probably going to be more complicated than just:
sleep_enable();
set_sleep_mode(SLEEP_MODE_PWR_DOWN);
sleep_cpu();

how much power does the radio consume?

The attiny itself consumes 5ma or 1ma at 1mhz and this is too much to run on batteries; thus I'd like to use deep sleep mode if possible.

I couldn't do that with my 433Mhz module. It would constantly trigger my interrupt pin, even if there wasn't any being send by me. There was enough noise/interference on the 433Mhz, that my Arduino would have no time to sleep.

@Gerben Yes I thought this would be the problem. Indeed PCINT are bit-based (on/off), and reading a message Manchester-encoded is higher level (bytes, etc.), so I really wonder how to do this properly!

source: Stack Exchange

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

sort: votes


text:
Possible configure ESP8266 as wifi shield for Arduino?
I know there's sketch to make ESP8266 becoming a simple web server. ESP8266 is cheap, small and consume less power compared to a Arduino Wifi shield.
Due to a more complex functionality requirement, I wish to place the web server code inside the Arduino itself (UNO, Nano or Pro Mini maybe). Is it possible to do this by configuring ESP8266 as a wifi bridge/shield to the Arduino? Or some mechanism methods which can route network traffics from ESP8266 to/from Arduino?
Updated
It connected to 4 relays & one I2C RTC DS1307.
It needs to sync RTC time with NTP server, and implement a web server which allows on-demand turn on/off each individual relay or by scheduling (e.g: turn on/off different relay at particular time of day). If RAM spaces allows, would like to implement a password access scheme for the web server as well

The ESP has 40 kb of ram and the average SPI flash rom used by ESP modules have 1 ~ 8 MB of code space. The average Arduino has much less of both. Uno R3 has the ATMega328, with 2kb of SRAM and 32kb of code space. Your trying to drive a truck with a mini cooper engine.

hmm really? i should reconsider then. @Passerby, i need to control 4 relays, 1 I2C RTC DS1307, sync RTC time from NTP server, and a web server which allows scheduling setup (e.g: turn on/off different relay at particular time of day). Do you think ESP8266 able to handle all these?

I can't comment on Passerby's answer so here is an answer to that question in the comments: What ESP8266 are you using? The simple ESP-01, the one with just 8 pins, does not have four I/O ports. However if you have a more advanced ESP8266(for example the ESP12 on a breakout board) you do have 4 I/O pins and you could just threw out the Arduino entirely. The ESP8266 is better suited to serve as a webserver than your arduino. So as Passerby suggested try just using your ESP8266 alone instead of combined with your Arduino. Have a look at this. It is a tutorial on how to build a webserver controlling two LED's. All you would need to do is replace the LED's with the relays and add another two outputs. Note that you do need another powersupply for your ESP8266 than the Arduino. The arduino can only supply about 40mA, while the peek current of an ESP8266 can be around 250mA. Good Luck!

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


text:
Can the Sparkfun AVR pocket programmer bootload/program a 3.3 V ATmega328p
The product in question - https://www.sparkfun.com/products/9825 - operating at 5 V (and can also supply it to the device being programmed).
I need to program the bootloader onto a 3.3 V ATmega328p and don't have any level shifters immediately available. Thus the question. The "Hookup Guide" for the product (https://learn.sparkfun.com/tutorials/pocket-avr-programmer-hookup-guide) seems to suggest that it will work fine as long as the 3.3 V device being programmed isn't powered by the programmer. I wouldn't have thought it's the best idea in the world, but maybe I'm wrong.
So any practical experience?
Are the over voltage tolerances for input lines on Atmel devices good enough to handle the extra voltage?
I guess the output level from the device being programmed would be high enough to be buffered up to 5.0 V?

What is a "3.3V Mega328p"? Do you have a link to a product page?

"Mega328p" - can you please specify the exact kind of Arduino/break-out board you are working with? The ATmega328p max operating voltage is 5.5V

As a test run I would like to boot load an Arduino Pro Mini 328 - 3.3 V / 8 MHz - https://www.sparkfun.com/products/11114. (My actual intent is to bootload a custom board I've designed which also uses the same Atmel Mega 328p.)

Unless you copy the design of the board, the two experiences aren't directly comparable.

With that combination of programmer and Arduino you have two possible options:

Cut JP1 on the programmer and power the programmer from the Arduino. With this you will have to make sure that the Arduino is connected and powered up before you connect the programmer to USB.
Cut SJ1 on the Arduino and allow it to be powered by the programmer at 5V. The Arduino itself isn't required to be powered at 3.3V, that's simply what the on-board regulator provides, so we cut SJ1 in order to isolate the regulator from the MCU. Note that any devices connected to the Arduino will need to support 5V operation in order to this to be safe.

It is not safe to put 5V at the output of the regulator, so you must make sure that does not happen.

The SJ1 jumper controls the output of the MIC5205 regulator, no reason to remove it in order to feed the regulator with 5v

@Omer: You're feeding 5V to the output of the regulator. There is a parasitic diode in LDO regulators that can cause latchup if the output is allowed to go higher than the input, as may be the case if the Arduino is powered by a LiPo battery.

Not sure why you would want to feed the output and not the input (raw) side of the regulator? perhaps I'm missing something, but isn't the regulator "sits" between the breakboard's VCC and the ATmega328p's VCC?

@Omer: You feed the output because trying to use 5V programming signals on the MCU while supplying it 3.3V will fry it.

The Pocket AVR Programmer has a logic level shifting (74ACT125) on board, specifically for this situation. There is nothing wrong with powering the target with a separate power supply that the programmer. Why else would there be a "power target"/"No power" switch?
I don't see why other people would suggest cutting traces, when all you need to do is toggle a switch.

Although the schematic reads "ACT" directly at the device, the note just below it says "AC", as do the actual product shots. I agree that if it actually used an ACT/HCT device then it could be fine, but as it is the '125 may not be able to reliably detect the 3.3V signals coming back from the device.

Are you referring the the ACT version having a required supply voltage of 4.5v to 5.5v? I think all the IO voltages are well within the Minimum HIGH Level of both the buffer and the attiny?
If all this doesn't work, why would they bother putting in a buffer at all? I'd love to hear your thought, as I'm planning on building my own buffered programmer based on the usbASP. The 3.3v ones I have from ebay aren't really 3.3v while programming, I found out.

I'm talking about the high input levels. ACT/HCT has a high input voltage of 2.4V, which is within the high output voltage of 3.3V CMOS, but AC/HC has a high input voltage of 0.7Vcc, which with a 5V supply means 3.5V. If you're going to build your own then I recommend using a MAX3392E so that the target voltage is properly handled.

But the buffer is powered by the target's voltage. So if the target is 3.3v the minimal input HIGH would be 0.7*3.3 = 2.31V, right? By the way, I can't find the 0.7Vcc anywhere in the datasheet, or is that the wrong datasheet?

Okay, I've unpuzzled it. The '125 will be powered by the device if the jumper you mention is left disconnected. The AC has enough drive to push its output voltage high enough to reach the 0.6Vcc needed by the 5V '2313 when supplied with 3.3V. The datasheet gives explicit output voltages at various arbitrary values of Vcc instead of an equation, but if you do the math then you'll find that it's 0.7Vcc. Therefore your answer is correct, but I'd still prefer to err on the side of caution.

Thank you @IgnacioVazquez-Abrams . I think I got it now.

ATmega328p Operating Voltage is 1.8v-5.5v, as stated in the second page of the datasheet (PDF):

So there should be no problem feeding it with a regulated 5v VCC while programming it, and then supplying it with 3.3v on normal use. Just make sure you do not leave any 3.3v devices (which are not 5v tolerant) connected to the ATmega328p during the programming of the chip.
Regarding the Sparkfun's Pro Mini 328 3.3v/8Mhz, you can read in the comments section of the Pro Mini page that customers successfully managed to power it with 5v without any issue. You can see from the schematics that the voltage regulator in use (MIC5205) has a max input voltage of 20v, so 5v should not pose a problem to power it up.
EDIT: See Ignacio's answer. My answer apply for powering up the Pro Mini not for programming it with 5v signals and 3.3v VCC. The SJ1 jumper will need to be removed in order for the MIC5205 regulator to supply 5v instead of 3.3v.

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


text:
How to send data from a smartphone to Arduino
My goal is to build an extremely low cost quadcopter, by using the sensors of my smartphone (it will be mounted on the quadcopter). The arduino will only control the speed of each motor, as received from the smartphone. What methods exist to transfer data from a smartphone to arduino?
My first idea was to simply use USB, but it turns out that my smartphone doesn't support the USB host mode. Is it possible to send data over USB without USB host mode? What alternatives do I have? I thought of using the audio port: Can I directly connect an audio channel to analog in?

"Extremely low cost" and the lift capacity to carry a smartphone sound mutually exclusive. I reckon by the time you get that lift power it would have been significantly cheaper to buy a gyro shield

Hmm that is true. But sending data would also be interesting for other robot projects.

I have been using a bluetooth module - they can be had for just a few dollars (depending on which country you're in). I've got an HC-06 which works great : http://www.dx.com/s/hc-05
It has 4 pins: VCC (connect to +5V on Arduino), GND, RX and TX (connected to RX and TX, digital pins 0 and 1 on the Arduino).
You will probably not be able to use Bluetooth and USB at the same time - both will be sending to the Arduino at the same time, and the communications will get garbled.
I have an app called "Bluetooth Serial Controller", which lets me send commands over bluetooth.
If using this, think carefully about what will happen if your phone goes out of range of your arduino.


text:
Driving stepper motors adafruit motor shield v2
I got an Arduino Uno Rev3 and Adafruits Motor Shield V2. I also got two RepRap stepper motors:
Frame size 42 x 42mm - NEMA 17
1.8 degree step angle
Length 47mm
Holding torque 44 N.cm (4.4kg.cm, 62oz.in)
Voltage 2.8V
Current/Phase 1.68A
Resistance/Phase 1.65ohm
Inductance/Phase 2.8mH
Inertia 68g.cm
Bipolar, 4-wire

I thought I was going to be able to run the steppers with the motor shield, but when I tried run one of the steppers it jumps (runs little bit, then stops, then runs etc) until it reach  x steps. I'm driving the the motor shield with 12v 3A power supply.
I read somewhere that the Adafruit steppers should be at-least 5V. Is that correct? Do I need to buy new steppers or any suggestions of stepper driver (shield)?
How many amps do I need to run both steppers at the same time? 1.68 x 2 = 3.36A?
I'm building two of these: https://www.youtube.com/watch?v=C15yPENQ074
Any suggestions/help is appreciated! :)

Adafruit's page says "MOST 1.5-3V MOTORS WILL NOT WORK". https://learn.adafruit.com/adafruit-motor-shield-v2-for-arduino/powering-motors

Yeah, I did see that... So I need new motors or another shield/controller. Any suggestions? Thanks

That shield is a motor shield; not a stepper shield. You can use it to drive some steppers, but it's not ideal. Regular stepper drivers provide current limiting, micro-stepping etc. PS. by putting 12V on a 2.8v stepper, you can burn out the stepper.


text:
Measuring power consumption on Arduino off of DC supply
I am working on a project involving the Uno, and I would like to benchmark the power requirements of Arduino. I am using the external 9V supply option.
Specifically, the Uno will be in to states,power-intensive and power-save. In the first mode, I am doing some heavy processing tasks (RF and some sensors are the only external loads), and the Arduino typically runs loop() without any delays. In the second mode, loop() is execued about every 10-40 seconds.
I am interested in benchmarking how much power is consumed in both states (I need this to estimate the size of the battery required for the 9V supply).
Obviously, googling yielded me solutions that involved measuring current using chips in series with the supply (I probably can pull this off with a multimeter). What I am wondering is whether there exists an elegant solution for this, with (highly) accurate results (I would most likely quote the power values, so accuracy is a must for me)? Something I can dynamically measure on the Uno itself?

If you're worried about power consumption then you need to move away from Arduino completely and work on a standalone solution with the bare MCU and a switching power supply.

I just need to benchmark for comparision. Can you please elaborate.

A multimeter will be fine for battery life expectancy. If you want more precision, you need something like a uCurrent and a oscilloscope that can calculate the area underneath the curve. But first, I'd try using a multimeter and a 5V supply (5v as to eliminate the power usage of the voltage regulator). Measure the current during processes, and during "sleep".

What I am wondering is whether there exists an elegant solution for this, with (highly) accurate results (I would most likely quote the power values, so accuracy is a must for me)? Something I can dynamically measure on the Uno itself?

The Uno cannot measure its own power consumption. Indeed, a Uno which has a voltage regulator, power LED, and USB interface chip is not your ideal solution for low-power applications.
See Power saving techniques for microprocessors


text:
Compiling includes with Ino
I'm attempting to compile this simple bounce.ino example with the ino tool, but it's giving me the error:
Bounce2.h: No such file or directory

I've placed it in the same directory as bounce.ino. Why can't it find the header?
Edit: I'm using Ubuntu.

What the is the include code you are using? #include "bounce.h"?

What OS are you using?
If you're in Linux (and some OS X installations) you should note that bounce.h and Bounce.h are two completely different files - you need to make sure you have the capitalization the same in your #include directive as the actual file on disk is.

This wasn't the exact problem, but you were close. I was doing #include <Bounce2.h>, which seems to only look in the library path where it didn't exist. For local includes, I need to do #include "Bounce2.h".

I was going to suggest that, but then changed my mind as in the normal IDE I think it includes the sketch folder as part of the system paths, so <> and "" have no difference. I guess with inotool it does matter.


text:
Arduino reading serial data non-blocking

I have an Arduino reading serial data and responding to other inputs as well, I'm trying to read incoming serial data without using the while, if at all possible. the incoming serial data will be formatted in a specific manner each time and will be CSV; It will look like such:
19,1400700083, 1-0,1-10,and other values delimited with a new line character "/n".

The first value will tell how many bytes are coming in so the serial receive function wont parse data until it gets all the bytes,second value is a Unix time-stamp, the third value (1-0) is the "get" or set" value; which will tell the Arduino to return a value or to set a value. The fourth (1-10) value will correspond to what variable to get or set. and the other values will be integers as well but are dependent on the other values.
My code is as follows:
void CheckSerialData() { // begin function

  if(Serial.available() >= 2) { // begin one, first line will be how many bytes incoming.
  int NumberOfIncomingBytes = Serial.parseInt();
    if(Serial.available() >= NumberOfIncomingBytes) { //begin two
    int IncomingTime = Serial.parseInt();
    setTime(IncomingTime); //time is always incoming with serial values
    int GetOrSetValue = Serial.parseInt(); //this value should be 1 or 0 for "getting values(1)" or "setting values(0)"
      if(GetOrSetValue == 1) { //BEGIN THREE
        int ValueToGet = Serial.parseInt();
          switch(ValueToGet) {// BEGIN SWITCH
            case 0:
              Serial.print(GetTemp());
              Serial.print("/n");
              break;
            case 1:
              //serialwrite yaw pitch roll
              break;
            case 2:
              Serial.print(GetVoltage());
              Serial.print("/n");
              break;
            case 3:
              //append all RGB final values together and serial print it
              break;
            case 4:
              //print out accel values
              break;
            case 5:
              //print alarm alarmed status
              break;
            case 6:
              //print out last time alarm set off
              break;
            case 7:
              //print out time allowed lights to turn on
              break;
            case 8:
              //print out arduino time
              break;
            case 9:
              //print out system summary, (time,voltage,temp,yaw,pitch,roll,accel
              break;

          }//END SWITCH
         }//END THREE
      else { //BEGIN TWO B //SET VALUES
      int ValueToGet = Serial.parseInt();
          switch(ValueToGet) {// BEGIN SWITCH
            case 0:
              //set global rgb value set LEFT
              break;
            case 1:
              //set global rgb value set RIGHT
              break;
            case 2:
              //set global alarm value
              break;
            case 3:
              //set global angle to start flashing emergency led's
              break;
            case 4:
              //set turn signal RGB value
              break;
            case 5:
              //set time that lights are ok to turn on
              break;
            case 6:
              //set light override value
              break;
            case 7:
              //set pattern enable
              break;

          } //END SWITCH

      }//END TWO B

          }
        }//end two
      }//end one
    }//end function
    //**********************END SERIAL FUNCTION**************************

I would like to know if this looks like it can work, or am I going about this all wrong?
(I don't have access to my Arduino currently to test the code)

Unfortunately your code could end up dropping data quite easily, or parsing it incorrectly.
Let's say your code has successfully read the first couple of bytes into NumberOfIncomingBytes. However, when it reaches begin two, let's imagine the sender hasn't finished sending all the data yet.
Your code will drop through to end two, discarding the NumberOfIncomingBytes value it just read. Next time round, it will start all over again from scratch, and attempt to read NumberOfIncomingBytes again. However, that data isn't there anymore. The next data waiting on serial will actually be the timestamp from the previous message.
From there, it could end up parsing arbitrary data with unpredictable results, getting completely out-of-sync with the sender.
A way to fix it would be to store the NumberOfIncomingBytes value outside the function (e.g. as a global variable), along with a flag indicating if you're still waiting for the rest of the data to arrive. At the start of CheckSerialData(), the code should check that flag. If it's true, then it should skip trying to read NumberOfIncomingBytes. Instead, go straight on to begin two.
An alternative approach would be to avoid using NumberOfIncomingBytes at all. Each call to CheckSerialData() would read whatever serial data is available, and accumulate it in a buffer. As soon as it hits a newline character, it will stop reading, and parse the data it's accumulated. If it runs out of serial data before it hits a newline, it should stop and carry on from there next time it's called.


text:
Is setup and loop provided for convenience?
Arduino sketches usually feature a setup and loop function. Are these functions only provided for convenience or do they actually have special purposes? (e.g.: are some operations disallowed or allowed in setup and loop)
Are these two pieces of code equivalent:
Classic
void setup() {
    pinMode(LED_BUILTIN, OUTPUT);
}

void loop() {
    digitalWrite(LED_BUILTIN, HIGH);
    delay(1000);
    digitalWrite(LED_BUILTIN, LOW);
    delay(1000);
}

Without loop
void setup() {
    pinMode(LED_BUILTIN, OUTPUT);

    while(true) {
        digitalWrite(LED_BUILTIN, HIGH);
        delay(1000);
        digitalWrite(LED_BUILTIN, LOW);
        delay(1000);
    }
}

void loop() {
}

Is it possible to write code without either setup or loop, providing, for example, a main method or other entry point?

Those pieces of code are pretty much the same.
If you look at the Arduino source code you'll see:
setup();

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

(I'm not sure what serialEventRun() does.)
I don't think you can 'overload' the main function declaration. Also note that the main function calls init, which e.g. configures the timers, so millis() etc. will work.

Are these functions only provided for convenience or do they actually have special purposes?

The Arduino libraries do a tiny bit of housekeeping with loop(), related to serial handling.

Are these two pieces of code equivalent:

Only if you never use serial events.

Is it possible to write code without either setup or loop, providing, for example, a main method or other entry point?

Not while strictly using the Arduino libraries via the IDE; the linker will complain of either duplicate main definitions or of missing setup or loop definitions.

Is it possible to write code without either setup or loop, providing, for example, a main method or other entry point?

The last time I used the IDE, you could have a project with no .ino/.pde file, only .cppfiles; since it's the mangling of the .ino into a .cpp that defines the main function, if you bypass that step then you can define your own main.
If the IDE no longer allows this (as I've heard) you can still do the same thing with e.g. a Makefile-based build outside the IDE, without giving up the Arduino libraries. The caveats that I know of are:

You should #include "Arduino.h" if you want access to the library functions.
You should call init() if you want the library to set up peripherals the way you're used to.
You should put the serialEvent code that Gerben points out in your mainloop if you want a serialEvent handler to run (but you probably don't need this anyway if you want to write your own mainloop).

Arduino sketches usually feature a setup and loop function. Are these functions only provided for convenience or do they actually have special purposes?

They throw in an extra function call to init which initializes the timers which let millis, micros and delay work without further effort. Other than that, no.
This code compiles (and runs) under the IDE:
int main ()
  {
  }

Effectively the IDE generates code like this:
int main ()
  {
  init ();  // set up timers
  setup (); // your own initialization
  while (true)
    loop ();  // stuff you want to keep doing
  }

They have fiddled with it since then, as Ignacio Vazquez-Abrams said, but basically you can ignore that. There is nothing particularly special about setup and loop.
You can use main like I showed above. You can do everything in setup if you want. You can do everything in loop if you want (if you never return from it).
Remember, you are dealing with a C++ compiler here. Functions don't have some magic significance based on their names.


text:
Arduino with WS2812 using Adafruit NeoPixel library fade in/out different patterns
Hey all I have been trying to figure out a way to random set patterns for my fade in/ out code below:
int PIN = 3;
int totalLEDs = 11;
int ledFadeTime = 5;

Adafruit_NeoPixel strip = Adafruit_NeoPixel(totalLEDs, PIN, NEO_GRB + NEO_KHZ800);

void setup() {
  strip.begin();
  strip.show(); // Initialize all pixels to 'off'
}

void loop() {
  rgbFadeInAndOut(0, 0, 255, ledFadeTime); // Blue
}

void rgbFadeInAndOut(uint8_t red, uint8_t green, uint8_t blue, uint8_t wait) {
  for(uint8_t b = 0; b <255; b++) {
     for(uint8_t i=0; i < strip.numPixels(); i++) {
        strip.setPixelColor(i, red * b/255, green * b/255, blue * b/255);
     }

     strip.show();
     delay(wait);
  };

  for(uint8_t b=255; b > 0; b--) {
     for(uint8_t i = 0; i < strip.numPixels(); i++) {
        strip.setPixelColor(i, red * b/255, green * b/255, blue * b/255);
     }
     strip.show();
     delay(wait);
  };
};

The code above works great. Fades the blue in and out infinity times. However, I am wanting random LEDs to be off or have a lighter/darker shade of the color I choose (in the above it's blue).
Example:
[off][blue][blue][off][off][dark blue][blue][off][dark blue][dark blue][off]
[blue][blue][blue][dark blue][off][blue][dark blue][blue][dark blue][off][off]
etc etc...

Would anyone happen to have code already like this?
Any help would be great! Thanks!

To make randomly-changing colours for the whole strip, change:
void loop() {
  rgbFadeInAndOut(0, 0, 255, ledFadeTime); // Blue
}

to:
void loop() {
  rgbFadeInAndOut(random (256),
                  random (256),
                  random (256), ledFadeTime); // random colour
}

If you want to make individual pixels different colours you could set up an array of colours, randomly initialize it, and use that. Like this:
#include <Adafruit_NeoPixel.h>

int PIN = 3;
int totalLEDs = 11;
int ledFadeTime = 5;

Adafruit_NeoPixel strip = Adafruit_NeoPixel(totalLEDs, PIN, NEO_GRB + NEO_KHZ800);

void setup() {
  strip.begin();
  strip.show(); // Initialize all pixels to 'off'
}

void loop() {
  rgbFadeInAndOut(ledFadeTime);
}

void rgbFadeInAndOut(uint8_t wait) {

  uint8_t red [totalLEDs];
  uint8_t green [totalLEDs];
  uint8_t blue [totalLEDs];

  // randomly set each colour
  for (int i = 0; i < totalLEDs; i++)
    {
    red [i] = random(256);
    green [i] = random(256);
    blue [i] = random(256);
    }

  for(uint8_t b = 0; b <255; b++) {
     for(uint8_t i=0; i < strip.numPixels(); i++) {
        strip.setPixelColor(i, red [i] * b/255, green [i] * b/255, blue [i] * b/255);
     }

     strip.show();
     delay(wait);
  }

  for(uint8_t b=255; b > 0; b--) {
     for(uint8_t i = 0; i < strip.numPixels(); i++) {
        strip.setPixelColor(i, red [i] * b/255, green [i] * b/255, blue [i] * b/255);
     }
     strip.show();
     delay(wait);
  }
}


text:
Arduino (or clone) powered with one or two AA batteries or one CR2032, but still able to give +3.3V or +5V
Are there Arduinos (or clones) that can be powered with one or two AA batteries or one CR2032 3V battery? (it would sleep 99% of the day, and only send a few bytes per day)
If so, will they also have a +3.3V or even +5V output (produced by an internal step-up chip) that can be used by another chip?
(I know it might sound like having one's cake and eat it too, but maybe it exists?)

there's a lot of 5v output boost dc-dc converters that would work a treat for AA batteries.

@dandavis do you think there are ready-to-use Arduinos or clones that would work with 2 AA and include a 3.3 V or 5V boost, out of the box?

not that i've seen, although i think they make power/battery shields that would handle it.

The modern low voltage versions of a bare ATmega chip can run from either 2xAA or a lithium coin cell - you wouldn't want to use a voltage regulator, as that is not only unnecessary but introduces losses but increases the required input voltage by its dropout meaning your circuit will fail earlier in the discharge curve that in it would without.
Bypassing the regulator on an Arduino Mini style of board is possible.  You probably do not want a board with an on-board USB-serial solution.
You'll need to make sure the clock rate is low enough for operation at the rated voltage (and for sleep efficiency).  This might involve using the fuse for the internal oscillator and ignoring a crystal/resonator that might be present, though if your board was originally intended for 3.3v operation it might be okay.
You will also need to set the brownout detector to the lowest voltage or disable it entirely - this again is in the fuses.
A boost converter to a higher voltage is possible but may not be a good idea, especially from a coin cell.  This is because to supply 1 milliamp at 5v, a boost converter must draw 2 milliamps at 2.5v - and then a bit more, to account for its own losses.  If you go shopping for a boost converter to use, make sure it has an enable, look at the quiescent power consumption when disabled and enabled without load, and look at the minimum input voltage.

Thanks @ChrisStratton. Do you think there are ready-to-use Arduinos or clones that would work with 2 AA and include a 3.3 V or 5V boost, out of the box?

Not that I'm aware of. Note that asking for recommendations of products to buy is off topic here.

Actually, I do think of one possibility - before they wisely abandoned the idea, some "drone" flight controllers were Arduino based and included a boost converter to allow 5v operation from a single lithium polymer cell.  This tends to have a higher minimum voltage than the power sources you are looking at, so you'd have to investigate the actual minimum operating voltage.  But it would be best to get the higher voltage requirements our of your design entirely - and realize that for micropower stuff you'll likely end up making your own board anyway.

Good idea! If you find a source/link about such Arduinos I'm still interested :)

That's probably too fine a distinction - besides, if someone said "yes that product exists" wouldn't your next questions be "what is it called" or "who sells it"?

I was wondering @ChrisStratton: The modern low voltage versions of a bare ATmega chip in which Arduino model is this present?

The chip would be present in any modern Arduino, but no Arduino board that I'm aware of can run off such a low voltage without being modified to remove the regulator, and probably also any USB/serial solution.


text:
Wifi radio with an Arduino
I've done a Wifi radio with a headless Raspberry Pi in the past (connecting a radio MP3 stream available on internet directly on boot, without any user input), and now I'm wondering: would it be possible to do the same with an Arduino, battery-powered?
Please correct me if I'm wrong but it seems that all these features are available:

battery-powered: this is definitely possible with a few AAs
audio output (easily possible with a DAC I think?)
Wifi (possible with a shield, right?)
Internet access to http://198.51.100.0/myradio.mp3 stream
real-ime MP3 stream decoding (Is an Atmega enough for this?)

Does this mean that a Wifi radio based on Arduino is possible?

real-ime MP3 stream decoding (Is an Atmega enough for this?) -- Certainly not, no.  I have managed it with a 200MHz PIC32. I wouldn't even begin to consider doing it with a tiny 8-bit MCU...

@Majenko I looked at ESP8266, and it seems possible. Is this really true, or do you think it relies on additional hardware chip?

Have you read the readme?

After re-reading now, yes it seems it's possible without any other chip, but not recommended (RAM is a plus for buffering and DAC for better output quality)

I have/had a wifi radio in the OpenWRT part of a Arduino Yún. OpenWRT is a minimal linux. For software decoding, I strongly advise to use some kind of linux computer, because they already have packages for mp3 decoding. There are Arduino projects using the VS1053 as a hardware MP3 decoder. An Arduino board with Ethernet Shield uses a lot of power, that is not something for a battery. What about an ESP32 with a hardware MP3 decoder ?

There are many types of Arduino boards (reads: many different platforms and processors) and many Arduino hardware add-ons.  If you spend enough, eventually you may find a platform and / or hardware combination capable of supporting your feature list.  However, it is likely the RaspberryPi will be able to support your feature list for far less money.  Certainly in much less time and effort.

if the ESP8266 looks possible, the ESP32 should be a lot better, what with it's dual-core and all...


text:
Is there a way to add external RAM (let's say 100 MB or 200 MB) in this audio buffer mixing context?
I'm coding a music sampler device: for fast playback / minimal latency (only a few milliseconds), it's better to have all audio .wav samples we want to use in RAM, so that when some of them are  played, the data arrays are immediately accessible. That's what I did for a Raspberry Pi project called SamplerBox. It was possible because RPi had 1 GB RAM.
Note: When using SDcard reading, and playing many notes at the same time (imagine a pianist playing a big chord), it's usually not good in terms of latency.
Now I'm thinking about porting this project to Arduino: in which extent can we add external RAM to an ATmega? Or if not "RAM", some volatile memory (let's call it "RAM2") that would be 10 times faster than reading an SD card.
What I'd like to achieve:

load 200 MB of audio samples into the "RAM2"
Max polyphony allowed = 100, so at a given time, all audio buffers that have to be mixed can be copied from "RAM2" to the "real" RAM of the microcontroller, and the mixing will be done with the (maximum 100 of them) buffers in the real RAM

I would think you'd want 100 Arduinos, each playing one sound indendently, each with it's on SRAM buffer that was very quickly played back via SPI bus and DAC, and then  mix all the outputs in analog domain (vs digital). Latency from trigger to DAC output will be next to nothing. Could load each from an SD card before playing - have one 'controller' to read the SD card and send the file to each arduino to store in its locally controlled SRAM.

There are SRAM ICs / boards, however, don't expect 100 MB, more like 1 MB (with the pin numbers and connectivity / protocols that an Arduino offers).
With Flash you can get much further, but it can only be written a number of times; not sure if that suits your requirements.
Beyond that, I'm afraid the real problem is in the processing speed. Mixing 100 samples with 48 KHz stero would mean (48000 * 2) = 96 KSamples/s. Since the Arduino is only 16 MHz you have just 16e6/96e3 = 166 clock cycles to mix all those 100 samples. Probably way too less.
Update
Winbond is a brand that is supported by Arduino libraries and the biggest supported IC is e.g. W25Q128FVSSIG, which is 128 Mbit, thus 8 MB. For 200 MB you need 25 of them which is quite a lot, and not sure if there will be issues using so many (let alone the cost). For this you do not need a file system, however you need to write it per page (if you want to do it efficiently). Which should be ok, since the SD card also is read per page (maybe not the same page size though).
However, you still have to copy the Flash memory into SRAM to be able to process it, so it's not the same as SRAM. Getting 200 MB SRAM will be very costly.

Thank you for your answer. Can we add a 200MB flash to an arduino? Can we use it as a RAM (just load arrays from a SD card to a memory buffer) or do we have to use a filesystem like a disk (then it's not really useful for audio buffers)

@Basj I updated my answer with your additional questions.

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


text:
PCINT0, PCINT1, PCINT2, etc. on ATtiny45/85
According to the datasheet:

we could think that, if we want to have a pin change interrupt for 3 pins, we have to create multiple instances:
ISR(PCINT0_vect){
   ...
}

ISR(PCINT1_vect){
   ...
}

ISR(PCINT2_vect){
   ...
}

void setup(){
  GIMSK = 0b00100000;
  PCMSK = 0b00000111;
}

However, this does not work, and I read here and here that we have to define just one interrupt function:
ISR(PCINT0_vect){
   if (digitalRead(0) == LOW)
     ...
   if (digitalRead(1) == LOW)
     ...
   if (digitalRead(2) == LOW)
     ...
}

Why is that so? What is PCINT1, 2, 3, ... made for then in this pinout schematics, if we don't have to use it?

You are confusing Pin Change Interrupt pins with Pin Change Interrupt vectors. The two are very different.
Many Pin Change Interrupt pins are associated with just one Pin Change Interrupt vector.
You use the pin number (the value shown in the pinout) to decide if you want that pin to respond or not. You use the vector to respond any of the pins that are assigned to that vector.
In the ATTiny chips, since there are so few Pin Change Interrupt pins (8 or less) you only need one Pin Change Interrupt vector to handle them.
You can know if "PCINT4" corresponds to a pin or a vector by the context. If you see it on a pin then it is a pin. If you see it in code with _vect after it then it's a vector.

Perfect answer, thanks!

That is simply the difference between an external interrupt INTx and a pin change interrupt PCINT. The first is an interrupt for a single pin. The second is an interrupt for a complete group of pins. Normally this group is a complete port. As the Attiny85 only has one port, this is the case here. So the whole group is only 1 single interrupt source. Thus it only has one interrupt vector named PCINT0_vect.
A pin change interrupt triggers, when any of the pins under it's supervision changes. You can remove pins from it's supervision by masking them with the PCMSK register.
So the interrupt vector PCINT_vect will be triggered by every change on any of the pins, that are not masked out. It is up to you to check, which one changed it's level.

On bigger microcontrollers, there are more pins and mostly also most of them are connected to a pin change interrupt. Here mostly every complete port is connected to a single pin change interrupt. Thus the corresponding registers are additionally marked with a number (PCINT0_vect as the interrupt vector for the first port, ...)

Ok, so in fact for ATtiny45, PCINT0_vect works for all the pins 0..5? Then why put "PCINT1", "PCINT2" on the pinout schematics? Then PCINT0_vect should be called PCINT_vect0, don't you think so? Because it's the the "first" vector of pin change interrupts... With a naming like PCINTx_vect, we could think it's relative to the pin x since the pinout schematics shows PCINTx for every pin x=0..5.

I cannot say, why they named them as such, that is only known by Atmel. A PCINT_vect0 doesn't exist, because their naming convention is <Interrupt Name>_vect for the interrupt vectors. For the pin description I think, they wanted to keep it short. On bigger microcontrollers, the PCINT pins are numbered completely though, so on the Atmega328P (from the Uno) there are pins up to PCINT20

Basically you need to understand what Pin Change interrupts are. Those things are normally explained rather detailed in the datasheet. For example this sentence from the External Interrupt section of the datasheet: "Pin change interrupts PCI will trigger if any enabled PCINT[5:0] pin toggles."

I know what they are, and I do understand they are grouped, but I don't understand the naming...

For example for the 328p, PCINT0_vect covers which group of pins? Idem for PCINT1_vect? I can imagine they can handle up to 8 pins each?

If you look at the register description for the corresponding mask registers in the datasheet, you see that each bit of the mask is marked with the corresponding pin name. Also in the description of the PCI enable bits you find the information, for which pins they are used and also which mask register.

Let us continue this discussion in chat.

You can enable/disable Pin Change INTerrupts for individual pins using the Pin Change Mask Register PCMSK.
The names on the pins map the bit in PCMSK to the physical pin.
You find more information in section 9.3.4 on p. 52 in the ATtiny85 Data Sheet

I did this with PCMSK = 0b00000111; indeed. But why don't we use PCINT1_vect? The pinout schematics mentions "PCINT1", why don't we use it?

Section 9.1 lists all available interrupt vectors. Pin Change Interrupts are grouped to not waste resources. Only INTx is dedicated to a single pin. It is also much more powerful, als it can be triggered on rising or falling edges instead of each change. ATtiny85 only has with INT0 one dedicated pin for that.

I understand that they are grouped to not waste resources @Kwasmich, but then if all pins can be handled with just PCINT0_vect alone, isn't this a mistake in the schematics to write PCINT0, PCINT1, ..., PCINT5?

No, again, it is to show you wich bit in PCMSK corresponds to which physical pin. Otherwise you would not know what pin is affected. The naming is ambiguos, for sure.


text:
Speeding up Girino gives strange readouts
I was reproducing the Girino (the Instructable by Caffeinomane) bundled with the Girinoscope (the Java GUI by Chatanga). The results worked well and I went on to see if the oscilloscope can go up to higher kS/s.
In short, originally only upto prescaler 8 works. I removed PWM pin and it works upto 4 but prescaler 2 strangely behaves. Here are the details:
I did a preliminary test on prescaler 32 (~38.5kHz). Settings as follows and the same in other tests.

The signal (the same hereafter) is generated by a 555 timer astable multivibrator running at 4.5V (3 AA batteries).
The circuitry was simply omitted. I just tied 3.3V of Arduino NANO / ATmega328 to digital pin 6 as the trigger level.
There is no +2.5V offset done by the original Girino. (The scale should be 0~5V and the signal is 0~4V)

So then I wanted to try if it can speed up more. The code optimization quoted by Chatanga allowed prescaler 8 and 16 (76.9kHz and 151.8 kHz).
In order to push it the poor Arduino to the limits, I disabled PWM pin in the original Girino which sets the trigger level with duty cycles (PWM from pin ~3 being fed into pin 6). It's because I simply used a fixed 3.3V trigger level.
Prescaler 4 is unlocked.

Ambitious I go on to test prescaler 2. The GUI did not provide this option so I simply set it in the Arduino code.

I thought it did not work. I noticed if the prescaler is exceeding the Arduino's capability, TXRX simply does not blink. But this time the TXRX is just blinking! To verify this, I shifted the wait duration.

In previous screenshots, the leftmost green line is dashed (probably because it's below fullscale deflection). But in the last two, be it offset or not, the line is solid.
The debug output is like this: (8bits 0~255 given by ADC)

many 0 then suddenly 255 thereafter. (matches the GUI output)

I suspect it's due to slow TXRX? How to solve this? Or anything I overlooked?
Hope that this overdetailed question does not sicken you.

Links: optimization code(https://github.com/Chatanga/Girinoscope/blob/master/doc/girino_optimization.md) and circuitry (http://i923.photobucket.com/albums/ad74/w_khs/g-001.png)

Just a thought. If you only care about low or high signals, why not use a digital read, instead of an analog read.

Yes that suffices for digital signals. But in fact I'm making an oscilloscope.

From the ATmega328P datasheet, section 29.8, "ADC Characteristics":

Clock Frequency — Min.: 50kHz, Max: 1000kHz

With a 16MHz system clock this means that a /16 prescaler is the most the ADC is considered reliable under for a reasonable 10 bit result (for a full 10 bit result the maximum frequency is 200kHz, which corresponds to a prescaler of /80).
As the frequency increases the sample-and-hold circuitry of the ADC gets less time to do the "sample" part before conversion begins. As such any correctness goes out the window, certainly at the lower bits. The fact that you got any sort of result that you did at /4 is luck.
TL;DR: The ADC is too slow.

Thanks for your quick answer! The original code sets a 8bit ADC. Does that explain why I can get a /4 result? Aside from this, how low should the resolution be if I badly need a, say, /2 prescaler?

At /2 you should not expect the ADC to work at all. What you need is a faster ADC.

So I shall buy a faster ADC IC.

Consider that you also need to get the results into the MCU fast enough as well though.


text:
Use std::list in Arduino programming
When trying to compile
#include <list>
std::list<byte> l = { 7, 5, 16, 8 };

in the Arduino IDE (with ATtinyCore for ATtiny4313), I get this message:

error: list: No such file or directory
    #include <list>

How to use the standard C++ std::list with Arduino/ATtiny?

I back up Michel Keijzers' suggestion to use a plain array, especially
given the tiny amount of RAM in your MCU (only 256 bytes).
Concerning the removal of items from the list, and given that your list
will be 16 bytes at most, you don't need to get fancy: just move back
the items that are past the one you removed. It will not take long.
Here is a barebones implementation of a list that can hold at most
16 bytes and supports removal:
class List {
public:
    byte length;
    byte data[16];
    void append(byte item) {
        if (length < 16) data[length++] = item;
    }
    void remove(byte index) {
        if (index >= length) return;
        memmove(&data[index], &data[index+1], length - index - 1);
        length--;
    }
};

Note that this only takes 17 bytes of RAM (16 items max plus a
length count). There is not vtable, as it has no virtual methods. You
can get fancier if you want, make this a template parametrized by the
data type and the maximum length, add accessors and such... but if you
are just writing a simple sketch (as opposed to a general purpose
library), I would recommend keeping it as simple as possible.
Example usage, based on your pseudo-code:
List l { .length = 3, .data = { 12, 82, 29 } };
l.remove(1);

This will indeed result in the list [12, 29].

Very useful, thanks a lot! Both answers are now very good, I don't know which one to choose!

PS: what is this syntax: List l { .length = 3 ... }; Is it a shortcut for something else to instanciate a class?

@Basj: It's an aggregate initialization: just filling the data fields, like in plain C. Handy when you are too lazy to write a proper constructor. ;-)

Thanks @EdgarBonet. Do you see a clever/lightweight way to find the index of a given element? Example: L = [12, 82, 29, 128].  L.indexof(29) would return 2. It's the last thing I need on these lists :)

@Basj: I see no clever way. But the list is so small that brute force is OK: just loop through the list until you find the element.

I did this, working!

I don't think that this library is supported by attiny (or even Arduino in general).
However, beyond that, it is not advised to use it, since it is uncertain how much memory and flash overhead it consumes.
Especially the memory is an issue for two reasons:

Internally, you don't know the exact data structures used for the list. In most efficient way, it will only use 4 bytes (4 times 1 byte for the array), however, since it is a class under the hood a vtable is added, and who knows what more memory (maximum capacity, current capacity of the list etc).
Also when adding/removing an item from the list, either the entire list is copied, or some tricks with pointers are used. In the first case you get memory gaps, in the second case maybe (and additional memory for the pointers is used).

My advice is to use just a simple array, and define a maximum of the array at compile time (if possible). Not as flexible, but robust, less memory usage and more reliable with a low SRAM  device like the Attiny (and Arduino in general).
Removing elements
Based on your first comment:
Removing items is indeed an issue, however, note that if you use the standard library it might copy the entire array (excluding) the new item, so temporarily you will have double the array AND a memory gap.
There are some ways to implement it yourself:

If you only want to remove items (and never add), add a new array with booleans that denote which are present and which are deleted (e.g. deleted[4] = 1 means that item 4 is deleted. This only cost 1 bit per element.
Use two arrays with items, and copy them back and forth each time. This will cause not really a memory gap, but you need the storage needed for two arrays. And keep a variable which of the two arrays is the 'current'.

Thank you for your answer. I would be happy to use a simple array (I need a list of 16 bytes maximum anyway). The only thing I cannot do easily with a simple array is this (pseudo-code): L = [12, 82, 29] => L.remove(index=1) => L = [12, 29] i.e. remove elements in the middle or at the beginning. Any idea how to do this easily without reinventing the wheel?

I updated my answer (only works for deleting items, adding items might be more tricky).


text:
Arduino Pong game Circuit Board Troubleshoot
I am following a tutorial online to make a pong game. I have managed to make quiet a lot work apart from my paddles in the game keep on shaking. The buttons do work fine, up and down on both ends.
Tutorial Link
I am sure, there is something with the power being supplied and not reaching to all points in the breadboard.
I am attaching a picture of my circuit board. Any advice?
Thank you,
W

The + and - along the bottom of the picture aren't connected to anything.
It also looks like this board has a separate left and right side.
So just make sure everything is connected along the sides.

Do you mean, I should supply the + & - from top side to the bottom?


text:
Using Interrupt on Arduino
I'm currently working on a project in which I'm supposed to make an Arduino car dodge any kinds of obstacles. I know how to do without using Interruptions but as I was searching online I found out that this is something that is used and would turn out better. Is it really possible? And if so, I don't exactly grasp the concept of using it to make (for example) the car stop once it senses an object. I know that it is supposed to be the first thing it will do if I program it that way but, can I program how the Interrupt will act upon the machine? And if so, how exactly?
Thanks

Interrupts help if an event needs to be dealt with over the time period of a few processor clock cycles. Such as the deployment of air bags.  If the accumulated delay of not responding in a few processor clock cycles adds up to considerable error.  Such as a Real Time Clock (RTC). Or, if an event is so short that it might be missed during periodic polling (checking). Such as counting flashes of lighting during a storm.
If this type of response time is not needed, interrupts may be more trouble than they are worth.
This is because interrupts can stop the processor from executing the normal program and force it to execute the interrupt program.  This can be very confusing to new programmers.  At any moment an interrupt may stop their program and possibly erase or change what that program was working on.  Both the program that is running and the interrupt program need to be written to tolerate this processor behavior.
It is almost always easier to "poll" the state of obstacle sensors (in this case) rather than tying its state to an "interrupt".  Using the Arduino paradigm, the purposes of the loop() entry point is to do just this.  A function which will be called over and over again.  Each time it is called you can "poll" the sensor and cause the model car to vier around an obstacle.

Yeah, your bot would have to be moving awfully fast to really need an interrupt to respond to an obstacle.  For most of these types of bots you have a few milliseconds to react.

Is it really possible?

anything is possible.

And if so, I don't exactly grasp the concept of using it to make (for example) the car stop once it senses an object.

all an interrupt does is to take the execution to a different place. in practical terms, an interrupt would execute some quick functions and set some flags for the main loop to execute.
interrupts are critical to embedded engineering and it is very difficult for a real-world code to run without interrupts.

See How do interrupts work on the Arduino Uno and similar boards?

I was searching online I found out that this is something that is used and would turn out better. Is it really possible?

That's very vague. What did you find online?

And if so, I don't exactly grasp the concept of using it to make (for example) the car stop once it senses an object.

Set a flag in the interrupt, which you detect in your main loop. In the main loop make the car stop when the flag becomes true.


text:
How to convert this prototype to finished product?
My prototype contains below components:

Arduino Uno R3
Bluetooth LE nRF8001 Break-out (https://www.adafruit.com/products/1697)
MicroSD Break-out (https://www.adafruit.com/products/254)
ADXL335 triple-axis Accelerometer

I think It's OK on paper (and presumably on a breadboard too). I'm trying to wrap my head around on how to convert it to a finished product that sits inside a plastic box.
What are my options?
For instance, can I create a single PCB that contains all the components? If not, how can I connect these multiple break-out boards together? Is soldering some wires on both boards to connect them is a viable option?
Edit:
My ultimate goal is to create a product that is for sale. So I mean something that can be mass-produced and can meet regulatory requirements.
This is why I was thinking about a single PCB. Arduino (or should I say ATMegaXXX?) is fairly simple to place on a custom PCB. So I was thinking perhaps I could "re-create" my break-outs (see above) on this PCB thus creating a single piece including all components and the microcontroller. For some reason this makes sense to me but I don't know how hard it is or if it is even possible.

Chances are you can drop the ATmega and run it all on an nrf51822, so you only need the rf matching components, crystals, caps and ferrites, accelerometer, sd socket, and supply.

First, you should read this this question here.
The reasonable answer here varies a lot depending on how involved you want to get, and what volumes you want to sell at.
Fortunately, you're not using any breakouts with truly exotic parts. The nRF8001 is just a QFN part, which can be soldered by hand without too much trouble.
Speaking loosely, the process would look like this:

Design a PCB layout that contains everything.
(Optional) - Figure out if you want to put it in a enclosure of some sort.
(Optional) - Determine how you're going to have the enclosures produced or modified from an existing product. You can have a contract machine-shop do the work, but again, $$$$.
Send out to have PCB prototypes manufactured. I like OSHPark, but there are LOTS of options.
Assemble your boards.
Find out your prototype doesn't work.
Go back to step 1 (expect this to happen a few times)
Rent/Beg/Borrow some equipment to do EMC pre-qualification testing (for FCC).
Realize you have an EMC disaster.
Respin boards a few more times (e.g. go back to 1 again) to fix the pre-qualification EMC issues.
Feel like you have a decent layout, have it FCC tested.
Pay $10K+ for FCC testing.
If you're lucky, you passed, you now have a proper, FCC certified product.
Nope, go back to 1 again if you failed.
Do lot assembly, either manually (major time investment), or contract out (expensive!).
Sell your widget!

Note that you can contract out the prototype assembly, but doing so is expensive, even if you do it in china. The magic (or cursed, really) term here is "NRE", or non-reoccurring expenses/engineering. Colloquially, it's the "setup cost" of doing a production run. Sure, you may only pay $5-50 per-widget to have them assembled, but there will be a $1000+ base charge. This reflects the fact that the primary time-cost on the part of an assembly house to build your widget is setting up the production line, working up and debugging a pick-and-place routine, building test-setups, etc... Once everything is up and running, the actual per-unit cost is fairly marginal.
This is also why commercial electronic devices can be so cheap. They're made in truly enormous volumes, and that lets the companies amortize the NREs across the entire production run. NREs are basically the bane of any small electronics business. They're also basically the reason specialty widgets are so expensive. Places like spark-fun can get away with fairly cheap products because they have their own complete assembly line in-house, and even there, you're often paying 4X+ the cost of parts for just the IC on a PCB with a few cents worth of passives.
Since you seem to be new to PCB design, this is possibly not a great first project. It's doable, but expect it to cost 4X+ what you expect, and take 2X+ the time you planned. There are a LOT of facets to designing a proper product, and they each contain an entire field.
It'd probably be better off to start out with some simpler boards, maybe a through-hole-only arduino clone, or similar (though SOIC can be soldered without a hot-air station or anything).

Some assumptions I'm making:

If you're serious, you will have to lean SMT assembly practices. Through-hole only is not a viable stance anymore.
Expect to buy a lot of tools, and burn a lot of money in failed prototypes.
Expect 3 board revisions. At minimum, before you have something you can get tested. I could maybe do it in 2, if I got really, really lucky, but I doubt that would happen, and this sort of thing is my day-job.

Hardware is HARD, and worse, it's completely unforgiving. If you're coming from a software engineering background, you basically have to discard all your assumptions, as they will actively hurt you.
Imagine a software project where "compiling" can take 4 weeks. That's hardware development.

You'are right, I'm totally new to PCB design (I've never done it before) and I'm 99.9% a software engineer. I think your opinion on how hard Hardware is absolutely right. Fail and learn cycle can be extremely long compared to Software and all those "guides" and "tutorials" on the internet will take you nowhere but blinking LEDs all day like a crazy person. Also, since I'm currently located in Bahrain, multiply that 4 weeks with 2 or 3.

@frbry - I'm not trying to discourage you, hardware design can be tremendously rewarding and fascinating. However, it brings a whole suite of challenges with it, and you should make sure you know what you're getting into before spending a lot of money on prototypes, etc...

By "product", do you mean for sale? Giveaways to friends? One for yourself? How many do you expect to make? It isn't (monetarily) worth creating a board for one or five pieces unless you want to for reasons of aesthetics, reliability, demonstrating your skills to a potential employer, etc. OTOH, if you sell a product, it will to meet regulatory requirements in the jurisdiction(s) in which you intend to sell it. So the - admittedly unsatisfying - answer is: it depends. :)  (In other words, we need more information).
Chinese board houses advertise they can do small runs for quite reasonable prices, but expect to spin the board several times unless it's a pretty simple one. Not dissing their abilities or skills as I have no experience with any of them, but as a practical matter of communicating exactly what you want, the first time, to a business half a planet away, a business you might not be familar with yet, and someone with whom you might not share a native language. Even with those obstacles out of the way, boards can take several- to many spins to get to a first production revision.
For a small handful of boards (depending the size of a "handful"), hand-wiring on hobby PCBs or strip-boards can be effective and not too expensive.

Hi, thanks for your response! I've updated the question with some additional information.

Adafruit's breakouts are great at making available to experimenters, devices that would be too difficult for most of us to build with. If you're intending to hand-build your boards, soldering surface-mount devices might be a show stopper; if so, breakout boards would be key. But if the numbers warrant, you'd probably contract out the boards, with the bare devices on them. If you're going for regulatory approvals, that's almost a requirement, just to limit the number of things that could prevent your device from passing.

Could you please elaborate more on how I can contract out the boards and what the bare devices mean? :)

By bare devices, I meant using the ICs directly on your PCB, i.e., without a breakout board. It will be cheaper, smaller, and won't have a bunch of off-board wires to radiate garbage that will prevent your device passing certification. For board fabricators, LadyAda reviews a few of them; a quick search will turn up many, many more.

step1: Make the hardware

Refer the schematics of arduino you are using and make your own pcb
Approach any PCB manufactures and deliver them your GERBER files with correct Bill of Materials.
You can easily make a single PCB. consider PCB with components on both sides, and multi stackable PCB only if the dimension of required PCB matters.
Try not to place nRF antenna and crystal for the micro controller close to each other.

Step2: Firmware
This step is about getting .hex file from arduino code and givin this to the same pcb manufacturer, with proper fuse values

Go to file->preferences in arduino
Check show verbos
open the temp file (type %temp% on RUN)
Compile your arduino code. this will generate a build folder inside temp
folder Search for yourArduinoProjectName.hex inside that folder.

This is the code you need  to get fuse bits
#include <avr/boot.h>;
void setup() { Serial.begin(57600);

cli();
uint8_t lowBits      = boot_lock_fuse_bits_get(GET_LOW_FUSE_BITS);
uint8_t highBits     = boot_lock_fuse_bits_get(GET_HIGH_FUSE_BITS);
uint8_t extendedBits = boot_lock_fuse_bits_get(GET_EXTENDED_FUSE_BITS);
uint8_t lockBits     = boot_lock_fuse_bits_get(GET_LOCK_BITS);
sei();

Serial.print("Low:  0x");
Serial.println(lowBits, HEX);
Serial.print("High: 0x");
Serial.println(highBits, HEX);
Serial.print("Ext:  0x");
Serial.println(extendedBits, HEX);
Serial.print("Lock: 0x");
Serial.println(lockBits, HEX);    }
void loop() { }

Or check the file

C:\Program Files (x86)\Arduino\hardware\arduino\avr\boards.txt

to find the fuses.

Single PCB is not viable, as some chips are near impossible to solder by hand. Also, you'd have to get your PCB checked for FCC compliance (because of the bluetooth), which you don't want.
You could design a PCB that contains the Arduino micro controller (ATMega328), and that all the other board plug into.
Wires could also be a solution, by you probably need to find a way to securely mount all the boards inside the enclosure (no rattling).
PS I'd suggest something like an Arduino Nano as it's smaller, and you can remove the header pins and solder wires directly to PCB.

Hi Gerben, why don't I want my PCB to be checked by FCC? Isn't it the standard procedure? Probably a newbie question, which I definitely am.

It would cost a huge amounts of money. Also, if something isn't okay, you'd have to have it rechecked, costing more money.

I don't see a single chip anywhere on those eval boards that's even that challenging to solder. Furthermore, if you're designing your own PCB, not just using a plain ATmega328P is just violently silly. Why pay all that money for the Arduino people to do a little soldering for you?

A $100 hot air station will save a lot of aggravation when playing with QFN. If that is considered a big ticket investment the project is implausible.


text:
Arduino hangs on second GSM message (was GSM based led matrix display)
Friends, my team and I are working on a gsm based wireless display as a part of our project. We are using Arduino UNO as the microcontroller which is interfaced with a sim900 module. Upon arrival of a new sms in the gsm module, its contents will be passed on to the dot matrix led display through SoftwareSerial. We almost got the code working but the problem we now encounter is the reception of new sms. The code works fine for the first sms but to display the next new sms, we had to manually reset the Arduino every time. Can you guys help me? This is the code:
#include <SoftwareSerial.h>
#include <SPI.h>
#include <DMD.h>
#include <TimerOne.h>
#include "SystemFont5x7.h"
#include "Arial_black_16.h"

#define DISPLAYS_ACROSS 1
#define DISPLAYS_DOWN 1
DMD dmd(DISPLAYS_ACROSS, DISPLAYS_DOWN);

int temp=0,i=0,x=0,k=0;
char str[160],msg[160];
void ScanDMD()
{
  dmd.scanDisplayBySPI();
}

SoftwareSerial SIM900(0, 1);

void setup()
{

   Timer1.initialize( 5000 );
   Timer1.attachInterrupt( ScanDMD );

   dmd.clearScreen( true );
   Serial.begin(9600);

   SIM900.begin(9600);
   void SIM900power();
   delay(20000);

     SIM900.print("AT+CMGF=1\r");
  delay(100);
  SIM900.print("AT+CNMI=2,2,0,0,0\r");
  delay(100);
}

  void SIM900power()

{
  digitalWrite(9, HIGH);
  delay(1000);
  digitalWrite(9, LOW);
  delay(7000);
}

void loop(){
for(unsigned int t=0;t<60000;t++){
  void serialEvent();
  if(temp==1)
  {
    x=0,k=0,temp=0;
    while(x<i)
    {
      while(str=='#')

      {
        x++;
        while(str!='*')

        {
          msg[k++]=str[x++];
        }
      }
      x++;
    }
   }
  }
     const char* dchars;
      dchars=msg;
     dmd.clearScreen( true );
   dmd.selectFont(Arial_Black_16);

  for(unsigned int i=0;i<=300;i++){
   dmd.drawMarquee(dchars,strlen(dchars),(32*DISPLAYS_ACROSS)-1,0);
   long start=millis();
   long timer=start;
   boolean ret=false;
   while(!ret){
     if ((timer+30) < millis()){
       ret=dmd.stepMarquee(-1,0);
       timer=millis();
     }
   }
 }
}

void serialEvent(){
  while(Serial.available())
  {
    char ch=(char)Serial.read();
    str[i++]=ch;
    if(ch == '*')
    {
      temp=1;
    }
  }
}

The DMD library was found on the net.

Please use the code format button to format the code properly.

i did @Avamander

Surely you have noticed there are syntax errors in your code?

The code compiled successfully i can't find errors.can u pls pin point them

I have confusions in value passing through buffer and once this buffer value enters dmd loop there is no way out, hw can i improve that

Does nothing clear 'i' at the end of a message?  If not, then long/unexpected/multiple messages can overflow your str[160] buffer.
It also looks like writing to the msg[160] buffer isn't well protected from overflow.

How can i protect msg(160) from overflow,can you please share the code

strncopy() is made for copying strings up to the length of a buffer.  I'd set a const int buffermax = 160; and use that as one limit on incrementing the buffer indices.


text:
Regarding the USB port, what is the difference between Uno/Mega and the older boards?
I would like to know what the exact difference is between the Uno and Mega boards and the older boards (Duemilanove, Diecimila, etc.).  Why do I need to install a FTDI driver for the older boards, and not for the Uno/Mega boards?  I was in a class the other day, using the Nano, and the lecturer recommended the FTDI drivers. The Nano is a newer type board, so why does that require a driver? I've just discovered that the Nano is old tech from 2008, after reading Are there any reasons to pick Nano over Micro?
What is it about the Uno and Mega boards that don't require the FTDI to be separately installed?
I see that the Getting Started w/ Arduino on Mac OS X page states that the older boards use the FTDI chip. Does that imply that the Uno/Mega boards do not? If they do not, then what do they use?
I have a vague notion that some USB sticks, keyboards, mouse and other various USB devices may contain a driver within the circuitry/firmware(?) of the device, which when connected to a PC for the first time, can be used to install the driver without the PC needing to access the web for the driver. Is this what the difference is between the UNO/Mega and the older devices? If so, is it possible to modify, or flash the firmware of the older boards so that they can connect without the need for an FTDI driver?

The older Arduino boards used an FTDI FT232R chip to handle the USB port. This chip is a special purpose, USB to serial UART interface.
In the current Arduino boards, the USB to serial conversion is handled by dedicated Atmel Atmega8u2 processor. This is a processor that is similar to the main ATmega328p processor, but the added benefit of having built-in USB capabilities.
So, why the change? Well, first, it's cheaper than the FTDI chip, and second, it can do much more. Being that it's an actual microprocessor, you can actually reprogram this chip to behave like different USB devices. For example, you can reprogram it to make your Arduino look like a keyboard, a joystick, a thumb drive, a MIDI instrument - anything that you can do via USB. The FTDI chip does not have this capability, and so it can only ever look like a serial COM port to your PC.
Why have 2 microprocessors on the Arduino? By having a dedicated processor to handle the USB communication, it keeps the main processor free to run your sketches. Plus, the Arduino team felt that this design keeps the Arduino more "hackable".
Wouldn't it be cheaper to make a board using just the one processor that has built-in USB? Yes! That is exactly what the Arduino Leonardo is. It uses the Atmega32U2, the big brother to the Atmega8U2.


text:
I need a random code for Arduino Uno to trigger a single relay
I am trying to get a random triggering of a single relay from an Arduino Uno. I would also ultimately like to be able to adjust the speed that the random triggering happens at. How are the times between the randoms adjusted?
I have tried some codes and have the relay hooked up to pin 8 on the Uno, and would like more control. Thanks
void setup () {
pinMode(8, OUTPUT);
}

void loop() {

long randnumber;
long randnumber2;
long randnumber5;
long randnumber6;

randomSeed(analogRead(A0));

randnumber = random(5, 9);
randnumber2 = random(5,9);
randnumber5 = random(3370,498);
randnumber6 = random(537,4370);

digitalWrite(randnumber, HIGH);
digitalWrite(randnumber2, LOW);
delay(randnumber5);
digitalWrite(randnumber, LOW);
digitalWrite(randnumber2, HIGH);
delay(randnumber5);
}

Can you show us the sketch you are using now?

Use the blink-without-delay https://www.arduino.cc/en/tutorial/BlinkWithoutDelay Remove the 'const' of the variable interval, and use random https://www.arduino.cc/reference/en/language/functions/random-numbers/random/ for the interval. Set the new random interval inside the if-statement. Adjust the min and max parameters of the random for speed control.

VE7JRO, Here is the code I have so far:       void setup () {
pinMode(8, OUTPUT);
}
void loop() {
long randnumber;
long randnumber2;
long randnumber5;
long randnumber6;
randomSeed(analogRead(A0));
randnumber = random(5, 9);
randnumber2 = random(5,9);
randnumber5 = random(3370,498);
randnumber6 = random(537,4370);
digitalWrite(randnumber, HIGH);
digitalWrite(randnumber2, LOW);
delay(randnumber5);
digitalWrite(randnumber, LOW);
digitalWrite(randnumber2, HIGH);
delay(randnumber5);
}

This is my 1st Arduino project

@WaddyP consider editing your original post by adding your code section. Non trival code in a comment section is nearly unreadable.

Yeah, don't post multiple lines of code in comments. Edit your question and add the code using code tags.

RamblinRose, don't know how to do that. I am new here

there are 4 buttons just below your question .... one of then is edit


text:
Why are the PWM variables in this RC code snippet handled this way? What are the magic numbers?
tcommand=(pwm_value-480.0)/8.22;
flapmag=(pwm_value-880)/41.0+10;

In this piece of code used in arduino radio control aircraft, I don't understand why PWM value is subtracted and divided like this. This is not my code, it came from here. Any explanation would be of great help. I have read about PWM but all have different explanations.
//Arduino servo flap system
//copyright Steve Morris 10-25-16
#include <Servo.h>
volatile int pwm_value = 0;
volatile int prev_time = 0;
static int servo_comm1 = 0;
static int servo_comm2 = 0;
volatile int flapangle1 = 0;
volatile int flapangle2 = 0;
volatile int millisold = 0;
int millinow = 0;
float dt = 0;
float flapmag = 0;
static float flapdeg = 0;
float tcommand = 0;
float floattime = 0;
float temp = 0;
float glide_deg = -10.0;
static int pwm_value_temp = 0;
float omegadot = 0.0;
float thetadot = 0.0;
static float omega = 0.0;
static float theta = 0.0;
static float k0 = 1.0;
static float k2 = 10.0;
static float servo_zero1 = -4;
static float servo_zero2 = 0;

Servo myservo1, myservo2; // create servo object to control a servo

void setup() {
  //Serial.begin(115200);
  // when pin D2 goes high, call the rising function
  attachInterrupt(0, rising, RISING);
  myservo1.attach(5); // attaches the servo on pin 5 to the servo object
  myservo2.attach(6); // attaches the servo on pin 6 to the servo object
}
void loop() {

  millinow = millis();
  floattime = millinow / 1000.0;
  dt = (millinow - millisold) / 1000.0;
  millisold = millinow;

  tcommand = (pwm_value - 480.0) / 8.22;
  omegadot = k0 * tcommand - k2 * omega;
  thetadot = omega;
  flapdeg = sin(theta);
  theta = theta + omega * dt;
  omega = omega + omegadot * dt;

  flapmag = (pwm_value - 880) / 41.0 + 10;
  flapdeg = flapmag * sin(theta); //variable amplitude+freq

  flapangle1 = (int)((30.0 - flapdeg + servo_zero1) * 2.0 + 25.0);
  flapangle2 = (int)((30.0 + flapdeg + servo_zero2) * 2.0 + 25 .0);

  if (pwm_value > 930) {
    servo_comm1 = flapangle1;
    servo_comm2 = flapangle2;
  }

  //Glide Lock
  if (pwm_value < 910) {

    servo_comm1 = (int)((30.0 - glide_deg + servo_zero1) * 2.0 + 25.0);
    servo_comm2 = (int)((30.0 + glide_deg + servo_zero2) * 2.0 + 25.0);

  }

  myservo1.write(servo_comm1); // tell servo to go to position in variable 'pos'
  myservo2.write(servo_comm2); // tell servo to go to position in variable 'pos'

  //Serial.println(servo_comm1);
  //Serial.println(floattime);
  //Serial.println(dt);
  //Serial.println(flapangle);
  //Serial.println(flapdeg);
  //Serial.println(temp);
  //Serial.println(tcommand);
  //Serial.println(pwm_value);

}

void rising() {
  attachInterrupt(0, falling, FALLING);
  prev_time = micros();
}

void falling() {
  attachInterrupt(0, rising, RISING);
  pwm_value = micros() - prev_time;
}

There is not enough context to be certain, but given the variable names I can assume that this is code from a sketch that receives information from an RC controller and is intended to control parts of some form of flying craft.
So with that in mind, let's take this line:
flapmag=(pwm_value-880)/41.0+10;

I assume that this is to calculate the amount the flaps should be extended or retracted.
RC controllers, or rather the receivers that pick up the signals, usually output a PWM signal (square wave with a variable duty cycle) where the duty cycle is directly related to the position of the joystick.
A joystick is usually zero in the center and goes plus or minus for up and down (or right and left). But you can't have a negative PWM value, since that makes no sense (how can you have a signal that is off for less that 0% of the time?!).  So the output is "offset" by a certain amount (that's not quite true - actually the joystick is 0 for fully down, and 100% for fully up, with "0" being somewhere in the middle, so the offset is applied by the joystick, not the receiver, but that really doesn't matter for us right now).
So we have a signal that is at any time somewhere between 0% and 100%, with "zero" being somewhere in the middle.  What actual value the "100%" is, or exactly where "zero" is, can vary depending on many many factors, so we'll just use "100" for the maximum, and "50" for the middle "zero" offset.
The first thing you want to do, then, is remove that "zero" offset. And that is as simple as subtracting it.  With our example numbers above, if you subtract the "zero" offset of "50" from the incoming signal it now goes between -50 and +50 instead of 0 and 100. That now relates much better to how a joystick appears - 0-50 in an upwards direction (+) and 0-50 in a downwards direction (-).
And that is exactly what is happening with pwm_value-880 in your code.  The middle "zero" value of 880 is being subtracted from the incoming joystick position to give you an "up" or "down" value that is positive or negative respectively.
Next comes the division.  This scales the incoming value to the right size for the device you are driving. In our example we have a ±50 signal. But what if our flaps require a ±10 signal to give the correct movement range. So simply dividing the value by 5 will change ±50 into ±10. That's exactly what the /41.0 is doing - scaling the result to fit the range of the target device.
Then there's one final +10 in there. This simply adds a small offset to the result. You can think of this as a "trim" value. It sets the actual "zero" point of the target device - in this case when the joystick is centered it means the flaps are set to a +10 position.
As to how the pwm_value itself is created, that is usually done through capturing the rising and falling edges of the incoming waveform from the receiver and timing how long the signal is in the HIGH or LOW state. That may be performed by some unspecified library.

Actually, this is what I was asking. Thanks for the information.


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 creates strange files in SD card
I'm new to Arduino and electronics. I want to make a project including SD data-logger, but I had a problem. I would appreciate if someone show me where I made a mistake.
Firstly, circuit  was set up as in picture:

I am using 8 Gb micro SDHC card with SD adapter. I formatted in FAT32. I can play audio files which are in appropriate format and read and the print contents of text files.
But when I want to create a new file, strange file is obtained in SD card as in pic:

So I reformat SD card. the code that is used while creating file is as this;
// open a new file and immediately close it:
Serial.println("Creating example.txt...");
myFile = SD.open("example.txt", FILE_WRITE);
myFile.close();

Somewhere I read SDHC card with more than 2 Gb capacity  is not supported in Arduino and I bought 2 Gb SD micro with SD adaptor.
But in this case aurduino does not detect SD card. please someone help me.

Please post all of your code and format it right. (Also, if you are talking about yourself (I am, I will and so on) then capitalize the "I").

I formatted with SD formatter 4.0 but did not make difference.
Probably, aurduino doesn't support some SD cards, this problem looks like some cd driver or writer doesn't detect some compact discs.
I have two micro sd one of them 8 gb micro sdhc - sandisk  - this is supported reading but not supported for writing
other one 2gb microsd- noname - this is not supported for reading and writing
is there someone tell me mark and type of sd card to be able read and write successfully.

https://www.arduino.cc/en/Tutorial/Files this is code I work on

It sounds like you tried using a card that is too big, so it didn't work. Then you bought some cheap 2GB cards that either don't work full-stop or don't have SPI support. Bite the bullet and buy cards from a reputable retailer.

instead of buying new sd card because it is hard to find good quality 2gb capacity I am considering buying microsd module http://urun.n11.com/diger/arduino-micro-sd-kart-modulu-spi-P70554983?cid=604001&gclid=CLKEgqXyjcgCFUbmwgod5XgOcA which is supporting sdhc etc.

@dursung - SDHC support mostly depends on software, so that module won't help you.

It's a long shot but check your wiring and voltage levels. I've seen similar corruption issues when writing to SD cards when the power supply to the card wasn't quite up to the job.

I've had similar issues with large (> 1Gb) SD cards, I've had various different problems with different cards, some things that helped me debugging the problem:

make sure your wires are the same length and try to use short wires
make sure your power supply is sufficient, sd card readers can draw up to 150mA
format the card in either FAT16 or FAT32 and never use "quick erase", try to use official tools (like https://www.sdcard.org/downloads/formatter_4/index.html)
make sure if you're the correct BAUD rate (9600) to talk to your card
filename support is pretty old so keep them short and don't use spaces or special characters
make sure the SD card is not in "write lock" mode, there's a small switch on the side of some SD cards that can prohibit writing (but will allow reading)

Note that write protection on a SD card is dependent on the socket and host honoring it; turning it on does nothing to actually prevent the host from writing successfully to the card.

Also, SD uses SPI, not UART, so "baud rate" is irrelevant, only the serial clock speed.

I've seen this exact issue before being caused by power supply brownout. There is a current spike during writes, if the voltage drops too much you get this effect. Slower/smaller cards are less prone to it because they have a smaller spike. Improving the power supply to the card fixed it.

I have faced this problem. Try

If you are using multiple devices with SPI communication ignore the others by keeping their slave select HIGH
Never forget file.close()

If file.close() is so important wrap the file access in a class so close is always called in the destructor.


text:
Any way to not explicitly include dependent libraries?
When I am including the Adafruit_BMP280 library, Arduino IDE 1.7.10 complains that it wants all dependent libraries included:
Adafruit_Sensors.h
Wire.h
SPI.h

Isn't it possible to circumvent that? This question says to include the first library like
#include "Adafruit_BMP280"

but also with the full path, this doesn't work and just returns the same error.

You could put these includes in a separate file, and include that file? I'm not sure if that's what you mean? Or probably include them in the BM280 file? I'm actually not sure. Maybe newer versions of Arduino IDE, I don't believe I ever had to include SPI?

No, it is not possible. The IDE needs to know which libraries you are using so that it can compile the source code for them.
Other IDEs have got around the problem by recursively scanning the libraries themselves and building up a list of dependencies (such as UECIDE) but this is not something that the Arduino IDE has been programmed to do.
The only other possible option might be to create a single massive library that contains everything that the "main" library relies on, however this may cause problems with other libraries also wanting the same things and you ending up with massive conflicts.