text:
Powering Infrared and Sonar sensors using BEC
I'm new to Arduino. I'm using Arduino Mega 2560 board & MATLAB Simulink-Arduino support package and trying to integrate Maxbotix Sonar and Sharp IR sensor for my class project. When I powered single US sensor from Arduino 5V output, the readings are fine. However, when I tried to power IR sensor in parallel with US sensor, IR readings are fine but US readings fluctuate.
So, I tried powering the sensors using BEC (5V-3A). The readings for both sensors are fluctuating(extremely noisy). From the specification mentioned by manufacturers, Maxbotix US sensor draws 2mA of current, whereas IR sensor averagely draws 20mA. Is there any way to solve this problem?
Thank you.

I've managed to solve the problem. When external power supply is used to power multiple sensors, connect the GND of that supply with that of the Arduino GND input. For more details, refer to the link below.
http://www.thebox.myzen.co.uk/Tutorial/Power_Supplies.html


text:
How to debug MIDI input?
I'm trying to receive MIDI messages on a Leonardo. To do that I used the circuit in the diagram below (only the top half for receiving). The only thing I did differently was using an 1N4148 diode instead of the 1N914. I connected GND to pin GND, 5V to pin 5V and RX to pin 0 (RX), and I used code below to see whether I do get any inputs or not. (I first started with some more complex code but it seems this is the minimal thing I can do.) As a MIDI source I used an Arturia Keystep which I tested on a midi instrument.
Unfortunately I don't get any input, and I don't know why. What I tried so far:

Verified the polarity of all cables, and made sure all connections work.
Swapped the Leonardo with a different one (both new).
Swapped out the 6N137 optocoupler with another one (both new).
Addded above the if-statement a Serial.println("test"); which then resulted in an endless avalanche of "test" in the serial monitor - just to check if the USB connection works.
Measured the voltage between pin 5 and 8 on the 6N137 and it is indeed 5V.

Is there anything obvious I'm doing wrong? What things do you suggest doing to try to find the bug? (I do have a multimeter but no oscilloscope.)
 (from this answer).
byte b;
void setup() {
  Serial.begin(9600); //USB
  Serial1.begin(31250); //MIDI
}

void loop() {
  if (Serial1.available() > 0) {
    b = Serial1.read();
    Serial.println((int)b);
  }
}

I don't see any obvious problem, but I used a similar circuit (long time ago though), and I used an 1N4148 without any problem. I had some trouble using the correct resistor value, and I added ferrite beads, but this should not be a problem on a breadboard.

Have you checked the plugs according to diagram => solder side.

perhaps you reversed pins 4 and 5

@Codebreaker007 I think that is it, it seems I have swapped pin 2 and 3 on my stripboard. I'll try to fix that and report back - it would be nice if it was that simple:)

https://learn.sparkfun.com/tutorials/midi-tutorial/all

@MichelKeijzers Thanks, that is good to know. What are these ferrite beads you mentioned?

They are for reducing EMI, shouldn't be any problem in a normal environment.

@Codebreaker007 It was exactly that, I swapped pin 2 and 3, thanks for mentioning that - with all the warnings about this I thought i wouldn't make such a silly mistake:)

The solution:
On the image is stated plugs are solder-side. So swapping pin 2/3 does the trick

Actually I should have clarified: The picture is a top down view on the component side - my mistake was that I misinterpreted the diagram:)

I think problem is in baudrate of your USB, message from usb is slow and this destroy MIDI message (timing of 31250 baudrate). Set little bit faster USB serial speed. And make buffer between.
Is only try, i dont know if its solve this problem.

Hi devbob, the problem was already solved and acknowledged.

source: Stack Exchange

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

sort: votes


text:
How long will program stay in memory without power?
Let's say we program an arduino uno or nano and then stop using it for a while. How long can we expect the program to last on the arduino?

More than 20 years, and probably more than 100 years.
That's the guaranteed minimum:

Data retention: 20 years at 85°C/100 years at 25°C(1)
(1)  Reliability Qualification results show that the projected data retention failure rate is much less than 1 PPM over
  20 years at 85°C or 100 years at 25°C.

Practically forever. Rather make sure the contacts don't become too rusty.
( 83.7 % of Arduino problems are mechanical and contact issues :) )
Will your grandchildren still have a legacy USB cable and be interested in that thing and your c++ coding skills then?

upto 20 years at 85°C and upto 100 years at 25°C

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


text:
How to send a pitch bend MIDI message using arcore?
I'm new to MIDI and started playing with an Arduino Leonardo and arcore.
Based on the example code, I can easily send noteOn/noteOff/controlChange messages, but I can't seem to send a pitch bend message.
Having a look at this table:
0xE0    Chan 1 Pitch wheel range    Pitch wheel LSB (0-127) Pitch wheel MSB (0-127)
    0xE1    Chan 2 Pitch wheel range    Pitch wheel LSB (0-127) Pitch wheel MSB (0-127)
    0xE2    Chan 3 Pitch wheel range    Pitch wheel LSB (0-127) Pitch wheel MSB (0-127)
    0xE3    Chan 4 Pitch wheel range    Pitch wheel LSB (0-127) Pitch wheel MSB (0-127)
    0xE4    Chan 5 Pitch wheel range    Pitch wheel LSB (0-127) Pitch wheel MSB (0-127)
    0xE5    Chan 6 Pitch wheel range    Pitch wheel LSB (0-127) Pitch wheel MSB (0-127)
    0xE6    Chan 7 Pitch wheel range    Pitch wheel LSB (0-127) Pitch wheel MSB (0-127)
    0xE7    Chan 8 Pitch wheel range    Pitch wheel LSB (0-127) Pitch wheel MSB (0-127)
    0xE8    Chan 9 Pitch wheel range    Pitch wheel LSB (0-127) Pitch wheel MSB (0-127)
    0xE9    Chan 10 Pitch wheel range   Pitch wheel LSB (0-127) Pitch wheel MSB (0-127)
    0xEA    Chan 11 Pitch wheel range   Pitch wheel LSB (0-127) Pitch wheel MSB (0-127)
    0xEB    Chan 12 Pitch wheel range   Pitch wheel LSB (0-127) Pitch wheel MSB (0-127)
    0xEC    Chan 13 Pitch wheel range   Pitch wheel LSB (0-127) Pitch wheel MSB (0-127)
    0xED    Chan 14 Pitch wheel range   Pitch wheel LSB (0-127) Pitch wheel MSB (0-127)
    0xEE    Chan 15 Pitch wheel range   Pitch wheel LSB (0-127) Pitch wheel MSB (0-127)
    0xEF    Chan 16 Pitch wheel range   Pitch wheel LSB (0-127) Pitch wheel MSB (0-127)

I've tried to send a message like so:
MIDIEvent pitchwheel = {0xe0, 127,127};
MIDIUSB.write(pitchwheel);

but this didn't work and I'm not sure what I'm missing/doing wrong.
Any hints/tips will be helpful.

Please show the working code to send a note-on message.

arcore creator Ralf Kistner provided the answer:
// The pitch bend value is a 14-bit number (0-16383). 0x2000 (8192) is the default / middle value.

// First byte is the event type (0x0E = pitch bend change).
// Second byte is the event type, combined with the channel.
// Third byte is the 7 least significant bits of the value.
// Fourth byte is the 7 most significant bits of the value.
void pitchBendChange(byte channel, int value) {
  byte lowValue = value & 0x7F;
  byte highValue = value >> 7;
  MIDIEvent event = {0x0E, 0xE0 | channel, lowValue, highValue};
  MIDIUSB.write(event);
}

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


text:
How do I connect two slaves of same type in I2C?
I am not experienced about I2C communications, but I do happen to have two HMC5883L magnetometer modules that I wish to connect to a single arduino. It uses I2C protocol, and hence the slave device will have a fixed address. Now Can I change the address of one of my sensors so that the Arduino can differentiate between the two? (I seem to find no way out by reading the datasheet)
Thanks in Advance
Siddharth Jha
P.S. Can an MPU 6050 module be used to find angle of rotation in X-Y plane (Parallel to the ground)?

Just take a look at the datasheet for this component. Typically, when a component is likely to exist in several instances on the same I2C bus, then that component has a way to select one among a few addresses; that's typically done through little switches on the board (or possibly by soldering a short somewhere on the PCB).

The problem is with the magnetometer:
"The HMC5883L has a fixed I2C address, you can only connect one sensor per microcontroller!"
Wiring and Test
Also, it says it in the specs on page 2:
 I2C Address
8-bit read address 0x3D
8-bit write address 0x3C
3-Axis Digital Compass IC HMC5883L
Low cost magnetometers appear to have fixed I2C addresses. One solution would be to get a different one in addition to yours. For example, the MAG3110 has I2C address 0x0E and the FXMS3110CDR1 has I2C address 0x0F.
Xtrinsic MAG3110 Three-Axis, Digital
Magnetometer
More information on this page:
How to connect multiple of the same device to an Arduino using I2C?
P.S. You are more likely to get an answer to your second question by posting it separately (and help others in the process).

You can't change the address. You could connect it to some other pins, and bit-bang the I2C protocol.
Or connect the vcc of the unit to an arduino pin, so you can turn it on and off.

Enabling only one device is a good idea; doing it by switching Vcc usually isn't.  In addition to possible startup time, generally speaking IOs should not exceed the supply voltage except where it is documented that is allowed.

Good point. You could add a some buffer logic, but that would make it a bit more complicated.

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


text:
How to flush the input serial buffer in Arduino?
I am communicating with the esp8266 WiFi module using Arduino. The module returns GET requests from other clients. They will be of the form
GET /101011 HTTP/1.1\r\nHost...

