text:
Long Distance Communication with Arduino
I am reading the value of six potentiometers with a TX Arduino and receiving that data and applying those numbers to a motor using serial. It is working fine through TTL but I am going to need to do this over a 60 ft tether.
I have done a little research and see that I could use RS 232 but that the maximum you should go with that is 50 ft, which will not work if I'm not mistaken. I have also seen RS 485 which will give us 4000 ft, which is overkill but will work. However, that only offers one-way communication, if I'm not mistaken. What I'm wondering is which protocol should I convert it to, and how I would have to adjust my RX and TX code.
TX code:
/*
  Transmitting Code
  Reads potentiometers and sends them through serial
*/

int data [10];     // to send bytes
int start [2];
int pot0Pin = A0;  // analog pin used to connect the potentiometer
int pot0;          // variable to read the pot0ue from the analog pin
int pot1Pin = A1;
int pot1;
int pot2Pin = A2;
int pot2;
unsigned char checksum0;
unsigned char checksum1;
unsigned char checksum2;

void setup() {
  Serial.begin(9600);
  Serial1.begin(9600);
  pinMode(19, INPUT);
  pinMode(18, OUTPUT);
}

void loop() {

// READ THE POTENTIOMETERS:

  pot0 = analogRead(pot0Pin);   // reads the value of the potentiometer (pot0ue between 0 and 1023)
  data[0] = pot0 & 0xFF; //least significant 8 bit byte
  data[1] = (pot0 >> 8); //most significant 2 bits

  pot1 = analogRead(pot1Pin);
  data[2] = pot1 & 0xFF;
  data[3] = (pot1 >> 8);

  pot2 = analogRead(pot2Pin);
  data[4] = pot2 & 0xFF;
  data[5] = (pot2 >> 8);

// CREATE CHECKSUMS:

  checksum0 = ~(data[0]+data[1]) + 1;

  checksum1 = ~(data[2]+data[3]) + 1;

  checksum2 = ~(data[2]+data[3]) + 1;

// WRITE VALUES AND CHECKSUMS TO SERIAL:

  Serial1.write(data[0]);
  Serial1.write(data[1]);

  Serial1.write(data[2]);
  Serial1.write(data[3]); //bytes sent

  Serial1.write(data[4]);
  Serial1.write(data[5]);

  Serial1.write(checksum0);

  Serial1.write(checksum1);

  Serial1.write(checksum2); // send the checksum

 delay(10);        // delay in between reads for stability

}

RX code:
/*
  Receving Code
  Reads bytes from Transmitting Code and put thems back together
  Applies the read bytes to our motor control board
*/
unsigned char val[10];    // variable to read the value from the analog pin
int motorVal;
int coolVal;      // 0-1024 received from serial
int coolVal1;
int coolVal2;
unsigned char checksum1;
unsigned char checksum2;
unsigned char checksum3;
unsigned char checkit1;
unsigned char checkit2;
unsigned char checkit3;
int directionPin = 8;
int PWM_out_pin = 9; // works on pins 2 - 13 and 44 - 46

void setup() {
  Serial.begin(9600);
  Serial1.begin(9600);
//  Serial1.begin(9600);
  pinMode(10, INPUT);
  pinMode(18, OUTPUT);
  pinMode(8, OUTPUT);
  pinMode(9, OUTPUT);
}

void loop() {

  if (Serial1.available()>5) {

    val[0]=Serial1.read();         // least significant 8 bits
    val[1]=Serial1.read();         // most significant 2 bits

    val[2]=Serial1.read();
    val[3]=Serial1.read();

    val[4]=Serial1.read();
    val[5]=Serial1.read();

    checksum1=Serial1.read();
    checksum2=Serial1.read();
    checksum3=Serial1.read();// get the checksum last

    checkit1 = val[0]+val[1]+checksum1;
    checkit2 = val[2]+val[3]+checksum2;
    checkit3 = val[4]+val[5]+checksum3;

  if (checkit1==0);  {
    coolVal = val[1]<<8 | val[0]; }

  if (checkit2==0);  {
    coolVal1 = val[3]<<8 | val[2];}

  if (checkit3==0);  {
    coolVal2 = val[5]<<8 | val[4];
    }

    Serial.print(coolVal);
    Serial.print(" ");
    Serial.print(coolVal1);
    Serial.print(" ");
    Serial.println(coolVal2);
    delay(10);

  }

// FOR MOTOR 1 (more will be added once we achieve successful serial):
  if (coolVal > 550) {
    digitalWrite (directionPin, HIGH);
    motorVal = map(coolVal, 550, 1023, 0, 1023);
    analogWrite (PWM_out_pin, motorVal / 4); }

  if ((coolVal < 550) && (coolVal > 500)) {
    digitalWrite (directionPin, HIGH);
    analogWrite (PWM_out_pin, 0); }

  if (coolVal < 500) {
    digitalWrite (directionPin, LOW);
    motorVal = map(coolVal, 0, 500, 1023, 0);
    analogWrite (PWM_out_pin, motorVal / 4); }

}

You're right that 60' exceeds the spec for RS-232. That said, distance specs are often quite conservative (as they should be, the spec is a promise that it will work and needs to account for marginal components and an unfavorable environment). I think the 50' limit for RS-232 was more observed in the breach than in practice. So for starters I'd be inclined to see if you could get 60' using RS-232 – I'd be kind of surprised if it didn't work.
Since reliability is important you're doing the right thing by checksumming and checking the data. If the checksum you use is good, it will go a long ways towards letting you detect corrupted data. Then, even if you are using a less than perfect underlying medium (e.g., RS-232 over a long distance), you can improve reliability by ignoring any corrupted values you receive. What that won't protect you from is a major data loss – for example a cut in your cable or a very noisy environment where most of your messages are getting lost. To defend against that you need a mechanism that also acknowledges your transmissions.
So, at this point you've got a choice – you could keep thinking of what might go wrong and designing solutions, or you could see if you could build on existing work. One thing you might want to look at is using something like the SLIP (Serial Line IP) protocol which was developed to run TCP/IP over a dialup modem back in the dark ages of the Internet. I found, but haven't tried out, a couple of implementations for the Arduino:

SerialIP Library for Arduino - a "proof of concept" version on the Arduino Playground.
Open Sound Control over SLIP - newer, but not sure how hard it would be to extract out the SLIP part.

RS-485 is (can be) bi-directional, you just need a transmitter and receiver at each end. Another approach would be to use a 4-20 mA current loop.
You might also want to look into making the controller wireless. That would get you some added convenience (at the expense of a tether to help you find where you put the box) as well as a reliable two-way communication protocol.

I would say the same but this has to be very reliable. It seems that the farther it'll go the less reliable it'll get. What do you think?

Why do you need it to be very reliable? You are already adding checksums, and sending the data every 10ms. It seems to me like some loss wouldn't be that much of a problem. Though extended durations of loss would be.

So dlu, do you think that if using the checksums RS-232 makes the most sense? We want our tether as light as possible so it would be helpful to have just the three wires from RS-232 vs. the two twisted pair on RS-485, as we plan on having the RX code also transmit some information back.

Also, @dlu, am I not using the checksum correctly in my portion of code that states:  if (checkit1==0);  {
coolVal = val[1]<<8 | val[0]; }

Since you need a reliable way to get the values from your tether then checksumming is a really good idea – it helps you know that you got the data you sent. Then the choice of medium (RS-232 vs. 485 vs. current-loop) can be based on other considerations – for example, cost or ease of use. Not that you should ignore the reliability of the underlying medium, but now you have a way to be more confident of it. Since there is no guarantee that the medium is good (e.g., the cable could get disconnected or cut) sending information back is a good thing, it further ensures reliability.

My apologies, after reading your comment and your code more carefully, it does look like the checksum is being used. I'm sorry about that. However, I notice that you're not initializing any of the coolVal* variables. I'd (strongly) suggest doing that, both as documentation and as a guard against the possibility that the compiler doesn't set them to 0 (hangs head and admits that he doesn't remember what the standard says here).

@dlu - I thought I was using the checksums but when viewing the Serial Monitor I'm not getting correct values, it seems some bytes are shifting. Is there a reason for this?

9600 baud isn't very demanding by today's standards. I'd try going the 60' with RS-232. Maybe you'd need to use a shielded cable if your environment is noisy. Try sending some readable strings that you can quickly check by just reading, such as "The quick 9600 baud data string leaps over the fifty foot barrier." or some such. :)  You'll know quickly whether your data got walked on or your checksum calculations are failing.

@MichaelGeorgariou - one reason could be the Serial1.available() > 5 test. I think it is wrong, since you need to read 9 bytes to get your checksum and data.

Another thing to keep in mind is that you don't currently have any way to sync up your transmitter and receiver, you just assume that you'll get a complete packet each time. You should probably be sending a "Start of Message" byte (some value that will never appear as part of the normal data stream) that you search for before starting to read values.

@dlu What could I use for the Start of Message byte?

It could be anything – thinking about it, it doesn't have to be a value that doesn't show up else wise. You just start by looking for it. If it is in the "wrong" place then the checksums will fail and you'll need to start over. Eventually you should (will) sync.

You can do two-way communication with RS485. I have a page about RS485 with schematics and code, including calculating checksums.
You don't have to use twisted cable, that would just add to the reliability. You would need 4 cores (power, ground, A and /B) however if the other end was self-powered (ie. a battery) then you could skip that. There has been a bit of debate about whether the ground wire is needed (assuming you don't send power) but it is probably sensible to include it.
The page I linked above also describes a rolling master system, where each node has a chance to "talk" to other nodes. This demonstrates that you can send and receive on the same pair of wires.
In my test of the rolling master (using UTP cable) I had it working over 40 meters (ignore the figure on the schematic). So your 50 feet range should be easily achievable.

Thanks, Nick. The reason we're hesitant is that we want to limit the amount of wires in the tether, because we are under a weight limitation and would like to have as much as backup weight allocation as possible. Another rule is not being able to have a power source on the other end.


text:
Arduino Uno - Analog Circuit Simulator
I control an analog circuit with Arduino Uno. I want to simulate an Arduino Uno with operational amplifiers (741). Can I simulate Arduino with SPICE?

No, there is no SPICE model for an Arduino. But then given that an ATMega328 doesn't have any DAC capabilities you would only need to feed in a digital stimulus to your simulation.

Here is the one which is closest to be useful for your question
Link: https://markmegarry.github.io/AVR8js-Falstad/
Try it out for yourself
It is very slow though.

You could use https://en.wikipedia.org/wiki/Ngspice.
From what is written there, the Xspice part could be used for creating a simple model of the Arduino, for checking how the analog part of your circuit interacts with the uC.
Unfortunately the main site () is down, atm, as many other projects hosted on SourceForge. But it might be worth having a look, once it's back online.

source: Stack Exchange

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

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

sort: votes


