text:
Uno - PCA9685 Servos are too shaky before stabilizing - when using two channels
I'm trying to control a Tilt pan with an Arduino Uno. And the Sunrounder servo driver is used to do this, which comes with it's own capacitor out of the box.
The pan has two Servo motors, that help it face any direction.
I have set this up and even calibrated, so that I can input numbers between -90 degrees to +90 degrees horizontally, and 0 to 90 vertically. And it is working...
But the problem is that, when it is idle for too long, or when I connect it in the beginning, The tilt pan shakes intensely for about 20 to 30 seconds and turns every other direction before stabilizing to the correct point. As if it had a seizure!
When I disconnect one of the Servos, this problem solves. Two servos are connected to the first and second channel of the servo driver. So it seems that these two channels have an effect on each other.
Besides, there is not much weight on the tilt pane. And removing the weight does not seem to help.
init code:
pwm = Adafruit_PWMServoDriver();
pwm.begin();
pwm.setPWMFreq(60);  // Analog servos run at ~60 Hz updates
yield();

turning horizontally:
void Platform::setHorizontal(int d){
  if(d > 90)
    d = 90;
  if(d < -90)
    d = -90;
  point->setHorizontal(d);
  d = (d * 2.555) + 70.0; // calibrating.
  pwm.setPWM(0, 0, 325 + d); // 325 = (150 + 600) / 2
}

How can I solve this?

Start by verifying the power supply is adequate, then go from there. If nothing else try a much bigger capacitor.

Changed the power supply with a more expensive one, Worked like a charm. I wish I could give you a Medal.


text:
Uno - measure the voltage, NOT connecting GND
I'm trying to use an Arduino Uno, to measure the Voltage over a Resistor in a circuit. I guess the usual way would be to connect GND to one side of the Resistor and the AD0 Pin to the other end, and scale the (0..1023) to (0..5V).
The problem is however, that connecting the GND to one side of the Resistor affects the circuit. Since the GND of Arduino is also connected to a Servo Driver (and other stuff), Some of the power that was supposed to be consumed by my Resistor, is now consumed by the parallel circuits.
Is there any way to measure the Voltage over the resistor without using GND?

If I understand the description correctly, neither side of the resistor is at ground potential.  There's a wide gamut of methods of dealing with this, for example using a differential ADC unit, or using an instrumentation amplifier ahead of a single-ended ADC.  But perhaps the simplest method is to use two ADC channels, one attached to each end of the resistor, with ADC ground connected to some common reference point.  Measure both voltages and take their difference .

Thank you! Yes you got the question right. Nice idea specifically since I can't afford to add more circuitry. And True, The Resistor's "GND" doesn't need to level with the GND of the rest of the circuit. I'll implement soon and provide feedback

It turns out that by attaching two ADC channels to the ends of the resistor, I don't get a valid or even stable result. The result is a chaotic number. Any suggestions?

@MakanTayebi, Do you print all 3 values? (Ie, both analogs & their difference)?  If not, printing them all might indicate if variation at one end is causing the problem.  Or might indicate wrong pin being read.  Note, if you use the same ref voltage for both readings, subtract the two readings before scaling instead of after

I print both and both fluctuate, so much that their difference is not also meaningful. And that's even before scaling. But what about the Refererence Voltage? What PIN would that be?

The AREF pin can be used to input a reference voltage of 1 V or more, which can be selected for use via analogReference(EXTERNAL) (see link).  By default, analogReference(DEFAULT) is in effect, and it selects +5 V on a 5 V board, or 3.3 V on a 3.3 V board.  For most-stable results on Unos/Nanos, use analogReference(INTERNAL) if a 1.1 V max reading is acceptable.

I just tried it and it works great

Why you are using AD0 pin for analog read? use A0-A7 for Arduino mega and A0- A5 for arduino uno case for reading of analog values. For more detail study the voltage devider and you will understand the problem more easily. As i understand there is no need to use ground.

I don't get why this answer has gotten negative reps. I'll try taking the GND out of the loop.

“There is no need to use ground” is untrue.  Yes, voltages are differences in potential between points, neither of which need be ground.  But when you measure voltages using an Arduino ADC, some ground-reference point in the circuit under test should connect to the Arduino's ADC ground (which, on Mega, Uno, Nano, is wired to digital ground...)

And what do you think AD0 refers to in this context?

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:
Recommendations for 24V to 5V AC/DC converter
I'm working on an ESP8266 thermostat that should be powered by the 24V AC from the furnace. I'm looking for a converter to 5V DC that would be small enough to fit in a smaller enclosure and not dissipate too much heat. Not fully sure about the current, but I'm planning for up to 500 mA for short periods of time. I found on ebay this, but it accepts input from 85V upwards. What would happen if I would feed 24V AC to it? Would it still work. Or alternatively doesn anyone have a link for something similar that would work with 24V?

Search for "24vac to 5vdc converter" or "24v ac/dc 5v converter". Don't buy a cheap converter from ebay, that might damage your project.

Transformers for furnaces are typically Class 2 transformers, energy limited. Unloaded, or lightly loaded, they produce a significantly higher output voltage than the rated output voltage, 24 volts in this case. 28 volts is typical, and it may be higher during high line situation. The 24 volt rating is a loaded voltage, with a resistive load.
28rms x 1.4 = 39.2 volts
You should be using a regulator with a voltage rating of at least 40 volts, and that is really marginal.
https://www.aliexpress.com/item/1pcs-2018-new-dc-dc-converter-12V-24V-36V-48V-60V-72V-to-5V-0-5A/32922897633.html
The AC-DC converter you linked to would not work. It has a low voltage cutout. It also would not be able to provide the power if it was able to work at the lower voltage. The input current would be much higher than the normal input current at a normal line voltage.

24VAC rectified with a full diode bridge rectifier (4 diodes) becomes 36VDC when smoothed with a cap, the datasheet indicates this part would be okay with that. You'd probably be okay as you're planning <500mA output most of the time.
https://www.digikey.com/product-detail/en/murata-power-solutions-inc/OKI-78SR-5-1.5-W36-C/811-2196-5-ND/2259781

How does 24VAC become 36 VDC when rectified?

VDC = VAC * sqrt(2)  or 1.41 under no load. 24*1,41 = 33.84V, so not quite 36V.  The explanation behind it is here.

You say "here" but did not provide a link. I gather your talking about peak-to-peak voltage vs RMS voltage? Won't the voltage drop to 24 under any meaningful load?

Lost the original link. Read this one  http://www.bristolwatch.com/ele/basic_ac_rectification.htm  Even with a drop, there will be plenty to make 5V unless you're really loading it down.  Much better explanation here  http://www.circuitstoday.com/full-wave-bridge-rectifier

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


text:
How to forward sms using arduino uno + gsm shield
hey there I'm new to arduino. I'm working on a project that needs to send an sms to get a response and forward the response to another mobile.
What is the easiest way to do so

Why do you want to involve an arduino in this?

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


text:
Seamlessly loop through LED's - Shift Register
I am using the following code to create a snake-like affect (3 LED's wide) moving through 24 LED's using 3 shift registers:
 for(int i = 0; i < 27; i++){
    setRegisterPin(i, HIGH);
    writeRegisters();
    if(i >= 3){
     setRegisterPin(i-LEDLength, LOW);
     writeRegisters();
    }
    delay(100);
  }//end for

The problem with this is that the snake has to completely end before it starts again, instead of looking like one continuous snake going in circles.
So when the three LED's get to the end I want it to immediately begin to light the beginning again. If 2 are lit at the end then 1 should be lit at the start, etc. Like this pattern:

You mean something like this? (untested):
void loop() {
  // use static or global variables to remember positions (these are initialized only once):
  static uint8_t hi_pos = 0;  // where HIGH should be set
  static uint8_t lo_pos = 21; // where LOW should be set

  setRegisterPin(hi_pos, HIGH); // turn on led in head
  setRegisterPin(lo_pos, LOW);  // turn off led in tail
  writeRegisters();             // update registers

  // ensure it won't overflow:
  if (++hi_pos == 24) hi_pos = 0;
  if (++lo_pos == 24) lo_pos = 0;

  // or:  hi_pos = (hi_pos+1) % 24;  // but divisions are slower on AVR

  delay(100);
}

It will go in sequence:
ON  OFF
 0   21
 1   22
 2   23
 3    0
 4    1
...
22   19
23   20
0    21
...

forever

wow, I'm not sure how you did that but it works. Can you explain the code further please?


text:
How to use Arduino Nano with Arduino Uno
I am using an Arduino Uno and have used up all it's pins so I have plugged up a Nano to a couple of the Uno's pins and using the Uno's 5v and ground to power the Nano. Is this ok?
It's been working fine until recently. My Uno will no longer allow me to upload code but everything still powers fine and runs on the existing code I had uploaded before. The reset button on the Uno does not work so I assume it's bricked, but it does still operate fine on the code it has, as I said.
Anyway, my question, is it ok to run the Nano like this? Is it using too much of the Uno's current... because the Nano's pins are also all being used. I'm no good at regulating current and just want to make sure that the Nano isn't eating up a bunch of current from the Uno by lighting it's LED's and it's other operations.

Are your Arduinos driving heavy loads or are their outputs only connected to high impedance inputs?

Nothing too heavy. Uno - motor controller (2 tiny motors), 2 servos, push button. Nano - Several LED's (just a few on at one time) and two range finders.

The Nano itself will not draw much current. So, if the sum of your loads is within the Uno's capabilities, it normally should work fine.

Two servos is a really heavy load.

try to connect uno and nano with I2C or serial, with I2C it connected to SCA/SDL pin (analog 4/5) or with serial it connected to tx rx. Make sure you use a pull up resistor. From the main site of arduino there's a tutorial in there but forgot to set up a pull up resistor.

Maybe it is a very good idea to connect Arduino UNO's only one DIGITAL out point among other digital output pins. This pin can trig Arduino Nano's analog input pins so that you can work your task for further you needed. But you have to seperate your shields or your motors or other things. Like this:

By the way, if you get an upload error, please plug out your shileds or motors or LEDs then try to upload your code again into Arduino UNO.

Connect the GNDs as well.

Be careful not to power any sort of motor directly from an Arduino (or any of it's siblings directly) without a transistor or H-bridge in between, unless you know exactly how much current your motor draws, peak, and how much your arduino can supply on any given pin. The same applies to any other high-draw device too.
If you are using LEDs, make sure you have a resistor in series with the LED - google "LED resistor calculator" to help you figure out which resistor you need.
Also, when you upload the program, it uses two of the pins - rx and tx, should be digital pins 0 & 1 on a Uno (any other, check your docs).

What are you talking about? I didn't ask any of this. I already know all of this. Terrible response.


text:
Light sensor acting up when used with other code
I have a light sensor that works fine and outputs the correct data to the serial monitor when I only upload the following code to the nano:
const int lightSensorPin = A0;
int lightSensorValue = 0;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);

}