I wish to extract only the 101011 from the received serial data and discard the rest. I came up with this small chunk of code to test it by sending data from my laptop.
This is the code:
String s;

void setup() {

  Serial.begin(9600);
}

void loop() {

  if(Serial.available())
  {
    Serial.println("Inside");
    Serial.find("/");
    s = Serial.readStringUntil(' ');
    Serial.println(s);
    // Discard the rest of the data . Snippet from Jeremy Blum's Blog

    while(Serial.available()>0) Serial.read();

  }

}

Jeremy's Blog
But when I run this using the input GET /101011 HTTP/1.1\r\n the output produced is
Inside
101011
Inside
1.1\r\n

Why is Serial.available() returning true even after reading everything? How to discard the rest of data from the serial input buffer?

How do you know you have read everything? Serial data is still arriving from the ESP8266 while you are clearing the buffer - and you are clearing it much faster than the data is arriving.  Remember: serial data arrives s...l...o...w...l...y...

Read this:~ https://hackingmajenkoblog.wordpress.com/2016/02/01/reading-serial-on-the-arduino/

@Majenko Thank you. Read your blog. Will try to implement it in my design.

One possible approach is to read and discard everything for a fixed time, like a second. For example:
unsigned long now = millis ();
while (millis () - now < 1000)
  Serial.read ();  // read and discard any input

I'm not a big fan of trying to "flush the input buffer". How do you know if a second is long enough? Or maybe it is too long? You are better off reading to some known delimiter.


text:
Arduino Bluetooth data (large data files) transfer efficiency using HC05 module
Im using an HC-05 Bluetooth module connected to my Arduino MEGA. The Arduino has an SD card with some data files stored (sensor readings). After the sensor readings are done, the Arduino then connects to Android phone via Bluetooth and transfers the file data.
This is working fine. Arduino sends the data to HC-05 over Serial port, which transfers it over the air to my Android phone.
But its kinda slow and I hence had a question.
QUESTION: Does the HC-05 buffer the data coming from the Arduino Serial and then send efficiently filled packets over the air. I would like to make sure that the HC-05 isn't inefficiently sending just a single byte or so per Bluetooth packet.
Thank you.

Please add some performance measurement. What is "kinda slow"? Also add snippet of your sketch showing the serial baudrate and interaction.

Please upload your code, I will look into it.

What baud rate is the HC05 using? This will be the limiting factor. It can be changed up to 460800 baud (according to a random datasheet I googled).


text:
Migrating from ATMega2560 to ARM based -- Teensy vs Due?
I currently have a project that is working on an AtMega2560 platform (heavily derived off the Arduino Mega). It mainly involves a GPS module and SD card.
Going forward I am looking to add a few more sensors (IMU etc.). I would like to a more powerful microcontroller -- for the high rate logging I need and also it seems best from a future scalability perspective.
I would like to start with using one of the ARM based uC platforms available out there, transition my software to it using a breadboard setup, and then eventually make a custom board.
So my QUESTION is:
Which would be an easier option from a migration/transition and community support point of view --- Teensy or Due? I currently use the SDFat and Adafruit GPS libraries, the SDFat being a major concern for migration.
Any other considerations/suggestions/advice will be appreciated.
Thank you.

If compatability is what you are after I would say go for the Due. If good products are what you are after, go for the Teeensy. The Due, being a real Arduino, will have the best software support and forum community and thus the best chance of getting existing libraries to work with it. The Teensy, because the project really centers around one guy's brilliance, is highly dependant on that one person's time, and while he has done a stirling job with the Teeensy core, he is still only one guy and can only do so much. So it may be harder to get third party libraries working on it.
That said, the Due is not a nice board. The SAM3X chips are awful. Any chip that needs an erase button attached to it to get around the "possibility it won't be able to enter the bootloader" (which incidentally is hard coded in ROM and can NEVER be replaced or upgraded) is destined for the scrap heap IMHO.
There are of course other options as well. There are about a million and one ARM based Arduino-like boards out there with varying amounts of support, either from the chip manufacturer (such as the ST boards), or third party builders. Then of course there are other architectures that are in my biased opinion much better than the ARM ones - chips such as the MIPS based PIC32, used in the chipKIT family of boards. Those latter though don't yet have a port of the SdFat library yet, although it is something that is being actively worked on. There are even Sparc based boards out there that are worth a look.

Thanks Majenko. I do care about compatibility but a better long term solution is a higher priority (also because it will be a learning vehicle for me working on arm uCs). So based on your answer I am leaning towards using the Teensy. Interested in seeing other replies as well (basically if someone has suggestions on boards at par with Teensy in terms of a good board but perhaps with better community support)

Personally i do all my work with pic32 or pic18 because i know those chips intimately, so i am somewhay biased towards those. Maybe you should have a dabble with the chipkit boards to see what you think. There are a number of inexpensive options, like the Fubarino Mini, that could let you experience them without breaking the bank...


text:
How to drive 16 stepper motors with Arduino?
I'm trying to drive 16 of these little steppers on an Arduino Uno.
Each test driver uses 4 digital pins for control (2 for each coil) so that would be 64 pins I will need.
I'm thinking either getting something like this or 4 of these.
Would something like that work ?
What's the most straight forward way to drive these on an Arduino Uno ?

I wouldn't get those steppers. One part of the description says it has one chip to drive it, and another part says a completely different chip. Unless you actually have them already, in which case you can manually identify what the chip is on it. The two different chips need completely different driving strategies.

@Majenko Looks like an ULN2003 (SOIC16 !) driver in the picture, not an A3967 (SOIC24) like in the description. I, personally, would just use 8 shift registers.

If you need to drive all 16 simultaneously and independently, the Uno may not have enough capability to do it. Consider the worst-case number of motors and highest rate(s) you expect to drive at once, plus anything else you need the Uno doing at the same time. You might try a simple sketch to do all of these things (substituting LEDs for the motor drivers) at once, and use a scope to examine those LED output signals for the right frequency, wave-form, and lack of jitter. Without I/O expanders, you won't get to 16 motors' worth of outputs (unless you already have an I/O expander) but you might try doubling up on the existing output (use non-overlapping motor phases if you can).
If the Uno can manage that with clean outputs, you'll have a better idea whether it can manage the full load. If it doesn't, you may need to reconsider your choice of processor with respect to its clock-speed, both kinds of memory (depending on what you learned), number of outputs, possibly number of available timers and of interrupts.

Alternatively: split the load between multiple MCUs.

The maximum (reliable) speed I could get with those steppers was at 3ms per step.


text:
How to process this XBee analog pins signal?
I'm new to XBee and a colleague setup a sender/receiver pair. I'm using an usb breakout and reading the values using this java XBee API in Processing/Java.
The issue I'm having is two of the pins(analog 3 and 4) seem to have a strange alternating pattern and this makes it harder to read the values. Here's what I mean:
a recording of the plot I'm drawing of the values:

and here are some values. I noticed there were duplicate entries, so I removed those:
654,28
65,28
65,366
52,366
52,263
607,263
607,23
45,23
45,554
164,554
164,138
393,138
393,14
33,14
33,677
432,677
432,64
77,64
24,237
24,345
659,345
659,29
61,29
74,378
74,226
455,226
455,16
42,16
42,592
225,592
225,107
348,107
348,13
27,13
27,700
515,700
515,56
60,56
60,392
372,392
372,70
98,70
98,141
12,141
12,456
663,456
663,30
64,30
74,349
74,224
554,224
554,20
41,20
41,600
256,600
256,96
127,96
127,87
13,87
13,502
659,502
659,37
75,37
75,251
20,251
20,364
631,364
631,25
55,25
55,436
128,436
128,165
447,165
447,16
38,16
38,618
224,618
224,107
251,14
25,14
25,700
535,700
535,54
67,54
69,323
69,235
568,235
568,21
49,21
49,503
182,503
330,128
330,12
13,12
13,498
665,498
665,35
76,35
76,247
47,247
47,277
313,277
313,12
22,12
22,691
513,691
513,56
157,56
157,53
18,53
18,640
169,640
103,48
103,105
12,105
12,389
209,389
209,30
65,30
65,353
19,353
19,282
200,282
200,18
21,18
21,681
152,681
152,54
123,54
123,47
14,47
14,526
654,526
654,37
74,37
74,260
17,260
17,387
655,387
655,29
61,29
61,375
74,375
74,249
512,249
512,18
32,18
32,678
255,678
255,92
270,92
270,11
25,11
25,319
557,319
557,53
61,53
61,165
115,165
115,133
195,133
195,18
20,18
20,317
594,317
594,48
126,48
126,41
14,41
14,281
653,281
653,40
80,40
80,96
35,96
35,189
623,189
623,25
55,25
55,191
139,191
139,123
468,123
468,16
31,16
31,306
622,306
622,45
82,45
82,90
24,90
24,345
207,345
207,32
66,32
66,347
22,347
22,247
201,247
201,18
41,18
41,616
82,616
82,82
93,82
93,147
12,147
12,472
206,472
206,33
73,33
73,287
18,287
18,274
204,274
204,19
49,19
49,526
64,526
64,103
182,103
182,14
27,14
27,701
457,701
457,61
225,61
225,19
19,19
19,654
592,654
592,48
105,48
105,125

Looking at the pattern I noticed the higher values occur every 3rd value but also the values seem to oscillate like on a sine wave. If I read only the 3rd value of each sensor that seems remove the 'gaps', but the sine wave pattern is still visible. When I physically get the two pots connected to analog pins 3 and 4 (index 2 and 3 in my plot) I can notice the maximum value either increases or decreases, but the sine pattern is still there.
I've also started going though the XBee manual and found this:

Analog samples are returned as 10-bit values. The analog reading is
  scaled such that 0x0000 represents 0V, and 0x3FF = 1.2V. (The analog
  inputs on the module cannot read more than 1.2V.) Analog samples are
  returned in order starting with AIN0 and finishing with AIN3, and the
  supply voltage. Only enabled analog input channels return data as
  shown in the figure below. To convert the A/D reading to mV, do the
  following: AD(mV) = (A/D reading * 1200mV) / 1023

Unfortunately I'm not very experienced with electronics, but it looks like a linear mapping to me and I haven't found anything else pointing to this oscillation.
My naive approach would be to work out the period or this sine wave and see how much the amplitude changes when I physically turn the pots versus the 'default' position.
I've also started looking at signal processing and thought that potentially I could use a 'wavelet' to detect a pattern and then see difference between the expected one and the current signal, but that sounds a bit overkill.
Is my naive approach decent ? What's the simplest way to read values from a signal like this ?

Sounds like your pots are not connected correctly and you pick up noise. The waveform you are seeing could be from the mains, or another source. Stray magnetic fields from transformers etc. can couple and be picked up by your circuit and you will notice them if your input is of high impedance. The atmosphere is also full of electromagnetic radiation from human sources and from space, that you can also pick up. The longer wires that are connected to your high impedance input, the more noise you will pick up.
Your pots should be wired 1.2V-AIN-GND, with the 1.2V source being low impedance, coming from a power supply/regulator and not eg. a voltage divider. If your potentiometer is high impedance (say 100 kOhm), and it is connected with wires from eg. a breadboard, you might want to add a decoupling capacitor between AIN and GND. 0.1 uF would be a typical value. It will short out AC waveforms(noise) to ground.

Thank you for the tip(+1)My colleague hooked up the circuit to an oscilloscope and the signal looks like an oscillation. The pots are L/R triggers on a joypad and it looks like that's how the joypad deals with these.I did a quick test using pygame and the joystick class and I see 5 axis weridly: 4 are for the horizontal/vertical for the two thumb sticks, but the 5th axis changes values based on these L/R triggers: L goes from 0 to ~-900, R goes from 0 to ~900 and when either L/R are released or fully pressed the value is 0 (the 900 and -900 add to 0). Any hints on reading oscillating signals ?

At what frequency does the signal oscillate? What's the amplitude? How does the waveform change when you press a button / move a joystik? A circuit diagram and/or product name would be helpful. I doubt that it's really supposed to oscillate though. How are the two circuits(xbee, joypad) grounded?