text:
I need help purchasing components for my Arduino project
I am a newbie on this hardware stuff. I need help on purchasing the components
Brief description of my project
I need a device that would remotely detect weight or pressure when somebody push on it and send the info to the webserver or websockets. The device could be located up to 300 ft.
After doing some research on it I learned that I need, arduino uno as the device main platform, xbee for wireless communication with the web, xbee shield for the xbee and Force sensitive resistor sensor to detect small weight or pressure.
Question
First am I correct above mentioned components would solve what I am trying to do? If not what am I missing? Anything I mis-stated?
I have learned that there are stuff like xbee explorer, Arduino stackable headers, break-away headers, and breadboard. Do I really need these?
In the future I want to be able do other experiments with the board like use ultrasonic sensor with it or infrared sensor to detect objects. Will I need to buy anything specific to make these sensors compatible with the board or they are all standard?
Basically I want to buy everything I need in one shot. Thank you in advance. Any help will be appreciated.

Shopping questions are explicitly OFF TOPIC on this site.  Re-read the guidelines you were supposed to have read when you signed up.

I would rather go with ESP8266. You can program that from the Arduino IDE. You don't need anything else than a programming cable (an USB-UART adapter), and you can connect the force sensor to the analog input with one pullup resistor.
There is a similar idea with one button here:
https://www.hackster.io/noelportugal/esp8266-ifttt-easy-button-888a87
You can build your own force sensor:
http://www.todayifoundout.com/index.php/2010/01/how-to-make-a-ridiculously-cheap-analog-pressure-sensor/
If you don't really need to measure the force, there are much easier solutions to detect weight of a person. These give a simple contact once pressed, and can be used like a button (see the first link in my answer).
http://learning.media.mit.edu/projects/gogo/documents/making%20sensors.html#Paper and Aluminum foil.
It is not really possible to buy everything as one batch :) I would say you need:

connection wires
plyers
some cheap multimeter
you may wish to power your device from a battery, so you may need a battery holder and batteries
battery voltage may not be a perfect match for ESP8266, so you might want to get a board with internal regulator, such as https://www.adafruit.com/products/2471
it is handy to start with a breadboard with jumper wires, something like https://startingelectronics.org/beginners/start-electronics-now/tut1-breadboard-circuits/building-cct-step5.jpg

I suggest you to find an ESP8266 based tutorial, Adafruit has a lot of those, and then you'll have an understanding about the tools and components needed.
If you buy some Arduino, consider buying the ones using 32u4 chip, such as Arduino Leonardo or Arduino Micro. The 32u4 chip has more memory, and more performance than the original Arduino Uno, plus it can work as an USB mouse or an USB keyboard too.
For infra (do you mean a PIR which detects humans, or a reflective sensor?) you have quite a lot of possibilities. In case of using ESP8266 directly, check that the sensors work on 3.3V. Some stuff works on 5V, others on 3.3V. You can interface them easily, but this is just another extra thing to cover, so better go with a dedicated 3.3V sensor.
Ultrasonic sensors are coming also in a lot of varieties. Do you need something ridiculously cheap? A sensor with a short range? A sensor with a longer range? I think you have to set up your goal first.
The Leonardo and Uno and Micro boards work both with 5V and 3.3V sensors. Driving these sensors are quite standard, you need to power them with two wires, and have one wire which goes from 0V to 5V (or vice versa) when something is detected. Ultrasonic sensors vary: there are sensors with one analog output, giving a voltage between 0V and 5V propoprtional to the distance. However most of ultrasonic sensors are simple as the ultrasonic principles: they have one input what you drive, and will give one output of the recived echo signal. In this case you have to measure the time elapsed between the drive signal and the echo, which depends on the distance of the object from the sensor.

The ATmega32u4 does have some advantages, and the ability to run code directly on the ESP8266 can simplify projects too.  However, it might not be a bad idea for a beginner to have an absolutely ordinary Uno/Duemilanove type ATmega328p board on hand in order to be able to use peripheral example code without any changes - as working out what does have to change for other boards can take a little experience.

@Gee Bee Thank you very much. Do you think xbee should work for sending data to the internet(through websocket)? (I don't want to user ethernet because i want it to be wireless and i don't want to use wifi because it consumes lots of power.)

I am unsure how do you mean xbee. It is a form factor of various communication products from Digi, see http://www.digi.com/lp/xbee Unless you're using xbee wifi, you can't go to the internet with an xbee module alone. These modules are built to form an intellingent internal wireless network, but require a sort of a concentrator or network hub which has a wifi or ethernet connection if you want to go to the Internet.

You may not wish to rule out wifi just "because it consumes a lot of power". Any technology will consume a lot of power. The trick is to keep the communication interval at a minimum. In your case, the device can do nothing, and stay in deep sleep consuming 88uA when no humans are detected. The detection can wake up the module, the module will connect to an access point, send the data, and will consume 200-400mA for 1.5 seconds, then go back to sleep. Average current draw? It runs for 2 days on 2 AA batteries if you don't do sleep. If you do the sleep trick, it can run a year.

Oh wow i didn't know that.Thank you very much that was helpful.

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


text:
Project 2: Arduino controlled spaceship interface
The circuit diagram attached shows that the switch is open. Yet, the LED connected to pin 3 of the arduino board lights up.

I don't understand this - the circuit is open, so why should pin 3 light up?
I discussed this with one of my friends - he said that each pin on the board receives voltage after the battery is connected. If this is true, then that would answer my question.
This is my code:
int switchState = 0;
//configures the digital pins
void setup() {
  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(5, OUTPUT);
  pinMode(2, INPUT);
}

//Checks the voltageo of the digital input and chooses the pin for voltage ( pin 2 )
void loop() {
  switchState = digitalRead(2);

  if (switchState == LOW) {
    //Button is not pressed

    digitalWrite(3, HIGH); //Green LED
    digitalWrite(4, LOW); //Red LED
    digitalWrite(5, LOW); //red LED
  }

  else { //the button is pressed
    digitalWrite(3, LOW);
    digitalWrite(4, LOW);
    digitalWrite(5, HIGH);

    delay(250); //wait for a quarter second
    //toggle the LEDs
    digitalWrite(4, HIGH);
    digitalWrite(5, LOW);
    delay(250); //wait for a quarter second
  }
} //go back to the beginning of the loop

Impossible to say without seeing your code. Why does anything happen in code that you can't see? Please edit your question and include it.

What I can tell you from the diagram is that pin 2 is grounded when the switch is open and at 5V when it's closed.  That wouldn't mean anything for pin 3 unless the chip alters 3 depending on 2.

he said that each pin on the board receives voltage after the battery is connected - not unless the code tells it to.

To elaborate on Nick Gammon's comment, at power on, all the Arduino pins, except power lines, are tri-stated, i.e. in a high-impedance state. This means they will not source nor sink any significant current. Then the Arduino starts executing whatever program was last uploaded into it. If an LED lights up, it does so under the program's command.

@NickGammon: Here's the code:

http://forum.codecall.net/blog/1824/entry-1957-arduino-project-02/