void loop() {
  // put your main code here, to run repeatedly:
  lightSensorValue = analogRead(lightSensorPin);
  delay(100);
  Serial.println(lightSensorValue);
}

Now when I upload it with all of my other code, which includes lighting up about 6 LED's at one time and getting readings from two rangefinder sensors, the light sensors no longer output expected data, instead spewing out a bunch of random numbers, 0 to over 3000.
Could sharing the ground with all the LED's and rangefinders be causing interference for the light sensor? Or could it be a code optimization issue? Here's my entire code if it helps at all:
int trigPin1 = 5;
int echoPin1 = 6;
int blue1 =  7;
int green1 = 8;

int trigPin2 = A3;
int echoPin2 = A4;
int blue2 =  A2;
int green2 = A1;

int redLED = 10;
int greenLED = 3;
int yellowLED = 9;
int blueLED = 4;

const int lightSensorPin = A0;
int lightSensorValue = 0;

int securityLength1 = 28;
int securityLength2 = 28;

int frontEyes(11);
int backEyes(12);

const char* front = "front";
const char* back = "back";

void setup()
{
  Serial.begin(9600);

  pinMode(trigPin1, OUTPUT);
  pinMode(echoPin1, INPUT);
  pinMode(trigPin2, OUTPUT);
  pinMode(echoPin2, INPUT);

  pinMode(blue1, OUTPUT);
  pinMode(green1, OUTPUT);
  pinMode(blue2, OUTPUT);
  pinMode(green2, OUTPUT);

  pinMode(frontEyes, OUTPUT);
  pinMode(backEyes, OUTPUT);

  pinMode(redLED, OUTPUT);
  pinMode(greenLED, OUTPUT);
  pinMode(yellowLED, OUTPUT);

}//end setup

void loop(){

  digitalWrite(redLED, HIGH);
  digitalWrite(greenLED, HIGH);
  digitalWrite(yellowLED, HIGH);
  digitalWrite(blueLED, HIGH);

eyeballs(trigPin1, echoPin1, securityLength1, green1, blue1, front);
eyeballs(trigPin2, echoPin2, securityLength2, green2, blue2, back);

  lightSensorValue = analogRead(lightSensorPin);
  delay(100);
  Serial.println(lightSensorValue);

}//end loop

void eyeballs(int trigPin, int echoPin, int securityLength, int green, int blue, const char* frontOrBack){
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  long duration = pulseIn(echoPin, HIGH);
  long distance = (duration/2) / 29.1;

  Serial.println(distance);

 if (distance >= securityLength || distance <= 0) {
  digitalWrite(green,HIGH);
  digitalWrite(blue,LOW);
  if (frontOrBack == "front") {
    digitalWrite(frontEyes, LOW);
  }//end if
  else if (frontOrBack == "back") {
    digitalWrite(backEyes, LOW);
  }//end else
  }//end if

  else if(distance < securityLength) {
  digitalWrite(blue,HIGH);
  digitalWrite(green,LOW);

  if (frontOrBack == "front") {
    digitalWrite(frontEyes, HIGH);
  }//end if
  else if (frontOrBack == "back") {
    digitalWrite(backEyes, HIGH);
  }//end else

 }//end else if

}//end function

It wouldn't be something as simple as the light sensor "seeing" all those LED's, could it? :)

No, they aren't bright enough. And even covering it with my hand it results in totally random numbers.

I see two things to try: 1) lightSensorPin's i/O direction hasn't been set; 2) There's a lot of I/O going on immediately before you call analogRead(). Try delaying for a couple of milliseconds before that read to let any transients settle out.

@JRobert I've actually already tried doing both of those things. Set the pin to INPUT then put half a second delays on both ends. Seems like it reads the light better when my hand is over it but still get's a lot of random super high numbers like something is interfering.

0 - 3000? I missed that. You're seeing bigger numbers than the A/D can deliver (0 - 1023). Can something be over-writing lightSensorValue? Have you tried making  lightSensorValue local to the loop() function? That would move it far away from the other globals (though it wouldn't live between calls to loop(). Also, Serial.println(analogRead(lightSensorPin)); should directly print the return from analogRead() (though the compiler may have already done that for you).

Ok I moved the variable to the loop with same results. I tried process of elimination and found that when I delete the function outside of the loop it works perfectly fine. Here is what bad results kind of look like:
7
632
6
6
634
6
6
630
6
7
630
6
7
634
6
6
632 - It gets a good value then throws it a few bad ones in between.

Let us continue this discussion in chat.

@MichaelRader I've just read your solution. Thank you for cheering me up. And as far as embarassing mistakes go, welcome to the club.

I'd prefer to delete this question because I'm so embarrassed by the answer. I didn't notice I had Serial.println(distance); in my function. The odd numbers were coming from my rangefinders and being printed in between my light readings.

There's no pinMode(lightSensorPin, INPUT); in either of your codes. In the original code this probably doesn't matter because you set no other pins to In or Out.
As a side note, instead of declaring all your pin number as int then defining them, make use of preprocessor directives:
#define trigPin1  5;
#define echoPin1  6;
#define blue1     7;
#define green1    8;

When you hit Verify or Upload the preprocessor sweeps through your code and replaces all instances of a defined term with whatever comes immediately after it in the definition. You can't use it for variables of course, but it's perfect for designating pins.
This will cut down on unnecessary memory usage. Not a huge saving in your case, but I don't see why people don't do it more often.

Thanks for the tip on the preprocessor directive. Do those go in the setup? Also, we already discussed that the pinMode(lightSensorPin, INPUT); does nothing different. It doesn't solve the problem.

Also how do you specify INPUT or OUTPUT with the preprocessor directive?

#define goes at the top of the program, along with things like #include <A_LIBRARY>. That said, you can put #define at the bottom, or in the middle, but code before it that relies on the definition will not compile. You can't specify if a pin is input or output with #define - think of it as a 'find-and-replace' command. Change the first block of code to what I put in my answer above, in exactly the same place it is in currently, and you won't have to change a single bit of the remaining code from void setup() and beyond.


text:
How to use Ultrasonic Sensor's trig pin, and why it is needed?
I have HC-SR04 Ultrasonic Sensor with me. I couldn't understand the "Trig" pin's working structure and the working technic. Do we really need it while we use?
(With Arduino examples, I generally use Echo pin more than trig pin.)

I wonder how you can get anything meaningful from Echo, if you do not use Trig. Are you sure that Trig is not activated by some library you might be using? Or you might have some circuitry driving Trig for you?

This is a reasonable question, as the Arduino example assumes a 3-pin device where Trigger and Echo are combined, but most suppliers provide a 4-pin one where they are distinct.

Yes, you do need it.
The purpose of the TRIG pin is to cause the module to send out a "Ping".  It's what makes the whole thing work.  As soon as the TRIG pin goes HIGH then LOW (for a period of not less than 10µs) the internal clocks start ticking.  8 cycles of 40KHz audio are sent out of the transmitter and it starts counting how long it takes for the echo to arrive.
If you don't use the TRIG pin the module won't be able to do anything at all.

There are two versions of this device. In the threepin version you trigger the measurement and receive the echo pulse on the same pin. In the four pin version trigger and echo are on separate pins.
Possibly your Arduino example is written for the three pin version.

If we can use it with three pins, why do we need it with the four? And Is it meanful with using four pinned one in any project? How? What is the difference?

Two different solutions to the same problem. Both works. You have to interface the version you have. Do you need help with modifying your code?

No, thanks. I learnt how to do. You are kind. Thanks.

I stumbled across your topic while working in a personal project. As people said earlier, your doubts must be related to the different versions of this board.
Keep in mind that, when using the 4-pin you can keep the ECHO full online as an input, while in the 3-pin version, you need to cancel the ECHO to use it as Output for the TRIG.
This is particularly useful when you need to make a environmental analysis to different responses to different actions.


text:
Wiring BMP280 to Arduino Uno
I bought a BMP280 and it looks like this:

How can I connect BMP280 to Arduino Uno?
I tried the following examples on the web, but they didn't work.
I used  this library, connecting the PINS in this way:
VCC  ->  3.3V
GND  ->  GND
SCL  -> 13
SDA  -> 12
SDO  -> 11

But the sensor did not initialize.

Eventually as reported here, it worked using this pinout:
VCC --> 3.3V
GND --> GND
SCK --> A5
SDI --> A4

And this code:
#include <Wire.h>

#define BME280_ADDRESS 0x76
unsigned long int hum_raw,temp_raw,pres_raw;
signed long int t_fine;

uint16_t dig_T1;
 int16_t dig_T2;
 int16_t dig_T3;
uint16_t dig_P1;
 int16_t dig_P2;
 int16_t dig_P3;
 int16_t dig_P4;
 int16_t dig_P5;
 int16_t dig_P6;
 int16_t dig_P7;
 int16_t dig_P8;
 int16_t dig_P9;
 int8_t  dig_H1;
 int16_t dig_H2;
 int8_t  dig_H3;
 int16_t dig_H4;
 int16_t dig_H5;
 int8_t  dig_H6;

void setup()
{
    uint8_t osrs_t = 1;             //Temperature oversampling x 1
    uint8_t osrs_p = 1;             //Pressure oversampling x 1
    uint8_t osrs_h = 1;             //Humidity oversampling x 1
    uint8_t mode = 3;               //Normal mode
    uint8_t t_sb = 5;               //Tstandby 1000ms
    uint8_t filter = 0;             //Filter off
    uint8_t spi3w_en = 0;           //3-wire SPI Disable

    uint8_t ctrl_meas_reg = (osrs_t << 5) | (osrs_p << 2) | mode;
    uint8_t config_reg    = (t_sb << 5) | (filter << 2) | spi3w_en;
    uint8_t ctrl_hum_reg  = osrs_h;

    Serial.begin(9600);
    Wire.begin();

    writeReg(0xF2,ctrl_hum_reg);
    writeReg(0xF4,ctrl_meas_reg);
    writeReg(0xF5,config_reg);
    readTrim();                    //
}