The product is an Xbox One controller and it's the LT/RT I'm trying to get. One problems is the wave frequency is faster than what the XBee can send so what I'm receiving doesn't have a peak at the same distance (it's 3 samples away, then 4 depending on what samples I might be missing). However, I've managed to get something off the ground in two steps: 1st I'm detecting the peaks (by checking the signs of the difference between the current and the previous and the current and the next: if they're both positive I'm looking at a peak), then seeing the maximum value. Then I threshold the maximum

Where in the circuit are you sampling from?

Sounds familiar .
First i will test whether i am reading something or just picking up random noise due to poor connection or error in coding (data conversion arithmetic etc).
Connect 1 pin to ground and another to 1.2V.
You should read 1024 and 0 on e 2 pins . If not check circuit and code.
Anyway
Vadc = (ADC/1024) * Vref

Did you connect Vref ?


text:
How to avoid blocking while loop reading Serial?
I am currently playing with a MindWave Mobile headset. I am parsing bluetooth data received from a connected BlueSMIRF Silver.
The code I started from is a sample from the MindWave wiki and it works using hardware Serial.
For reference here is the original code:
////////////////////////////////////////////////////////////////////////
// Arduino Bluetooth Interface with Mindwave
//
// This is example code provided by NeuroSky, Inc. and is provided
// license free.
////////////////////////////////////////////////////////////////////////

#define LED 13
#define BAUDRATE 57600
#define DEBUGOUTPUT 1

#define GREENLED1  3
#define GREENLED2  4
#define GREENLED3  5
#define YELLOWLED1 6
#define YELLOWLED2 7
#define YELLOWLED3 8
#define YELLOWLED4 9
#define REDLED1    10
#define REDLED2    11
#define REDLED3    12

#define powercontrol 10

// checksum variables
byte generatedChecksum = 0;
byte checksum = 0;
int payloadLength = 0;
byte payloadData[64] = {
  0};
byte poorQuality = 0;
byte attention = 0;
byte meditation = 0;

// system variables
long lastReceivedPacket = 0;
boolean bigPacket = false;

//////////////////////////
// Microprocessor Setup //
//////////////////////////
void setup() {

  pinMode(GREENLED1, OUTPUT);
  pinMode(GREENLED2, OUTPUT);
  pinMode(GREENLED3, OUTPUT);
  pinMode(YELLOWLED1, OUTPUT);
  pinMode(YELLOWLED2, OUTPUT);
  pinMode(YELLOWLED3, OUTPUT);
  pinMode(YELLOWLED4, OUTPUT);
  pinMode(REDLED1, OUTPUT);
  pinMode(REDLED2, OUTPUT);
  pinMode(REDLED3, OUTPUT);

  pinMode(LED, OUTPUT);
  Serial.begin(BAUDRATE);           // USB

}

////////////////////////////////
// Read data from Serial UART //
////////////////////////////////
byte ReadOneByte() {
  int ByteRead;

  while(!Serial.available());
  ByteRead = Serial.read();

#if DEBUGOUTPUT
  Serial.print((char)ByteRead);   // echo the same byte out the USB serial (for debug purposes)
#endif

  return ByteRead;
}

/////////////
//MAIN LOOP//
/////////////
void loop() {

  // Look for sync bytes
  if(ReadOneByte() == 170) {
    if(ReadOneByte() == 170) {

      payloadLength = ReadOneByte();
      if(payloadLength > 169)                      //Payload length can not be greater than 169
          return;

      generatedChecksum = 0;
      for(int i = 0; i < payloadLength; i++) {
        payloadData[i] = ReadOneByte();            //Read payload into memory
        generatedChecksum += payloadData[i];
      }

      checksum = ReadOneByte();                      //Read checksum byte from stream
      generatedChecksum = 255 - generatedChecksum;   //Take one's compliment of generated checksum

        if(checksum == generatedChecksum) {

        poorQuality = 200;
        attention = 0;
        meditation = 0;

        for(int i = 0; i < payloadLength; i++) {    // Parse the payload
          switch (payloadData[i]) {
          case 2:
            i++;
            poorQuality = payloadData[i];
            bigPacket = true;
            break;
          case 4:
            i++;
            attention = payloadData[i];
            break;
          case 5:
            i++;
            meditation = payloadData[i];
            break;
          case 0x80:
            i = i + 3;
            break;
          case 0x83:
            i = i + 25;
            break;
          default:
            break;
          } // switch
        } // for loop

#if !DEBUGOUTPUT

        // *** Add your code here ***

        if(bigPacket) {
          if(poorQuality == 0)
            digitalWrite(LED, HIGH);
          else
            digitalWrite(LED, LOW);
          Serial.print("PoorQuality: ");
          Serial.print(poorQuality, DEC);
          Serial.print(" Attention: ");
          Serial.print(attention, DEC);
          Serial.print(" Time since last packet: ");
          Serial.print(millis() - lastReceivedPacket, DEC);
          lastReceivedPacket = millis();
          Serial.print("\n");
        }
#endif
        bigPacket = false;
      }
      else {
        // Checksum Error
      }  // end if else for checksum
    } // end if read 0xAA byte
  } // end if read 0xAA byte
}

One problem I have is the blocking while loop in the ReadOneByte function:
byte ReadOneByte() {
  int ByteRead;

  while(!Serial.available());
  ByteRead = Serial.read();

#if DEBUGOUTPUT
  Serial.print((char)ByteRead);   // echo the same byte out the USB serial (for debug purposes)
#endif

  return ByteRead;
}

I am trying to avoid this so I started drafting a basic state machine approach:
#define BAUDRATE 57600

// checksum variables
byte generatedChecksum = 0;
byte checksum = 0;
int payloadLength = 0;
byte payloadData[169] = {0};
byte poorQuality = 0;
byte attention = 0;
byte meditation = 0;

// system variables
long lastReceivedPacket = 0;
boolean bigPacket = false;

int payloadIndex;

int state = 0;
const int STATE_WAIT_FOR_FIRST_A        = 0;
const int STATE_WAIT_FOR_SECOND_A       = 1;
const int STATE_WAIT_FOR_PAYLOAD_LENGTH = 2;
const int STATE_WAIT_FOR_PAYLOAD        = 3;
const int STATE_WAIT_FOR_CHECKSUM       = 4;
const String stateNames[5] = {"waiting for first A","waiting for second A","waiting for payload length","accumulating payload","waiting for checksum"};

void setup() {
  Serial.begin(BAUDRATE);           // USB
}
void loop() {}
void parsePayload(){
  poorQuality = 200;
  attention = 0;
  meditation = 0;

  for(int i = 0; i < payloadLength; i++) {    // Parse the payload
    switch (payloadData[i]) {
    case 2:
      i++;
      poorQuality = payloadData[i];
      bigPacket = true;
      break;
    case 4:
      i++;
      attention = payloadData[i];
      break;
    case 5:
      i++;
      meditation = payloadData[i];
      break;
    case 0x80:
      i = i + 3;
      break;
    case 0x83:
      i = i + 25;
      break;
    default:
      break;
    } // switch
  } // for loop
  Serial.print("bigPacket:");
  Serial.println(bigPacket);
  if(bigPacket) {
    Serial.print("PoorQuality: ");
    Serial.print(poorQuality, DEC);
    Serial.print(" Attention: ");
    Serial.print(attention, DEC);
    Serial.print(" Time since last packet: ");
    Serial.print(millis() - lastReceivedPacket, DEC);
    lastReceivedPacket = millis();
    Serial.print("\n");
  }
  bigPacket = false;
}

void printState(){
  Serial.print("state:");
  Serial.println(stateNames[state]);
}
void serialEvent(){
  if(Serial.available() > 0){
    switch(state){
      case STATE_WAIT_FOR_FIRST_A:
        printState();
        if(Serial.read() == 170) state = STATE_WAIT_FOR_SECOND_A;
      break;
      case STATE_WAIT_FOR_SECOND_A:
        printState();
        if(Serial.read() == 170) state = STATE_WAIT_FOR_PAYLOAD_LENGTH;
      break;
      case STATE_WAIT_FOR_PAYLOAD_LENGTH:
        printState();
        payloadLength = Serial.read();
        Serial.print("payloadLength:");Serial.println(payloadLength);
        if(payloadLength > 169){
          Serial.println(payloadLength > 169);
          state = STATE_WAIT_FOR_FIRST_A;
          return;
        }
        generatedChecksum = payloadIndex = 0;
        state = STATE_WAIT_FOR_PAYLOAD;
      break;
      case STATE_WAIT_FOR_PAYLOAD:
        printState();
        if(payloadIndex < payloadLength){
          payloadData[payloadIndex] = Serial.read();
          generatedChecksum += payloadData[payloadIndex];
          Serial.print("payloadData[");Serial.print(payloadIndex);Serial.print(" of ");Serial.print(payloadLength);Serial.print("]: ");
          Serial.println(payloadData[payloadIndex]);
        }else{
          state = STATE_WAIT_FOR_CHECKSUM;
        }
      break;
      case STATE_WAIT_FOR_CHECKSUM:
        printState();
        checksum = Serial.read();
        generatedChecksum = 255 - generatedChecksum;
        if(checksum == generatedChecksum) {
          Serial.println("checksum MATCH! parsing payload");
          parsePayload();
          state = STATE_WAIT_FOR_FIRST_A;
        }else{
          Serial.println("checksum FAIL!");
          state = STATE_WAIT_FOR_FIRST_A;
        }
      break;
    }
  }
}

As far as I can understand from the serialEvent() reference this function would be called only when a new byte is available. I've also added a condition to check if Serial.available() > 0.
I can see the messages I expect when parsing the data, but only small packets(usually 4 bytes long) end up having a correct checksum and never receive a payload with the useful EEG data I'm looking for.
How can I check that my approach is correct or not/ I'm not loosing bytes using serialEvent() instead of the blocking while(!Serial.available()) ?
If so, how can I rewrite the while loop in a non blocking way ?
I've not super experienced with Arduino, but I started reading on interrupts. Would a USART_RX interrupt help at all ? (or would it do the same as serialEvent -> trigger when a new byte is available?)
Update!
Using Wirewrap's suggestion to use read() which returns -1 if there is no data, I've used peek() which does almost the same, except it doesn't remove the character peeked at from the buffer.
For reference here is the code used:
#define BAUDRATE 57600
#define DEBUGOUTPUT 1

// checksum variables
byte generatedChecksum = 0;
byte checksum = 0;
int payloadLength = 0;
int payloadIndex;
byte payloadData[169] = {0};
byte poorQuality = 0;
byte attention = 0;
byte meditation = 0;

// system variables
long lastReceivedPacket = 0;
boolean bigPacket = false;

int state = 0;
const int STATE_WAIT_FOR_FIRST_A        = 0;
const int STATE_WAIT_FOR_SECOND_A       = 1;
const int STATE_WAIT_FOR_PAYLOAD_LENGTH = 2;
const int STATE_WAIT_FOR_PAYLOAD        = 3;
const int STATE_WAIT_FOR_CHECKSUM       = 4;

void setup() {
  Serial.begin(BAUDRATE);           // USB
}
void loop() {}
void parsePayload(){
  poorQuality = 200;
  attention = 0;
  meditation = 0;

  for(int i = 0; i < payloadLength; i++) {    // Parse the payload
    switch (payloadData[i]) {
    case 2:
      i++;
      poorQuality = payloadData[i];
      bigPacket = true;
      break;
    case 4:
      i++;
      attention = payloadData[i];
      break;
    case 5:
      i++;
      meditation = payloadData[i];
      break;
    case 0x80:
      i = i + 3;
      break;
    case 0x83:
      i = i + 25;
      break;
    default:
      break;
    } // switch
  } // for loop
  if(bigPacket) {
    Serial.print("PoorQuality: ");
    Serial.print(poorQuality, DEC);
    Serial.print(" Attention: ");
    Serial.print(attention, DEC);
    Serial.print(" Time since last packet: ");
    Serial.print(millis() - lastReceivedPacket, DEC);
    lastReceivedPacket = millis();
    Serial.print("\n");
  }
  bigPacket = false;
}

void serialEvent(){
  if(Serial.peek() >= 0){
    switch(state){
      case STATE_WAIT_FOR_FIRST_A:
        if(Serial.read() == 170) state = STATE_WAIT_FOR_SECOND_A;
      break;
      case STATE_WAIT_FOR_SECOND_A:
        if(Serial.read() == 170) state = STATE_WAIT_FOR_PAYLOAD_LENGTH;
      break;
      case STATE_WAIT_FOR_PAYLOAD_LENGTH:
        payloadLength = Serial.read();
        if(payloadLength > 169){
          state = STATE_WAIT_FOR_FIRST_A;
          return;
        }
        generatedChecksum = payloadIndex = 0;
        state = STATE_WAIT_FOR_PAYLOAD;
      break;
      case STATE_WAIT_FOR_PAYLOAD:
        if(payloadIndex < payloadLength){
          payloadData[payloadIndex] = Serial.read();
          generatedChecksum += payloadData[payloadIndex];
          payloadIndex++;
        }else{
          state = STATE_WAIT_FOR_CHECKSUM;
        }
      break;
      case STATE_WAIT_FOR_CHECKSUM:
        checksum = Serial.read();
        generatedChecksum = 255 - generatedChecksum;
        if(checksum == generatedChecksum) {
          parsePayload();
          state = STATE_WAIT_FOR_FIRST_A;
        }else{
          state = STATE_WAIT_FOR_FIRST_A;
        }
      break;
    }
  }
}

Interestingly enough, Serial.read() does not work like most of us think.
Serial.read() is not blocking, it always returns immediately with a byte 0-255 or -1 if there is no character to read.
From Arduino Reference

Description
Reads incoming serial data. read() inherits from the Stream utility class.
Syntax
Serial.read()
Parameters
None
Returns
the first byte of incoming serial data available (or -1 if no data is available) - int

Interesting indeed(+1). I will try to adapt the code without using available() and simply checking if Serial.read() > -1. Is there a change of missing a byte this way ?

Serial.read() reads from a 64 bytes buffer. If you can avoid filling up the buffer you will be okay.

"Serial.read() is not blocking, it always returns immediately with a byte 0-255 or -1 if there is no character to read." unless it returns a multi-byte data type, it couldn't return 0-255 or -1 -> as -1 is 128. it likely returns 0-127 and -1 instead.

Nick Gammon, a moderator on the official Arduino site and a very active member of the Arduino community on Stackoverflow, has done a very nice post on reading serial without blocking. I've posted the relevant code.
    /*
    Example of processing incoming serial data without blocking.
Author:   Nick Gammon
Date:     13 November 2011.
Modified: 31 August 2013.

Released for public use.
*/

// how much serial data we expect before a newline
const unsigned int MAX_INPUT = 50;

void setup (){
Serial.begin (115200);
} // end of setup

// here to process incoming serial data after a terminator received
void process_data (const char * data)
 {
 // for now just display it
 // (but you could compare it to some value, convert to an integer, etc.)
 Serial.println (data);
 }  // end of process_data

void processIncomingByte (const byte inByte)
{
  static char input_line [MAX_INPUT];
  static unsigned int input_pos = 0;

switch (inByte)
  {

  case '\n':   // end of text
    input_line [input_pos] = 0;  // terminating null byte

    // terminator reached! process input_line here ...
    process_data (input_line);

    // reset buffer for next time
    input_pos = 0;
    break;

  case '\r':   // discard carriage return
    break;

  default:
    // keep adding if not full ... allow for terminating null byte
    if (input_pos < (MAX_INPUT - 1))
      input_line [input_pos++] = inByte;
    break;

  }  // end of switch

} // end of processIncomingByte

void loop()
{
// if serial data available, process it
while (Serial.available () > 0)
  processIncomingByte (Serial.read ());

// do other stuff here like testing digital input (button presses) ...

}  // end of loop

Didn't know about this, thanks! (+1)

I don't like serialEvent() because it only checks to see if it should run that function after the whole loop is executed. With your new example, it's basically the same as the original (except you moved that code to the very bottom of the loop).
I'm not sure exactly how fast the data is sent, but you should first ask yourself if the data is sent fast enough that you don't even notice that it's blocking. Blocking code isn't bad itself (except maybe from a standpoint of the other device freezing up and stalling your program), but blocking code that takes a long time is bad.
Since you need five bytes, the best thing would be to wrap the blocking code in an if statement like this:
if(Serial.available >= 5) {
  //Blocking code here
}

It's simple and readable, yet effective.

Thanks for the tips (+1). I didn't know about serialEvent being called once at the end of loop. Reading all the bytes in a full packet with a big payload takes between 900ms and 2500ms from what I can observe. Is there a chance of missing bytes using serialEvent instead of while(!Serial.available()) ?

@GeorgeProfenza it shouldn't remove any bytes unless it's a major bug.

Since then I've figured out how to rewrite the code to be non-blocking, by replacing the while loop with states, accumulating one byte at a time.
I've written my first Arduino library with this occasion: Mindwave.
Here's a basic example:
#include <Mindwave.h>                   //import the library
Mindwave mindwave;                      //start using it

void setup() {
  Serial.begin(MINDWAVE_BAUDRATE);      //setup serial communication (MindWave mobile is set to 57600 baud rate)
}
//create a function to received new values as soon as they're avaialble
void onMindwaveData(){
  Serial.print("attention: ");
  Serial.println(mindwave.attention()); //access attention value
}
void loop() {
  mindwave.update(Serial,onMindwaveData);//update using the data input(Serial in this case) and the function to call when data is ready
}

It's non blocking, you can see the implementation here
This was used for the Walk with Me art installation.


text:
How can I make pinMode calls faster?
I'm trying to use 3 pins as capacitive pins along side the Mozzi.
I had several attempts and so far the closest I had was using code from the ADCTouch library straight into the main code, but with the current implementation (removing averaging and taking less samples to speed things up) it's only fast enough to process 1 pin and I'd like to use 3.
Here is my implementation so far:
/*  Based on the Gain Example changing the gain of a sinewave,
    using Mozzi sonification library.

    Demonstrates the use of a control variable to influence an
    audio signal.

    Circuit: Audio output on digital pin 9 on a Uno or similar, or
    DAC/A14 on Teensy 3.0/3.1, or
    check the README or http://sensorium.github.com/Mozzi/

    Mozzi help/discussion/announcements:
    https://groups.google.com/forum/#!forum/mozzi-users

    Tim Barrass 2012, CC by-nc-sa.
*/

#include <MozziGuts.h>
#include <Oscil.h> // oscillator template
#include <tables/sin2048_int8.h> // sine table for oscillator

// use: Oscil <table_size, update_rate> oscilName (wavetable), look in .h file of table #included above
Oscil <SIN2048_NUM_CELLS, AUDIO_RATE> aSin(SIN2048_DATA);

// control variable, use the smallest data size you can for anything used in audio
byte gain = 255;

//ADC Touch setup
int sampleCount[3] = {0};
int values[3] = {0};

void setup(){
  startMozzi(); // start with default control rate of 64
  aSin.setFreq(4200); // set the frequency
}

void updateControl(){
  if(gain > 3){
    gain = gain - 3 ;
  }else{
    gain = 0;
  }
  //begin ADCTouch
  pinMode(A4, INPUT_PULLUP);

  ADMUX |=   0b11111;
  ADCSRA |= (1<<ADSC); //start conversion
  ADCSRA |= (1<<ADIF); //reset the flag

  pinMode(A4, INPUT);

  values[0] = mozziAnalogRead(A4);
  sampleCount[0]++;
  //end ADCTouch

  if(sampleCount[0] == 64){//wait for 64 samples
    if(values[0] > 500) {//did we get a touch with all these samples ?
      gain = 255;//amp it up
    }
    sampleCount[0] = 0;//reset count
  }

}

int updateAudio(){
  return (aSin.next()* gain)>>8; // shift back to STANDARD audio range, like /256 but faster
}

void loop(){
  audioHook(); // required here
}

The issue is as soon as do the pinMode calls for the second pin I'd like to use (A5) so I'm guessing pinMode needs to work faster. To use pinMode(INPUT_PULLUP) and pinMode(INPUT) calls for pins A4,A5 and digital 10, now can I write this using direct port manipulation ?
(I'm new to avr/arduino internals and slowly getting the grips with this).

First, figure out which port and pin you're using. Then, manipulate them.
DDRC &= ~_BV(PC5);
PORTC |= _BV(PC5);

...
DDRF &= ~_BV(PF5);
PORTF |= _BV(PF5);

...
DDRF &= ~_BV(PF0);
PORTF |= _BV(PF0);

Thank you for the quick reply(+1). Since I'm still a n00b I had to do a bit of googling. Found this nice diagram and also found a note that I should rename these constants to PORTC5/PORTF5/PORTF0 and that's how I could compile my modified code. Also, I assume these are for INPUT_PULLUP. and for INPUT I just need to do PORT |= 0,PORTF |= 0 right ? Thanks again for your help and sorry to "pull your sleeve", but could use more details as a novice

@GeorgeProfenza You're not improving your code by renaming the constants. Nobody will be able to understand it when you ask for support or try to Google for information. I'd advise to use the standard names. Download the full datasheet for the ATmega328 from the Atmel website and read chapter 14. I/O-Ports. The AVR datasheets are usually pretty good and you should consider to check out other chapters too. You'll also notice that these register names are used

throughout the datasheet.

@jippie The datasheet actually used PORTC5 instead of PC5 in the older versions of the datasheet. My 2009 version does (guess I should update my local pdf file)

@Gerben Always use the latest release of (any) the datasheet. Check errata if you like, mistakes are corrected every so often an some can cost you lots of troubleshooting time. Whenever possible check the vendor website of a device an use other websites only for backup.

@Ignacio Vazquez-Abrams I don't mind sticking to the constants you recommend. Where these be defined so I can include them in my sketch ?

They're available via <avr/io.h>, which is already included by the IDE.

Hmm, I must be doing something wrong because I added the include but I still get errors finding these constants:sketch_jan28a.ino:64:3: error: 'DDRF' was not declared in this scope In file included from /Applications/Arduino.app/Contents/Resources/Java/hardware/tools/avr/avr/include/avr/io.h:99:0,                  from sketch_jan28a.ino:16: sketch_jan28a.ino:64:16: error: 'PF5' was not declared in this scope sketch_jan28a.ino:65:3: error: 'PORTF' was not declared in this scope Error compiling.

Does your Arduino actually have a port F?

I have no idea, but I'm guessing not since your code doesn't compile ? I did mention I'm new to this and I don't really have control over what I'm doing at the moment. Any hints/tips in the right direction are more than welcome

... Let's start with the very basics. What Arduino are you using?

Thank you for your patience. I am using a SquareWear2.3 board which uses an atmega328p mcu

Take a look at both the Arduino pin mapping for the '168/'328 as well as the datasheet itself.

Thank you for all the advice. Sorry I haven't marked it. I also found this library which looks helpful


text:
Reading a 10 pin 7 segment (2 digits) sing Arduino 1. Please Help!
thanks for taking the time to read this, I really appreciate it.
I am very new to Arduino and the Micro controller world so please forgive my ignorance.
So I have an old 7 segment display that displays outside temperature, what i want to do is read the temp into the Arduino and light up an LED if the temperature gets high, and a different color if the temp gets low.
I know i can use a thermometer and plug it into the Arduino and go from there, but that would be cheating. So my question is, can i read each pin of the 7 segment display and translate that into a number into the Arduino?

Task: Read a dual  10 pin 7 segment by jumping wires into the Arduino.
Setup: I am using the code and setup found here: "http://blog.rastating.com/using-a-7-segment-led-display-w-arduino-uno/" to display a number (21) for testing purposes. I want to jump the pins into another Arduino and read "21"

please see pictures.
Any help would be very very appreciated!!
Thanks again for reading.

This last picture shows "21" using the code and set up on the above link.
I want to jump another Arduino into the breadboard and read "21" or any other temperature (depends on outside thermometer) into the serial monitor. Now the challenging part is the code, Im not really good at coding but i understand if this had 1 pin for each LED i would just read each one and translate it into the serial monitor. However this only has 10 pins therefore represents a challenge.
Any input is greatly appreciated, I dont even know how to start.

Have you checked (eg with a DMM or an oscilloscope) the voltage between the anode and cathode for one lit segment of the display? This will tell you if this can be directly used as a digital input of Arduino or it it requires additional circuitry.

In order to get the value from any display pin, you will also need a ground that you can plug to Arduino GND, do you have such a pin onn the display board, or you just have 8+2 pins, 8 for the 7 segments + DP, 2 for each common anode?

This post helped me to develop an Arduino circuit to read multiplexed display.
The solution can be found https://github.com/bunhoel/FT107m good luck

Your display is multiplexed, so you will need to monitor not only the segment lines but also the digit lines.
First figure out if your display is "common anode" or "common cathode" as the logic in one case will be inverted from that of the other.
For your test case, you can write the driving and reading arduinos to the display in the same way, but configure all the connected pins on the reading one as inputs.
The tricky part is going to be detecting when the segment select has changed, but you could do it by storing the current value of each select pin, and then reading the new value.  If you see that the old value was inactive and the new value active, then wait a tiny amount of time and read all of the segment lines.  You want to wait long enough to make sure that the data lines have been driven to match, but no so long that you get the data for the next digit instead.  If you have access to a scope, you can find the best value, but you could also experiment by making the delay short until you get wrong data, making it long until you get wrong data, and then picking an intermediate value.
You may find it easiest to read all 7 or 8 segment lines into a single byte value, and then compare it to each element in the lookup table you used in the driver code until you find a match.
If you don't know the exact wiring of the segments on the unknown target board, consider printing the bytes to the serial monitor as you cause the displayed values to change (cup of ice water, cup of hot water...) and taking notes of the segment values vs. the digits you see display.  It will be a puzzle, but one you should be able to figure out.

I have a common anode setting. I am really new to code, is there an example anywhere that i could go over?

First of all, make sure that the voltage is below 5V (but above 2.5V so it can register as HIGH on a digital pin). If not, it will either fry your Arduino or won't work.
As for the code, you can do one of the two following things:

Use a library like PinChangeInt to help you detect when and what changed.
Store the data and check every so often.

Chris Stratton had a good idea with the byte and compare it. To do this, you would do something like this:
byte data = 0;
if(digitalRead(10) == HIGH) {
  data |= B00000001;
}
if(digitalRead(11) == HIGH) {
  data |= B00000010;
}
if(digitalRead(12) == HIGH) {
  data |= B00000100;
}
//...

Basically, this is bit-wise math that sets one bit of your byte to a 1. If it is a 0, then you leave it alone (all bits default to 0 because of how I declared data).
If pins 10 and 12 were HIGH, the byte would look like this in binary:
00000101

Hi! so I realized that the 2 pins that are driving this toggle at 4kHz, when one is on the other is off, but there is a 6usec time when both pins are on. So what im trying to do now is adding "if right bit is == 1, if A=1 b=0 c=1 d=1... and so on" then number 'code'

@user3537 Do you need help with that? If so, what I can I help you with?

It would be so much more efficient to read an entire AVR port register, even if a few bits spill into the next.  Does Arduino support that cleanly, or only by ignoring it and doing a raw read?

so I realized that the 2 pins that are driving this toggle at 4kHz, when one is on the other is off, but there is a 6usec time when both pins are on. So what im trying to do now is adding "if right bit is == 1, if A=1 b=0 c=1 d=1... and so on" then number = 6 then scan for it. Im not sure how to use that library.
void loop() {
// read the input pin:
//int buttonState = digitalRead(pushButton);
int State_A = digitalRead(A);
int State_B = digitalRead(B);
int State_C = digitalRead(c);
int State_D = digitalRead(D);
int State_E = digitalRead(E);
int State_F = digitalRead(F);
int State_G = digitalRead(G);
int State_DP = digitalRead(DP);
int State_RIGHT = digitalRead(RIGHT);
int State_LEFT = digitalRead(LEFT);

if (State_LEFT==1)
{
 if(State_A==0 & State_B==1 & State_C==0 & State_D==0 & State_E==0 & State_F==0 & State_G==0)
{
number=6;
Serial.println(number);
// Serial.print(State_LEFT);
}

i plan to add that for every digit. is there any easier way to do that?

This should be edited into your question, as it is not an answer.

I would personally tie the two select pins to an level changing interrupt input on Arduino. Then when you receive an interrupt from one of the digits you have 'all the' time to read the segments. When you don't do the interrupt thing, you may read segments from different digits. A further optimization would be to replace all digitalRead's with a single segments = PINB which would read 8 input lines in a single go.

Using port registers would be cleaner, but much less portable. The port assignments are different between Arduino models.

"segments = PINB" how does this work? if i have all 7 pins a-g

What you are trying to do is tricky and awkward, and probably not worth the trouble.
It's also above your current skill level, both in hardware and software.
As the other poster has said, the display is likely multiplexed. If so, it sends a value to 1 digit, then to the next, and alternates them quickly. Only one digit at a time is actually lit.
It's also possible that the digits are latched. The processor sends a value to one digit at a time and that digit's circuitry remembers the value until it changes again. However that's  less likely because it's more complex and expensive to do
To decode a multiplexed display you'll need to figure out how the multiplexing is done. There are lots of different ways it could be done.
You say it's common anode. It might have the anodes of a digit wired together, and have them both connected to the controller. The anode that's currently being displayed would be connected to +5, and the cathodes of like segments from each digit would be wired together in parallel. To drive a digit, the control circuitry would connect the anode of that digit to the positive supply, and connect the segments to be displayed to ground. All other connections would be left floating. Then it would disconnect the anode of the first digit and connect the anode of the other digit to the positive supply.
The display may also have a logic level that determines which segment is being driven. For a 2 digit display all you'd need is one line, and a HIGH would drive 1 digit and a LOW would drive the other digit.
A logic analyzer would help you sort this out, but you need to know how to use it.
You might also try researching the thermometer you're using and see if you can find a schematic for it, in the documentation, the manufacturer website, or in a patent
Once you figure out how to read the segment values from each digit, you will need a truth table that maps segment values to numbers, and will need to do a lookup. That is intermediate level C programming.


text:
Release power to stepper motor
I'm driving a large stepper motor via a GeckoBoard G213V and arduino UNO and I have that mostly working fine. However, I'd like to 'release' the stepper so it can swing freely.
There's two reasons I want to do this:
1) (Most important) I want the rotated object to naturally swing back to the 0 position thanks to gravity.
2) The motor gets hot - I'd rather not juice it when it should just be sat at 0.
Anybody know how I can do this? I'm using the AccelStepper library so a solution compatible with that would be ideal.

btw - there really should be a 'stepper motor' and/or 'stepper driver' tags available. Be great if an admin could create and add such to this post.

From the documentation:

TERMINAL 7 Disable
  This terminal will force the winding currents to zero when tied to the step and direction controller +5V.
The DISABLE input on the G213V is optically isolated and requires logic “1” to DISABLE and logic “0” to ENABLE the drive. Once it is disabled, the motor windings are unergenized[sic] and the motor freewheels. (emphasis mine)

So, feed the disable input a high.

Thanks - trying this now and it doesn't seem to work. I wired the DISABLE terminal to pin 5, called pinMode(5, OUTPUT) and whether I digitalWrite(5, HIGH or LOW) it always free wheels. Any ideas?

Does it stop freewheeling if you disconnect it?

total n00b failure, pin 5 is used by accelstepper. Moved to 7 and all is good. AccelStepper also has setEnablePin, disableOutputs and enableOutputs methods. Easy! Since the gecko has a DISABLE pin I had to call setPinsInverted(false, false, true) to invert the enable pin.


text:
When setting hardware timers as interrupts, should I prefer a lower prescaler value or a lower CTC?
I'm currently playing with Arduino's hardware timers, and a question came to my mind. Let me explain it a bit.
Let's suppose I want a certain function to execute every 1024 clock ticks. AFAIK, I could achieve this in several ways, playing with the prescaler value for Timer2, and its CTC:

Setting the prescaler to 1 and the CTC to 1024
Setting the prescaler to 8 and the CTC to 128
...
Setting the prescaler to 1024 and the CTC to 1.

All these ways would achieve what I want, but, which one is more efficient? Or it doesn't matter at all?
Thanks in advance for sharing your knowledge :P

Larger prescaler values will result in a very slight decrease in power consumption as whatever circuitry is connected to the output of the prescaler will switch at a lower frequency, and power consumption is proportional to c v^2 f.

CTC is not a number, it's a mode of operation of the counter (mode 2). You set the period of the timer by setting OCR2A, the actual period being (OCR2A+1)×prescaler CPU cycles. Thus, if you set the prescaler to 8, you have to set OCR2A=127.

If 'clock tick' count (here 1024), timer width and  MCU clock used are constant (a fixed value), I would not go for last option i.e. prescalar 1024 and CTC of 1. Here are my reasons (specially for Arduino )
1) When CTC is close to zero ( like 1-> 10), sometimes timer behaves as if count is zero and outputs a square wave (with 50% duty ratio) with half the demanded frequency. So make CTC reasonably big. But again selecting a high clock frequency (pre scalar 1) may also show reduced accuracy. A intermediate option I think is better.
2) When count CTC changes dynamically in a process, timer pre scalar should be selected such that CTC count will always be less than or equal to timer width over whole process.
i.e. the maximum 'timer tick count' should be comfortably accommodated by the timer with it's given width. Even here same dilemma again occurs, then selection based on point 1 is better.
If this is not enough, then only way I think is to implement each case  physically and check which combination gives you the best results. Practical results I think are more reliable ( may be you will get a board specific efficient combination!)