@NickGammon - thanks for your replies. See my comment below:
I understand the code well. But my question is more to do with the circuit diagram (see http://c03.apogee.net/contentplayer/?coursetype=foe&utilityid=gulfpower&id=4702) - based on this link, no current flows through the open circuit and the bulb doesn't light up.
The code tells Uno "if the switch isn't connected", light up green led that is connected to pin 3. Does that mean that there is some internal wiring between ground and pin 3 that supplies current to the green LED?

@EdgarBonet  - see comment to Nick Gammon.

@CandiedOrange - see comment to Nick Gammon.

You don't need to copy and paste the same comment 3 times. That's just clutter. Four times if you count virtually the same comment on the answer below. I've edited the duplicate comments out.

“there is some internal wiring between ground and pin 3”. There is an internal electrically controlled switch (we call that a transistor) between each pin and GND, and another one between the pin and +5V. The latter is the one that lights up the LED.

@EdgarBonet - thank you, Mr Bonet (& RSM and CandiedOrange as well) for you insights.

So everyone else knows where this is from enter image description here.

EDIT
I have edited the image you gave to attempt to answer your question on 'wiring' :

The first image shows simply and crudely how the parts are basically connected or there relationship.
The second one shows how the current flows on the circuit, there is a key.
What you need to do is take the information from the link you give in the comment and apply logic to it, like if you used a logic probe and stuck it one end of the switch, the right side in that image, it would be high, if though you do so on the left it would be low. Hence no current flows in that circuit but there is current flow in the circuit looking at it.

What you have not examined is the code related to your project or the description of the project.
Looking at the code:
// Create a global variable to hold the
// state of the switch. This variable is persistent
// throughout the program. Whenever you refer to
// switchState, you’re talking about the number it holds
int switchstate = 0;

void setup() {
  // declare the LED pins as outputs
  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(5, OUTPUT);

  // declare the switch pin as an input
  pinMode(2, INPUT);
}

void loop() {

  // read the value of the switch
  // digitalRead() checks to see if there is voltage
  // on the pin or not
  switchstate = digitalRead(2);

  // if the button is not pressed
  // turn on the green LED and off the red LEDs
  if (switchstate == LOW) {
    digitalWrite(3, HIGH); // turn the green LED on pin 3 on
    digitalWrite(4, LOW);  // turn the red LED on pin 4 off
    digitalWrite(5, LOW);  // turn the red LED on pin 5 off
  }
  // this else is part of the above if() statement.
  // if the switch is not LOW (the button is pressed)
  // turn off the green LED and blink alternatively the red LEDs
  else {
    digitalWrite(3, LOW);  // turn the green LED on pin 3 off
    digitalWrite(4, LOW);  // turn the red LED on pin 4 off
    digitalWrite(5, HIGH); // turn the red LED on pin 5 on
    // wait for a quarter second before changing the light
    delay(250);
    digitalWrite(4, HIGH); // turn the red LED on pin 4 on
    digitalWrite(5, LOW);  // turn the red LED on pin 5 off
    // wait for a quarter second before changing the light
    delay(250);
  }
}

From this we see that the default state of this code in the first if() statement is to turn on PIN3 and leave the rest off when the button is not pressed.
From Arduino:

 A green LED will be ON, until you press a button. When the Arduino
 gets a signal from the button, the green light will turn off and 2
 other lights will start blinking.

Thanks @RSM - I understand the code well. But my question is more to do with the circuit diagram (see http://c03.apogee.net/contentplayer/?coursetype=foe&utilityid=gulfpower&id=4702) - based on this link, no current flows through the open circuit and the bulb doesn't light up.
The code tells Uno "if the switch isn't connected", light up green led that is connected to pin 3. Does that mean that there is some internal wiring between ground and pin 3 that supplies current to the green LED?

@user755939 Yes, that internal wiring is called the chip.  You don't see it in the diagram. The code is controlling the behavior of that internal wiring but if the chip wasn't getting pulled high on the 5V pin and grounded on the GND pin it wouldn't be able to do a blessed thing with any of the other pins no matter what your code says.

@user755939 Is your problem that the diagram doesn't show any power source?  That's supposed to be assumed.  It doesn't come from the chip.  It's simply not shown as anything other than 5V and GND.

@user755939    I am going to be honest, I don't think you have grasped the basics of electronics and to your credit you are attempting to apply general electrical knowledge to embedded design and electronics. What you need to do is understand the basic construction of a microcontroller, this will help you understand the interaction between it and the code and external components.

@user755939    please examine the updated answer attempting to simplify the basic of the circuit

Where is all this confusion coming from?
  if (switchState == LOW) {
    //Button is not pressed

    digitalWrite(3, HIGH); //Green LED

Your code says, if the switch is not pressed, light LED on pin 3.

I don't understand this - the circuit is open, so why should pin 3 light up?

Because that is what the code tells it to do.

Does that mean that there is some internal wiring between ground and pin 3 that supplies current to the green LED?

Get the idea out of your head that this is some wiring issue. Your device is doing exactly what you are telling it to do.
When you digitalWrite HIGH to some pin, the processor activates the output driver MOSFET that attempts to drive the pin to +5V. Therefore current flows through the resistor to the LED which lights up.


text:
How to unify all RPS reading in one function?
Want to unify rps reading in one function.
However, it shows incorrect values.
when it is reading for one it works fine.
Following is the code. Appreciate for your help.
float rps[4] = {0.00, 0.00, 0.00, 0.00};
long int PRINT_PERIOD = 1000;
long int lastTimePrinted = 0;

void setup() {
    Serial.begin(9600);
    DDRD &= ~_BV(7); // pinMode(7, INPUT);     // rps_1
    DDRB &= ~_BV(0); // pinMode(8, INPUT);     // rps_2
    DDRC &= ~_BV(1); // pinMode(A1, INPUT);    // rps_3
    DDRD &= ~_BV(2); // pinMode(2, INPUT);     // rps_4
}

float rps_out(int k) {
    static int lastReedState;
    static unsigned long lastTransition;
    static float rps_result;
    int reedState;
    unsigned long now;
    unsigned long revolutionTime;

    if (k == 1)    reedState = (PIND & _BV (7)) == 0; // digitalRead(7);
    else if (k==2) reedState = (PINB & _BV (0)) == 0; // digitalRead(8);
    else if (k==3) reedState = (PINC & _BV (1)) == 0; // digitalRead(A1);
    else if (k==4) reedState = (PIND & _BV (2)) == 0; // digitalRead(2);

    // HIGH LOW measuring the low period
    // LOW HIGH measuring the high period
    // On a rising transition of the reed switch:
    if (reedState == HIGH && lastReedState == LOW) {

        // Compute time since last valid transition.
        now = micros();
        revolutionTime = now - lastTransition;    // measuring the High period
         rps_result = 1.00 / (12.00*revolutionTime) *1000000.00;  // 12 is rotary encoders resolution
        // Remember this transition.
        lastTransition = now;
    }

    // Remember last state.
    lastReedState = reedState;

    return rps_result;
}

void loop() {
    rps[0] = rps_out(1);
    rps[1] = rps_out(2);
    rps[2] = rps_out(3);
    rps[3] = rps_out(4);

    if (millis() - lastTimePrinted >= PRINT_PERIOD) {
        Serial.println(rps[0]);
        Serial.print(',');
        Serial.println(rps[1]);
        Serial.print(',');
        Serial.print(rps[2]);
        Serial.print(',');
        Serial.println(rps[3]);
        lastTimePrinted = millis();
    }
}

worked code except for rps[3] at the beginning. it shows rps[3] = 672.04
float rps[4];
long int PRINT_PERIOD = 100;
long int lastTimePrinted = 0;
int lastReedState[4];
unsigned long lastTransition[4];
int reedState[4];
unsigned long now[4];
float rps_result[4];
unsigned long revolutionTime[4];

void setup(){

 Serial.begin(9600);

 DDRD &= ~_BV (7); // pinMode (7, INPUT);       // rps_1
 DDRB &= ~_BV (0); // pinMode (8, INPUT);       // rps_2
 DDRC &= ~_BV (1); // pinMode (A1, INPUT);      //  rps_3
 DDRD &= ~_BV (2); // pinMode (2, INPUT);       //  rps_4

}

float rps_out(int k){

    //static int lastReedState;
    //static unsigned long lastTransition;
    //static float rps_result;
    //float rps_result;
    //int reedState;
    //unsigned long now;
    //unsigned long revolutionTime;

   if ( k == 0 )     reedState[0] = (PIND & _BV (7)) == 0; // digitalRead (7);
   else if ( k==1 )  reedState[1] = (PINB & _BV (0)) == 0; // digitalRead (8);
   else if ( k==2 )  reedState[2] = (PINC & _BV (1)) == 0; // digitalRead (A1);
   else if ( k==3 )  reedState[3] = (PIND & _BV (2)) == 0; // digitalRead (2);

    // On a rising transition of the reed switch:
    if (reedState[k] == HIGH && lastReedState[k] == LOW) {                   // HIGH  LOW   measuring the low period    // LOW HIGH measuring the high period
        // Compute time since last valid transition.
        //unsigned long now = micros();
        //unsigned long revolutionTime = now - lastTransition;       // measuring the High period
         now[k] = micros();
         revolutionTime[k] = now[k] - lastTransition[k];       // measuring the High period
        // Compute the rps

        if(revolutionTime[k] == 0 ) rps_result[k] = 0.00;     // avoid deviding by zero

        else rps_result[k] = 1.00 / (12.00*revolutionTime[k]) *1000000.00;  // 12 is rotary encoders resolution

        // Remember this transition.
        lastTransition[k] = now[k];

    }

    // Remember last state.
    lastReedState[k] = reedState[k];

    return rps_result[k];

}

void loop() {

   rps[0] = rps_out(0);
   rps[1] = rps_out(1);
   rps[2] = rps_out(2);
   rps[3] = rps_out(3);

    if (millis() - lastTimePrinted >= PRINT_PERIOD) {

     Serial.print(rps[0]);
     Serial.print(',');
     Serial.print(rps[1]);
     Serial.print(',');
     Serial.print(rps[2]);
     Serial.print(',');
     Serial.println(rps[3]);

      lastTimePrinted = millis();

     }

}

Remember your question Getting different results from function? Same problem here: rps_out() has state (its static variables), and the state should be stored independently for each channel. Same solutions as in the answers you already got. Oh, and you forgot to actually compute rps_result.

ok, I added rps_result calculation.

So you mean I have to make rps_result as an array?

@edgar could  you please explain in detail which one should be as global array?

I have done it, except for the last one rps[3]. it is  supposed to be rps[3].=0.00 at the beginning. However, it shows  rps[3] = 672.04.  What is wrong?

Any help please.

I got stuck with the initial value of the last one.

I only see a couple of small issues with your updated code: 1) lastTimePrinted and PRINT_PERIOD should be unsigned, PRINT_PERIOD should be const also. 2) reedState, now and revolutionTime don't need to be stored between calls to rps_out(): they can be local scalar (i.e. not array) variables of rps_out(). However, none of these are critical, and I see no reason why channel 3 should behave differently than the others. The reason may well be outside the code, in the hardware.

Your problem is that you have one set of (static) state information that you are trying to use for all your inputs. That's never going to work. You need separate state information for each and every input.
There's numerous ways of doing that:

The traditional C library "re-entrant" style. This involves passing pointers to any state variables into your function. The caller is responsible for creating and managing these variables and passing the pointers when the function is called. This is messy but pretty much completely portable across systems since it doesn't rely on any C++ facilities.
Similar to option 1 but grouping your different state variables into a struct to make things cleaner.
Global arrays - have a global array (maybe of structs as in option 2) to store the state information and pass the slice number to your function.
The OOP (C++) way - create a class with all the state variables and functions within it then instantiate a new object for each input. This is by far the cleanest and most self contained way but does require knowledge of creating and using classes.

Of the four options I would most likely choose option 4:
class RPS {
    private:
        uint8_t _pin;
        uint8_t _lastReedState;
        uint32_t _lastTransitionTime;
        uint32_t _rps;

    public:
        RPS(uint8_t pin) : _pin(pin) {}
        void begin() {
            pinMode(_pin, INPUT);
            _lastReedState = digitalRead(_pin);
            _lastTransitionTime = millis();
            _rps = 0;
        }
        void calc() {
            uint8_t reedState = digitalRead(_pin);
            if (reedState != _lastReedState) {
                uint32_t now = millis();
                _lastReedState = reedState;
                if (reedState == HIGH) {
                    uint32_t diff = now - _lastTransitionTime;
                    if (diff == 0) {
                        _rps = 0; // Avoid divide by zero
                    } else {
                        _rps = 1000 / diff;
                    }
                }
                _lastTransitionTime = now;
            }
        }
        uint32_t get() {
            return _rps;
        }
};

RPS rps1(1);
RPS rps2(2);

#define PRINT_PERIOD 1000

void setup() {
    rps1.begin();
    rps2.begin();
}
void loop() {
    static uint32_t lastTimePrinted = 0;

    rps1.calc();
    rps2.calc();

    if (millis() - lastTimePrinted >= PRINT_PERIOD) {
        lastTimePrinted = millis();
        Serial.print("RPS 1: ");
        Serial.println(rps1.get());
        Serial.print("RPS 2: ");
        Serial.println(rps2.get());
    }
}

(note: Untested. It may not even compile)

Your get() method has to be called as often as possible in order to get an accurate reading of the transition time, but your loop() only calls it one per second. You may want to split this method into update() (takes the reading, to be called often) and read() (just returns _rps). You may also want to use micros() instead of millis(), for better resolution.

Good point. Fixing now.

As to millis/micros, that's up to the end user to choose. This just gives a framework for them to build on to demonstrate the concept. If you feel the need to use microseconds then you won't be wanting to use micros() since it is only a rough guestimate at the best of times. Using IC would be preferable.


text:
Getting different results from function. How to retrieve values correctly?
Trying to implement PI controller in function.
Already worked for one controller.
However, for more than one controller, the results are shifting.
Suppose to get same values in the following code.
Any help I appreciate it.
float r_in_1 = 10.00;
float y_out_1 = 5.00;

float r_in_2 = 10.00;
float y_out_2 = 5.00;

float r_o_1;
float y_o_1;

float r_o_2;
float y_o_2;

float vi_1 = 0;
float vi_2 = 0;

void setup() {

 Serial.begin(9600);

  // put your setup code here, to run once:

}

void loop() {
  // put your main code here, to run repeatedly:

r_o_1 = pow_2(r_in_1);

r_o_2 = pow_2(r_in_2);

y_o_1 = pow_2(y_out_1);

y_o_2 = pow_2(y_out_2);

vi_1 = PI_1(r_o_1, y_o_1);
vi_2 = PI_1(r_o_2, y_o_2);

Serial.print(vi_1);
Serial.print(',');
Serial.println(vi_2);
delay(1000);

}

float pow_2(float x){

float z;

z = x*x;

return z;

}

float PI_1(float r, float y){

float e;
static float sum_e=0;
float vi;
float kp=2.00;
float ki=10.00;

e = r - y;
sum_e =  sum_e + e;
vi = kp * e + ki * sum_e;

return vi;
}

What do you mean by 'more than one controller'? Please be detailed about what you are trying to achieve, and what is wrong the current result

The current result should become same value for vi_1 and vi_2. But it is shifting.

I mean when I comment out one of those  vi_1 = PI_1(r_o_1, y_o_1); or
vi_2 = PI_1(r_o_2, y_o_2); it is working fine. But when both of them are executing the result are shifting.

what is your current result? I am a bit confused by "shifting". Edit your question, add the result you got.

Ok, what I suppose to get is this  (vi_1,vi_2) is what I get in serial monitor. (900,900), (1650,1650), (2400,2400) ,(3150,3150), (3900,3900)

However, I am getting these (900,1650), (2400,3150), (3900,4650)

You see that  values are shifting, but they actually should  be identical.

Zalt, please edit the question to include that additional information, instead of just putting it in throwaway comments.

A PI controller has “state”: it has to remember the sum of all the
previous errors. If you want several controllers you have to
independently store the state of each one.
The traditional solution used by C programmers is to write a controller
function that takes an extra parameter which is a pointer to the state.
In C++ you can use a reference instead:
// PI controller.
float PIController(float &sum, float r, float y)
{
    const float kp = 2.00;
    const float ki = 10.00;

    float e = r - y;  // error
    sum += e;         // integral of error
    return kp * e + ki * sum;
}

You would use it like this:
void loop()
{
    static float sum_1, sum_2;  // State of the controllers.
    // ...
    vi_1 = PIController(sum_1, r_o_1, y_o_1);
    vi_2 = PIController(sum_2, r_o_1, y_o_1);
}

The C++ language provides a nicer way of writing the same thing: you can
use a class to wrap the state and the controlling method together under
the same name:
// PI controller.
class PIController {
public:
    PIController() : sum(0) {}
    float operator()(float r, float y);
private:
    float sum;
};

float PIController::operator()(float r, float y)
{
    const float kp = 2.00;
    const float ki = 10.00;

    float e = r - y;  // error
    sum += e;         // integral of error
    return kp * e + ki * sum;
}

Which you would use like this:
void loop()
{
    static PIController pi_1, pi_2;  // Controller instances.
    // ...
    vi_1 = pi_1(r_o_1, y_o_1);
    vi_2 = pi_2(r_o_1, y_o_1);
}

The generated assembly should not be much different. Note that in both
cases the static variables of loop() could be globals if you prefer.

The problem is you declare static float sum_e in PI_1 function. The value of will increase everytime PI_1 function is called. In 1 loop, you call PI_1 two times, resulting first call always smaller than second call because of the value of sum_e. Sum of error should be declared as global variable, and each controller has its own "sum" variable.
Declare as global :
float sum_e[100]; //for 100 controller.

Your function
float PI_1(float r, float y,int number){

float e;
float vi;
float kp=2.00;
float ki=10.00;

e = r - y;
sum_e[number] =  sum_e[number] + e;    //integrator for controller number
vi = kp * e + ki * sum_e[number];

return vi;
    }

function call
vi_1 = PI_1(r_o_1, y_o_1,1);
vi_2 = PI_1(r_o_2, y_o_2,2);

Here is the rough example. There are lot more efficient ways than this, but this should gives you some idea. You can reduce the code yourself since the values should be correct already.

If I remove static then the integrator term will not work. I mean it just prints same values constantly.

I edit my answer

what I want to do is to reduce the code.

I would like to have only one PI function. As the matter of fact  i have more controllers.

use array. you can also use it for other variables like r_o y_o vi_ etc.


text:
Arduino GSM Shield web server hangs
I use official Arduino GSM Shield with Uno R3.
I uploaded web server examples from official GSM library. I use a simple python script to make TCP/IP connections to my GSM Shield web server. I send simple requests from my computer to shield, and it responses back.
At first, this worked like a charm. I even connected a led to arduino uno, and started turn it on and off. But after some time, I get timeout errors from my script.
I turned on debug mode of gsm shield. At first, it displayed normal stuff. When connection gone between my computer and shield, it doesn't showed anything on serial window.
I thought there is something wrong with shield, but when I send a request from my computer; light of the shield indicates that there is a transmission incoming; but nothing shows on serial window. I think after some time, connection between arduino and gsm shield gets broken.
What could be done to make this web server more stable? I don't want it stop working after half an hour.
Edit: Other than loop function, my code is same as web server example in the Arduino examples.
// I connected leds to D11 and D12 to see what happens during program.
void loop(){
  GSMClient client = server.available();

  digitalWrite (11, HIGH);

  if (client) {
    while (client.connected())
    {
      if (client.available())
      {
        char c = client.read();

        // when it receives 1, D12 pin is high for 3 seconds.
        if (c == '1') {
          digitalWrite (12, HIGH);
          delay(1000);
          client.stop();
          delay(2000);
          digitalWrite (12, LOW);
        }
      }
    }
  }
}

Can you post a link to the exact example code you used? Have you made any modifications to it?

@PeterR.Bloomfield I just added what I have changed in web server example.


text:
Can I use string and int in Serial.println together?
I just yesterday started programming on Arduino, and I have a little problem.
I want to print "#S|SKAITYMAS|[1]#" in one line, except instead of "1" I would like to use an int value. However, this one doesn't work:
Serial.println ("#S|SKAITYMAS|[",LINENR,"]#");
Any hint or tips would be appreciated.

Do something like this:
Start with your string and integer:
String string = "PI is equal to ";
int integer   = 3.1416;

Then put this in your loop:
Serial.print(string);  //string here
Serial.print(integer); //int here

Serial.println();      //change line

Serial.print() doesn't change line. Its Serial.println() which is the print that changes line so everything that is printed without println will be on the same line.

The method above will work fine, but if you want to speed up the process I will recommend  to use sprint and use only once the print function from Serial.

Well as he said, he started with Arduino yesterday, let's not nuke him with some complicated stuff. keep it simple and keep it cool

Yep, just pointing out that if you want a faster way, use sprintf. Your solution works fine.

@max246: Do you have a benchmark to substantiate your claim?

I dont have one, but I used to work on a project where I had to send information pretty quickly, and by doing "print" 10 times because each parameter was a different type, this made the whole sending slow. It is probably not visible if you have a simple program but when you need to send a fast information and return very quickly, the print function was the slowest. There was a topic as well which confirmed that.

@max246: I just did a simple comparison printing a constant string (or format string) and an int variable. Not only is the sprintf() version 871 CPU cycles slower than individual Serial.print()s, it also makes the program 1314 bytes larger, and it creates an extra copy of the message in RAM. I'm glad sprintf() helped you, but that is likely related to some condition very specific to your program. You should not assume sprintf() to be generally faster. And you should not blindly recommend it over individual print()s, especially to beginners.

Wonder if using PI as an example of an Integer is a good practice, especially for beginners. Using 3 instead would have been better.

The answer by canadiancyborg is fine. However, it is always better to avoid using String objects if at all possible, because they use dynamic memory allocation, which carries some risk of memory fragmentation. Simple and safe:
int answer = 42;
Serial.print("The answer is ");
Serial.println(answer);

The only drawback is that the constant string ("The answer is ") takes some RAM. This can be avoided by embedding it in the F() macro, which means “keep this in Flash memory only”. Then, the most memory-friendly idiom is:
int answer = 42;
Serial.print(F("The answer is "));
Serial.println(answer);

He started Arduino yesterday, keep it simple for him. He ain't doing any memory large programs yet so don't comfuse him too much.

@canadiancyborg: That's why I made my first proposal simpler than yours.

It can be done the C way:
sprintf() can be used to generate a formatted string, and then Serial.println() to send the string
char buf[32];
sprintf(buf, "#S|SKAITYMAS|[%d]#", LINENR);
Serial.println(buf);

or with String class as explained here:
https://www.arduino.cc/en/Tutorial/StringAdditionOperator
  String str = "#S|SKAITYMAS|["
  str += LINENR;
  str += "]#";
  Serial.println(str);

Do not do everything in just one line, as explained on the page link above.

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


text:
Reading I2C sensors with a timer interrupt
I would like to read a sensor connected via I2C using Timer3 and Arduino Mega. Values are read from the sensor in the interrupt service routine and timer3 is set to trigger an interrupt at 200Hz.
Step I: testing the timer
I tested the timer using a counter and incrementing its value in the ISR. The output is displayed every second. It works!
200
201
200
201

CODE
// Timer variable
volatile int cont=0;

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

  setupL3G4200D(2000); // Configure L3G4200  - 250, 500 or 2000 deg/sec
  delay(1500); //wait for the sensor to be ready

  // Initialize Timer
  cli();
  TCCR3A = 0;
  TCCR3B = 0;

  // Set compare match register to the desired timer count
  OCR3A=77; //16*10^6/(200Hz*1024)-1 = 77 -> 200 Hz
  //OCR3A=193; //16*10^6/(80Hz*1024)-1 = 194 -> 80 Hz

  TCCR3B |= (1 << WGM32);
  // Set CS10 and CS12 bits for 1024 prescaler:
  TCCR3B |= (1 << CS30) | (1 << CS32);
  // enable timer compare interrupt:
  TIMSK3 |= (1 << OCIE3B);
  // enable global interrupts:
  sei();

  k = micros();
}