void loop()
{
    double temp_act = 0.0, press_act = 0.0,hum_act=0.0;
    signed long int temp_cal;
    unsigned long int press_cal,hum_cal;

    readData();

    temp_cal = calibration_T(temp_raw);
    press_cal = calibration_P(pres_raw);
    hum_cal = calibration_H(hum_raw);
    temp_act = (double)temp_cal / 100.0;
    press_act = (double)press_cal / 100.0;
    hum_act = (double)hum_cal / 1024.0;
    Serial.print("TEMP : ");
    Serial.print(temp_act);
    Serial.print(" DegC  PRESS : ");
    Serial.print(press_act);
    Serial.print(" hPa  HUM : ");
    Serial.print(hum_act);
    Serial.println(" %");

    delay(1000);
}
void readTrim()
{
    uint8_t data[32],i=0;                      // Fix 2014/04/06
    Wire.beginTransmission(BME280_ADDRESS);
    Wire.write(0x88);
    Wire.endTransmission();
    Wire.requestFrom(BME280_ADDRESS,24);       // Fix 2014/04/06
    while(Wire.available()){
        data[i] = Wire.read();
        i++;
    }

    Wire.beginTransmission(BME280_ADDRESS);    // Add 2014/04/06
    Wire.write(0xA1);                          // Add 2014/04/06
    Wire.endTransmission();                    // Add 2014/04/06
    Wire.requestFrom(BME280_ADDRESS,1);        // Add 2014/04/06
    data[i] = Wire.read();                     // Add 2014/04/06
    i++;                                       // Add 2014/04/06

    Wire.beginTransmission(BME280_ADDRESS);
    Wire.write(0xE1);
    Wire.endTransmission();
    Wire.requestFrom(BME280_ADDRESS,7);        // Fix 2014/04/06
    while(Wire.available()){
        data[i] = Wire.read();
        i++;
    }
    dig_T1 = (data[1] << 8) | data[0];
    dig_T2 = (data[3] << 8) | data[2];
    dig_T3 = (data[5] << 8) | data[4];
    dig_P1 = (data[7] << 8) | data[6];
    dig_P2 = (data[9] << 8) | data[8];
    dig_P3 = (data[11]<< 8) | data[10];
    dig_P4 = (data[13]<< 8) | data[12];
    dig_P5 = (data[15]<< 8) | data[14];
    dig_P6 = (data[17]<< 8) | data[16];
    dig_P7 = (data[19]<< 8) | data[18];
    dig_P8 = (data[21]<< 8) | data[20];
    dig_P9 = (data[23]<< 8) | data[22];
    dig_H1 = data[24];
    dig_H2 = (data[26]<< 8) | data[25];
    dig_H3 = data[27];
    dig_H4 = (data[28]<< 4) | (0x0F & data[29]);
    dig_H5 = (data[30] << 4) | ((data[29] >> 4) & 0x0F); // Fix 2014/04/06
    dig_H6 = data[31];                                   // Fix 2014/04/06
}
void writeReg(uint8_t reg_address, uint8_t data)
{
    Wire.beginTransmission(BME280_ADDRESS);
    Wire.write(reg_address);
    Wire.write(data);
    Wire.endTransmission();
}

void readData()
{
    int i = 0;
    uint32_t data[8];
    Wire.beginTransmission(BME280_ADDRESS);
    Wire.write(0xF7);
    Wire.endTransmission();
    Wire.requestFrom(BME280_ADDRESS,8);
    while(Wire.available()){
        data[i] = Wire.read();
        i++;
    }
    pres_raw = (data[0] << 12) | (data[1] << 4) | (data[2] >> 4);
    temp_raw = (data[3] << 12) | (data[4] << 4) | (data[5] >> 4);
    hum_raw  = (data[6] << 8) | data[7];
}

signed long int calibration_T(signed long int adc_T)
{

    signed long int var1, var2, T;
    var1 = ((((adc_T >> 3) - ((signed long int)dig_T1<<1))) * ((signed long int)dig_T2)) >> 11;
    var2 = (((((adc_T >> 4) - ((signed long int)dig_T1)) * ((adc_T>>4) - ((signed long int)dig_T1))) >> 12) * ((signed long int)dig_T3)) >> 14;

    t_fine = var1 + var2;
    T = (t_fine * 5 + 128) >> 8;
    return T;
}

unsigned long int calibration_P(signed long int adc_P)
{
    signed long int var1, var2;
    unsigned long int P;
    var1 = (((signed long int)t_fine)>>1) - (signed long int)64000;
    var2 = (((var1>>2) * (var1>>2)) >> 11) * ((signed long int)dig_P6);
    var2 = var2 + ((var1*((signed long int)dig_P5))<<1);
    var2 = (var2>>2)+(((signed long int)dig_P4)<<16);
    var1 = (((dig_P3 * (((var1>>2)*(var1>>2)) >> 13)) >>3) + ((((signed long int)dig_P2) * var1)>>1))>>18;
    var1 = ((((32768+var1))*((signed long int)dig_P1))>>15);
    if (var1 == 0)
    {
        return 0;
    }
    P = (((unsigned long int)(((signed long int)1048576)-adc_P)-(var2>>12)))*3125;
    if(P<0x80000000)
    {
       P = (P << 1) / ((unsigned long int) var1);
    }
    else
    {
        P = (P / (unsigned long int)var1) * 2;
    }
    var1 = (((signed long int)dig_P9) * ((signed long int)(((P>>3) * (P>>3))>>13)))>>12;
    var2 = (((signed long int)(P>>2)) * ((signed long int)dig_P8))>>13;
    P = (unsigned long int)((signed long int)P + ((var1 + var2 + dig_P7) >> 4));
    return P;
}

unsigned long int calibration_H(signed long int adc_H)
{
    signed long int v_x1;

    v_x1 = (t_fine - ((signed long int)76800));
    v_x1 = (((((adc_H << 14) -(((signed long int)dig_H4) << 20) - (((signed long int)dig_H5) * v_x1)) +
              ((signed long int)16384)) >> 15) * (((((((v_x1 * ((signed long int)dig_H6)) >> 10) *
              (((v_x1 * ((signed long int)dig_H3)) >> 11) + ((signed long int) 32768))) >> 10) + (( signed long int)2097152)) *
              ((signed long int) dig_H2) + 8192) >> 14));
   v_x1 = (v_x1 - (((((v_x1 >> 15) * (v_x1 >> 15)) >> 7) * ((signed long int)dig_H1)) >> 4));
   v_x1 = (v_x1 < 0 ? 0 : v_x1);
   v_x1 = (v_x1 > 419430400 ? 419430400 : v_x1);
   return (unsigned long int)(v_x1 >> 12);
}

Actually, BMP280 doesn't monitor relative humidity so you can delete the part related to the humidity control.
#include <Wire.h>

#define BME280_ADDRESS 0x76
unsigned long int temp_raw,pres_raw;
signed long int t_fine;

uint16_t dig_T1;
 int16_t dig_T2;
 int16_t dig_T3;
uint16_t dig_P1;
 int16_t dig_P2;
 int16_t dig_P3;
 int16_t dig_P4;
 int16_t dig_P5;
 int16_t dig_P6;
 int16_t dig_P7;
 int16_t dig_P8;
 int16_t dig_P9;

void setup()
{
    uint8_t osrs_t = 1;             //Temperature oversampling x 1
    uint8_t osrs_p = 1;             //Pressure oversampling x 1
    uint8_t mode = 3;               //Normal mode
    uint8_t t_sb = 5;               //Tstandby 1000ms
    uint8_t filter = 0;             //Filter off
    uint8_t spi3w_en = 0;           //3-wire SPI Disable

    uint8_t ctrl_meas_reg = (osrs_t << 5) | (osrs_p << 2) | mode;
    uint8_t config_reg    = (t_sb << 5) | (filter << 2) | spi3w_en;

    Serial.begin(9600);
    Wire.begin();

    writeReg(0xF4,ctrl_meas_reg);
    writeReg(0xF5,config_reg);
    readTrim();                    //
}

void loop()
{
    double temp_act = 0.0, press_act = 0.0;
    signed long int temp_cal;
    unsigned long int press_cal;

    readData();

    temp_cal = calibration_T(temp_raw);
    press_cal = calibration_P(pres_raw);
    temp_act = (double)temp_cal / 100.0;
    press_act = (double)press_cal / 100.0;
    Serial.print("TEMP : ");
    Serial.print(temp_act);
    Serial.print(" DegC  PRESS : ");
    Serial.println(press_act);
    delay(1000);
}
void readTrim()
{
    uint8_t data[32],i=0;                      // Fix 2014/04/06
    Wire.beginTransmission(BME280_ADDRESS);
    Wire.write(0x88);
    Wire.endTransmission();
    Wire.requestFrom(BME280_ADDRESS,24);       // Fix 2014/04/06
    while(Wire.available()){
        data[i] = Wire.read();
        i++;
    }

    Wire.beginTransmission(BME280_ADDRESS);    // Add 2014/04/06
    Wire.write(0xA1);                          // Add 2014/04/06
    Wire.endTransmission();                    // Add 2014/04/06
    Wire.requestFrom(BME280_ADDRESS,1);        // Add 2014/04/06
    data[i] = Wire.read();                     // Add 2014/04/06
    i++;                                       // Add 2014/04/06

    Wire.beginTransmission(BME280_ADDRESS);
    Wire.write(0xE1);
    Wire.endTransmission();
    Wire.requestFrom(BME280_ADDRESS,7);        // Fix 2014/04/06
    while(Wire.available()){
        data[i] = Wire.read();
        i++;
    }
    dig_T1 = (data[1] << 8) | data[0];
    dig_T2 = (data[3] << 8) | data[2];
    dig_T3 = (data[5] << 8) | data[4];
    dig_P1 = (data[7] << 8) | data[6];
    dig_P2 = (data[9] << 8) | data[8];
    dig_P3 = (data[11]<< 8) | data[10];
    dig_P4 = (data[13]<< 8) | data[12];
    dig_P5 = (data[15]<< 8) | data[14];
    dig_P6 = (data[17]<< 8) | data[16];
    dig_P7 = (data[19]<< 8) | data[18];
    dig_P8 = (data[21]<< 8) | data[20];
    dig_P9 = (data[23]<< 8) | data[22];

}
void writeReg(uint8_t reg_address, uint8_t data)
{
    Wire.beginTransmission(BME280_ADDRESS);
    Wire.write(reg_address);
    Wire.write(data);
    Wire.endTransmission();
}

void readData()
{
    int i = 0;
    uint32_t data[8];
    Wire.beginTransmission(BME280_ADDRESS);
    Wire.write(0xF7);
    Wire.endTransmission();
    Wire.requestFrom(BME280_ADDRESS,8);
    while(Wire.available()){
        data[i] = Wire.read();
        i++;
    }
    pres_raw = (data[0] << 12) | (data[1] << 4) | (data[2] >> 4);
    temp_raw = (data[3] << 12) | (data[4] << 4) | (data[5] >> 4);
}

signed long int calibration_T(signed long int adc_T)
{

    signed long int var1, var2, T;
    var1 = ((((adc_T >> 3) - ((signed long int)dig_T1<<1))) * ((signed long int)dig_T2)) >> 11;
    var2 = (((((adc_T >> 4) - ((signed long int)dig_T1)) * ((adc_T>>4) - ((signed long int)dig_T1))) >> 12) * ((signed long int)dig_T3)) >> 14;

    t_fine = var1 + var2;
    T = (t_fine * 5 + 128) >> 8;
    return T;
}