I don't see any reasonable root cause to validate your remark about low CTC values that may reduce accuracy. In particular, the "sometimes timer behaves..." is obviously wrong: why would timers in the AVR architecture would have not repeatable behavior in this case?

I said low pre scalars (not CTC values) may reduce accuracy. Low CTC values may give unwanted outputs from timers.

'Sometimes' here means for 'some boards' of Arduino. I used this word because question not was asked for specific board. I have many times worked with 'Arduino Due' timers, with timer frequency 10.5 MHz and whenever I gave CTC count  less than 15 ( or near by ) timers gave me a square wave, so obvious reason is that count is taken as zero. This is not mathematical but a practical observation. As said I have only worked with 'Due' for my purpose which is an ARM ( not AVR with lesser clock frequencies used in Arduino ) and so using 'sometimes' is valid I think.

There is a trade-off between resolution and achievable frequencies. You mention Timer 2, but on the Atmega328P Timer 2 is an 8-bit timer, thus you would not be able to set the CTC to 1024.
Let's assume we are talking about an 16-bit timer, like Timer 1 on the Atmega328P. With a prescaler of one, you can time (assuming a 16 MHz clock) from 1 to 65536 "ticks", that is 62.5 ns up to 4096 µs.
This would be the most precise measurement because you are using one (processor) clock tick per timer tick (a prescaler of one).
However if you plan to time for more than 4.096 ms then you need to bump up the prescaler. The next prescaler up on Timer 1 is 8, so now you can time for an interval 8 times as long (32768 µs) however your accuracy (precision) has now decreased by a factor of 8. The granularity of the timer has increased from 62.5 ns to 62.5 * 8 ns, which is 500 ns.
If you need to time longer than 32.768 ms then the prescaler has to be larger again, the next one being 64. So now you can time up to 262144 µs, but with a granularity of 62.5 * 64, which is 4000 ns (4 µs).
My suggestion would be to use the lowest prescaler that you can, but still get the interval you want. So obviously you can't use a prescaler of one to time 10 ms.