void loop()
{
  delay(1000);
  Serial.println(cont);
  cont=0;
}

ISR(TIMER3_COMPB_vect)
{
  cont++;
}

Step II: Reading values from the sensor in the ISR
Now I add the I2C function in the Interrupt Service Routine, but the program is blocked after the calcBias() function which reads from the sensor, measures and saves the acquisition time in the samplingTime variable.
CODE
// Timer variables
volatile float phi=0;
volatile float theta=0;
volatile float psi=0;
volatile int x = 0;
volatile int y = 0;
volatile int z = 0;
volatile int cont=0;

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

  setupL3G4200D(2000); // Configure L3G4200  - 250, 500 or 2000 deg/sec
  delay(1500); //wait for the sensor to be ready

  calcBias():
  Serial.print("Readings take: (us)");
  Serial.println(samplingTime);

  // Initialize Timer
  cli();
  TCCR3A = 0;
  TCCR3B = 0;

  // Set compare match register to the desired timer count
  OCR3A=77; //16*10^6/(200Hz*1024)-1 = 77 -> 200 Hz
  //OCR3A=193; //16*10^6/(80Hz*1024)-1 = 194 -> 80 Hz

  TCCR3B |= (1 << WGM32);
  // Set CS10 and CS12 bits for 1024 prescaler:
  TCCR3B |= (1 << CS30) | (1 << CS32);
  // enable timer compare interrupt:
  TIMSK3 |= (1 << OCIE3B);

  Serial.println("Enabling interrupts..");
  // enable global interrupts:
  sei();

  k = micros();
}

void loop()
{
  delay(1000);
  Serial.println(cont);
  Serial.println(z);
  cont=0;
}

ISR(TIMER3_COMPB_vect)
{
  // Update x, y, and z with new values 2.5ms
  getGyroValues();
  cont++;
}

void getGyroValues()
{

  //starting samplingTimer
  samplingTime = micros();

  // Gets the angular velocity from the sensor
  byte zMSB = readRegister(L3G4200D_Address, 0x2D);
  byte zLSB = readRegister(L3G4200D_Address, 0x2C);
  z = ((zMSB << 8) | zLSB);

  samplingTime = micros()- samplingTime;
}