unsigned long int calibration_P(signed long int adc_P)
{
    signed long int var1, var2;
    unsigned long int P;
    var1 = (((signed long int)t_fine)>>1) - (signed long int)64000;
    var2 = (((var1>>2) * (var1>>2)) >> 11) * ((signed long int)dig_P6);
    var2 = var2 + ((var1*((signed long int)dig_P5))<<1);
    var2 = (var2>>2)+(((signed long int)dig_P4)<<16);
    var1 = (((dig_P3 * (((var1>>2)*(var1>>2)) >> 13)) >>3) + ((((signed long int)dig_P2) * var1)>>1))>>18;
    var1 = ((((32768+var1))*((signed long int)dig_P1))>>15);
    if (var1 == 0)
    {
        return 0;
    }
    P = (((unsigned long int)(((signed long int)1048576)-adc_P)-(var2>>12)))*3125;
    if(P<0x80000000)
    {
       P = (P << 1) / ((unsigned long int) var1);
    }
    else
    {
        P = (P / (unsigned long int)var1) * 2;
    }
    var1 = (((signed long int)dig_P9) * ((signed long int)(((P>>3) * (P>>3))>>13)))>>12;
    var2 = (((signed long int)(P>>2)) * ((signed long int)dig_P8))>>13;
    P = (unsigned long int)((signed long int)P + ((var1 + var2 + dig_P7) >> 4));
    return P;
}

The BMP280 is a sensor that can be used at 3.3V, but not at 5V. The datasheet tells that the interface pins may be maximum 3.6V (when the sensor is powered with 3.3V). That means you may not connect the sensor to an Arduino Uno. Not to the SPI interface and not to the I2C interface. The sensor might already be damaged. This is not a joke. When sensor is still working, the results might be noisy or the values could drift too much.
The easiest solution is a level shifter module for I2C. Another option is to add two extra pullup resistors of 10k from SDA to 3.3V and from SCL to 3.3V and connect the SDA and SCL directly to the Arduino Uno. It will not be reliable, but with some luck it will work. You need some luck, because it will not be okay according to the datasheet of the ATmega328P.
You could also buy a 3.3V Arduino board (Arduino Due, Arduino Zero, Arduino M0, and so on), or buy a BMP280 module that is compatible with 3.3V and 5V signals: Adafruit BMP280

Thanks for the answer, but I am wiring it at 3.3 V so where is the problem?

I was talking about the signals of the SPI bus and I2C bus. Even the I2C bus is not fully compatible with a 3.3V sensor. The internal pullup resistors are enabled and the Arduino Uno requires 3.5V for a reliable high level at SDA and SCL according to the datasheet of the ATmega328P. The internal 50k pullup resistors together with the 10k pullup resistors on the module make a voltage at SDA and SCL of 3.58V. That is enough for a high level of the ATmega328P and it won't damage the sensor. But that is pure luck. It changes if you add something to the I2C bus.


text:
How to use a microSD card reader with SCK instead of CLK?
I've bought this microSD reader/writer: http://www.ebay.com/itm/131132034753
I've found only one tutorial, where the pins are similar to my pins, but in the example there is a CLK instead of SCK: https://learn.sparkfun.com/tutorials/microsd-shield-and-sd-breakout-hookup-guide
The pins on my MicroSD reader are:

CS
SCK
MOSI
MISO
VCC
GND

SCK is actually a clock signal. So basically, they are the same thing here.

SCK stands for SPI ClocK
CLK stands for SPI CLocK
Two different acronyms for the same thing.

It's common practice for speakers/writers to use the generic term: "clock" (CLK) for various different situations. This clearly being a serial interface we don't need to specifically say Serial cloCK each time the signal mentioned, as it's more of a mouthful than saying "clock".
In this case consider "CLK" and "SCK" as fully interchangeable.


text:
Esp8266 server unreachable. Port doesn't open
I have followed all the instructions provided on  http://allaboutee.com/2015/01/20/esp8266-android-application-for-arduino-pin-control/
I have got the correct setup, I have got the message "Server Ready" in the serial monitor, i have an app similar to this, means the only thing i have done different from the web page is removing two buttons from the app.
But then also whenever i use my app to send request parameters to arduino it says "connection to 192.168.x.x:xx refused" , when i put the same ip and port in chrome, it says Server not reachable, the website may be down, What to do ? , Please help...

First of all check that your ESP is connected to your WiFi network, to do this go to your router and check that your device got that IP address. Only when it shows up at your router you'll be sure that it is available on the network.

i did that already, my router homepage shows the same ip address on which i am trying to send the http request