I have a discussion about timers on http://www.gammon.com.au/timers.
On that page is a chart which helps visualize the effects of different prescalers:

The top part (count of one) effectively gives you the granularity of each prescaler. For example, a prescaler of 256 has a granularity of 16,000 ns (16 µs). Certain frequencies (powers of 2) will lend themselves to combinations (eg. prescaler of 1 with a count of 256, or prescaler of 256 with a count of 1).
However for frequencies that don't have that property, the smaller prescaler will (if it can be used) give a finer granularity.

Using a higher prescaler does not loose any precision at all. You do get bigger granularity, but if you target a cycle count that is a power of two (like in the question), granularity is not an issue.

But if not, then the lower prescaler lets you get closer to the target. Say you want to time 30 clock cycles. A prescaler of 1 lets you enter the number 30 directly. A prescaler of 8 means you have to use 30 / 8 (3.75) which you cannot directly enter into the register, thus losing precision.

The question was worded with 1024 counts, so my remarks don't apply to that, but I was trying to give a more general answer, in case the fact that 1024 is a rather special case wasn't obvious.


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

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

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

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

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

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

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

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

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

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

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


text:
Arduino Hardware serial library with rts/cts flow control support
Does there exist (any user developed etc.) version of the Hardware UART serial library that has support for RTS/CTS based flow control?
More interested in the Tx side (Arduino sends data, while the peripheral can back-pressure). The library should enable the Arduino to stop transmitting within 1 character of seeing a 'not ready' indication from the peripheral.
Thank you.