void calcBias()
{
  Serial.println("Bias");

  // Reads sensors and display three values
  getGyroValues();

  [...]

  Serial.println(bx);
  Serial.println(by);
  Serial.println(bz);
}

void writeRegister(int deviceAddress, byte address, byte val)
{
    Wire.beginTransmission(deviceAddress); // start transmission to device
    Wire.write(address);       // send register address
    Wire.write(val);         // send value to write
    Wire.endTransmission();     // end transmission
}

int readRegister(int deviceAddress, byte address)
{
    int v;
    Wire.beginTransmission(deviceAddress);
    Wire.write(address); // register to read
    Wire.endTransmission();

    Wire.requestFrom(deviceAddress, 1); // read a byte

    while(!Wire.available())
    {
        // waiting
       // Serial.println("No Data");
    }

    v = Wire.read();
    return v;
}

I thought that the interrupt frequency was to high and I tried with 80 Hz and 20 Hz. Same results.
Here is the output:
starting up L3G4200D
Bias
4.00
0.00
-3.00
Read

Try putting sei(); at the start of the ISR. Also avoid using Serial.print inside an ISR.

Grande Gerben! It works, please write your an answer. Why do I need to enable interrupts again?

By default interrupts are disabled inside ISRs.

Try putting sei(); at the start of the ISR. I think I2C needs interrupts enabled to work.

To explain why it's necessary to (re)enable interrupts, this is what the ATmega328P datasheet says: "When an interrupt occurs, the Global Interrupt Enable I-bit is cleared and all interrupts are disabled. The user
software can write logic one to the I-bit to enable nested interrupts."