Ok, then that means that your ESP is connecting to the WiFi network, but that doesn't mean that the web server is up and running. Arduino is showing up the Server Ready string but that doesn't mean that the actual ESP is actually running. Where the line if(esp8266.available()) // check if the esp is sending a message
{ create an ELSE statement just to check if the .available is returning false (meaning that the ESP is not there for Arduino.

absolutely, you are right, it is not actual sending anything, i just created a else statement making it print "no message send" and my serial buffer got filled up with the Same. Now, we now the problem, now the job is half done, what to do next.

That doesn't work

The ESP module is not that difficult to work with, if you send the correct parameters to it AND you have the correct power it should work as expected.
My main suspicions will be cabling (just triple check that connections are as expected) and power source (the ESP is VERY power hungry, if you are powering the ESP from the Arduino that is your problem, you need a very good and stable power for the ESP to work (it might show up on your network but will not have enough power to actually send anything and it will disconnect (that will still show up on your router, it depends on how fast it connects/disconnects but won't be able to send anything).
This link can provide some good information about this subject:
http://bbs.espressif.com/viewtopic.php?t=133

But, just now, i uploaded bare minimum and then opened the serial monitor and typed the commands one by one it worked out, the server was ready and it was also accepting my http request, but how can i compile all those commands in the sketch.

Ok, progress. What exactly did you do? how did you "uploaded" those commands? Using Arduino? Also, you didn't answer my question, how are you powering your ESP?

i have connected ESP to 3.3v on arduino and then i uploaded a empty sketch, then opened the serial monitor and typed in AT and got response OK likewise i typed in each AT command and the server was setup and it responded, but you know serial monitor has it's own limitations

Ok, I understand that you think it worked (in fact you saw it)  but the BIG difference here is power. If you send those commands one time it might not do a lot but as soon as you start sending other commands the ESP will start to consume more and more power (the library on the Arduino is not doing only the send of those commands but much more) and that's when the ESP just dies, it doesn't have enough power to stay up.

i have a malfunctioned arduino board but it can supple enough power, should i add that also keeping the present arduino as it is

Good, glad that you were able to solve your problem.

No that didn't solve my problem

I had the same problem and it worked when I disconnected my phone from 3g/4G.


text:
how to detect 125khz tags with mfrc 522
I have just ordered MFRC 522 RFID reader from amzon, and I have also orders 5 RFID tags with keychains and a arduino uno board for my project, I have received RFID reader and tags and I have tested the tags with my Sony xperia NFC. The tags that I received with the readers are working fine but the key chain ones are not working. I think because of the frequency difference 13.56 MHz and 125 KHz. So, please tell will this key chain tags work with the Reader

than what would be frequency range of the card/tag the one which came with the mfrc522 reader???

You are correct NFC is 13.56MHz the key chain ones you are referring to are most likely 125kHz The reader you have will only read 13.56MHz this is the NFC and HID cards. If you want to read the Key Chain ones you will need a reader like this one. Weigand 26 Card Reader Most Phones will not read the 125kHz

You can buy a 125 kHz reader from eBay for around $7. I got one like this:

You can communicate with it (listen to it) with a single serial pin (plus ground and power of course). I have a post about that board which describes the connections.

So, please tell will this key chain tags work with the Reader

No, the 125 kHz tags won't work with the 13.56 MHz reader. However you can work around this (if you want to) by using the 125 kHz tags with a different reader.


text:
Hardware to measure velocity via string/wire attatchment? beginner
This is a broad question but I want advice on what type of hardware I should look for to make a device that could measure the velocity of an object attached via a string/wire to some sort of rotary wheel.
The purpose of this is to attach it to a barbell and measure mean-velocity for weightlifting atheletes.
I'm a software engineer by trade but know nothing about hardware. I will obviously need to start with simple projects to learn, but I would like to know which hardware I should lean towards buying, so I don't have to re-buy anything?

Attach a optical rotary encoder. Similar to the one that can be found in mouse scroll-wheels. (Since direction isn't needed for you problem only a single photo-interrupter is needed.)

I wonder though how I would get the encoder to "rewind" back into position (between subsequent weight lifting repetitions) without affecting the velocity measurement, or causing undue asymmetrical stress on the athlete?

Some small spring would retract the wire without exerting any noticeable force for the athlete. Or have the wire loop around the "wheel" and attach a counterweight (just like a lot of fitness devices do).

You can use a dog lead (or replace it with a fishing line). I made one my self. I used a rotary encoder and a dog lead, an Arduino board Paralax, and Excel.
It will use interrupts. Once the wire is triggered, the Arduino will send to Excel time and distance traveled. Once the weight goes down distance and time will be printed too, however distance will run in a minus direction. Later just press one button in Excel and each set of lifts will appear on the desktop. I can see my lift speed, power generated, distance travelled and so on.

This is an example of the optical encoder.
You want to use interrupt detection, rather than polling.
Or maybe even an HW counter.
That's all you really need.
I am using 4 of them for a car.
I am in the process of refactoring the code, but you could already have a look at the driver & example I wrote for ChibiOS, here.

Second link appears empty

Ooops, sorry. Fixed.


text:
Multiple (3) RF transmitters to a single receiver?
How can I have three remote transmitters send distinct signals to a single receiver?
My project requires 3 remote controls, each with 2 inputs.
I need to distinctly identify these 6 signals from the 3 remotes onto one arduino board.
Is this possible to do with one receiver?
Would I be able to pair one remote to one receiver (so 3 receivers), or will there be noise / interference?
What is the simplest and/or cheapest solution to this?
FYI I am going to be using a 315 Mhz remote / receiver (remote control has 4 inputs). I am waiting for them to come in the mail but I want to start thinking about how I will build this.

What transmitters?

Please provide exact reference to these transmitters/receivers. Also, what Arduino library do you use to interface with these devices?

Why all of the down votes? What dose this question lack? Despite the absence of the exact library and device, this concept of this question is clear I think

These transmitter all transmit on the same frequency so if you have multiple receivers they will all get the same signal.
The only way I can see you can do this is make some type of protocol where you send data with a station ID and only the receiver with the station ID matching the message will act on it.
EDIT:
Sorry have to get used to the double-enter making a send.
@JamesWierzba your 'remotes' will need to be more than just a push button to send a HIGH or LOW signal via the transmitter.
Your 'remotes' will need to each have a unique ID, we usually use DIP switches for this. A small microcontroller will need to read these DIP switch and compose the message to be send to the receiver.
A simple message like "ID_BUTTON_PRESS" where ID is the decimal or hex equivalent of the DIP switches.
On reception of the message the microcontroller receiving the message will know which remote it comes from by looking at the ID part of the message.

So each transmitter  will have a unique ID? In the message?

Well, without code they don't, you would have to make your own code to do so.

Oups pressed sent too fast.
You could use the VirtualWire library -> https://www.pjrc.com/teensy/td_libs_VirtualWire.html

Let's give a simple example. You program each receiver with an ID (1, 2 or 3). At the start of every transmission you put the ID of the device you'd like to send to. For example: 2,test. All your receivers get this message, but only the receiver with ID equals 2 will use it. The rest will discard the message.

@Len I'm broadcasting from 3 tramistters, not trying to receive on 3 different receivers (although I can if necassary). The basic problem is this: I have 3 remotes ( 3 people each hold a remote). I need to know which person pressed it. IS that more clear?

Yes, but same principle applies. Let each transmitter send their ID as well and you know which transmitter was used.

@JamesWierzba your 'remotes' will need to be more than just a push button to send a HIGH or LOW signal via the transmitter.


text:
Can I measure velocity from an accelerometer? How accurately?
I've bought this module
Kootek GY-521 MPU-6050 MPU6050 Module 3 Axis analog gyro sensors+ 3 Axis Accelerometer Module
My project will involve affixing this to a moving object, moving at velocities varying from 0.1 to 1.0 meters per second.
From what I understand, this module will allow me to infer rotation and acceleration, will I be able to derive velocity?
How much accuracy can I expect?

http://www.chrobotics.com/library/accel-position-velocity

Attempting to integrate velocity from acceleration leads to integrating the error, ie, the error rapidly grows to the point where the result of the calculation is not so much "inaccurate" as "meaningless"

@ChrisStratton I'm pondering this as a replacement for my current prototype, which is a retractable string attached to a rotary encoder. Are you suggesting this is not feasible?

I need to be accurate within at least 0.05 meters per second

I don't think that will be possible. If my understanding of accelerometers is correct, they measure acceleration. Then you have a situation when the speed is constant. Acceleration = 0, according to Newton's laws. You would have to keep track of changes in acceleration then perform math to maintain the state. As Chris Stratton suggest, that will lead to keep integrating the error to the very likely situation of a meaningless value. Edit: however, I have never worked with an accelerometer before, so it can be possible at a certain extent.

@fabrosell This makes mathematical sense. Velocity is certainly the most important value for my project, so it sounds like this will be viable. You can post your response as an answer and I will accept it

The sensor in itself can't provide you the velocity. I have used it accelerometers in a couple of projects the easiest way to get the velocity is to constantly monitor acceleration changes and calculate velocity instantaneaously.
In order to do so follow these instruction. Pleas note that this is only 1 axis reading in actual case you will have to perform this for all three axis i.e. x,y and z.
I hope you are aware of the equation of motion (V = Vo + at)... The sensor will provide you value of acceleration at any given time. But acceleration can vary quite significantly during a huge time intervals so keep the time intervals 't' small. Lets say t = 10ms (depends on you). So calculate V after every 10ms intervale and this will give you current velocity at any given time. But what about Vo? As you know it is refered to as initial velocity so in the beginning it will be 0. Immediately after first reading when you are about to take second reading the Vo will change to the previous V calculated and hence forth.
This means Vo at any given interval is actually the V calculated in the previous interval.
I tried this method in my project when using accelerometer. hope it helps you as well.

Exactly. I forgot to add the Vo issue in my previous post.

How accurate was this? Did you verify or compare in some way?

And yes, I can correctly assume start velocity of V0 = 0m/s, however it is possible that the object might get moving from 0 a,d then stay at some velocity, or close to it, and not accelerate very much. Will this be a problem?

Well as long as your time delta's (intervals) are short enough that won't be a problem at all. Since this equation will provide you instantaneously velocity at any given time. If accelaration is zero at any given time that means velocity will be what it initially was.

@JamesWierzba As for how accurate. That totally depends on you accelarometer. I used a couple of them but they gave quite buggy values but they were the cheapest available. If you go for something solid then the results can me close to 100% precision.

@UsamaZafar do I need to increment t by 10ms every time? Or t will always be 10?

I work with Arduino-based autopilot modules, which usually use similar sensors in addition to GPS data to maintain a reasonable estimate of its position/velocity/acceleration.  If you were to add other sensors (i.e. a GPS) to your project, it might be worth looking into Extended Kalman Filters (https://github.com/simondlevy/TinyEKF), which are usually able to provide fairly accurate results.
If you're only using an accelerometer, EKF would probably be overkill, so you could look into other noise-reduction techniques.  For example, using a weighted average of the last two readings:
// alpha is value between 0 and 1
acceleration = alpha * readAccelerationSensor() + (1 - alpha) * lastSensorReading

Another strategy to filter out noise would be to take multiple sensor readings at each time step and use the median value to integrate for velocity.

The total distance moved is no more than 1-2 meters in +Z direction so gps is no good. Are you suggesting taking 3 readings at a single point in time? Why? Is the hardware that unpredictable?

Accelerometers in general are somewhat susceptible to noise from mechanical vibration of your device, so averaging the sensor readings would help to reduce the error from higher-frequency noise.  Whether this is an significant issue will depend on your application (how much your device vibrates during normal operation, and how much precision you need from your velocity measurement).

I don't think that will be possible. If my understanding of accelerometers is correct, they measure acceleration. Then you have a situation when the speed is constant. Acceleration = 0, according to Newton's laws.
You would have to keep track of changes in acceleration then perform math to maintain the state. As @Chris Stratton suggest, that will lead to keep integrating the error to the very likely situation of getting a meaningless value.
However, I have never worked with an accelerometer before, so it can be possible at a certain extent.
It would be great to hear from someone who actually tried this.

I think that calculating the instantaneous velocity as described by Usama is the correct method so long as you can deal with the cumulative error. I would also suggest that you provide regular recalibration to deal with that (like a return to home).
However, if you are trying to calculate velocity the best method would be to use a gyroscope, not an accelerometer.
Gyroscopes were (are?) how submarines navigate underwater. To measure acceleration with gyro sensors it is of course the rate of change of the velocity. V = Vo + at and d = Vo.t + (a.t^2)/2 are your two most important formulas.
Which you choose depends upon your application.  I would chose either based on whether my application is more likely to have constant velocity or frequently accelerating and decelerating. Maybe even have both...
I have not experimented with digital gyro sensors but note that there are a couple of Arduino shields available.

A gyro doesn't measure acceleration it measures rotation.

Rotation is by definition acceleration. A vector is speed plus direction. When you change either you are accelerating. So a gyro is measuring both speed and direction and giving you data in three dimensions.

Gyros measure angular velocity not lineair velocity. When you accelerate a giro in a straight line you don't get any output. One gyro will only give you angular velocity in one direction (axis).

We will have to agree to disagree. Yes you are right about angular velocity - but it is angular in relation to the gravity of the earth. So any movement will record a change. That includes a straight line that is tangent to the earth or moves around the circumference in an arc.  (I am not sure about how it works when moving in a straight line toward or away from the center of the earth’s mass.)

Clarification - Texas Instruments supply solid state gyros that work in three dimensions and the application notes indicate that they can measure movement in any axis so moving directly along the line of the gravitational force must be possible.

It seems that you confuse acceleration meters with gyro's. And you confuse the fundamental difference between lateral movement and rotation. Suppose a body with a gyro travels a full circle (i.e. around a circular trajectory). Then during the travel the gyro will tell you the angular velocity and, by integration, the amount of degrees it rotated from the start. At the end of the trip this will be 360 degrees. What the gyro will not tell you is the diameter of the circle.

@PimV okay. I am not one to hold back from admitting I was wrong. I was conflating this with using accelerometers with gyrostabilisation to keep the orientation of X,Y, and Z constant to you can track your location in a three dimensional space. The section on gyrostabilisation is where I got confused.  https://en.m.wikipedia.org/wiki/Inertial_navigation_system

Fair enough, case closed!

Use to compass + accelerometer
Use compass to eliminate g from the readings

Please expand upon your answer


text:
Max double value or NAN as a sentinel value?
I am in need of a sentinel value to use to assign to a double variable initially.
0 or -1 won't work because these values are valid values in my computation and I need a value that will stand out.
Possible choices are:

Maximum double value
Minimum double value
NAN (I would also need a method to check is_nan as well)

How can I accomplish this in the Arduino language?

AVR GCC doesn't technically support double at all.

This is a matter of personal preference. I like NAN because it is almost
always obvious it cannot be a valid value.
You can test for the value being NAN with
isnan().

Right but do they exist in arduino language? The constant NAN and isnan() function (in standard c++ it's a std:: library function)

The link I provided is to the doc of the avr-libc. You can use NAN and isnan() with no prefix on any AVR-based Arduino. No need to explicitly include <math.h>, as the Arduino IDE does that for you (via <Arduino.h>). I do not know about the ARM-based Arduinos (e.g., the Due).


text:
How to include <SPI.h> outside the .ino file
As I understand, Arduino IDE considers two paths for the libraries:
first,

"C:\Program Files\Arduino\libraries"

and second, the "libraries" folder next to the schetchbook.
I have a configuration.h file, that I include in the main file, Test.ino, like this:
#include <configuration.h>

and in the configuration.h file I try to include SPI.h like this:
#include <SPI.h>

But I get the following error:
fatal error: SPI.h: No such file or directory

It seems that I am obliged to include SPI.h only from the ino file. But why?
And how can I do what I want here? do I have to change IDE?
P.S: the software is large and I am improving maintainability.

It seems that I am obliged to include SPI.h only from the ino file. But why? And how can I do what I want here? do I have to change IDE?

The background is how the Arduino IDE pre-processor works together with the GCC AVR compiler and build tools.
The compiler needs to know the include path to the libraries. This is created by the pre-processor by scanning the ino file and searching the known libraries. A compiler command line is built with the include paths to the located libraries.
If you move the library includes to a configuration file the IDE pre-processor will not be able to locate the libraries and create the include paths. The pre-processor does not recursively scan library files.
Cheers!

Any references for this info?

The wiki https://github.com/arduino/Arduino/wiki/Build-Process gives a hint.

See my answer How the IDE organizes things. There is no easy way to avoid having to put an include in the main .ino file, unless you write your own build process (or perhaps use another toolchain).
I think you could put SPI.h (and other things, like Wire.h) in the main .ino file, even if they aren't used due to your configuration parameters. The linker would strip them out because the modules were not referenced.

The IDE has to be explicitly told each and every library that you use. It also has to be told each and every library that every library that you use uses. And so on.
The Arduino IDE only looks in the INO files. As a result: if the library is not included in the main INO file then the IDE doesn't know that you intend to use it, and so it doesn't look for it.
Only when it's in the INO file will the IDE actually look for where that library is located and append the right flags (-I...path...) to the compilation commands to be able to get at the files for it.
Further, it is only then that it actually knows that it should compile the source code for a library. Without that knowledge, even if you explicitly point to the header file with a relative path, the IDE won't know that it should compile and link the source code.
There is no way around it, it's just the way the IDE works. The only option is to change to a different IDE that has more intelligence and can recursively deep-scan the libraries to maintain a list of prerequisites (such as my popular UECIDE IDE).

I'm not fully agreeing here. It is a decision of the arduino core team to only scan the ino files for libraries.There have been several issues raised to fix this. I do agree that the PO should consider another IDE. I however would advice to use arduino eclipse plugin called sloeber that can be found at sloeber.io.

@jantje Only because you wrote it. At least I have the good grace to mention that UECIDE is mine. If you advise someone to use something you have created you should mention that it is your product.

Sorry I forgot. As it was you I assumed that you knew (which you do) and I forgot to mention (for the other readers) that I do develop the arduino eclipse plugin named sloeber. I think people should use the ide of their choice and choice is a good thing. So I didn't mean I do not fully agree with the IDE you propose. I probably should have done a edit :-(


text:
ISR halts in DUE
I am using the following simple code to test the interrupt functionality of due:
void aMillion(){
    for(int i = 0; i < 1000000; i++){
        if(i % 1000 == 0){
            Serial.print("m");
        }
    }
}

void setup(){
  Serial.begin(9600);
  pinMode(2, INPUT);
  attachInterrupt(digitalPinToInterrupt(2), aMillion, CHANGE);
}
void loop()
{
}

obviously what we expect to see is a thousand "m" characters after each interrupt event. On Arduino Mega, this worked fine. But I have tested it on multiple Due boards.
Very odd news is that on the reset event of due, I do get a single "m" character printed.

Just a thought, check http://arduino.stackexchange.com/questions/23006/digitalpintointerrupt-doesnt-work

Doing a lot of stuff inside the ISR isn't advised. Especially if you are doing serial communication. What happens if you do just a single serial.print?

I am surprised this could ever work on the Mega. The test i < 1000000 is always true due to the limited range of int type. And you get undefined behavior when i overflows.

@EdgarBonet haha yea, but an automatic cast during the comparison would make the loop run forever. wouldn't it? That's what I saw with MEGA

I don't understand your comment. Could you be more explicit? I just compiled aMillion() for AVR and got “warning: comparison is always true due to limited range of data type”. And gcc optimized out the test i < 1000000. The generated assembly is just an infinite loop.

@EdgarBonet I guessed that it might have been cast to 'long' automatically. But apparently that is not what happens. In any case you are right and this is an infinite loop.

@EdgarBonet Initially I had extra delays in the loop, So I never reached a thousand output characters. That is why I did not notice this in the beginning.

thanks @Jesse but that link was a totally different issue. That was a Pin mismatch.

as @EdgarBonet and Gerben pointed out, It is not possible to have very long ISRs in the DUE. For the MEGA however, an infinite loop including anything, will be executed with no problem. that is why the infinite loop ran a good time in the MEGA. I will post this as the answer

An attempt to run long loops in the ISR for the DUE fails. This is the result of some sort of a run time monitoring system. An infinite loop like this one here, or even a loop with a thousand repetitions of a Serial Print will result in an early halt of ISR on the DUE.
On the MEGA however, This is not the case. ISRs can run much longer. (At least ten minutes as I tried)


text:
Binary reader with arduino blinking 8 leds
I´m trying to insert a binary raw sequence (01010100, 01101000, 01100001) into Arduino. I would like to make 8-led group blink in a loop, showing with light each 8-group binary sequence when: 0=light off and 1=light on.
It´s possible to do this operation with Arduino-uno ?

i don't think binary is supported in arduino, but you could use bitwise operators with the decimal values of these binaries

You should be able to do what you are asking, however your question is not very clear.  Are you asking how you would turn on/off the LEDs based on the binary value of a variable, or how you would get the raw sequence into the Arduino/source code?  Or both?  How are you wanting to get the sequence into the Arduino?  Is it to be pre-scripted in the source code, stored on some external device (such as an SD card), input by a user from some other hardware (such as a keypad) or transmitted (either wirelessly or via a serial connection)?

@razzak: Binary not being supported by Arduino is the silliest statement I ever heard about this platform. Almost everything inside the Arduino is binary. Decimal is only used for I/O, and only because we, humans, like it better that binary.

@EdgarBonet i was talking about using binary literals not the operations at the cpu level, you can not do int x = 01001001; in arduino. You can however use binary special notation (formatter) like int x = B01001001; which is not actual binary but rather a predefined decimal like doing #define B01001001 73.

Then, in your initial comment, you failed to make clear what you were talking about. The “B” notation is, in actual practice not that different from “0x” for hex. Or even decimal, which is only a notation after all: you do not really care whether it is interpreted by the preprocessor or the compiler proper.

You just prepend the number in binary with B e.g. B01100100 which is 100 in decimal
byte sequence[] = {
    B10000000,
    B01000000,
    B00100000,
    B00010000,
    B00001000,
    B00000100,
    B00000010,
    B00000001
}

And to check the n-th bit from the right in a number you do
boolean bit_set = number & (1 << (n - 1)) != 0;


text:
Arduino constant clock output
I am controlling an ADC with my Arduino Uno. I would like the clock of the ADC to be the same frequency of the Arduino.
Is there any way that I can have a constant clock output from one of the Arduino pin ?
Thanks,
Liam

Sounds a lot like this question

Which ADC? If you are reading via SPI, than the clock speed is typically the SPI clock speed, default is 4 MHz, and 8 MHz, 2 MHz, 1 MHz, 512KHz, 256KHz, 125 KHZ and I think 62/5KHz are selectable as well.  If you just want a constant, free running clock, then 16 MHz is available at the CKPOUT pin with a change to Low Fuse byte bit 6: The CKOUT Fuse allows the system clock to be output on PORTB0 [on a '328P chip]. Refer to Clock Output Buffer section in the System Clock and Clock Options chapter for details.  Ah - 2015 - well, maybe this will come in handy for someone.

This outputs 8 MHz on pin 9:
#ifdef __AVR_ATmega2560__
  const byte CLOCKOUT = 11;  // Mega 2560
#else
  const byte CLOCKOUT = 9;   // Uno, Duemilanove, etc.
#endif

void setup ()
  {
  // set up 8 MHz timer on CLOCKOUT (OC1A)
  pinMode (CLOCKOUT, OUTPUT);
  // set up Timer 1
  TCCR1A = bit (COM1A0);  // toggle OC1A on Compare Match
  TCCR1B = bit (WGM12) | bit (CS10);   // CTC, no prescaling
  OCR1A =  0;       // output every cycle
  }  // end of setup

void loop ()
  {
  // whatever
  }  // end of loop

How can add a prescaler?

You change the prescaler bits. You can look at the datasheet or my cheat sheet here:

You may not need a prescaler, depending on the frequency. Change OCR1A to some number between 0 and 65535 to slow it down.
Edit by Edgar: I tested the OCR1A values with an oscilloscope. At the end of this answer are the frequencies.

you use TCR1A, COM1A0 and similar variables. Are these always present and implicitly defined when running code on the ATmega

Registers like TCCR1A and so on are defined in files which are automatically included by the Arduino IDE. If you use another toolchain they may be also automatically included. The start point is:
#define <avr/io.h>

Inside that file it checks your processor type (from a symbol passed to the compiler) and then includes an appropriate sub-file. Inside those files are defines which relate the register names to their address in the address-space of that particular chip. For example:
#define TCCR1A _SFR_MEM8(0x80)

The _SFR_MEM8 basically generates a pointer to a volatile address (because it might change without the compiler knowing it) and then dereferences that variable.
Notice that the number 0x80 in that define agrees with the number shown on my chart.
Underneath that define in the appropriate file are also the bit positions for the bits in that register, like this:
#define TCCR1A _SFR_MEM8(0x80)
#define WGM10 0
#define WGM11 1
#define COM1B0 4
#define COM1B1 5
#define COM1A0 6
#define COM1A1 7

Secondly, do I correctly understand that the output pin is defined in TCR1A, Output A and Output B, to be on Digital Pin 9 and 10 respectively?

Yes, in effect. The datasheet says that if you set the appropriate bits in TCCR1A (note the spelling) then OC1A (board pin 9 on the Uno) or OC1B (board pin 10 on the Uno) will be unchanged/toggled/cleared/set depending on the bits. You can find these names on the datasheet for the Atmega328P (and other devices) and then use the Arduino schematic to find which processor pins are connected to which board pins.
Atmega328P datasheet snippet:

Uno datasheet snippet:

Why do you set it to "Toggle" rather than "Set"?

Because every time the counter matches I want to flip the pin. That is, on/off/on/off etc.

What does CTC stand for?

Clear Timer on Compare. What this means is that (unlike other modes) once the compare match is made, the timer is cleared, thus it starts counting up from zero again.
Edit by Edgar: OCR1A values and frequencies
Value, MHz
 0 8.00
 1 4.00
 2 2.67
 3 2.00
 4 1.60
 5 1.33
 6 1.14
 7 1.00
 8 0.889
 9 0.800
10 0.727
11 0.667
12 0.615
13 0.571
14 0.533
15 0.500

This is exactly what I needed . How can add a prescaler ?

See amended reply.

Thank you for this helpful chart and code. I have trouble understanding some finer points.
First, you just, well, use TCR1A, COM1A0 and similar variables. Are these always present and implicitly defined when running code on the ATmega (or just on an arduino) or do you actually declare them outside of your shown code snippet?
Secondly, do I correctly understand that the output pin is defined in TCR1A, Output A and Output B, to be on Digital Pin 9 and 10 respectively?
Why do you set it to "Toggle" rather than "Set"?
And lastly, an easy one: What does CTC stand for?
Many thanks to you.

See amended reply.

This is an absolutely amazing answer. I wish I had more rep to give you bounty points. For now: Thank you!

In “The start point is: #define <avr/io.h>”, define presumably s.b. include

Huh? What is "s.b."?

I just added the frequencies for different values. I did this in the original answer because the formatting makes it a lot easier readable compared to a comment.

You can use one of the PWM pins on Arduino to output a PWM signal.
If you want a constant clock, you need to set the duty cycle of the PWM to be 0.5, i.e. 50%.
Syntax: analogWrite(pin, value) where the parameter "value" is the duty cycle ranges from 0 (always off) to 255 (always on) since it is a 8-bit PWM generator inside Arduino.
If you need a PWM wave with duty cycle of 0.5, you need to set the "value" above to be 127, which is exactly in middle of 0 and 255:
analogWrite(clkpin, 127);

analogWrite only works on PWM pins, not on the analog pins.

You are right, my fault.


text:
What is the best way to make a good but simple line follower?
I am new in this site, and like you can see I want to do a line follower, not a clumsy and slow line follower, but a fast and "fancy".
I investigated about the PID method, but can someone explain me in simple words what is it.
Thanks for your answers.

Have you already chosen/built the robot? what kind of hardware do you want to use? BTW, I suspect that PID will only be useful if you have a continuous/fluid way to sense the line and not just 3 infrared sensors like many basic line follow bots have.

The chasis... I have not make it yet, and i have 8 sensors in an array.

This might be a good tutorial for you to look at:
http://letsmakerobots.com/node/39972

Did you check wikipedia, for example?
I doubt it is possible to describe a PID controller in simpler words than those used by the article.
The pseudocode is quite simple and should be also very good for understanding the concept, when applied to a digital system.
See also the limitations of PID controllers.


text:
Servo Speed Control
I work in a robot using arduino, and i have a few questions:
It is possible to increase the speed of a servo, for example a parallax?
It is possible to measure the current that pass through a servo?

Assuming the on-board controller is already driving the motor with full effort, the only way to increase speed is to lessen the load at the servo output, increase the voltage, or change the servo.  You can of course measure the current, perhaps by measuring the voltage drop across a very small sense resistor.  Generally speaking, continuous rotation servos (presumably what you mean when you reference parallax) are rather crude (and arguably open loop, not "servos" at all once so modified) so before investing much effort you may want to start with something better.

If you are powering the servo from the arduino 5v rail you could try to power it from something else, if you use a battery pack or powersupply, then put the Vin of the servo directly to that instead of using the arduino 5v rail. It is not healthy to run high current stuff from the arduino rails anyways.

Part 1: Can I increase the speed of the servo motor?
Solution #1 :
You can run your servo motor at its maximum rated voltage, which will give you the fastest response. If angle is all you want, that should be ok.
Solution #2 :
If speed control is just as important, you're better off using a DC motor with an encoder. You will have to write a PI control loop, but in return you will be granted a fine-tune control and potentially superior performance.
Solution #3 :
If you need to hold a physical load accurately at a certain angle, then I would go for a stepper motor. But you need to make sure that you do not overload it, as it will cause a misstep.
Part 2: Can I measure the current?
The simplest and cheapest method, is to connect a current sensing resistor to your servo and measure the potential difference using the analog input. Since the resistance is known, you can calculate the current using the formula I = V/R.
Two things to make sure:
1) Your resistor power rating is not exceeded.
2) The voltage difference has to be large enough to be measurable. (e.g. 2 ohm resistor gives .05V @ 100mA, .5V @ 1A and your Arduino analog input may have the resolution of roughly 0.005V)
What? Did I hear you say that the accuracy isn't good enough? Well actually you can buy an op amp to amplify to the scale that you need. Or to make life easier: buy one from Adafruit. :p
Hope this helps.

The speed of most servos cannot be changed in your code (unless your code is limiting the speed by changing the position in small increments with long delays between your writes). Most servos, in my experience, try to get to the set position as fast as the physical motors can possibly move while keeping the motion somewhat motors. However, motors can only go so fast, so you are limited.
One thing to note: some servo motors can be powered at higher voltages, but still controlled at 5V. With the increase in voltage, it might allow the motor to go a little faster, although the results will vary based on the servo's electrical characteristics and the motor driver's algorithm.
As for the current, you can buy cheap current sensors online that can be interfaced with the Arduino. You will want to measure the current (in series) flowing either from your power source to the VCC of the stepper, or from the GND of the stepper back to the GND of your Arduino.

Thank you very much, your answer was so complete and helped me so much, now things are so much clear. Sorry for my English, I am not a native speaker.


text:
Velocity from Sensor Data - Best Approach?
I am attempting to develop a control system based upon rocket velocity. My first step is attempting to properly filter my sensor data in order to calculate velocity.
What is the best approach to get accurate, smooth, and fast data to my control logic?
Would I benefit from combining accelerometer and barometric data? If so, how?

Background:
I am currently only using a BMP180 barometer to get altitude and then calculating velocity from the last altitude measurement. I am operating the BMP180 on ultra low power to increase the sample rate, but that comes at a cost of a RMS noise of around 0.5 meters.
Using 1D Kalman filtering I can get it smoothed out somewhat (tried on both velocity and altitude), but it is still not anywhere near as smooth as I need for my control system. It also lags behind the data far too much when I get it smoothed.
I have attached an example of what I have done with Kalman filtering. The original data is from a Featherweight Raven altimeter. I used the reported altitude data to calculate velocity (standard deltX/deltT) for each iteration, filtered it, and compared it with the Raven's own calculated velocity from it's accelerometer. The altitude data is at 20 Hz which is about what I am achieving with my Arduino setup right now.

Thanks!

First off, this is cool. When I first read your question, I was going to say that this is by no means easy, but the fact that you know what a Kalman filter removed any doubts entirely. In any case, I have a few ideas, but questions first! (1) How smooth do you want your data? It looks relatively smooth to me, but I can't say I know the sensitivity of your control system. (2) What was your impetus to use a Kalman filter? (3) How did you implement the filter? (4) Do you have a gyroscope, (5) Could you post your code?

Thanks for the reply! I am not too familiar with the Kalman filter, but I do have an aerospace engineering background.

For example, in this case, the rocket's velocity should only be affected by air drag and gravity. There should be no spikes down or especially up like in the data I tested against. I would like to see a curve similar to the grey line, but it seems to lead rather than follow the as the Kalman filter is causing.
I have read about it being used in similar control systems such as robotics (which I consider this very similar to).
It is a very simple implementation.....

...I wanted to initially just filter the sensor data versus model the system (which the Kalman filter can do) so I opted for the simplest approach.
4) I do have a gyroscope (L3GD20H) and accelerometer/compass (LSM303) from the Adafruit 10DOF.
5) I do not currently have the filtering implemented in my code, I tweaked the parameters and tested it using my data output and excel (and in the case of the screenshot, previous rocket flight data from another altimeter). My steady state parameters...

... from the Kalman filter implementation I posted are as follows:
P: 27.92 or 22.92 (depending upon where in the code)
K: 0.1791
R: 128
Q: 5
@Mlagma The reason I haven't moved onto using a matrix implementation of the Kalman filter yet, is that I am worried it may still produce significant lag and I wanted to know if there was a better filtering technique for what I am doing.

I just wanted to thank you for making this post. I had a similar question.

Welcome to the world of signal processing! (Starting off with a Kalman filter, though, is not very welcoming).
The first few things to address are in regard to the barometer:
(1) Inevitably, it's going to be noisy, and barometers in particular are known to be noisy. Considering the unfiltered data you posted, I'd say it's reasonable. The spikes are completely normal, especially being that your calculating the derivative from the barometer data. If you want to try to smooth the barometer data before passing it to the Kalman filter, you could apply a nth order low pass filter to the sampled data. This, of course, would add more lag to your calculations - it's really a trade off.
(2) Looking at the unfiltered data and the velocity calculated from the Raven, it appears that there might be an issue. Starting at time 0, the unfiltered data and the Raven data is nearly identical. Once the rocket reaches 180ft/s, though, the filtered data appears to diverge. After it passes the global maxima and hits 180ft/s again, the two data outputs start to converge. This makes me suspect that your sampling rate may be too low. A hard-core, by the book, DSP engineer will probably start crying when he reads this, but consider this: at a velocity of 180ft/s with a sample rate of 20S/s, each sample corresponds to a change in position of 9ft. So, at best, you have a resolution of 9ft per second. This can pose at least two problems. (1) The barometer has to continuously update temperature and pressure readings in order to calculate an accurate altitude. I only glanced at the datasheet, but it seems like the temperature (and I think one other parameter) is updated at a slower rate than the pressure sampling - that is, there's an oversampling factor for the pressure measurement. Hence, your calculation may start to diverge from reality. And as the rocket's velocity increases, this problem may be exacerbated. Of course, temperature changes at rate of about 9.8C/1000m, so it may not be that significant of an issue. Just wanted to throw it out there.  (2) Again, at 180ft/s with a 20Hz sampling rate, you basically have a resolution of 9ft/S. This isn't necessarily bad, but one thing to keep in mind is that a Kalman filter is predictive; it predicts the state of the system 1/20 of a second into the future. If your underlying model is off, this could lead to slower convergence and larger corrections that would make the filtered data look "jerky."
Just one more thing before we get into the filter...
It's worth considering how you're implementing this on the Arduino. There shouldn't be any issues with computation time that could result in significant lag. If your only sampling the altitude at 20Hz and then feeding it to the filter at the same speed, you should be good to go. The only issue I can foresee is if you're using the Arduino Libraries. If you are, you'll probably run into bottlenecks and missed deadlines.
Anyway, the primary issue you're having - in my opinion - is not related to computational speed or hardware issues. Instead, I suspect it's your implementation of the filter.
One thing that stood out to me were your values of R and Q. R is the measurement noise covariance, and Q is the process noise covariance. Covariance ranges between [-1, 1]. Your Q = 5. I quickly scanned the link you provided, so I might have missed a simplification they did. I've seen in some cases that the covariance is simplified to a proportional expectation value and left unnormalized, similar to what's seen in Gram matrices.
Regardless, here's some insight that may be useful:
The Kalman filter is very much dependent on how you model your system.
To illustrate this, let's consider an example analogous to your rocket. (I came across this example at some point, but I don't recall the source):
Say you want to measure the water level in a bucket, but you have a sensor that gives you noisy data. And of course, to filter the data, you decide to use a 1-D Kalman filter.
We assume that we have a pretty accurate model of our system, so we'll let Q = 0.001. We iterate through the filter, and we may get data that looks like this:

The filter works fairly well.
But what if our model happened to be off - that is, it doesn't reflect what's really happening?
In the image above, the water level was constant. In reality, perhaps the tank was filling at a constant rate. What happens now if we use the same filter?

Clearly, the filter is diverging. The lag, as you call it, isn't really lag or a delay in the sense that the computation is slow. (In some ways it is a delay, but only in the mathematical sense that the filter is slowly converging). The "lag" effect we're seeing is due to our model. In essence, the filter we designed thinks our model is so good (as indicated by our low Q) that it gives greater weight to our model of the system. As you probably guessed, one way we can fix this problem is by increasing Q. So, let Q = 0.1:

You can keep increasing Q, and when Q = 1, your filtered data should actually match your measurement data.
This, though, really ins't the best way. Ideally, you need to start with a relatively accurate model. Q can be thought of as a measure of the error in your model, and you want to minimize error. At this point, you'll inevitable need to start work with matrices. This won't increase "lag." In fact, it should help your filtered data converge quicker.
There is one more thing to note. Kalman filters prefer linear data (speaking generally here). Look what happens when you feed in nonlinear data:

To accurately and effectively apply a Kalman filter to non-linear data without such pronounced "lag",  you need to use what is known as an extended Kalman filter - which basically linearizes your data.
Before you go down that route, which would probably be overkill, I would suggest improving your model used in your Kalman filter to better reflect it's true state. This means ditching the simplified filter you found and going into the matrix math.
In any case, I hope this helped. Feel free to ask any questions.
(Another method just crossed my mind that may be a simpler approach than a Kalman filter. I'll add it tomorrow).

Thanks for the awesome info! I want to get into the Kalman filter modeling for the actual rocket launch, but I don't have any unfiltered data. The Raven already filters its data and I can't test against that.
I have been messing around with combining the low pass filter with the 1DKalman I was using before, it certainly gives better results for less lag time!
Would I be best off (unless I can get real sensor data) to implement some sensor fusion? I was thinking by combining accelerometer data with the baro, I can smooth it out, but I am not quite sure how to do that yet.

I am starting to feel like this is going well past the scope of my original question. I have been doing some research and it may sound like to get good data I may need to implement a full IMU system. Do you have any reading suggestions for books or otherwise? I frankly don't know where to start.

@ZNaught Sensor fusion will certainly give you better data, and this is where the Kalman filter excels. However, it can quickly become hairy because you'll automatically be using a 2-D filter. An IMU is probably the best sensor you can use for this application - some already do the filtering for you. If you're going to be using an accelerometer, you'll need to process its data with a gyroscope in order to retrieve accurate data. In regards to books, are you looking for references on filtering, control systems, both, or other?

Also, I know you said your background is in aerospace engineering (degreed, student?), but what's your mathematical background? I'm not sure what math courses aerospace engineers take.

The IMU I am currently using is the Adafruit 10DOF which does absolutely no filtering (except the sensors themselves which you can select resolutions and such). It has a gyro, compass, accelerometer, and barometer (with temp). As for books, I could use background on both of those subjects for sure. My math background is up to differential equations and I have a year left until I graduate with my BSE.
I did find this awesome resource, it seems to be what I am trying to do: http://home.earthlink.net/~david.schultz/rnd/2004/KalmanApogeeII.pdf He has a bunch of info on his website too

Sounds good. The article you linked is probably one of the best I've seen as an introduction to Kalman filtering. I know at my University the aerospace department has a course on linear systems. Now my background is primarily applied math and signal processing, so the course I took on linear systems may be slightly different. The books I used, Signals and Systems by Oppenheimer, is a great place to start. Its dense, but I don't think you'd have an issue getting through it. The reason I mention it is that it gives you a solid basis to branch off into control systems and filtering.

I'll also try to recall the name of one of the  controls books I have. In regards to filtering, I'd start with the book I mentioned. The complexity and the amount of math required for signal processing can grow fairly quickly. A solid understanding of linear algebra and probability is extremely helpful. Sheldon Ross has a good book on probability theory, and Applied Linear Algebra by Oliver and Shakiban is a nice, self-contained reference. I'll also try to post some PDFs later.

Thanks! Do these cover the Extended Kalman Filter? That is definitely what I need to implement.

I don't believe they cover the EKF. I don't really know of any textbooks that cover it. Typically, if I need to implement one of these filters or read up on them, I'll pull up a research paper or lecture such as this: http://www.cs.cmu.edu/~motionplanning/papers/sbp_papers/kalman/ekf_lecture_notes.pdf They tend to be pretty thorough.

Hey thanks! I will see what kind of progress I can make

You can use Excel to smooth out data and do graphs if you need to. That's what I use myself. Easiest way is to create a table and type formula to make average from range of numbers, smoother data needs a bigger range of numbers.


text:
Can I write to Flash Memory using PROGMEM?
On the documentation of Arduino, I quote:

http://playground.arduino.cc/Learning/Memory
  Note: Flash (PROGMEM) memory can only be populated at program burn time. You can’t change > the values in the flash after the program has started running.

And on the PROGMEM description:

http://arduino.cc/en/Reference/PROGMEM
  Store data in flash (program) memory instead of SRAM. There's a description of the various types of memory available on an Arduino board.
The PROGMEM keyword is a variable modifier, it should be used only with the datatypes defined in pgmspace.h. It tells the compiler "put this information into flash memory", instead of into SRAM, where it would normally go.

So can we or can't we? Or it's not the same thing?

While you can write to (flash) program memory at run time (unless it is locked), the process is a bit more involved, and cannot be accomplished with the PROGMEM directive, which basically just control the allocation process.  If you want to see how it can be done, look at the bootloader source.

Page write blocks does not make writing to flash impractical. In fact its something looked forward to.

The short answer is no: PROGMEM data is read-only.
Flash memory limitations
The first thing to understand is that Flash memory (where program space lives) is designed for long-term fixed storage. Reading from it is very fast and precise. However, generally speaking, you can't modify it on a byte-by-byte basis (e.g. changing a specific variable). You usually have to erase and re-write it in large blocks. That makes it completely impractical for run-time manipulation, because you'd have to store a lot of redundant information somewhere else while you do the erase and write cycle.
What PROGMEM actually does
Any literal data specified in your code (such as strings and numbers) always reside in program space at first (i.e. in Flash). However, when your sketch actually wants to use that data at runtime, it normally has to allocate some space for it in SRAM and copy it over. That means you end up with two copies: the fixed original in Flash, and the temporary copy in SRAM.
When you use the PROGMEM modifier, you're telling it not to make that second copy in SRAM. Instead, your sketch will simply access the original in Flash. That's very useful if you only ever have to read the data, as it avoids the allocation and copy operations.
However, copying it to SRAM is essential if you want to modify the data. Aside from the Flash limitations I mentioned above, it's also a question of code safety.
If you're able to modify the data stored in program space, then it follows logically that you could also modify the code stored in program space. That would mean that a simple mistake (or in theory a malicious attack) could result in your sketch being partially or fully rewritten at run-time. This could have very unpredictable results, ranging from simply ceasing to work, through to damaging/destroying any connected equipment.
More information
You can learn more about the low-level PROGMEM stuff from here:

http://www.fourwalledcubicle.com/AVRArticles.php

An older version of the same PROGMEM tutorial is available here:

http://www.avrfreaks.net/index.php?name=PNphpBB2&file=viewtopic&p=243018

https://mon.im/2014/11/modifying-avr-progmem-at-runtime.html


text:
Is it possible to transmit Longitude and Latitude via RF433MHz?
I want to make a drone project, and to that I will use arduino as the platform. My plane is to use a Play Station controller to control the Drone in the air. In addition to that I want to connect a GPS-module. My question goes, is it possible to transmit the longitude and latitude from the GPS via the RF 433MHz to the receiver? When received the longitude and latitude how can I transmit them further to the Smartphone and display the data on google maps? I suggest it could be possible through the Xbee, but I am not sure.
I would like if someone can confirm my idea, if not bring me a better way to do that.
In the image below, you can see the diagram of my design.

Welcome AdiT! I've seen you posted the same question at EE.SE. I would like to let you know that cross-posting across SE sites is not generally a good idea. See this post for more details.

@Ricardo Okay I'm sorry, I didn't know it :)

That's ok. It's just a minor sin :D I just really wanted to let you know. Let's just wait for some answers.

Your design suffers several redundancies that should be fixed. First of all, you have an Xbee (only one, not a pair) and a a 433 MHz transmitter/receiver combo. Why not just add another Xbee to the drone and remove the RF combo? That would save a little battery life for the receiver end, and a lot of your time. You'll also get two way communication with error checking. Although an Xbee would increase your project size a little, if you manually wired the Xbee instead of a shield (3.3V), it would save a lot of space.
As some people point out, Bluetooth is a viable option that's fairly small and low cost. However, it would suffer shorter ranges and it would need a special configuration on the host side for a BT stack.

I want to use RF because of I want a longer range. Therefore I'm not using WiFi. I don't understand what do you mean with this "if you manually wired it (3.3V)"? What should I manually wired?

@AdiT Edited post a bit. I meant manually wiring the Xbee module as opposed to a shield to save space/reduce weight. By the way, Xbee is RF. You can get several different distance ranges of Xbee to suit your needs.

If you are using Xbee modules in your project, why add 433MHz RF, just for the sole purpose of transmitting the location?  With the 433Mhz, you will have to implement error-correction yourself.

You have a point. How else is it possible to transmit the data to smartphone?

@AdiT bluetooth for one


text:
how can I change the setting for number of upload retries in the IDE?
I run into this problem when I mess something up, and it's pretty annoying to wait for 10 not in sync timeouts before I can try some different method.
...
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x85

How can I set the number of "attempts" to say 2 instead of 10? Or how can I safely interrupt the upload process in the IDE?

The code is not in the arduino ide but in the tool chain (.exe) that it runs.
Normally it is a program called avrdude.exe that is running so you would need to rebuild the avrdude.exe tool which is not practical.
The easiest way, but rather crude, is to pull the usb cable. If the port disappears avrdude should stop immediately.


text:
Powering Arduino from 7805 voltage regulator
I am trying to build an Arduino Uno based robot. My questions are the following:
1) The motor driver also has an on-board 78M05 voltage regulator from ST electronics. I used a 9V battery to power the robot, and the 9V was connected to the input of the voltage regulator, and the +5V output I used to power the Arduino. I did so by connecting the 5V from the regulator to the 5V pin on the Arduino and the GND's together. I read that this is not advised, and solutions ranged from making sure the 5V is regulated, to connecting a diode between +5V and Vin to using one of the ICSP pins and so on. So which is actually a good way to do this?
2) I later realized that the DC motors are rated for max 6V dc, and so switched the 9V battery to 4x AA batteries giving a total voltage of 6V. When I connected this to the regulator, the regulator and the Arduino still turned on, even though the data sheet says the minimum input voltage is 7V. So what is going on here? Can anyone help me understand what is happening?

I read that this is not advised, and solutions ranged from making sure the 5V is regulated, to connecting a diode between +5V and Vin to using one of the ICSP pins and so on. So which is actually a good way to do this?

Nothing wrong with that as long as it is regulated 5V (which yours is). You can use either the 5V pin on the header, or the 5V pin on the ICSP connector. They are both the same.  It is good practice to connect a diode between 5V and VIN to prevent current flowing backwards through the onboard regulator should something connected to VIN want to draw current.

I later realized that the DC motors are rated for max 6V dc, and so switched the 9V battery to 4x AA batteries giving a total voltage of 6V. When I connected this to the regulator, the regulator and the Arduino still turned on, even though the data sheet says the minimum input voltage is 7V. So what is going on here? Can anyone help me understand what is happening?

A regulator has a "drop-out" voltage. That is often in the order of 1.2V for these kind of regulators (it's certainly right for the Arduino's on-board one.
You are providing less than the regulation voltage plus the drop-out voltage, so the output of the regulator will be the input voltage minus the drop-out voltage.
As long as that is above the lowest voltage the Arduino can run from at 16MHz then it will still work fine. You should be fine down to about 4V output from the regulator, and even lower if you're lucky (you may start getting stability problems though since the ATMega328P isn't rated to run at 16MHz at lower voltages).
It also means that the GPIOs on the Arduino will be running at a lower voltage as well.

Which way should the diode between +5V and Vin go? Also, does this mean that when I connect 6V the output is 4.8V and that is what the Arduino is running from?

Anode to +5V, cathode to Vin. Yes.

I actually did a measurement just now with a multimeter, and it confirmed what you said. The unregulated voltage from the AA batteries was 6.4 V and the output voltage was 4.8 V from the 7805. Now I don't know what do: if I go over this I can get 5V on the Arduino but I overpower the motors, if I leave it like this the Arduino will be under-voltage.

4.8V is perfectly fine for the Arduino. Even USB is allowed to be as low as 4.75V...