This library may help for the AVR-based Arduinos: https://github.com/i-am-bigmike/HardwareSerial_flow_control

I am not aware of any such library. You could try to implement one
yourself, and maybe share it with the community. :-)
If you take this route, you will have to copy the file
HardwareSerial.cpp from the Arduino core, make your
changes there, and have your version replace the one from the core. Here
are some ideas that may help to get you started:

Wire the 'ready' signal from the device to an interrupt-capable pin of
the Arduino.
Inside the interrupt handler:

when 'ready' is deasserted, disable the UDRE interrupt by issuing
cbi(*_ucsrb, UDRIE0)
when ready is asserted, enable it again, but only if the output
buffer is not empty:
if (_tx_buffer_head != _tx_buffer_tail) sbi(*_ucsrb, UDRIE0);

Patch HardwareSerial::write() to enable the interrupt only if
'ready' is asserted.
Note that the UDRE IRQ can be explicitly called
by HardwareSerial::flush()
and by HardwareSerial::write() if interrupts are globally
disabled. You will have to condition this on the 'ready' signal.
Note also that HardwareSerial::write() can write directly to the
UART if the buffer is empty. This also has to be
conditioned on the 'ready' signal.

I believe that CTS would be fairly easy to implement:
void loop() {
  uint8_t clear_to_send = digitalRead(CTS);
  volatile char data;
  if (clear_to_send) {
    Serial.write(data);
  }
}

I'm not sure about RTS.

This wont work to stop the transmission within a one (or even a few) characters, because although you stopped the Serial.write, there may already be data in the serial buffer (default 64bytes I think in Arduino lib) that could continue to go out (and potentially lost).
Anyways, I shifted to Teensy, which has hardware based RTS/CTS flow control, so it is capable of stopping as soon as (i believe 1 character) CTS is deasserted

Hardware USART is better for sure. Though, you could flush the buffer Serial.flush() after every write and    store the last sent byte to be sent later.

I'd be surprised if there is no Arduino implementation. Usually, the (hardware) send buffer on an UNO is, I believe, 1 byte. The Arduino serial wrapper has it's own software buffer implemented. You could change it there. But you may have to retrigger the sending manually (since I think they use the "tx complete interrupt" to wait for the next possible send, which won't happen if you stop the sending)

I have I discovered that RTS/CTS may be implemented in genuine Arduinos, but is not supported by Arduinos that use the CH340 USB to serial chip. I found this when my JAVA program could talk with a genuine Uno ok, but didn't send any data to several Arduino compatibles that use the CH340 chip (but did receive from them). I had RTS/CTS set on the JAVA program. When I changed it to FLOWCONTROL_NONE it started working just fine.


text:
US-100 Ultrasound sensor doesn't work on Arduino mega 2560
Im using a Arduino Mega 2560, and I tried to connect a us-100 ultrasonic sensor for distance measurement.
I connected it as shown in the image
The code I used was:
const int trigger=6;
const int echo=7;
float distance;
void setup(){
Serial.begin(9600);
pinMode(trigger,OUTPUT);
pinMode(echo,INPUT);
}
void loop(){
// Trigger US-100 to start measurement
// Set up trigger
digitalWrite(trigger,LOW);
delayMicroseconds(5);
// Start Measurement
digitalWrite(trigger,HIGH);
delayMicroseconds(10);
digitalWrite(trigger,LOW);
// Acquire and convert to mtrs
distance=pulseIn(echo,HIGH);
distance=distance*0.0001657;
// send result to UART
Serial.println(distance);
delay(50);
}

But It won't work, as in the only output i get is 0.00 cm as shown in the image
Can someone tell me if I'm doing something wrong(also, i tried putting two probes between the vcc and one of the gnd pins, and a resistance was shown.This should mean the sensor isn't broken.yes?)? this is my first time using arduino and I greatly appreciate help to fix this.

Try sending the value of pulse in via serial to see if that is returning the right value.

People can answer your questions much more quickly if you add a direct link to the datasheet in your question.

This questions lacks the details needed to be answerable, and has been abandoned without any attempt to provide them for half a year, so should be closed as off topic.

I'm going to close this question as "unclear what you are asking". A link to the datasheet would help. I can't personally see from the photo what is connected to what. Feel free to edit the question with new information. Thanks for your understanding and cooperation!

Have you removed the "Serial Data Mode" shunt to put the device in "Pulse Width Mode"?
On the other hand, perhaps the "Serial Data Mode" would actually work better for your application?
Where I work, we have a coding style that strongly encourages
all "magic numbers" to be documented
with a link to the website it came from
or a reference to the book and page it came from.
Would something like this work for you?:
void loop(){
    // Trigger US-100 to start measurement
    // at least 50 us high, then set it low,
    // as recommended by
    // https://www.bananarobotics.com/shop/US-100-Ultrasonic-Distance-Sensor-Module
    digitalWrite(trigger,HIGH);
    delayMicroseconds(50);
    digitalWrite(trigger,LOW);
    // Acquire
    unsigned long echo_microseconds = pulseIn(echo,HIGH);
    // debugging
    serial.println( echo_microseconds );
    Serial.println(F(" microseconds"));
    // conversion factor from
    // https://www.bananarobotics.com/shop/US-100-Ultrasonic-Distance-Sensor-Module
    unsigned long distance_mm = echo_microseconds * 34 / 100 / 2;
    Serial.print(distance_mm);
    Serial.println(F(" mm"));
    delay(50);
}

It might be easier to use the Ping library as described at
Arduino-Info: UltraSonic Distance Measurement.
You might find the
Arduino Forum: Measuring Distances with Ultrasonic Sensors
thread educational.

I tried all the above ways you said. None of the works. :/ I tried both serial data mode and PWM.


text:
How to use Aiduino module to connect to computer network?
I have 4 usb Hard Drives and I just want to connect them to computer network directly without a traditional computer. Is there an any module with 4 usb ports and one RJ45 port. The module should able to connect drives to network as NAS (Network Area Storage) or other mounting possibility.

An Arduino is completely incapable of doing such a difficult task. It's literally impossible because the processor isn't strong enough, it has no built in network capabilities that support NAS, it has no USB software built in, and so on and so on.
But you can use a Raspberry Pi. They are cheap for their capabilities, they do require quite some programming to get it to work but there's a huge community that has guides for everything. Best of luck :)


text:
Adafruit CC3000 jumper pads
if I solder the jumper pads on the adafruit cc3000 for use with the Arduino Mega will it still work fine with the Uno?

+1 Looks like there is a phantom down-voter doing the rounds

What specific pads are you talking about? There seem to be some on the back of the module but those seem to be there for only testing.

@seb - did this meet your need?

I know this is a bit late, but is this question referring to the solder points for the ICSP pins on the full CC3000 board (not breakout)? If so then it will work fine with both, but then you're using two sets of pins for the same thing. Annoying design.

This module is designed to be "plug in and go" without access to anything except the connector pads at the board edge. While there are a number of pads on the face of the board these are for "experts only" access and are unneeded for normal operation.
The only soldering required should be the addition of a 9 pin row of pins to allow the CC3000 module to be plugged into a solderless breadboard or a socket. If this is all you do then the module will work directly and interchangeably with  Arduino Uno, Leonardo/Micro & Mega. These are the only Arduino versions that a full library is available for so far. ADAFruit promise more versions will be supported "sometime".
Additional information is available from
WIRELESS / WIFI / ADAFRUIT HUZZAH CC3000 WIFI BREAKOUT WITH ONBOARD ANTENNA
Solder on connector and go ...
Larger version of photo here makes pin use clear - + see link above

Example use weather station
Low power use tutorial
Example use wireless lamp
Library


text:
RTClib library dependency on Wire library
I downloaded the RTClib library from https://github.com/adafruit/RTClib.  In every provided example, #include <Wire.h> is written immediately above #include "RTClib.h" at the top of the sketch.
Why is this necessary?  I know the RTClib library requires the functionality of the Wire library but, if this is the case, why can't I just #include <Wire.h> at the top of RTClib.h?  I have tried the latter, even using just the following sketch, but my sketch failed to compile.
RTClib.h:
// Code by JeeLabs http://news.jeelabs.org/code/
// Released to the public domain! Enjoy!

#ifndef _RTCLIB_H_
#define _RTCLIB_H_

#include <Wire.h>
...

#endif // _RTCLIB_H_

Sketch:
#include "RTClib.h"
void setup() {}
void loop() {}