Also, note that Arduino defines an interrupts() "function" that can be used as a more readable alternative to sei() (on AVRs, it's defined as a macro that is directly equivalent to sei()).

I2C requires interrupts to work, however enabling interrupts inside an ISR is not recommended. For one thing you may get into a race condition, where another interrupt occurs while processing the existing one.
Since you are doing virtually nothing in your main loop, a more sensible design would be to simply test if it is time to take a reading, and when that time is up, take the reading then.
As an example, your main loop could be rewritten as:
unsigned long lastReading;
unsigned long lastDisplay;
void loop()
{
  if (millis () - lastReading >= 5)   // 200 Hz
    {
    lastReading = millis ();
    // Update x, y, and z with new values 2.5ms
    getGyroValues();
    cont++;
    }

  if (millis () - lastDisplay >= 1000)  // one second
    {
    lastDisplay = millis ();
    Serial.println(cont);
    Serial.println(z);
    cont=0;
    }
}

Now you don't need the timer, and you are interrupt-friendly. :)
More information about interrupts: http://www.gammon.com.au/interrupts

Thank you, with your code this solution is perfect. But in my case, there is a SerialRoutine in the loop() which sometimes takes a long time to send /receive data over the serial. If the getGyroValues is placed in the main loop, it will be delayed by the other running task and its reliability compromised


text:
Using external power supply to power leds on multiple pins (A0-A5)
I'm totally new to Arduino, and microcontrollers for that matter, so I'm having a hard time figuring out how to connect LEDs to multiple pins, but using a common external power supply...
I've created a starting light that's connected to pin A0-A4 + A5 (turn all LEDs on). I hooked each LED to its own pin directly (A0-A4) for the countdown part ("5, 4, 3, 2, 1, ..."), and then 5 additional LEDs to pin A5 ("GO!").
For the countdown part, when only one LED is on at a time, there's enough power. But if I were to light them all up at the same time, there won't be. So I figured that I should put a relay into the mix for that part, and have them draw power from an external 12 V power supply.
I did manage to make the relay work in the circuit - switching all LEDs on/off, and getting power from the external power supply, but only through one pin.
I'm not sure how to have the start lights use an external power supply, and at the same time get signals from multiple pins. How do I do that?
I'm sorry if my description is unclear. So please let me know if you need more information.

The LEDs are 3.4 V 20 mA.
The power supply I'm planning to use is 12 V.

I'm planning to have this start light - which is built in its own casing - use its own power supply, while the Arduino is running of the power from USB. So all I want to do, is to have the signals sent over to this starting light unit, and not power and ground.
UPDATE:
Here's a quick overview of how I'm testing this whole thing at the moment:

The 5 red countdown LEDs (red) is getting powered by the board itself through the pins, while the 5 "GO!" LEDs (green) are getting powered from a 12 V power supply since they're all are going to be turned on simultaneously.
My question is how I can get both the 5 red LEDs, that uses separate pins, to get powered from the external power supply as well?
Since all the LEDs are built in its own casing, apart from the microcontroller because that also handles other stuff...
Did that make any more sense at all?

You don't need a 12V supply for the LEDs. You probably don't need a separate supply at all. All you need is to switch the LEDs externally.

Could you please show your circuit? In particular, it is important to see if you use resistors in series with eache LED.

In general you don't really need 20mA current to light your LEDs, typically limiting the current to 10mA or even less will be OK. If you need 5 LEDs in parallel though, you'll probably need a transistor. Forget about relays, that's probably the most awkward way to switch LEDs!

Added some more details now

No that doesn't :))) The relay part is totally incorrect :)

How is the realy part inncorrect?

The relay part is fine. Awkward, but fine.

heh.. well, I didn't found any similar relay in fritzing (it might be there somewhere though), so I added it with photoshop.. But the way it is illustrated seems to be working though...

Caveat: I too am new to this. The answer below is my understanding and I need an expert to confirm.
Current in your Arduino:

A single digital pin on a Uno will provide 40mA -- and could conceivably power two of your LEDs.
The VCC pin outputs 200mA and could therefore conceivably power ten.

So all you need to do is power your LEDs from your VCC, but use your digital pin as a switch. One idea, which you had, was to use a relay. But a relay is an inductor so don't connect it directly to the Arduino. Make sure it's on a shield. But that shield will essentially do exactly what you need to do, but to drive the relay rather than drive your LEDs: It will use the digital pin to switch the VCC and activate the relay.
Luckily this isn't hard. All you need is the most magical of all components: the transistor. A transistor can be used as a switch to turn on a higher current. In your case, the transistor can switch the VCC connection to the LED array when the digital pin is high.

This question was answered nicely over at the electronics stack exchange.
Here's a PDF tutorial on using transistors as switches.
Found a nice reference on figuring out the transistor / resistor relationship.

Here's the circuit I believe you need based on my understanding. Note that the values of the resistors and transistors are just made up. Read the docs above to get the correct values.

Experts: if any of this is wrong, please help me learn! I'm happy to admit that this is just my understanding and it shouldn't be relied upon. But if I'm not trying to understand, I'll never learn :D

Very nice direction, and IMO transistors are the way to go here. Just not sure that the circuit fills OP's requirements to turn each led separately.

@Omer this is only for the 5 green leds. The 5 red leds can remain connected, directly to pins A0-A4

I've updated my answer. What I'm trying to accomplish is to have all the LEDs, both red and green, draw power from the external powersupply. That way, I would be able to just send the signals to the starting light, and not the power aswell... But thanks for great links and such.

@ThomasK: my point is you don't need an external power supply. But if you really really want to there's nothing stopping you. The transistor can switch an external source just the same way. Read the links.

I think one of the best way for you would be to use 74HC595 chip. You will learn a lot while developing board with this chip. It is well documented Serial to Parallel Shifting-Out with a 74HC595. Using 3 pins you will be able to turn on & off as many LED's as you wish, use external power supply and so on.
Also there is MAX7219 chip. The MAX7219 and MAX7221 Led drivers. And there are a lot more ways to do this.

If you really want an external power supply, you can use ULN2003 / ULN2803, which are 7/8 darlington 500 mA each transistor

If he wanted the LEDs to sequence as 1, 2, 3, 4, 5, 1+2+3+4+5 then I'd totally go with a darlington chip so you can control them all individually plus any combination. But as he wants 1, 2, 3, 4, 5, 6+7+8+9+10 it's only the 6-10 (which are group controlled) that need the higher current. I reckon a chip is overkill when it can be done with one transistor (or two in a darlington configuration, plus a diode if I'm remembering right)


text:
SAM3X8E (Arduino Due) Pin IO registers
How do the IO registers of Arduino Due work?
On Arduino Uno just set DDRx, then PINx to read, PORTx to write, I'd like to do the same thing with an Arduino Due, but it has many more registers, such as PIO_OWER, PIO_OSER, PIO_CODR, PIO_SODR, etc. I find no correspondence between Arduino Uno and Arduino Due registers.
There are also some useful functions such as pio_clear, pio_set, pio_get, and others, all explained here:
http://asf.atmel.com/docs/3.19.0/sam3x/html/group__sam__drivers__pio__group.html
Now, I think I've understood what the three mentioned functions do, but not others, for example:
pio_configure (Pio *p_pio, const pio_type_t ul_type, const uint32_t ul_mask, const uint32_t ul_attribute)

I can't figure out what ul_attribute and ul_type are.

Here is a GPIO class that is implemented for AVR and SAM. Might give a hint of how to use the registers: https://github.com/mikaelpatel/Arduino-GPIO/blob/master/src/Hardware/SAM/GPIO.h

If you have a read of section 31 of the Datasheet, available from here, things may come a little clearer for you.
Here's a summary of what I know:
PIO stands for Parallel Input/Output and offers the functionality to read and write multiple register ports at a time.  Where the datasheet mentions a register, for example PIO_OWER, the Arduino library has macros for accessing them in this format REG_PIO?_OWER where ? is either A, B, C or D for the different ports available.
I tend to still use the slow Arduino pinMode() function to set input/output on the pins as it makes the code more readable than the acronym based registers calls such as REG_PIOC_OWER = 0xdeadbeef, but then use the direct registers to set the pins for performance/synchronisation.  As yet, I haven't done anything with input, so my examples are all output based.
For basic usage, you would use REG_PIO?_SODR to set output lines high and REG_PIO?_CODR to set them low.  For example REG_PIOC_SODR = 0x00000002 would set bit 1 (numbered from zero) on PORTC (this is Due digital pin 33) high. All other pins on PORTC remain unchanged.  REG_POIC_CODR = 0x00000002 would set bit 1 on PORTC low.  Again all other pins would be unchanged.
As this is still not optimal, or synchronised if you are working with parallel data, there is a register that allows you to write all 32 bits of a port with a single call.  These are the REG_PIO?_ODSR, so REG_PIOC_ODSR = 0x00000002 would now set bit 1 on PORTC high and all other bits on PORTC would be set low instantly in a single CPU instruction.
Because it is unlikely that you would ever be in a situation where you need to set all 32 bits of a port at the same time, you would need to store the current value of the pins, perform an AND operation to mask out the ones you want to alter, perform an OR operation to set the ones you want set high then perform your write and again, and this is not optimal.  To overcome this, the CPU itself will perform the masking for you.  There is a register called OWSR (output write status register) that will mask out any bits that you write to ODSRs that don't match bits set in the OWSR.
So, now if we call REG_PIOC_OWER = 0x00000002 (this sets bit 1 of the OWSR high) and REG_PIOC_OWDR = 0xfffffffd (this clears all bits except bit 1 of the OWSR) and then call REG_PIOC_ODSR = 0x00000002 again, this time it would only change bit 1 of PORTC and all other bits remain unchanged.  Pay attention to the fact that OWER enables any bits that are set to 1 in the value you write and that OWDR disables any bits that are set to 1 in the value you write.  Even though I understood this when I read it, I still managed to make a code mistake when writing my first test code thinking that OWDR disabled bits that weren't set to 1 in the value I wrote.
I hope this has at least given you a bit of a start in understanding the PIO of the Due CPU.  Have a read and a play and if you have any further questions, I'll try to answer them.
Edit:
One more thing...
How do you know which bits of the PORTs correspond to which digital lines of the Due?  Check this out: Due Pinout

There is a fairly simple equivalence for the basic direct pin access. Below is some sample code which shows how to set a digital pin high and then low. The first is for an Arduino Due, the second is for the Arduino Uno/Mega/etc.
const unsigned int imThePin = 10; //e.g. digital Pin 10

#ifdef _LIB_SAM_

    //First lets get the pin and bit mask - this can be done once at the start and then used later in the code (as long as the variables are in scope
    Pio* imThePort = g_APinDescription[imThePin].pPort;
    unsigned int imTheMask = g_APinDescription[imThePin].ulPin;

    //Lets set the pin high
    imThePort->PIO_SODR = imTheMask;
    //And then low
    imThePort->PIO_CODR = imTheMask;

#else

    //First lets get the pin and bit mask - this can be done once at the start and then used later in the code (as long as the variables are in scope
    volatile unsigned char* imThePort = portOutputRegister(digitalPinToPort(imThePin));
    unsigned char imTheMask = digitalPinToBitMask(imThePin);

    //Lets set the pin high
    *imThePort |= imTheMask;
    //Now low
    *imThePort &= ~imTheMask;

#endif

Everything that is needed to do that should be included by default - and if not #include <Arduino.h> should be sufficient to get it there.
There are actually functions available that can be called once you have the Pio pointer to do the setting/clearing/pullup resistors/etc. using slightly cleaner looking function calls. A full list can be found in the  header file.

This is a code example that flashes a led on pin 33. Code borrowed from above - many thanks for the very helpful explanations :) This is the beginning of a project to talk to a TFT touchscreen display with dumping of 16bit color pixel data which needs fast access to the ports. I think I have the code right - particularly the line that sets the pin low. The led is happily flashing.
void setup()
{
  pinMode(33, OUTPUT);
  REG_PIOC_OWER = 0x00000002;
  REG_PIOC_OWDR = 0xfffffffd;
}

void loop()
{
  REG_PIOC_ODSR = 0x00000002;
  delay(1000);
  REG_PIOC_ODSR = 0x00000000;
  delay(1000);
}

I actually followed the above examples and did many tests that I am comfident the results will aid anyone looking into addressing the registers directly.
   void setup() {
  pinMode(25, OUTPUT);
  pinMode(26, OUTPUT);
  pinMode(27, OUTPUT);
  pinMode(28, OUTPUT);
  pinMode(29, OUTPUT);
  //REG_PIOD_SODR = 0b00000000000000000000000001001111; // written in binary form
  REG_PIOD_SODR = 0x0000004F; //written in Hexadecimal form. Note the differences. Thw two, binary and Hexadecimal are the same.
  delayMicroseconds (250000);
  //REG_PIOD_CODR = 0b00000000000000000000000001001111;
  REG_PIOD_CODR = 0x0000004F;
  delayMicroseconds (2000000);

}

void loop()
{
  //REG_PIOD_ODSR = 0b00000000000000000000000001001111; // serts all the bits set to 1 HIGH and the rest set to 0 LOW
  REG_PIOD_SODR = 0b00000000000000000000000001001111; // sets all the bits set to 1 HIGH and leaves the rest untouched
  delay(500);
  REG_PIOD_CODR = 0b00000000000000000000000000000100;//1
  //REG_PIOD_CODR = 0x00000004; //identical to the line above only that it is in Hexadecimal format
  //REG_PIOD_SODR = 0b00000000000000000000000000000100; // will disable the rest bits and leave only one HIGH
  delay(500);
  REG_PIOD_CODR = 0b00000000000000000000000000000010;//2
  delay(500);
  REG_PIOD_CODR = 0b00000000000000000000000001000000;//3
  delay(500);
  REG_PIOD_CODR = 0b00000000000000000000000000001000; //4
  delay(500);
  REG_PIOD_CODR = 0b00000000000000000000000000000001; //5
  delay(500);

}

To explain better, all pins desired to be OUTPUTs are set via pinMode and then, it is very optional toenable them while at SETUP. In this case, I just wanted the pins to be made HIGH just once while at SETUP and then LOW before the loop starts. I've used REG_PIO?_SODR (in this case, ? is port D so it is REG_PIOD_SODR) which only make its set to 1 HIGH and the rest are left untouched. I have used both in binary and Hexadecimal format. Binary makes it easier to identify which pins to enable. For instance, bit PD0 is the right most bit in the binary number. It starts from Right going to left. For example, 0b00000000000000000000000000000001, bit 1 is PD0, PD1 will be 0b00000000000000000000000000000010 and so on.
You've seen examples provided in this format, 0xfffffffd the x means it is in hexadecimal format and b is in binary format. To convert binary to Hexadecimal, youcan use the easiest route via this link
To explain, any Hexadecimal number represents 4 binary numbers, example, Hex 0 is binary 0000, Hex F is binary 1111, Hex 4 is binary 0100, Hex A is binary 1010.
Now that is understood, going to the main loop, I have used the REG_PIOD_SODR because it gives one the freedom to address the pins one wants without touching any other pins on that port. You can use REG_PIOD_ODSR ONLY when you want to set all bits at once. This is ideal when you want many pins set HIGH and/or LOW at once. It is not the best if you want to set just a few pins HIGH/LOW and leave the rest untouched. REG_PIOD_SODR is ideal when some pins needs to be left untouched. You don't want to set one bit HIGH then all pins are HIGH. This command REG_PIOD_CODR sets the bits set 1 LOW and leave all the rest set to 0 untouched.
This code simply makes the bits selected at setup HIGH for the said time in delay then LOW for the given time. In loop, all bits selected as 1 are made HIGH and the rest untouched. The following lines simply turn the selected bits LOW one at a time until all are OFF and then the process repeats.
I hope this oversimplified explanation aided someone.


text:
Arduino UNO Low-Power Consumption (Multiple Ultra-Sonic Sensors)
I've read post that it's possible to connect multiple Ultra-Sonic Sensors to one Arduino.
But I have a few questions:

If I use Arduino Uno, what is the maximum number of Ultra Sonic Sensors that I can connect one Arduino UNO?

Is there any option to power Arduino UNO in some kind of low-power mode so I can achieve power autonomy for at least 90 days.(I'm referring to battey life, or solar powered solutions)

Can Arduino UNO work on the low/high temperatures (e.g. -20 / +50 Celsius degrees), and what is the known work temperature range?

How to secure jumpers/cables to work on extreme temperatures (e.g. -20 / +50 Celsius degrees)
Thanks in advance :D

A "bare minimum" standalone Arduino will use less power. useful link

Don't use jumper cables. Use cables rates for the specified temperature range and solder them to the board

@newbie thanks, man. This link is very helpful

@chrisl Roger that. For the testing purpose, I wanted to use jumpers. :D

@rmir you're welcome. most electronic components have wide range of temperature tolerance but the real problem is humidity in outdoor environment.

You did not specified, what kind of ultrasonic sensor you want to use so I assume use of "standard" ultrasonic Arduino modules (like hc-sr04), which need 4 pin (VCC, GND, TRIGGER and ECHO). Since Arduino Uno has got 20 IO pins (6 analog and 14 digital), you can use 10 pins as outputs for TRIG signals and 10 as inputs for ECHO signals and thus connect up to 10 ultrasonic modules to one Arduino Uno.
In general, Arduino Uno is not designed for low-power applications. If you want more specific answer, you should ask more specific question...
Working temperature of Arduino Uno is -40 to 85 °C.
One of the options is using a terminal shield with screw terminals, e.g something like this.

Sorry for not being too specific, you know, when you are working on something, you think that everyone has the same process, same tools... And I'm a newbie to Arduino... :D

Yeah, you are right, I was referring to HC-SR04.
Again I wasn't too specific. Didn't want you to bother with too many details, but I need a measurement device that will measure distance every 15 seconds, my plan is to turn on/off Arduino every 15 seconds to measure the distance. Since I need this device to be used in the woods, I need a battery-powered device.
Thanks.
Awesome.

Look at sleep_mode() and set_sleep_mode(mode) function. You will also need to switch off the power supply for the ultrasonic sensors. Then you'll need to measure power consumption of the whole set to be able to decide what kind of battery you should use...


text:
Bluetooth HID for mouse project
I’m working on a project, to create an air mouse for people with repetitive strain injury (since I have it as well). I’m flexible with the hardware required. The plan is to use data from an IMU for movement. I’m currently learning how to work with the sensor.
I have also been researching how to eventually convert the sensor data to mouse movements. I understand that you can do this over Bluetooth (Bluetooth HID, or HID over GATT). However, this is where I reach my limits.
I was hoping to find a library, which can do this for me (similar to the mouse.h library) as it feels like it would take me months learning about the Bluetooth standards to try to implement it myself.
The options I found in my research:

Adafruit boards only library so ties you to their ecosystem
mbedOS library, code seems different then the arduino sketches I’ve
seen so far and is difficult to understand
esp32 based library,    would need to learn how to use that
processor and not sure if    supported properly in arduino IDE)
Arduinoble.h library, would    you need to create the mouse HID
profile from the ground up)

Since many of you are much more experienced than me, I would be grateful for any guidance on how to proceed. Would you show a preference for any of the options above? Or should I be attempting to do things differently, e.g. without a mouse library (but where would I start)?
PS. In case it’s useful, I have basic familiarity with C++ (e.g. I understand classes, pointers, etc.), but I don’t have a programming background. I have done a few simple arduino projects and most of the examples on the official website.

100% ESP32. Yes, it's fully supported by the Arduino IDE (and us).

Hi Majenko, thanks for responding. I saw from a previous reply you'd made a on a different topic that you have significant experience in USB protocols. In the other topic that you responded to, you advise the person not to try to build their own library because it's very difficult. Is the same true for Bluetooth?

I don't know much about bluetooth. I do know that the ESP32 has good libraries and support / documentation through the ESP-IDF though. What you'd have to do to write your own library depends 100% on the hardware. I'd say ESP32 would be the easiest to write for since all the work is done for you in the ESP-IDF and there will be plenty of Arduino-library-like abstraction layers around.

Thank you for the comment, I appreciate the information.

just bumping this in hope for some additional insights from the community.