In addition, it's generally bad practice to include libraries in header functions that are exposed to the user because that can often lead to odd bugs with multiple definitions/etc.

Not getting too formal here, The arduino IDE looks at which libraries are included in the top level sketch when deciding what libraries to include in the compilation.
It would make sense for only RTClib.h to include Wire.h yes, but the IDE does not get the information to add Wire to the compilation list that way. It is a quirk of the IDE that makes implementing libraries that use other libraries a bit more painful.


text:
Arduino UNO does not get recognized by PC(no USB connecting sound), also TX and RX not blinking, neither are lit
I am trying to build a robot, which needs motors to roll around. So I was trying to control two DC motors with H-Bridge that comes with Arduino StarterKit(H-bridge motor driver [L293D]). I used Sketch that looks something like that
I did read that Arduino needs separate powering, but i did not use any only USB connection. I connected 5V that comes from arduino to where + pin from battery should have been connected and motors were controlled and working.
However when i tried using 9V battery and connecting it as seen on above picture ,H-bridge did not control mototrs and nothing was working.
There is also another aspect - when robot was touching the surface then wheels did not move aka motors did not rotate and when you picked it up motors accelerated to quite some speed. Also when robot was on the surface and connected via USB, the PC made these USB connecting sounds repeatedly.
I am not sure when RX and TX stopped working. Power LED and L13 LED do work correctly.
Any ideas? Is it Fixable?

Probably not - connecting a higher voltage to the 5v line likely killed it.  As for your performance issue, bipolar bridges such as L293/L298 have a lot of loss, so on batteries you may do better with an FET device like a TB6612FNG - but beware it is more delicate in the face of electrical abuse.  Did your bridge get hot?  What is the voltage & current ratung if your motors?

I did not touch the bridge so I do not know if the bridge got hot or not. Motors operating voltage is 1.5V to 3,3V and 10000rmp. What do you mean "connecting a higher voltage to the 5v"? I never connected 9V battery to arduino's 5V pin.

You should definitely avoid connecting anything else than 5v to these 5v(!) PINs. The Uno has regulators, but these only work when powered through the power-dc-connector (or USB). You can easily buy a 9v-block to dc-jack cable to connect power to the right point easily.

The "5V" pin takes only regulated 5V input.  Your schematic shows the the board powered here, and you mention 9V battery.  That's not a good idea.
If you have 7V-12V, then you can supply the board via the "Vin" pin.  It passes through the same regulation circuits that the DC jack does.
http://arduino.cc/en/Main/ArduinoBoardUno

VIN. The input voltage to the Arduino board when it's using an external power source (as opposed to 5 volts from the USB connection or other regulated power source). You can supply voltage through this pin, or, if supplying voltage via the power jack, access it through this pin.

May be your ATmega328 IC would have been damaged or ATmega16u or ATmega8u chip was damaged. I also got same few days ago.


text:
Identifying Arduino-compatible board signatures in code
I am developing libraries for compatibility across a number of Arduino/compatible boards. I know that Arduino boards can be identified by the test "#if defined (AVR_ATmega328P)" and compatibles as well: #if defined(TM4C123GH6PM).   There are a few lists of these IDs on the web but are all outdated. I have searched various cores and library code and do not see where these defines are actually defined.
Nick Gammon's Sketch to detect Atmega chip types identifies the chip type. What I'm looking for the board type to define pin configurations, etc.
Where and in what format are board signatures stored? Is there c++ code that can find the board signature? Does anyone know of a site where these signatures are stored and updated by the Arduino community?

In the boards.txt file each board has a board type definition, such as:
uno.build.board=AVR_UNO

When you compile your sketch that is adapted into a "board" define by prepending -DARDUINO_ to it and adding it to the compilation command line - so that one becomes the same as #define ARDUINO_AVR_UNO.  You can, of course, test for it with:
#ifdef ARDUINO_AVR_UNO
....
#endif

The location of the boards.txt file varies with different versions of the IDE, but every installed core will have one.  Look around in your Arduino program folder in the hardware subdirectory.

Thanks, Majenko. That one has been bugging me for months.


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

Humidity rising too quickly indicates a lack of proper feedback.

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

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

Edit: You said, in comments:

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

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

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

@BrianLaebens, see my edits.

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

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


text:
Control Arduino via Wifi directly?
I want to build an arduino-based RC Tank, which should be controlled with a notebook or smartphone (Android). Bluetooth would be an easy solution, but the range is a bit short for a RC Vehicle, so I want to controll it via WIFI. I found a ton of examples and tutorials on how to do that but all of them reqire a router which both the arduino and the Smartphone are connected to. Any idea on how to directly control an Arduino with an smartphone via WIFI?

you could make an ad-hoc network with your computer and connect straight to that

If your computer/tablet/phone can act as a WiFi hotspot, you could use that to avoid the router. Many smartphones have that capability, as do many notebooks (as geometrikal mentioned, it's usually referred to as an 'ad-hoc' network on PCs). Create the network (or turn on hotspot capability), and connect to the network you created from your Arduino.


text:
Arduino Shield Pin Conflict
I have a Freetronics Etherten and am trying to use the NFC Shield - both the board and shield are trying to use Pins D10,D11,D12,D13
So my question - Is there an elegant way to have these two work together.  This really applies to any combination of shield with conflicting pins.  I'm thinking maybe use some in between headers or M/F jumper wires?
Is there a neat way to do it?

I blather on about something similar here: http://arduino.stackexchange.com/questions/3892/motor-shield-and-wireless-transceiver-compete-for-same-pins/3895#3895

You need this: https://www.sparkfun.com/products/11002
"The Go-Between Shield “goes between” two shields that aren’t compatible and effectively reassigns the pins. This trickery is achieved by isolating the top and bottom sides of the shield with surface mount headers and breaking them out into tables of jumpers that can be bridged to divert signals to and from different pins."

D11-D13 are the SPI pins. So you should only move D10 (SS) to another pin.


text:
Using a 16 bit ADC chip with arduino
I need to measure voltage between 0-10 volts using my Arduino Due.  I have an ADS7805p chip, which I believe will work, but am not sure how to wire it on my breadboard.  I'm used to just using the chip on the arduino, but that only goes 0-5 volts and I can't loose the resolution by converting.  Can someone, please, point me to or instruct me on how to wire something like this to my arduino?

Why not just halve the voltage?

When you say "using the chip on the arduino", I guess you mean "directly using the analog inputs of arduino", is that correct?

The important question here is: do you absolutely need 16 bits resolution (as offered by ADS7805 ADC) or can you deal with just 10 bits, or even 12 (as supported by Arduino DUE)?

If 10 or 12 bits resolution is OK, then @Ignacio suggestion is probably the best way to follow.

I do need 16 bit resolution.

A 16-bit ADC will give you a 16-bit result, but the least significant bits won't actually be correctly representative of the signal.  You'll get better results if you can take multiple measurements and filter them (average them in the simplest case).

@ChrisStratton This tampering technique works for standard applications, low quality sensors, low quality ADCs. What if the sensor has a great dynamic range?. What if the application captures the high order modes? Removing LSB data and FIR averaging by design is inappropriate.

@hyprfrcb please spend some time studying signal processing theory, as your claims are exactly backwards.  Averaging doesn't decrease level resolution ("removing LSB data") on the contrary, provided you do not truncate your calculation, it actually increases resolution.  If the extra data is meaningful or not depends on if the input and conversion noise has a characteristic suitable for statistically sampling the desired signal.  Often in the real world it does to a useful extent.

"Averaging" from "extra", "statistical", "meaningful" data, only confirms that your sensors are untrustable. With high dynamic range (~120dB), low noise (~0.01% error or less) sensors, you dont need to do that. Never. And again, when interested in high frequency modes, that tampering is the worst design.

@hyprfrcb "tampering" is not a meaningful term of signal processing - that you would persistently insist on mis-using only confirms this is not a familiar subject area for you.  Bandwidth and resolution are indeed extremely distinct subjects.  Very few sensors actually have > 120 dB dynamic range, when they do, they push the limits of ADC technology.  But if you study deeper, you'll discover that noise of the proper character can manage to statistically sample with finer resolution than the ADC.  Keep studying - you still have a lot to learn about everyday practices in this industry!

Well, you are the one who must study indeed. And it is a shame you dont have experience and knowledge in 24 bit ADC DAQs or 120dB dyn range sensors. Good luck averaging your sensors for getting ride of the noise!

The ADS7805 is old but still a pretty good ADC. I could imagine that you just have a few lying around that you want to use. I would simply wire it to two parallel in / serial out chips like the 74HC589 or CD4021 as used in this example:
http://www.arduino.cc/en/Tutorial/ShiftIn
Start the conversion as described in Duncan C's answer and then simply clock in all 16 bits. I think you could then probably get away with 4 or 5 control lines.

If you really need 16 bits of resolution then you could use that chip, but it's going to be a lot of work. Also beware that according to Mouser's website, it is not recommended for new applications. It sounds like it's being phased out/replaced.
Take a look at the data sheet linked from Mouser's website:
ADS7805p datasheet
It has 16 bits of parallel data output, plus what sounds like 2 control lines, CS and R/(not)C (Don't know how to make the proper symbol.)
It sounds like you pull CS and R/C low to trigger a conversion, then wait for not busy to go low, switch R/C to high, then read the 16 bits of data.
To use this chip you're going to need 18 or 19 pins from your Arduino. You might want to consider a chip with a serial interface instead.

I saw that bit about not being recommended for new applications.  I'm looking around now to see if I can find a 0-10v one now.  Thanks for the thought.

The due has plenty of pins, but they are 3.3v and the ADC uses 5v logic.