As a question, it's just overbroad for me to try to tackle with what parts I do know something about.  I didn't mark it that way because I suspect this is not the case for someone else.  I can tell you that HID used in bluetooth and over I2C is related to the HID as it's supported by USB, and that much of the pain of implementing a mouse (or airmouse) will port between them, and different radios/controllers.  This also means that is maybe not as big a problem as you might think if you have to switch between different Bluetooth or USB hardware.  Not compared to the rest of the project anyway.

Thanks for the comment

The Adafruit library does not tie you to Adafruit boards. Mostly it ties you to the bluetooth chip, that is used there (and if special hardware of the MCU is used, to that MCU family). But that will be the case for nearly every library. I'm not qualified enough to give a proper answer about bluetooth, but I would go for the esp32. It is properly supported in the Arduino IDE (you need to install the esp32 core) and gives you lots of possibilities. Also the programming is not that different from normal Arduinos. Did that transition myself a while ago

Thanks for the comment, I appreciate you helping out. Useful advice.

Hopefully we could get some more contributions? I've seen this questions asked a few times on various websites without a good answer. But I appreciate the help nonetheless, don't mean to sound entitled.


text:
Running Arduino mega on 5V power supply
I'm wondering if I can run Arduino mega on 5V power supply, even though it's recommended for 6-12V. USB has only 5V right, will it be a problem? I expect to draw quite a lot of power from the 5V pin too so could it be a problem?

Here's what I did for my project:
I used a high current regulated 5V supply. I took a USB cable with the square connector that goes into the Arduino and cut it in half. I attached the red and black wires to +5V and ground on my regulated power supply. I then drove the high current components in my project directly from the 5V supply.
If you use this approach you should probably also add filter capacitors between 5V and ground at both the Arduino and the high current load. Those will help  smooth out the voltage variations as the high current load switched on and off.

You should also make sure the grounds for USB (both host and Arduino sides) and the bench power supply are 1) connected and 2) at the same potential.  Plugging all the power sources (USB, bench) into the same power strip suffices for the latter.

You misunderstand what I'm suggesting. I power my project with a single 5V power supply. The high current components are connected directly to the 5V, and the Arduino and it's low current components are fed through a dummy USB cable that is also connected to the 5V supply. If I need to program the Arduino I instead use a real USB cable connected to my computer.

If you do this often, you can buy a variety of USB connectors to build your own cable, instead of sacrificing a cable. This could allow using a project box with a female USB input to a power rail, then over to the Arduino through the onboard USB connector. You can even hook up the data between the female USB on the box to the internal USB male connector, if you wanted to keep that functionality for debugging and reprogramming purposes.

The 6-12V range applies only to the onboard voltage regulator(if you provide power via Vin or the barrel jack). The Arduino itself runs on 5V and the regulator needs a bit headroom above that to do the regulation.
You can run the Arduino via USB, since it has 5V, just as needed by the Arduino
And you can provide power directly to the 5V pin (with a voltage of 5V or course).
If some of your components draw a lot of power, you should never draw that current through the Arduino. You need to connect the power supply in parallel to your components and the Arduino, so that the high currents can flow past the Arduino, not through it.

If you connect it from the USB port on your computer to the USB plug on the Mega, you'll do fine. What you can't do is connect a 5v source to the barrel jack; that goes to the board's voltage regulator which needs ~ 7v minimum to provide 5v out.
"Quite a bit of power" is a rather vague specification. A USB port can supply 500mA unless the device in question negotiates for more current and the port in question is capable of supplying it. What is probably more concerning is if you're trying to pull a lot of current through the Mega, you risky overloading its pin-drivers or its PCB tracks. The Mega's pins are spec'd for 20mA; 40mA Absolute Max, briefly, to not damage it. The total current budget is 200mA max. If you're planning to approach either of those levels, you should consider powering some of your devices separately. That might include powering from the same or another USB port, as long as you don't pass it through the board, and you observe the USB ports' maximum currents as well.

Yes, you can run the Arduino Mega off of a 5V supply. Instead of connecting the voltage to the DC jack, instead feed your 5V into the +5V pin on the Arduino header. (it is one of the red pins in the image below).

It's important to add that this only works if it's a regulated 5V power supply, that means it must be able to provide (more or less) exactly 5V, regardless of the load.


text:
Can I check if a message has been sent successfully using Radiohead_ASK?
I'm new to Arduino programming and I'm trying to get a simple 433 MHz transmitter and receiver module working on an Arduino Uno board. Unsurprisingly, it's not working as expected and I'm trying to debug the problem.
I'm using RadioHead and read in the documentation that the send() and waitPacketSent() methods return a boolean to indicate success. However, I disconnected the data wire and the send() method still returns true. As the module is no longer connected to the arduino I would have expected it to return false.
I understand that the messages are sent as unreliable datagrams, but I'm just trying to work out whether the transmitter has actually sent something. Is there some way I can do this?
The code I'm using is relatively short, so I've included it in full below, for what it's worth
#include <RH_ASK.h>
#include <RadioHead.h>

#ifdef RH_HAVE_HARDWARE_SPI
#include <SPI.h> // Not actually used but needed to compile
#endif

RH_ASK driver;

bool sent;

void setup()
{
#ifdef RH_HAVE_SERIAL
    Serial.begin(9600);    // Debugging only
#endif
    if (!driver.init())
#ifdef RH_HAVE_SERIAL
      Serial.println("init failed");
#else
  ;
#endif
  sent = false;
}

void loop()
{
    uint8_t buf[RH_ASK_MAX_MESSAGE_LEN];
    uint8_t buflen = sizeof(buf);

    const char *msg = "hello";
    bool sendSuccess;
    bool waitSuccess;

    if (!sent) {
      Serial.println("sending");
      sendSuccess = driver.send((uint8_t *)msg, strlen(msg));
      if (sendSuccess) {
        Serial.println("Send completed successfully");
      } else {
        Serial.println("Send Error");
      }
      Serial.println("Waiting");

      waitSuccess = driver.waitPacketSent();
      if (waitSuccess) {
        Serial.println("Wait Sent Success");
      } else {
        Serial.println("Wait Sent Error");
      }
      Serial.println("Done Sending");
      sent = true;
      delay(1000);
    }

    if (driver.recv(buf, &buflen)) // Non-blocking
    {
      Serial.println("driver.recv");

      // Message with a good checksum received, dump it.
      driver.printBuffer("Got:", buf, buflen);
    }
}

The output on the serial monitor is as follows

22:22:30.647 -> sending
22:22:30.647 -> Send completed successfully
22:22:30.684 -> Waiting
22:22:30.753 -> Wait Sent Success
22:22:30.753 -> Done Sending

Thanks in advance!

There is no concept of "did the packet arrive", only "did it get sent" - and by "sent" I mean the data squirted out of the data pin for the attached module to send.
These 433MHz modules are dumb. Very dumb. You toggle the transmitter's pin high and low and the receiver sees that toggling, if it is in range, and toggles its output pin to mirror the signal.
The only way you can know if the packet arrived is if the receiver also has a transmitter and the transmitter also has a receiver. When a message arrives at the receiving node it sends a message back to the transmitting node to say "I got it". That takes a lot of work to get right, though. Especially since the original message may have arrived fine, but the acknowledgement didn't, and all sorts of horrible things can happen if you don't handle packet sequencing right.
Better is to pick a better module that does all these things for you, such as the nRF24L01+ with Auto-ACK turned on.

Thanks for the quick reply Majenko! I know I don't have any way of checking if the packets arrived. I'm just debugging at the moment and trying to check if it was sent. I would have thought that because the data pin isn't connecting the Arduino to the transmitter module then send() should fail? Have I misunderstood this?

You have misunderstood that. The Arduino neither knows not cares what is connected. Is there is nothing there the data pin still gets toggled. If a tree falls over in the forest and there's no one there to hear it the tree still fell over and the air still vibrated.

Ah, Ok. Thanks for clearing that up. Thanks also for the recommendation. Will check out the module you mentioned above.

Get a 2nd Arduino and let it receive the data pin signal. Then you'll know the signal is being created.  You cannot send and receive with one Arduino, you need a 2nd.  I think there will be some data wrapped around the message that is sent; some sync bytes, some padding to ensure there are enough hi/low and low/hi transitions to ensure all data is recognizable on the receive end. The Radiohead web pages discuss it in more detail. It's basically Software Serial, but with radio modules stuck in the middle.

@CrossRoads Thanks. This was the problem. I had been trying to send and receive from the same board. When I got a second arduino to act as the receiver it worked as expected.


text:
What is the real lifetime of EEPROM?
ATMEL says the cell lifetime of an EEPROM cell is about 100,000 write cycle/ cell.
Is this actually how the EEPROM performs in the wild?
If I do not change the value of a cell, does this stress the lifetime? For example, if I write the value 0xFF to the same cell again and again, is this any different to writing 0x00, 0xFF, 0x00 etc.

As you state, the internal EEPROM has a lifetime of 100,000 write cycles. This isn't a guess - a very significant proportion of ATmega328 will reach this number with no issues. I have tested three processors before, and all reached 150,000 cycles with no issues.
It is important to note the failure mode of EEPROM. Most "EEPROM destroyer" projects repeatedly read/write until the data is not written at all. Before this point, the EEPROM will still be damaged. This would be manifested by data not being retained for a reasonable period. It is unwise to rely on anything more than 100,000 write cycles for this reason.
EEPROM is different to the RAM on an ATmega. Writing to it is not simple or quick, but it is wrapped up in a friendly Arduino library, hiding this complexity from the user.
The first level of indirection is the EEPROM library, which is trivially simple], just calling two other functions for read and write. This calls eeprom_write_byte, found here.
This function uses inline assembly, so might not be easily understood. There is a comment that is easily understood though:

Set programming mode: erase and write

This hints to one of the complexities of dealing with EEPROM - to write to
it, you first need to erase it. This means that if you call EEPROM.write(), it will perform a write cycle regardless of the value you are writing.
This means that repeatedly writing 0xFF will likely have the same effect as writing 0xFF,0x00,0xFF,0x00 etc.
There are ways to work around this - you can try calling EEPROM.read() before EEPROM.write() to see if the value is already the same, but this takes additional time.
There are other techniques to avoid excessive EEPROM wear, but their use depends on your application.

Wear leveling for EEPROM: http://electronics.stackexchange.com/questions/60342/wear-leveling-on-a-microcontrollers-eeprom

@Cybergibbons I am trying to determine why an EEPROM in a system is only retaining a value for seconds. E.g. if I read the value back immediately it looks like the write was successful. If I read it back seconds later I start seeing bits go from 1 to 0. You mentioned above "Before this point, the EEPROM will still be damaged. This would be manifested by data not being retained for a reasonable period." Does the failure mode I am describing sounds like something that could occur from a high number of erase/write cycles to a particular EEPROM location?

I once ran an experiment on an external EEPROM with 1 million max rated cycles. It took about 6 million cycles to become majorly corrupted, and before that it had progressed having sporadic amounts of corruption.
When you say you do not change the value, i am assuming you are writing the same data to an address multiple times. This almost certainly would stress the life, although it would probably not stress the surrounding cells.

The magic solution - if you dont want to code what Cybergibbons said about reading before writing, is the EEPROM.update() function. It does exactly that:
EEPROM.update(address, value);
will only write and stress the memory if value is different from that already stored.

http://hackaday.com/2011/05/16/destroying-an-arduinos-eeprom/

The Arduino was plugged into a wall wart and sat, “behind a couch for a couple of months.” The EEPROM saw it’s first write error after 47 days and 1,230,163 cycles. This is an order of magnitude better than the spec on the atmel datasheet, but similar to the results of similar experiments.

This seems far too high. I had heard of 150k to 200k before, but never this :o

The problem is that this doesn't detect all the failure modes. When EEPROM becomes damaged, what happens is the length of time that it will retain data is gradually decreased. At 100,000 cycles, Atmel guarantee 20 years data retention. Beyond this, the data retention reduces. When 1.2m cycles are reached, and you see an error, this is an immediate error. at 1,230,160 cycles, there may not have been an immediate error, but the data might only have been retained for days.

Couple years ago I made run time logger for piece of equipment.  Memory got corrupted after 6 months 40 hours logged with 1s resolution => 144000 writes.
My solution was to spread writes over entire eeprom.

Can you provide more details about how you did this?

My 2ct: clear the memory (write all zeroes or 0xFF; something you can recognise). Then: every time you want to restore: find the first occurrence of the identifier, load from the address before it and save the new value to the spot you found. This way you move over the entire address space. Rise and repeat when you reach the end of the address space.


text:
Pressure transducer / sensor (0.5 - 4.5V) innacurate analog pin readings
I have a relatively cheap 0-15psi pressure transducer. It has 3 pins - ground 5V and signal. The signal outputs a voltage of 0.5V to 4.5V based on pressure from 0psi to 15psi. I can verify it does respond to significant pressure increases so it works at least to a point.
The issue is that the reading from arduino can differ by over 50% when at ambient atmospheric pressure (resting on a table). It should be significantly more accurate if the sensor data are to be trusted. The code is basic:
void setup(){
  Serial.begin(9600);
}

void measurePressure(){
  int rawReading = analogRead(A0);   // Range : 0..1024
  //float rawVoltage = (rawReading * (4.5 / 1023.0)) + 0.5;

  Serial.print("Raw reading: ");
  Serial.println(rawReading);

}

void loop() {
  measurePressure();
  delay(1000);
}

The output variations are not entirely random, it seems that the reading goes down and up in intervals of roughly 5-15 seconds. Below is a sample output:
Raw reading: 61
Raw reading: 67
Raw reading: 70
Raw reading: 73
Raw reading: 74
Raw reading: 78
Raw reading: 75
Raw reading: 82
Raw reading: 85
Raw reading: 90
Raw reading: 89
Raw reading: 97
Raw reading: 103
Raw reading: 119
Raw reading: 146
Raw reading: 165
Raw reading: 171
Raw reading: 168
Raw reading: 163
Raw reading: 150
Raw reading: 143
Raw reading: 118
Raw reading: 88
Raw reading: 70
Raw reading: 62
Raw reading: 64
Raw reading: 72
Raw reading: 78
Raw reading: 80
Raw reading: 82
Raw reading: 88
Raw reading: 92
Raw reading: 102
Raw reading: 134
Raw reading: 160
Raw reading: 170
Raw reading: 172
Raw reading: 166
Raw reading: 158
Raw reading: 149
Raw reading: 132
Raw reading: 100
Raw reading: 73
Raw reading: 63
Raw reading: 61
Raw reading: 71
Raw reading: 77
Raw reading: 79
Raw reading: 84
Raw reading: 90
Raw reading: 90
Raw reading: 99
Raw reading: 134
Raw reading: 161
Raw reading: 170
Raw reading: 166
Raw reading: 161
Raw reading: 151
Raw reading: 133
Raw reading: 103
Raw reading: 81
Raw reading: 68
Raw reading: 63
Raw reading: 63
Raw reading: 71
Raw reading: 73
Raw reading: 81
Raw reading: 83
Raw reading: 85
Raw reading: 89
Raw reading: 98
Raw reading: 128
Raw reading: 161
Raw reading: 171
Raw reading: 166
Raw reading: 159
Raw reading: 145
Raw reading: 120
Raw reading: 85
Raw reading: 67
Raw reading: 57
Raw reading: 63
Raw reading: 72
Raw reading: 75
Raw reading: 83
Raw reading: 85
Raw reading: 89
Raw reading: 97
Raw reading: 130
Raw reading: 164
Raw reading: 172
Raw reading: 163
Raw reading: 155
Raw reading: 135
Raw reading: 101
Raw reading: 69
Raw reading: 60
Raw reading: 62
Raw reading: 72
Raw reading: 78

I tried adding 4.7k pull down resistor with no change but that was just a blind try. I have a multimeter connected as well and the reading seems to be more stable ranging from about 0.495V to 0.535V (variations do not seem to match arduino output).
What could be causing the issue?

Do you seem the same variation with a voltage divider that produces ~0.5V connected?

I didn't have a voltage divider connected, voltage is in range of arduino voltage so not sure why I would need a voltage divider..?

No, just a voltage divider, absolutely nothing else. i.e. with a constant 0.5V input, do you see the same behaviour.

Didn't try that. With nothing connected I see more random variations but only up to a few hundred as opposed to 0-1023 full range. Does that tell you anything or should I still build the voltage divider and test? I also tried another pin with same result. I am using Arduino Pro Micro btw.

A floating input will drift. What you need to work out is if it is the Arduino, your meter, or the sensor causing this. The voltage divider will isolate the sensor.

I connected 33k and 3.3k resulting in 0.45V (0.417 multimeter reading). Got similar results but then I removed multimeter cables and it was stable at 91 with occasional 90. Connected the sensor and nothing else but got same issue. What can I try next?

I don't think you can trust your meter then - it's input impedance should be several orders of magnitude higher than the voltage divider. Does the sensor show the problem without the meter?

Yes, the sensor has the same problem. As for the meter it's a cheapo so no surprises there.

Your code is fundamentally correct. If a resistive voltage divider is providing consistent readings then the issue is with the sensor and the meter. Without a working meter, it would be hard to work out what is going wrong.

Well the meter is working, it just adds some interference when connected together with arduino. The reading itself seems correct.

A multimeter that disturbs the device under test to that extent isn't working correctly. If you connect it to the sensor and Arduino, is it the meter or the sensor or both causing a problem?

I tried same setup with arduino uno and the problem is gone. It also works on micro as long as gnd and 5v pin is connected to uno. Uno measured voltage is 4.88V and micro 4.60V could a voltage difference this small cause this? What else could this be?

Ok, so I have a new multimeter (extech 505). Still getting variations with arduino reading despite a tiny variation in voltage. Multimeter does not disturb the signal any more. What else could I try?

What make and model of pressure transducer is it?

Also, the 5V supply input for the transducer, are you attaching that to Arduino's 5V supply?

@gwideman It's and unbranded chineese sensor. Yes I am attaching it to 5V of arduino (4.6V measured).

Can you point to any eBay or other link for this sensor?

I tried same setup with arduino uno and the problem is gone. It also works on micro as long as gnd and 5v pin is connected to uno. Uno measured voltage is 4.88V and micro 4.60V could a voltage difference this small cause this? What else could this be?

Reinstatement of incorrect edits by Annonomus Person
(AP: Please do not edit answers in such a way that you entirely change their meaning. In the current discussion "the board" is meaningless. We are trying to distinguish between symptoms seen in two different 'boards', an Arduino Uno, and an Arduino Micro.)
Looks to me like the problem is with the Arduino Micro's 5V supply then.
If you are powering the Micro from an external supply (not USB), then 4.6V on the Micro's "5V" output would indicate that the 5V regulator is not operating within its expected range.
If you are powering from USB, then the regulator is not in play. The 4.6V would indicate a problem with the USB's 5V supply.
Likely possibilities:, either the upstream supply is inadequate, or the micros and whatever is attached to it is drawing too much current.
I suspect that the transducer output is fluctuating in a way that's too rapid to be seen by your meter, but which is sampled by the Arduino Micro, giving your varying result numbers.
Either the "4.6V" is inadequate to run the transducer, causing erratic transducer output, or the 4.6V itself is fluctuating, with similar results at the trans output.
And you might also check the ground between micro and transducer -- are you sure that's wired correctly?

Will test it with a different arduino mini, will need to wait for my soldering iron to arrive though, will update then.

For the setup that produces the fluctuating numbers, please confirm that you have the transducer connected to the Arduino Micro's +5V output, and tell whether you are powering the Micro from USB, or from an external supply, and if the latter, what kind of supply?

If you are powering from external power, such as batteries, please be aware that the specs for the Micro show that the 5V regulator is not reliable below 7V input.

Both the Uno and Mini are powered from usb port so it's not the issue especially since I also tried a different port. Transducer should work with 4.5 to 5.5V but you never know with cheap stuff. Will do some more testing when I receive my soldering iron...

@DominicM Note that I listed several possible issues, not just a single 'it'. A voltage of 4.6V DC may be fine for the transducer. But: (1) a meter measurement showing 4.6V can also result from a voltage fluctuating around 4.6V which will cause erratic transduce. Or (2) 4.6V is below USB 2.0 minimum spec of 4.75V, which in itself suggests something wrong with the supply or the path from USB to transducer. (4.6V is apparently legit for 3.0 though.). And again, it's worth checking the ground path between Micro and transducer.

And if you test the Uno and the Micro powered from the same USB port, should get the same Gnd to +5V voltage reading from their "5V" outputs. 4.88V vs 4.6V is enough of a difference to suggest there's something going on with the power.


text:
Redirecting Arduino Serial Output to a File
I am integrating the MPU-6050 Accelerometer + Gyro sensor into a large project that contains 12 Arduino boards and 6 Raspberry Pis. At some point, I will have to load the output of my MPU-6050 sensor into another application through command line. The process is to be all done with Python and Bash (on the Raspberry Pi side), and so what I need is a way to store the output of my Arduino boards.
What I am currently looking at is the python program ino. I have used the product for about a year now, and as far as I am aware of, the only way to exit out of serial mode in ino is by closing the command-line window!
Is there a way I can achieve what I've discussed above? Essentially, all I want is a way to hold the output of my Arduino serial output so I can use it later in other parts of my project.

If I understand you correctly, you want to store the data recorded from an Arduino Uno through serial on a Raspberry Pi?

not necessarily the Pi, but in my case, yes

Well, I don't know about your ino program, but here's how I'd do it:
get_serial.py
import serial, sys

with serial.Serial(port=sys.argv[1], baudrate=sys.argv[2]) as ser:
    while ser.isOpen():
        print(ser.readline())

The idea, here, is to print on stdout the data coming on the serial line:
python get_serial.py /dev/ttyACM0 115200 > output.log

or you can do it this way:
get_serial.py
import serial, sys

with open(sys.argv[3]) as f:
    with serial.Serial(port=sys.argv[1], baudrate=sys.argv[2]) as ser:
        while ser.isOpen():
            f.write(ser.readline())

which is ran:
python get_serial.py /dev/ttyACM0 115200 output.log

Hope this helps!