text:
Program hangs when correcting CO2
I am building a special chamber, where I'm dealing with humidity, temperature and co2 contamination, but I'm having difficulties with software. If I separate it by parts, everything works as it should, but when I combine everything together, the CO2 measuring stops and the CO2 is being added to the chamber continuosly.
Here are my requests:
-The temperature has to be between 36 and 37°C,
-It has to be known the exact humidity,
-The amount of CO2 (carbon dioxide) has to be around 5% (50.000 ppm), around +/- 0.2% is allowed,
-Everything should be shown on 1602 LCD display.
To measure temperature, I have a LM335, for measuring humidity a HIH-4004-001 humidity sensor and for measuring CO2 contamination I have a MH-Z16 sensor. If there is lack of CO2 in the chamber, I'm adding it with a electromagnetic gas valve, which is driven by a relay. To heat up the chamber, I'm also using a relay, to turn on the heater.
Here's the code.
Does anyone has any kind of clue, what could possibly go wrong here?
#include <SoftwareSerial.h>           //lib for serial communication for co2
#include <NDIR_SoftwareSerial.h>      //lib for co2

#include <LiquidCrystal.h>
LiquidCrystal lcd(8, 9, 4, 5, 6, 7);  //(RS, EN, D4, D5, D6, D7)

//LM335 sensor TEMP
int outputPin = 3;

//heater
const int rele = 2;  //relay output for HEATER
int flag = 0;       //flag for hysteresis at 37°C

//humidity
int HIH4000_Pin = A2; //analog pin 2, humidity sensor

//co2
NDIR_SoftwareSerial mySensor(11, 12); //green= 11; yellow= 12.
float percentage = 0.00; //co2 in percentage

//co2 gas valve
const int ventil = 3;  //relay output for CO2 GAS VALVE

void setup() {
  lcd.begin(16, 2);
  pinMode(rele, OUTPUT);      //relay for HEATER
  pinMode(ventil, OUTPUT);    //relay for CO2 GAS VALVE
  Serial.begin(9600);

  digitalWrite(rele, HIGH);   //heater off
  digitalWrite(ventil, HIGH);   //co2 gas valve off

  if (mySensor.begin()) {
    Serial.println("Wait 10 seconds for sensor initialization...");

    lcd.setCursor(0, 0);
    lcd.print("Wait_10_seconds");
    lcd.setCursor(2, 1);
    lcd.print("CALIBRATION");
    delay(1000);
    lcd.clear();
    lcd.print("Wait_9_seconds");
    lcd.setCursor(2, 1);
    lcd.print("CALIBRATION");
    delay(1000);
    lcd.clear();
    lcd.print("Wait_8_seconds");
    lcd.setCursor(2, 1);
    lcd.print("CALIBRATION");
    delay(1000);
    lcd.clear();
    lcd.print("Wait_7_seconds");
    lcd.setCursor(2, 1);
    lcd.print("CALIBRATION");
    delay(1000);
    lcd.clear();
    lcd.print("Wait_6_seconds");
    lcd.setCursor(2, 1);
    lcd.print("CALIBRATION");
    delay(1000);
    lcd.clear();
    lcd.print("Wait_5_seconds");
    lcd.setCursor(2, 1);
    lcd.print("CALIBRATION");
    delay(1000);
    lcd.clear();
    lcd.print("Wait_4_seconds");
    lcd.setCursor(2, 1);
    lcd.print("CALIBRATION");
    delay(1000);
    lcd.clear();
    lcd.print("Wait_3_seconds");
    lcd.setCursor(2, 1);
    lcd.print("CALIBRATION");
    delay(1000);
    lcd.clear();
    lcd.print("Wait_2_seconds");
    lcd.setCursor(2, 1);
    lcd.print("CALIBRATION");
    delay(1000);
    lcd.clear();
    lcd.print("Wait_1_second");
    lcd.setCursor(2, 1);
    lcd.print("CALIBRATION");
    delay(1000);
    lcd.clear();
  }
  else {
    Serial.println("ERROR: Failed to connect to the sensor.");
    lcd.setCursor(0, 0);
    lcd.print("Press RST button");
    while (1);
  }

  lcd.setCursor(0, 0);
  lcd.print("T= ");
  lcd.setCursor(7, 0);
  lcd.print((char)223);
  lcd.setCursor(8, 0);
  lcd.print("C");

  lcd.setCursor(10, 0);
  lcd.print("H=");
  lcd.setCursor(15, 0);
  lcd.print("%");

  lcd.setCursor(0, 1);
  lcd.print("CO2=");
  //lcd.setCursor(8,1);
  //lcd.print("%");
}

void loop() {
  delay(100);

  //beggining of measuring and displaying CO2
  if (mySensor.measure()) {
    Serial.print("CO2 Concentration is ");
    Serial.print(mySensor.ppm);
    Serial.println("ppm");
    lcd.setCursor(4, 1);
    lcd.print("        ");
    lcd.setCursor(4, 1);
    lcd.print(mySensor.ppm);
    percentage = mySensor.ppm;
  } else {
    Serial.println("Sensor communication error.");
  }
  //end of measuring and displaying CO2

  //beggining of CO2 gas valve
  if (percentage < 1000) {
    digitalWrite(ventil, LOW);
    delay(1000);
    digitalWrite(ventil, HIGH);
    /*lcd.setCursor(2,0);
      lcd.print(celsius);  */
  }
  else {
    digitalWrite(ventil, HIGH);
  }
  //end of CO2 gas valve

  //start measuring temperature
  int rawvoltage = analogRead(outputPin);
  float millivolts = (rawvoltage / 1024.0) * 5000;
  float celsius = (millivolts / 10) - 276.20;
  lcd.setCursor(2, 0);
  lcd.print(celsius);
  //stop measuring temperature

  //start humidity sensor
  float relativeHumidity  = analogRead(HIH4000_Pin);
  float av = 0.0048875 * relativeHumidity;
  float vlaga = (av - 0.86) / 0.03;
  int humi = vlaga;
  if (humi < 100) {
    lcd.setCursor(12, 0);
    lcd.print(" ");
    lcd.setCursor(13, 0);
    lcd.print(humi);
  }
  else {
    lcd.setCursor(12, 0);
    lcd.print(humi);
  }
  //end humidity sensor

  //start of relay for heater
  lcd.setCursor(12, 1);
  if (celsius < 37 && flag == 0) {    //upper treshold of hysteresis 37
    digitalWrite(rele, LOW);
    //lcd.print("WARM");
  }

  if (celsius < 36 && flag == 1) {    //lower treshold of hysteresis 36
    digitalWrite(rele, LOW);
    //lcd.print("WARM");
  }

  if (celsius > 37) {               // treshold of first heating up
    digitalWrite(rele, HIGH);
    //lcd.print("COOL");
    flag = 1;
  }
  //end of relay for heater

  delay(650);
}

Remember to cross the wires for the serial, so RX goes to TX and TX goes to RX.

That's already okay.

I noticed, that the valve will correct the value of the co2, but only 1 or 2 times, then it will crash; But if I look through serial, I can see, that I loose connection between sensor and Arduino: I start getting this message "Sensor communication error."

Okay, I figured it out, what was wrong. It's completely unlogical and strange, but it solved me a problem.
First off, I tried to disconnect the valve relay from arduino, while arduino was still giving logical 0 and 1 on the output. And the strange thing was, it worked.
So I took a step further and back connected the relay, but disconnected the burden (valve). It worked fine aswell. So I figured it out, that here's some sort of a problem, that the valve SHOULDN'T be opened with relay, so I just added a 2N2222 transistor and a 12k resistor to the base, and the whole thing is working now perfectly. I just connected the output of the arduino (which was on relay for valve before) and put it on base resistor of 2N2222.
But thanks everyone for help!

If the CO2 sensor stops working that means you should be getting a message out of the Serial console, you didn't mention it so I presume you aren't which means it is still reading a value.
If you are still reading a value and the CO2 is still being added this means the 'percentage' CO2 has to be less than 1000.
So, either the CO2 sensor is faulty (which because it works on its own it looks like it isn't) or there is a "wiring fault" and you aren't actually reading the CO2 sensor when you think you are.
Is it possible that you are misreading the result from the serial connection?  Is it possible that the library is misreading the data?
Try a simple program that reads the value from the CO2 sensor, prints it to the serial console and then opens the value for a second.
(Oh and in the setup function have a look at using a loop :) )

Thank You, it helped a bit and I came to a new conclusion:
As long as I have my arduino connected to my PC with a cable, it works perfectly. When I unplug the USB cable, it starts to mess around by not measuring anymore.
Is there any way for me to totally remove serial communication and work totally independent without the PC?

That behaviour sounds like a bad earth connection.  But to answer your question a phone charger will normally do the job, just chop the USB connector off and plug the wires into the Arduino's GND and VIN pins.  Make sure you get the wires the right way round though with a multi metre or an LED

I'm using a 230V -> 5VDC ac-dc converter, which is grounded. Everything is inside a plastic case.


text:
Cannot get any readings from DHT22 Sensor connected to Arduino M0 Pro
I have directly connected a DHT22 to my Arduino M0 Pro. I have put a 10k Resistor across the Data & V+ of the sensor pinout. The data is connected to pin 5 and I have it connected to 3.3V output of Arduino.
I am just trying to see some readings from the sensor via the SerialUSB console. I have downloaded and unpacked the DHT libraries that I got on the Adafruit website/GitHub. As far as I know I have these libraries in the right directory - C:\Program Files (x86)\Arduino\libraries\DHT...
I also have installed the Adafruit Unified Sensor library on the IDE.
I am trying to use the Tester program that is provided, this compiles ok but the SerialUSB printout prints:
Failed to read from DHT sensor!
Failed to read from DHT sensor!
Failed to read from DHT sensor!

And so on...
I have tried another DHT22 sensor to no avail.
The only part of the code I have changed is the pin number and changed from Serial to SerialUSB.
Not sure if I have to change anything else? Or am I doing something really silly!

Here is the code:
// Example testing sketch for various DHT humidity/temperature sensors
// Written by ladyada, public domain

#include "DHT.h"

#define DHTPIN 5     // what digital pin we're connected to

// Uncomment whatever type you're using!
//#define DHTTYPE DHT11   // DHT 11
#define DHTTYPE DHT22   // DHT 22  (AM2302), AM2321
//#define DHTTYPE DHT21   // DHT 21 (AM2301)

// Connect pin 1 (on the left) of the sensor to +5V
// NOTE: If using a board with 3.3V logic like an Arduino Due connect pin 1
// to 3.3V instead of 5V!
// Connect pin 2 of the sensor to whatever your DHTPIN is
// Connect pin 4 (on the right) of the sensor to GROUND
// Connect a 10K resistor from pin 2 (data) to pin 1 (power) of the sensor

// Initialize DHT sensor.
// Note that older versions of this library took an optional third parameter to
// tweak the timings for faster processors.  This parameter is no longer needed
// as the current DHT reading algorithm adjusts itself to work on faster procs.
DHT dht(DHTPIN, DHTTYPE);

void setup() {
  SerialUSB.begin(9600);
  SerialUSB.println("DHTxx test!");

  dht.begin();
}

void loop() {
  // Wait a few seconds between measurements.
  delay(2000);

  // Reading temperature or humidity takes about 250 milliseconds!
  // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
  float h = dht.readHumidity();
  // Read temperature as Celsius (the default)
  float t = dht.readTemperature();
  // Read temperature as Fahrenheit (isFahrenheit = true)
  float f = dht.readTemperature(true);

  // Check if any reads failed and exit early (to try again).
  if (isnan(h) || isnan(t) || isnan(f)) {
    SerialUSB.println("Failed to read from DHT sensor!");
    return;
  }

  // Compute heat index in Fahrenheit (the default)
  float hif = dht.computeHeatIndex(f, h);
  // Compute heat index in Celsius (isFahreheit = false)
  float hic = dht.computeHeatIndex(t, h, false);

  SerialUSB.print("Humidity: ");
  SerialUSB.print(h);
  SerialUSB.print(" %\t");
  SerialUSB.print("Temperature: ");
  SerialUSB.print(t);
  SerialUSB.print(" *C ");
  SerialUSB.print(f);
  SerialUSB.print(" *F\t");
  SerialUSB.print("Heat index: ");
  SerialUSB.print(hic);
  SerialUSB.print(" *C ");
  SerialUSB.print(hif);
  SerialUSB.println(" *F");
}

Unrelated to your problem, but FYI C:\Program Files (x86)\Arduino\libraries\DHT is not the correct place to install libraries. It does work but the problem is any time you update to a new version of the Arduino IDE everything you install to C:\Program Files (x86)\Arduino will be lost. This is why you should always install libraries to the libraries subfolder of your sketchbook folder. See https://www.arduino.cc/en/Guide/Libraries.

Thanks, yeah I had to figure that one out the hard way, thanks again though.

Found what the fault was, it was a solder short between pins on a custom PCB that was sitting on top of the Arduino board. My bad! At least I have it working now!

source: Stack Exchange

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

sort: votes


text:
Potentiometer on motor for position control
I am using a wiper motor as a rotor. I am trying to get it to at least point in different azimuths (compass azimuths eg. 180 degrees) In order to do this, I am thinking about attaching a potentiometer on the axle inside the motor housing to see where the motor is pointing.
So lets say the pot gives me a range of 0-1023. If I divide 1023 by 360 i get 2.84. So lets say the pot gives the Arduino a 1, I can relate that to 2.84 degrees?
Also, what if the motor is pointing at 350 degrees, and I want it to point at 2 degrees. Instead of it turning around 348 degrees, it just cross pass 360 and go to 2 degrees.  How would a pot handle going over a single step? If the motor passed a single step would it consistently give me a 1023 reading?
I am trying to get a wiper motor to have a known position 360 degrees around.

Most pots have a interrupted circle, made of something like carbon, with a wiper moving along it. Moving from one side of the circle to the other side of the interrupted circle, means the wiper will be disconnected for a few degrees, giving you some random analog value (unless you have a pull-down). You won't be able to measure the angle around this point. You could use two pots with there "0-point" opposite of each other. Or go with a rotary encoder, combined with a home-position sensor.

I am trying to get a wiper motor to have a known position 360 degrees around.

There might be a few possibilities.
First there are continuous rotation potentiometers on the market. They seem expensive though and I can't comment on how accurate they are.
Second, if your device is only ever going to turn through say ten revolutions then go back, you could just get a multiturn pot that will handle that range of turns. (Depends what you're building of course - for example I've heard of servo winches for model sailboats that use this method.)
Thirdly, and I accept this may not be a good answer to your question, but have you thought about using incremental encoders instead? In theory they could be more accurate too. The hardware is quite easy but a bit more programming is required to make these work...

The device in theory should only rotate once. No more than 5 times if need be. So I guess a mulit turn pot would be in order!

So lets say the pot gives the Ardunio a 1, I can relate that to 2.84
  degrees?

Yes, if the pot goes from 0 to 1023 in 360 degrees of rotation, and it can rotate continuously. That sounds unlikely - f/ex, thinking about how a pot is made, how will it get from its maximum resistance to its minimum resistance in 2.8 degrees?

Instead of it turning around 348 degrees, it just cross pass 360

Smart software. :) You would need to read the pot, decide which direction of rotation will get from the current position to the new position, and select that direction in the motor drive circuit.
Update:
A pot doesn't really "output" anything; it is a variable-resistor, whose resistance can be measured by placing it in a known electric circuit and using an Arduino A2D input to measure a voltage in that circuit which depends on the resistance of the pot. The reading you get is a 10-bit integer. If you divided that by 1024, you'd have a pure fraction representing the measured voltage as a fraction of the A2D's full-scale voltage, which you select as INTERNAL (1.1v internal reference voltage), or EXTERNAL and apply a reference voltage to the chip's Aref pin. Usually that is the power-supply voltage, and in any case must not exceed the power-supply voltage.
So, back to reality, if you use the EXTERNAL reference with Aref connected to +5v, then the A2D readings would mean:

 A2D  Volts  Mag.Azimuth
   0   0       0
 256   1.25   90
 512   2.5   180
 768   3.57  270
1023   4.99+ 359.6

In this case you probably don't care about the measured voltage, only it's relationship to 5v, which the A2D already gives you. That relationship equals the pot's relationship to 1 full rotation. So the azimuth, Az, you're seeking:
Az/360 = A2D / 1024, and
Az = (A2D * 360)/1024

I am thinking more along the lines of, if the pots reading at 511.5, then the motor is facing 180 degrees (half of the 360 magnetic degrees) I am referencing the position of the pot, to magnetic azimuth.also, how would i say the pot is reading at 511.5. What unit does the pot output? Ohms?

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


text:
Reading values from Wiznet w5500 chip over SPI
I am trying to get the MAC address that is stored on the Wiznet w5500 chip.
On page 29 - click here, it has the address of the values. It state that "This block can be selected by the BSB[4:0] value of SPI Frame". Then it lists the addresses of the MAC block from 0x001E to 0x0023.
How do I read these blocks using the SPI library? What does the BSB[4:0] mean?
EDIT 1: I am looking through the Wiznet Arduino library and it looks like there is a way to access the mac address through

Page 29 of what? Could you share this document with us please?

@MarkSmith thanks for pointing that out. I added the link.

The initial value is 00.00.00.00. The library/sketch sets the MAC address.

@MikaelPatel so there is no way to read the MAC into the software? I would have to use a separate MAC as a unique identifier?

You can read the SHAR register into the software but the initial value is not unique. Some Ethernet Shields have a sticker with an allocated MAC address to use. See http://wizwiki.net/forum/viewtopic.php?t=501 and http://arduino.stackexchange.com/questions/8719/didnt-have-mac-address-on-wiznet-based-ethernet-shield-cloned

@MikaelPatel ok. I thought the chip had a dedicated MAC burned into it. I guess I will just use an extra component with a MAC burned in the EEPROM.


text:
Forward kinematics of a differential drive robot
I've been braking my head over this for the past few days and can't make it work.. So, I have a small robot with a rotary encoder on each wheel and i want to track its position (in x and y) on a flat plane. I know it's called forward kinematics, but i can't seem to get it working. I found a lot of great public sheets, but i think, out of all of them, this is the best one It had the equations of how to calculate the X and Y on page 74:

Vicc=L * (Din / (Dout–Din) + ½) (page 73) //Din is the inner wheel of the turn traveled distance, Dout is the outer wheel
Xtδ=Xt+Vicc*(sin(θt+θΔ) – sinθt)
Ytδ=Yt+Vicc*(cosθt - cos(θt+θΔ))
θtδ=θt+θΔ //angle measurement

Where Xtδ and Ytδ are the position of the robot (x, y); Xt/Yt/θt is the position of the robot when the counting of the position has been started; θΔ is the angle of the robot now;
. Here's The code that I tried to write using the equations. I expected it to write my coordinates in x and y, but when i moved the wheels, it sent me big, random numbers, which are fluctuating up and down, which looks like a sine wave. What am I doing wrong? Could you guide me to the right path? My end result, that I want to reach is controlling 2 both motor speeds and knowing the robots position (doesn't need to be very precise though).
Thanks in advance!
EDIT: Added code from PasteBin
#include <Encoder.h>

Encoder Left(3, 2);
Encoder Right(0, 1);

float R = 385; //mm
float r = 12.5; //Wheel diameter in mm
float L = 8; //Distance between the wheels in cm

double LeftDist = 0;
long LOldPos  = -999;
float LNewPos;
int Correction;

double RightDist = 0;
long ROldPos  = -999;
float RNewPos;

int angle= 0; // Robots current angle
unsigned long t;

int Xold= 0; //position at the start of the calculation
int Xnew= 0; //new, calculated position
int Ystart= 0; //position at the start of the calculation
int Ynew= 0;//new, calculated position
int OldAngle= 0; //angle at the start of the calculation
int NewAngle= 0;// new angle at the end of the calculation
int Vicc;

void setup() {
  Serial.begin(9600);
  t = millis();
}

void loop() {
  Encoders();
  if ((millis() - t) >= 100) {
    Xold= Ynew; //setting the new position to old
    Yold= Ynew; // setting the new position to old
    OldAngle= NewAngle; //Setting the new angle to old

    Vicc = (L * (LeftDist / (RightDist / LeftDist))) + 0.5;
    Xnew= Xold + (Vicc * (sin(OldAngle + Angle) - sin (OldAngle))); //Calculation of X
    Ynew= Yold+ (Vicc * (cos(OldAngle) - cos(OldAngle+ Angle))); //Calculation of Y
    NewAngle = OldAngle+ Angle;

    t = millis();
  }

  Serial.print(angle);
  Serial.print("        ");
  Serial.print(Xnew);
  Serial.print("        ");
  Serial.println(Ynew);
}

//0.9mm/1 deg
void Encoders() {
  LNewPos = Left.read();
  if (LNewPos != LOldPos) {
    LOldPos = LNewPos;
    LeftDist = ((LNewPos / 840) * (2 * r * 3.14)) / 10; //cm/ Rev
  }
  //-----------------------------------------------------
  RNewPos = Right.read();
  if (RNewPos != ROldPos) {
    ROldPos = RNewPos;
    RightDist = ((RNewPos / 840) * (2 * r * 3.14)) / 10; //cm/ Rev
  }
  angle= (abs(RightDist - LeftDist) * 0.9) - Correction; //calculate the angle the robot has turned
  if (fi >= 360) Correction += 360;
  else if (fi <= -360) Correction -= 360;
}

Please, instead of " I thought will work, but it didn't" state exactly what you expected it to output / do and what you observed. Do you have intermediate values you can check? Isolated test cases? We don't have your hardware here and the code is practically uncommented

@MaximilianGerhardt, okay, sorry, i'll edit it in just a sec

While you’re at it, it might help to change the variable names from things that are easy to type to things that are easy to read and follow.

@Delta_G, okay, I'll do that

What units do you have the angles in?  Degrees or radians?

From your use of the number 360 at the end of the Encoders() function, I am thinking that you are using degrees for the angles.  That won't work with sin and cos.  The trig functions all expect angles in radians.  To convert degrees to radians, multiply by PI/180.

I have just changed it to calculate it in radians, but it does the same thing, the x and y values go up, reaches an integer overflow and goes back down,

Is angle still an int?  I would think radians would probably need to be in floating point.

No, i converted it to a float and I'm trying to take a little different approach and calculating velocities of each wheel/angular velocities and will try out a different equational you are not

OK.  You'll have to update the code here then to get further help.

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


text:
How to decrease adc accuracy?
I read in this atmega328p datasheet the following on page 308:
From sect. 28.4:

By default, the successive approximation circuitry requires an input
clock frequency between 50kHz and 200kHz to get maximum resolution. If
a lower resolution than 10 bits is needed, the input clock frequency
to the ADC can be higher than 200kHz to get a higher sample rate.
The
ADC module contains a prescaler, which generates an acceptable ADC
clock frequency from any CPU frequency above 100kHz. The prescaling is
selected by the ADC Prescaler Select bits in the ADC Control and
Status Register A (ADCSRA.ADPS). The prescaler starts counting from
the moment the ADC is switched on by writing the ADC Enable bit
ADCSRA.ADEN to '1'. The prescaler keeps running for as long as ADEN=1,
and is continuously reset when ADEN=0.
When initiating a single ended
conversion by writing a '1' to the ADC Start Conversion bit
(ADCSRA.ADSC), the conversion starts at the following rising edge of
the ADC clock cycle.
A normal conversion takes 13 ADC clock cycles.
The first conversion after the ADC is switched on (i.e., ADCSRA.ADEN
is written to '1') takes 25 ADC clock cycles in order to initialize
the analog circuitry.

By required bandwidth is 120 kHz, and 5 bit accuracy will suffice for my purpose. So, I understand that I can achieve this by changing the prescaler to a lower division number, thus increasing the clock frequency fed into the ADC (as per the diagram in the aforementioned document).
However, the document only specifies the min and max times required for ADC conversion for 50 kHz (12 to 280 microseconds at 50kHz bandwidth).
My question: Given my requirement of 120kHz bandwidth, what is the lowest prescaler division value I should use to guarantee ADC completion time to within 1/120kHz seconds (8.3us)?
EDIT: This is another question I have: Why does the accuracy change when using a lower divider value? Surely we are simply changing the clock frequency fed into the ADC converter, not the ADC algorithm itself; so why should the bit accuracy change?

From: http://forum.arduino.cc/index.php?topic=6549.0
The documentation states that 13 cycles are neccesary for ADC conversion. Thus, using the clk/13*8 divisor configuration, and 16 MHz system clock, the upper bound becomes 154KHz
The forum post in the above link continues to say that "ADC clock frequencies above 1MHz are uncharacterised", however this was quoting another document for which the link is dead. I could not find this statement in the most recent documentation.
Edit: Another forum post where a user successfully used an atmega328p to achieve 360000 samples/sec, so it is technically possible:
http://forum.arduino.cc/index.php?topic=8795.0

Nick Gammon did some tests with various prescaler values, and the data at prescaler = 8 shows errors as large as 17% of the full scale.


text:
What is LCD bias voltage and where do I have to connect it?
I noticed that I have VB0+, VB0-, VB1+ and VB1- pins on my LCD. In the datasheet it says they are for the "LCD Bias Voltage". I have never heard about that. So what is it? Where do I have to connect it?
Here is the datasheet of the LCD: http://www.buydisplay.com/download/manual/ERC12864-655_Series_Datasheet.pdf

You need to look at the interfacing document kindly provided on the same page as that datasheet:

http://www.buydisplay.com/download/interfacing/ERC12864-655_Interfacing.pdf

It shows plainly that you need to connect 2.2µF capacitors between the + and - of each pair of pins.


text:
i have problem in generating pwm in steps
Given below is my loop and it counts 1 to 250 using the push button i just added this part as this one is the main part. I want to make it in steps like one press (push button) SETS IT TO 10 OR 20 ETC. Many thanks in advance for your kindness.
if ((digitalRead(2)==HIGH) && (digitalRead(7)==LOW))
 {
   if (j<255)
   {j++;
   lcd.setCursor(5,1);
   lcd.print("                ");
   lcd.setCursor(5,1);
   lcd.print(j);
   while((digitalRead(2)==HIGH) && (digitalRead(7)==LOW));}
 }
else if ((digitalRead(2)==LOW) && (digitalRead(7)==HIGH))
 {
   if (j>0)
   {j--;
   lcd.setCursor(5,1);
   lcd.print("                ");
   lcd.setCursor(5,1);
   lcd.print(j);
   while((digitalRead(2)==LOW) && (digitalRead(7)==HIGH));}
}

analogWrite(9,j);
//lcd.noDisplay();
lcd.display();
delay(100);

}

the title says i have a problem ... there is nothing said about a problem in your post ... what happens when you run the program?

Where is j defined? What do you see on the LCD?

If you want to change j in bigger steps, just replace j++ and j-- by for example j+=10 and j-=10. Though I suspect that thats not all of the problem

I actually added the part in which i was having trouble so the j was defined at the start of the code while i have posted the main part of the code (not the full code). I think comment from Chrisl has solved the problem i was facing, i'll try it later and update it here if its solved. Thanks a lot for your precious time.

Finally thanks Chrisl to understand my question and helping me out. It worked.

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


text:
Using Arduino RS232 to a modem (only RS232)
I am a newbie to the arduino world. And am trying to work out a configuration that does not involve USB.
I wonder if this configuration will work.
Are there any 3g modems that work on Rs232 interface. That should get rid of the USB compatibility that costs 3 times a arduino.

I'd suggest buying a 3g/gprs shield, or the adafruit fona. That way you already have some sample code, and don't have to figure out everything yourself.

I am ruling out usb completely since a usb compliant host device increases the cost of the solution 3 fold. I need a rs232 interface, speed is not my requirement. I need to send 150 bytes every 60 seconds. Cost is the only factor for me at this time.

Just corrected the subject line.

There are more TTL/UART 3G modems than RS-232 3G modems.

In Aus: http://www.maxon.com.au   Arduino doesn't have RS232 however, so like for a TTL/UART interface as Ignacio suggests.

You might want to consider something with native USB support like a raspberry pi instead of the Arduino.


text:
setup() resets from loop, when I add parameters to http get `?identity=%2B0123456789&identityType=1`
I am trying to call a HTTP GET using my Arduino via SIM900A.
When I run the commands manually via the USB port, I am able to get the commands to run. Now, when I put the same sequence on arduino, the setup() is called repeatedly after the sendATcommand(httpAuthCommand, "OK", 2000);. Looks like a reset issue.
I read, this link to put all my code into loop to avoid the setup() reset issue. But seems like this is did not fix the issue.
I have debugged it to this one change.
This Works
char httpAuthCommand[] = "AT+HTTPPARA=\"URL\",\"http://www.m2msupport.net/m2msupport/http_get_test.php\"" ;

This Does Not work
char httpAuthCommand[] = "AT+HTTPPARA=\"URL\",\"http://1.1.1.1:8080/mytomcatservice/mypath/mycommand/Request?identity=%2B1234567890&identityType=1\"" ;

I debugged this a bit more, it does not work when I add ?identity=%2B0123456789&identityType=1 to the httpAuthCommand. Something crazy while sending parameters ??
In loop()
sendATcommand(httpAuthCommand, "OK", 2000);

sendATcommand method
int8_t sendATcommand(char* ATcommand, char* expected_answer, unsigned int timeout){

    uint8_t x=0,  answer=0;
    char response[100];
    unsigned long previous;
    memset(response, '\0', 100);    // Initialice the string
    delay(100);
    while( Serial.available() > 0) Serial.read();    // Clean the input buffer
    Serial.println(ATcommand);    // Send the AT command
    x = 0;
    previous = millis();
    // this loop waits for the answer
    do{
        // if there are data in the UART input buffer, reads it and checks for the asnwer
        if(Serial.available() != 0){
            response[x] = Serial.read();
            x++;
            // check if the desired answer is in the response of the module
            if (strstr(response, expected_answer) != NULL)
            {
                answer = 1;
            }
        }
    // Waits for the asnwer with time out
    }while((answer == 0) && ((millis() - previous) < timeout));

    return answer;
}

Raw commands work on Chrome

http://www.m2msupport.net/m2msupport/http_get_test.php
http://1.1.1.1:8080/mytomcatservice/mypath/mycommand/Request?identity=%2B918177900460&identityType=1

My Guess
I am missing some escape sequence characters in the command (especially in the parameters section ?identity=%2B0123456789&identityType=1).

Could you have exceeded the rather limited RAM?
First experiment: Replace the added string with "xxx....x". If you have the same problem, then it's not the contents of the string but its length.
Second experiment (or jump straight to this one): Compile your strings in flash instead of in RAM. Note this will only help if you have a number of them, since your code will have to copy each one to RAM (at run-time) in order to use it, taking up some of the space you had saved. If there is only one string moved to flash, your code will need a temporary buffer of equal size (though only during the actual print call). A possible way around this is to break up the long string into a number of short ones, put all of them in flash, then print them sequentially at run time. That will need a buffer only as large as your largest substring. The cost will be increased use of flash, both for string storage and for the extra number of print calls; and slightly slower execution (probably not an issue).
This may be telling you that you need a more capable processor (one with more RAM space) or that you need to start getting creative about fitting your application into the one you've got.

Its a ATMEGA328, and code size is just 3kb. Total size of memory is 28kb.

It only has 2K of RAM, though, and that is usually its toughest limitation. We don't know for a fact that you're out of RAM but it's easy to use it up, and when you do, something gets over-written and the program crashes. Resetting is one possible effect of that.

Ok, Ill look into that and report back. My power supply just konked, power led is blinking like crazy. And my 9v power is dropping to 2v after I connect it to the SIM900A board. Regulator and SIM900A ic are heating up. I think there may be a short somewhere.

"Something crazy while sending parameters ??"
Possibly your power supply is to weak so 5V drops low and the processor resets when the transmitter sends a message.

I have multimeter, can you tell me how to check for this to be true ? I do have a 1A power supply, and that may be the reason. What pin should I be checking for the power ?

I checked voltage between the Power Gnd, and Pin 55,56,57 of the sim900A. It reports a constant 3.9V.

1Amp is probably enough. your problem is something else then.


text:
Code does not pass `gsmAccess.begin(PINNUMBER)==GSM_READY)`
I am not able to get my code to pass

if(gsmAccess.begin(PINNUMBER)==GSM_READY) {

I have modified the PIN number on my sim card to be 0000, and yet its stuck on begin.
How do I prepare the SIM CARD to pass the begin

This has been abandoned for months without information sufficient to make it answerable ever being provided.  Voting to close as unclear.

Closing needs a better reason, not a vendetta.

That your problem is insufficiently specified is a valid reason.  Otherwise, edit your question to make it answerable.  Post the code of the method where it gets stuck, and add logging to determine where exactly that happens.

This would be an acceptable question if it had a bare minimum sketch (enough code that we could run it on our own Arduinos and reproduce the issue). Feel free to edit. Thanks!

Try putting the SIM card into a mobile phone in case it hasn't been initialised by your provider. Set up the PIN for the card using the settings on the phone, see the manual for instructions on how to do this.
Now you can use the PIN you entered on the phone to unlock the SIM in your code.

Tried it, did not work.


text:
When it says the Uno has logic level at 5 V is that also true of a bareduino/breadboard Arduino?
I want to hook up ESP8266, which has a 3.3v logic level to my bare-bones Arduino (basically a minimal interface for the ATmega382P IC).
I can power my circuit at 3.3 V without a 5 V regulator so will the voltage of the logic level also be 3.3 V?
I don't think there is a tiny boost converter in the IC... but I'm uncertain.

The logic level is the same as the voltage you supply the chip.
You can think of the IO pins as tiny switches that either connect the output pin to the supply voltage or to ground (when in output mode) or compare the incoming voltage to an input pin to a percentage of the supply voltage (typically <0.3×Vcc for low and >0.6Vcc for high)
So yes, if you run the chip at 3.3V the logic level will be 3.3V logic (or more specifically < 1.1v for low and > 2.2v for high).


text:
SPI: problems communicating with sensor using Arduino
I have a sensor which I am trying to communicate with over SPI using an Arduino UNO. It is my first time using SPI and I'm experiencing some problems which I'm hoping are just due to some misunderstanding on my part. I have written a simple code to perform one basic operation: Turn on the sensor's fan. The Arduino is being powered through the 2.1 mm barrel jack by a 1.5 A DC adapter. The 5V, GND, MOSI, MISO, SS and SCK pins on the Arduino are connected to the corresponding pins on the sensor. The sensor receives power from the Arduino, drawing up to 250 mA (with the fan on).
The manufacturer provides a list of commands corresponding to each function of the sensor. To turn on the fan, the command list gives the following information:
Command_byte: 0x03
Bytes: 0x03, 0x00
Bytes_in: 0xF3, 0x03
Time_between_current_and_next_byte: 1.7ms, NA
Note: 1ms would be adequate delay between command byte and following byte

Based on my understanding of this, to turn on the fan, I need to send a command byte (0x03), then wait 1.7 ms and send another byte (0x00). My code for doing this is as follows:
#include <SPI.h>
const int chipSelectPin = 10;

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

  SPI.begin();
  pinMode(chipSelectPin, OUTPUT);
  SPI.setClockDivider(SPI_CLOCK_DIV32); //set clock to 500kHz
  SPI.setDataMode(SPI_MODE1);
  SPI.setBitOrder(MSBFIRST);
  delay(10000); // Let the sensor settle for 10 seconds

  digitalWrite(chipSelectPin, LOW);
  indata = SPI.transfer(0x03); //command byte for fan on
  Serial.println(indata);// value returned should be 0xF3
  delay(2);
  indata = SPI.transfer(0x00); //Turn on fan
  digitalWrite(chipSelectPin, HIGH);
  Serial.println(indata);// value returned should be 0x03
}

void loop() {}

When I send the command byte, the returned value (which gets printed to the terminal) is 243 which corresponds to the expected hex value of 0xF3. However, the second command does not turn on the fan and the second returned value is 231 which does not correspond to the expected hex value of 0x03.
I don't think it's a hardware issue because at least one of the returned values is correct and because the sensor does work when used with a different platform. I also experimented with different delays between bytes.

May or may not be related but the current draw is out of spec for the chip. From the Atmega 328p datasheet:  DC Current per I/O Pin...40.0 mA and  DC Current VCC and GND Pins...200.0mA

Thanks for the comments. After I swithched from UNO to Galileo (with the logic level set to 3.3V) it worked fine!

@JRobert - the current specification you site is for the ATmega I/O pins, but the device should be drawing power from the Arduino's regulator, not the ATmega.

Change your chipSelectPin. Pin 10 is exclusively used by SPI library. See Arduino Uno description.
Similar issue has been discussed here.

Thanks for the comment. After I swithched from UNO to Galileo (with the logic level set to 3.3V) it worked fine! I kept the chip select pin as 10 and it wasn't a problem.

Great, I am happy you have solved the issue.

You are substantially mis-stating the issue.  First, the posted code is already using pin 10 as the slave select, which is the "default" implied by the hardware.  The issues is rather than if pin 10 is being used for a different purpose and as a result is configured as an input then the ATmega SPI engine may operate in slave rather than master mode.  It is entirely appropriate to use pin 10 as the slave select.  It is also entirely possible to use a different pin, provided that pin 10 is still configured as an output.

authors: عمار علي احمد ثابت الجلال


text:
Which input pins can I use on the ESP8266 NodeMCU
On the ESP8266 NodeMCU I have GPIO2 , GPIO3 , GPIO1 , GPIO9 free but when I assign them to a button they do not work. I assume it is because those pins have other function behind them. When I look at the schematic I found that they are TXD1, RXD0, TXD0, and SSD2. Is there a way to still use these pins as inputs?
If not, can I use an Arduino Uno for my inputs and send signals from there to the analog pin to my ESP8266 NodeMCU for the connection to the MQTT server?
For the record all my other pins are used so I can't use any other input pin than these 4.

safest pins to use are 4, 5, 12, 13, 14 then 16. 0, 2 and 15 can be safe to use as long as you realise that normal boot should have 15 LOW, and 0 and 2 High - so, if you have a pullup resistor on 0 and 2, and the button shorts to ground when pressed, and a pulldown resistor on 15, and the button shorts to vcc when pressed, you shouldn't have any issues using these

forgot to mention, all boards I've used (ESP07/12E/12F) have a pulldown resistor on GPIO15 already - so, check before adding another one

@JaromandaX I used your method with the pullup resistors for pins 0 and 2 and that worked thanks a lot. I do have 1 more question about your answered in the other command about the GPIO9 and GPIO10 . The 10 works fine but the 9 doesn't, it doesn't work as an output or input. I don't need the 9 but my question is if pin GPIO10 is safe to use for a button because the 9 and 10 are both SSD pins.
*All the other pins you mentioned are used I should've thought about this in the beginning of my project :D

The table at https://randomnerdtutorials.com/esp8266-pinout-reference-gpios/ might help

GPIO2 is NodeMCU D4 which is U1TXD, transmit for the second UART, generally available. GPIO3 is NodeMCU U0RXD, receive for the first UART, generally available if you aren't using serial. GPIO1 is NodeMCU U0TXD, transmit for the first UART, generally available if you aren't using serial. GPIO9 is NodeMCU SPIHD and is NOT available, as it is required for the flash memory. All that is well documented in many places. You can easily use serial to move data between modules, or multiplex your input to the one module. Cannot provide much insight without more details.

Thank you for the clarfication of the pins and your answer.
The problem i'm having with these pins are that when my esp8266 is in flash mode (when booting up and when uploading) there can't be a button connecting to these pins , when it is finished uploading /booting. The input pins work perfectly. Is there something in my code that i can tell the esp8266 to not check these ports while booting up. or other solutions.

on a nodemcu, GPIO9(11) and GPIO10(12) seem to be available - (node mcu io index number in brackets) perhaps only SDD0 and SDD1 are connected to the flash ram.

@JaromandaX according to this pin diagram for the NodeMCU, GPIO10 is also identified as SDD3 and GPIO9 is identified as SDD2. I think those pins might be involved in commuincations with flash storage? I've seen suggestions that these can be used but nothing definitive. Would love to know myself.

@S.Imp - if you use DOUT or DIO flash mode then GPIO9/10 are "available" - this is (possibly) true for ANY esp8266 dev board (that breaks out those pins, i.e. NOT ESP01) - however, I have read that they can only "reliably" be used for either OUT or IN (sorry, can't remember which, and it's been YEARS since I've worried about such things). Of course, I've also read that certain GPIO's are "best" for IN and others "best" for OUT" and yet others that can go either way - though, to be fair, as far as my experience goes, there's really no limits with any GPIO as to its direction


text:
strcat parameters throwing pointer errors in my tcp server / parser application
I am attempting to use an Arduino Uno WiFi Rev2 board to integrate some lonely data. I will use the NINA WiFi chipset and associated libraries to start a server that will periodically request and receive client information hosted on multiple types of devices that will run concurrently; thus it's pretty much divided in 2 sections:
1.) Manage the client connections and their character arrays
2.) Parsing the information and responding accordingly from a control aspect
This is what I have so far, and what I was just compiling the other day:
#include <stdlib.h>
#include <SPI.h>
#include <WiFiNINA.h>

char ssid[] = "***";                // House -- Network SSID (name)
char pass[] = "***";              // House -- SSID password (WPA2-PSK)

#define MAX_CLIENTS 5
#define MAX_LINE_LEN 50
char inputs[MAX_CLIENTS][MAX_LINE_LEN] = {0}; // Instantiate 2D array of
client/received data
int msg_array[] = {0,0};
int net_status = WL_IDLE_STATUS;              // The Wifi radio's status
WiFiServer server(80);           // Create server object on port of WiFi
                                 // server, which will be used to
                                 // respond to commands

WiFiClient *clients[MAX_CLIENTS] = {NULL};    // Create client objects
                                              // limited to size of
                                              // MAX_CLIENTS

byte mac[] = {0xDE,0xAD,0xBE,0xEF,0xFE,0xED}; // Arduino's physical MAC
byte ip[] = {192,168,9,25};              // IP of this controller
byte gateway[] = {192,168,0,1};          // Router address (internet)
byte subnet[] = {255,255,0,0};           // Subnet mask

unsigned long wd_Dside, wd_Cside = millis();   // Gather current tstamp
unsigned long wd_Delap, wd_Celap = 0;          // Create an elapsed time
                                               //counter

void setup(){

   pinMode(4, OUTPUT);                 // pin selected to control D SIDE
   pinMode(5, OUTPUT);                 // pin selected to control C SIDE

   //enable serial data print
   Serial.begin(9600);
   while (!Serial){
       Serial.println("No serial.");
   }

      Serial.println("Serial.begin was initiated.");

   if (WiFi.status() == WL_NO_SHIELD) {  // check for the WiFi module:
      Serial.println("Wi-Fi: Communication with NINA has failed!");
      // do nothing here
      while (true);
   }

   String fv = WiFi.firmwareVersion();
   if (fv < WIFI_FIRMWARE_LATEST_VERSION) {
      Serial.println("Please upgrade the firmware");
   }

   while (net_status != WL_CONNECTED) {
      Serial.print("Attempting to connect to WPA SSID: ");
      Serial.println(ssid);

      // Connect to WPA/WPA2 network:
      net_status = WiFi.begin(ssid, pass); // Attempt to join this SSID

      // wait 5 seconds for connection:
      delay(5000);

      listNetworks();

      server.begin();                      // Start Wi-Fi server
      Serial.print("Server started on ");
      Serial.println(WiFi.localIP());
    }
}

void loop() {

    delay(5);

    WiFiClient newClient = server.available(); // Begin listening for
                                               // client messages
    if (newClient) {
        Serial.println("New client discovered."); // Could use this as
                                                  // an ACK/handshake on
                                                  // client-side host
        for (int i=0; i<MAX_CLIENTS; i++) {
          if (clients[i] == NULL) {
            clients[i] = new WiFiClient(newClient);
            break;
      }
   }
}

    for (int i=0; i<MAX_CLIENTS; i++){      // Check client for data
      if (clients[i] != NULL && clients[i]->available()){
         // If the data isn't garbage and the data is available..

        char newChar = clients[i]->read();
        // Read the data

        if (newChar == 'x') {
        // Check for a termination character for separation

        // Now parse with strtok in order to get parameterization
          char delimiters[] = ",";
          char* valIndex;
          valIndex = strtok(inputs[i], delimiters);
          for (int j=0; j < 2; j++){
            // Expand later to largest anticipated character count
            msg_array[j] = atoi(valIndex);
            Serial.print(msg_array[j]);
            valIndex = strtok(NULL, delimiters);
          }

          switch(msg_array[0]) {
          // Determine type of message received (Character 0 parsed as
          // Message Type)

            case '3':
            // Examine string for client cmds to turn sides on or off.
            if(msg_array[1] == '1')
            // Msg type 3, Instruction 1: Turn D side ON
              {
                digitalWrite(4, HIGH);
                // Set pin 4 high
                Serial.println("Dside started.");
                wd_Delap = 0;
                // Reset elapsed time watchdog time value for D side.
                wd_Dside = millis();
                // Last good heartbeat from client device on D side.
              }
            if(msg_array[1] == '2')
            // Msg type 3, Instruction 2: Turn D side OFF
              {
                digitalWrite(4, LOW);
                // Set pin 4 low
                Serial.println("Dside stopped");
                wd_Delap = 0;
                // Reset elapsed time watchdog time value for D side.
                wd_Dside = millis();
                // Last good heartbeat from client device on D side.
              }
            if(msg_array[1] == '3')
                // Msg type 3, Instruction 3: Turn C side ON
              {
                digitalWrite(5, HIGH);
                // Set pin 5 high
                Serial.println("C side started.");
                wd_Celap = 0;
                // Reset elapsed time watchdog time value for C side.
                wd_Cside = millis();
                // Last good heartbeat from client device on C side.
              }
            if(msg_array[1] == '4')
                // Msg type 3, Instruction 4: Turn C side OFF
              {
                digitalWrite(5, LOW);
                // Set pin 5 low
                Serial.println("C side stopped.");
                wd_Celap = 0;
                // Reset elapsed time watchdog time value for C side.
                wd_Cside = millis();
                // Last good heartbeat from client device on C side.
              }
            break;

            case '6':

                // Examine string for another message type TBD
            break;

            default:
              Serial.println("Default break. Received crap.");
            break;

          }

        inputs[i][0] = '\0';
        // Clear out this array element for the next message
        // clients[i]->stop();
        // By default, kill client session, just wait for new TCP open
        // delete clients[i];
        // Remove client element's data
        // clients[i] = NULL;
        // Reset to NULL

        }

        else {

           if (strlen(inputs[i]) > MAX_LINE_LEN) {
                // First check for size compliance
           Serial.println("Max line length exceeded from client.");
           inputs[i][0] = '0';
                // Clear out this array element for the next message
           }
           else {
           **strcat(inputs[i], newChar);**
                // Add character to the received string
           }

          Serial.println();
          Serial.println(newChar);
        }
      }

    // Update watchdog timers

    wd_Delap += (millis()-wd_Dside);
    wd_Celap += (millis()-wd_Cside);

    if (wd_Delap>=60000)
          {
            Serial.print("Elapsed time on watchdog, D side: ");
            Serial.println(wd_Delap);
            Serial.print("Last message received: ");
            Serial.println(wd_Dside);
            digitalWrite(4, LOW);    // set pin 4 low
            Serial.println("D side didn't hear from a client in 60s;
                           defaulting to OFF.");
          }

    if (wd_Celap>=60000)
          {
            Serial.print("Elapsed time on watchdog, C side: ");
            Serial.println(wd_Celap);
            Serial.print("Last message recieved: ");
            Serial.println(wd_Cside);
            digitalWrite(5, LOW);    // set pin 5 low
            Serial.println("C side didn't hear from a client in 60s;
                            defaulting to OFF.");
          }

   }
}

I previously had this compiling and running, though with issues that I intedned on iteratively troubleshooting. Now it won't compile because of the following error:

arduino:302:37: error: invalid conversion from 'char' to 'const char*' [-fpermissive]
strcat(inputs[i], newChar);   // Add character to the received string

..which I have attempted to bold above in the final else clause. I realize these parameters require pointers, but it seems like some of the other functions like strtok and strlen which ask for pointers as well seem to work okay in my code.
Are there any suggestions or alternatives to strcat() as to how I could make this work? I have mostly stuck with character arrays instead of declaring String objects. I am also obviously pretty rusty at C(++) as I haven't been actively working with it in a while.
Thank you

strcat is a function to concatenate strings. It expects a char array as second parameter. You have only a single char newChar to add to your string.
size_t l = strlen(inputs[i]);
inputs[i][l] = newChar;
inputs[i][l + 1] = 0;

Note: It would be better to track the length of the inputs then use strlen. strlen iterates over the array until terminating zero.

Thank you. I think this will work. Question, is the third line necessary? Wouldn't that just add a character '0' at the end, or are you saying that's the character for termination, which I thought was '\0'

the next strlen would not work without the terminating zero. ascii code of '\0' is 0. some use NULL, which is 0 too


text:
LowPower.idle isn't waiting
I am trying to have my Arduino wait in a low power idle state given by the LowPower library made by rocketscream on an Uno. However, when I try to have it wait for 8 seconds, it seems to not pause at all. Does anyone know how to make it so it waits the full 8 seconds before running the next line of code?
Here is the code:
#include "LowPower.h"

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

void loop() {
   delay(100);
   Serial.println("above");
   delay(100);

   LowPower.idle(SLEEP_8S, ADC_OFF, TIMER2_OFF, TIMER1_OFF, TIMER0_ON, SPI_OFF, USART0_OFF, TWI_OFF);

   delay(100);
   Serial.println("below");
}

I would expect this to print "above", then wait 8 seconds, then print "below",  then do it again. But what happens is it runs right through the LowPower.idle without doing anything and the output looks like:

1:12:14.547 -> above
21:12:14.746 -> below
21:12:14.845 -> above
21:12:15.044 -> below
21:12:15.144 -> above
21:12:15.376 -> below

...and so on.
If anyone has any ideas on how to make idle wait, that would be great.
Thanks!

Try putting cli(); before  LowPower.idle(...). I think timer0 (used for millis and delay) is interrupting your idle time.

Thank you for your response but that does not seem to change anything.

FYI, this issue was brought up nearly 3 years ago, with no response from the author:  https://github.com/rocketscream/Low-Power/issues/36

That is unfortunate, but thank you for this information!


text:
Arduino nano stopped working
After programming Arduino Nano with the DIY Headtracker code, after trying to plug the Arduino to the receiver and some time, the LED stops flashing and now it's not recognized by the computer anymore.
When I plug it, it only lights the power LED.
The worst thing is that I've already tried with another Nano and it bricked also, can't use them any more. Anyone know any fix to this?
This is the error given when trying to upload the blink sketch to the board...
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0xb8
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0xb8
avrdude: stk500_recv(): programmer is not responding

I suggest you visit the page Have I bricked my Arduino Uno? - whilst you have a Nano and not a Uno, it is the same processor and most of the remarks there will apply.
As the Arduino Nano page says:

It has more or less the same functionality of the Arduino Duemilanove, but in a different package.

If you have another Uno or similar lying around you could conduct the "chip detector" test described on that page. You could also perform the loopback test.
It is possible on the FTDI chip (underneath) is damaged in which case there would be alternatives to using that.

If you have access to an AVR ICE MKII or an AVRDragon, you could try High Voltage programming. It is, AFAIK, the ultimate way to revive a bricked device. There might be some alternative method to perform HV programming without any of the devices I mentioned (for example with another AVR), but I'm not aware of it, if it exists.

It's not really practical with a chip soldered to the board to do high-voltage programming, because you would send 12 V via the /RESET pull-up resistor to the +5 V pins, which would damage the chip.

@NickGammon: I wonder if there is any relatively simple way to cut a track or two and place jumpers on them. A bit like the procedure to make USB-reset optional for the UNO when enabling debugWire.
First thing that comes to my mind is to desolder the pullup, use the pads to wire/solder a male pin header and attach the resistor to a female pin header.

If was desperate, I would consider doing that. The other thing is that you have a whole lot of wires to connect (as the chip is soldered in). I've got a post about high-voltage programming which shows that you have around 20 wires to connect. I'd be a little surprised if it came to that. Either the chip has been hopelessly damaged, or you can recover with ICSP programming.

@NickGammon the 12v is going through a 1k resistor. The 5v would rise by no more than a volt. Now for the math (correct me if I'm wrong); The 328 uses at least 5mA (5v @8Mhz), which is equivalent to a 1k resistor (R=V/I). So together with the 1k on the reset line, it would create a voltage divider, giving 6v at the VCC point. 6v is just with the maximum ratings. If there is anything else in the circuit using current, it would be even lower than 6v. Or just add a 2.5k resistor between vcc and gnd to get exactly 5v. Pretty interesting point you made. Quite a brain-breaker to figure out.

Yes, that might work. I think I like the idea of the 2.5 k resistor in case the processor uses less power at some point. Indeed, the fluctuations in power during programming mode (if there are any) might be amplified by this 12 V effect. You also would need to solder onto XTAL1 which is not broken out to a pin. Again, though, I would try ICSP programming first. Much simpler to do, and there is no real proof at this stage that whatever-it-is that is wrong could be fixed by high-voltage programming but not ICSP programming.

If it comes to the high-voltage programming I would cut the trace to the resistor. That would be safest. In any case the chip has an internal pull-up. You would have the issue of the reset button not working afterwards, though. The suggestion by @IgorStoppa about the male header is probably a good compromise.

https://www.sparkfun.com/news/1629
Maybe your windows update has installed new drivers for your FTDI chip.
You can check that your usb device PID is set to 0x0000
(You probably have the "Gravitech Nano V3.0" (with FTDI chip on the back)? I have, and this worked for me.)
In this case, you should download M_PROG from FTDI
And then check for the chip, when found, you set the PID to FTDI default (0x6001).
Then simply press program, and it will re-set your device PID.
Also, you should download the "CDM-v2.12.00-WHQL-Certified.zip" drivers.
Another source


text:
Teensy: SPI and Pressure Sensor
I'm first time working with a Teensy 3.1. I have to connect this (MS5803-01BA: http://www.amsys.de/products/ms5803.htm) pressure sensor via SPI to my Teensy.
My problem is, that I don't have any reliable knowledge on SPI. I read the Wikipedia for it and also the Teensy-Manual.
For the pressure sensor I already got a C-Code but it is only working with the ATMEL ATmega644p microcontroller. I tried to get the code to work with my Teensy, but it seems like I don't get either any input nor any output.
I hope that one of you can help me with the following code and tell me what I'm missing out on. Thank you.
Code:
http://pastebin.com/xaWXfRUR
Datasheet of the pressure sensor:
http://www.amsys.de/sheets/amsys.de.ms5803_01b.pdf
C-Code for the pressure sensor for the ATMEL ATmega644p microcontroller:
http://www.amsys.de/sheets/amsys.de.an520_e.pdf

PS: Please excuse my not perfect English for it's not my native language.

Details about SPI at SPI - Serial Peripheral Interface - for Arduino
This isn't right:
  SPI.transfer(CMD_ADC_READ); // send ADC read command
  SPDR = SPI.transfer(0x00); // send 0 to read 1st byte (MSB)
  ret = SPDR;
  temp = 65536 * ret;
  SPDR = SPI.transfer(0x00); // send 0 to read 2nd byte
  ret = SPDR;
  temp = temp + 256 * ret;
  SPDR = SPI.transfer(0x00); // send 0 to read 3rd byte (LSB)

The SPI library handles SPDR for you. Writing to it yourself will corrupt its behaviour.
It should be more like:
  SPI.transfer(CMD_ADC_READ); // send ADC read command
  ret = SPI.transfer(0x00); // send 0 to read 1st byte (MSB)
  temp = 65536 * ret;
  ret = SPI.transfer(0x00); // send 0 to read 2nd byte
  temp = temp + 256 * ret;
  ret = SPI.transfer(0x00); // send 0 to read 3rd byte (LSB)

Ditto for elsewhere.

Was the answer helpful? If so, please accept it and possibly upvote it. This indicates to other users that you found the answer useful, and it also stops Stack Exchange from periodically "bumping" your question in the hope of getting an accepted answer.


text:
Why do only specific arduinos support the keyboard and mouse libraries?
The Arduino website suggests that only three boards are supported for the Mouse and Keyboard library page:

Leonardo
Micro
Due

What is special about those boards, that the other boards in the Arduino family don't have? I thought they might have the same proceesing chip on them but only two of them do. The CPUs are correspondingly:

ATmega32u4
ATmega32u4
Atmel SAM3X8E ARM Cortex-M3

I have Nanos, Unos and Duemilanoves. I am out of luck aren't I?
So my question is: what do those three boards have that lets them support those libraries?

Another option is to use the PS2Keyboard library, a PS2 connector and a PS2-to-USB converter.
You will need only two digital pin of your Arduino and have keyboard solution.

i was actually more interested in simulating a mouse, but this is good to know.

There is also a library called PS2Mouse that enables the possibility to act as a ps2 mouse device (with ps2dev) or receive values from a existing PS2 mouse.

Those chips have hardware support built into them to handle the rather strict timing requirements for interpreting (and responding to) USB sequences. You will notice, for example, that on the Arduino Uno there is a second chip (the Atmega16U2) which also can handle USB. In fact the chips with a "U" in the name generally can do this.

I have Nanos, Unos and Duemilanoves. I am out of luck aren't I?

You have a couple of options. Some people reflash the USB chip on their Uno (for example), although personally I think that is a bit fiddly.
Alternatively, there is a library called VUSB (virtual USB) which lets you do some USB on the non USB chips. Google vusb arduino.
You need three resistors and two zener diodes to make up the hardware that lets this library do its stuff.


text:
Not able to receive the operation results from the slave after the command being sent by Master - SPI

Brief - I am using two arduino Uno's. One acts as a master and the other as slave using Arduino IDE.  Below is the Master Code:
// Taken from Nick Gammon's Forum//

#include "SPI.h"
#include"pin_arduino.h"
int ss = 10;
void setup()
  {
    pinMode(ss,OUTPUT);
    Serial.begin(9600);
    Serial.println();
    digitalWrite(ss,HIGH);
    SPI.begin();
    SPI.setClockDivider(SPI_CLOCK_DIV8);
   }
byte transferAndWait(const byte what)
 {
   byte a = SPI.transfer(what);
   delayMicroseconds(20);
   return a;
 }
void loop()
 {
   byte a,b,c;
   digitalWrite(ss,LOW);
   transferAndWait('a');
a = transferAndWait(17);
b =  transferAndWait(33);
c = transferAndWait(0);
digitalWrite(ss,HIGH);
Serial.println(a,DEC);
Serial.println(b,DEC);
Serial.println(c,DEC);
delay(1000);
 }

Before I go into the details of the results I obtained and the problem, below is the Slave code:
//Taken from Nick Gammon's Forum//

#include "SPI.h"
#include "pins_arduino.h"
int slave = 10;
int miso = 11;
byte c = 0;
void setup()
  {
    pinMode(miso,OUTPUT);
    pinMode(slave,INPUT);
    Serial.begin(9600);
    SPR|= BV_(SPE);
    SPR|= BV_(SPIE);
 }
ISR(SPI_STC_vect)
 {
   c = SPDR;
  switch(c)
    {
      case 0:
      SPDR = 0;
      break;

     case 'a':
     SPDR = c + 15;
     break;
   }
  }
  void loop(void)
   {
     if(digitalRead(slave)==HIGH)
     c = 0;
   }

My Results : After dumping the master and slave codes into their respective arduino uno's, then when I open the serial monitor of the master code, It displays the number 17, 33, 0 and the same goes with the slave, meaning that the data is being sent to the slave and received back successfully, and hence I presume the SPI bus is working properly!. But why isn't the add operation happening?
Problem: Now the problem is, when the command 'a' is sent from the master to the slave, the slave has to interpret this 'a' command as Addition command and perform the addition of a number 15 to the incoming byte from the master as shown in the slave code, and return the results to the master, which should display the addition results in the  masters serial monitor. I am having problem performing this task and looking forward to suggestions on how to test or where I am doing wrong or make changes to the code or methods in order to get this working. I am expecting answers relevant to the below codes and method.

Since I wrote that example, I'll try to answer this. First I tested with the code from my page about SPI.

SPI Master
This is the master:
#include <SPI.h>

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

  digitalWrite(SS, HIGH);  // ensure SS stays high for now

  // Put SCK, MOSI, SS pins into output mode
  // also put SCK, MOSI into LOW state, and SS into HIGH state.
  // Then put SPI hardware into Master mode and turn SPI on
  SPI.begin ();

  // Slow down the master a bit
  SPI.setClockDivider(SPI_CLOCK_DIV8);

}  // end of setup

byte transferAndWait (const byte what)
{
  byte a = SPI.transfer (what);
  delayMicroseconds (20);
  return a;
} // end of transferAndWait

void loop (void)
{

  byte a, b, c, d;

  // enable Slave Select
  digitalWrite(SS, LOW);

  transferAndWait ('a');  // add command
  transferAndWait (10);
  a = transferAndWait (17);
  b = transferAndWait (33);
  c = transferAndWait (42);
  d = transferAndWait (0);

  // disable Slave Select
  digitalWrite(SS, HIGH);

  Serial.println ("Adding results:");
  Serial.println (a, DEC);
  Serial.println (b, DEC);
  Serial.println (c, DEC);
  Serial.println (d, DEC);

  // enable Slave Select
  digitalWrite(SS, LOW);

  transferAndWait ('s');  // subtract command
  transferAndWait (10);
  a = transferAndWait (17);
  b = transferAndWait (33);
  c = transferAndWait (42);
  d = transferAndWait (0);

  // disable Slave Select
  digitalWrite(SS, HIGH);

  Serial.println ("Subtracting results:");
  Serial.println (a, DEC);
  Serial.println (b, DEC);
  Serial.println (c, DEC);
  Serial.println (d, DEC);

  delay (1000);  // 1 second delay
}  // end of loop

SPI Slave
And this is the slave:
// what to do with incoming data
volatile byte command = 0;

void setup (void)
{

  // have to send on master in, *slave out*
  pinMode(MISO, OUTPUT);

  // turn on SPI in slave mode
  SPCR |= _BV(SPE);

  // turn on interrupts
  SPCR |= _BV(SPIE);

}  // end of setup

// SPI interrupt routine
ISR (SPI_STC_vect)
{
  byte c = SPDR;

  switch (command)
  {
  // no command? then this is the command
  case 0:
    command = c;
    SPDR = 0;
    break;

  // add to incoming byte, return result
  case 'a':
    SPDR = c + 15;  // add 15
    break;

  // subtract from incoming byte, return result
  case 's':
    SPDR = c - 8;  // subtract 8
    break;

  } // end of switch

}  // end of interrupt service routine (ISR) SPI_STC_vect

void loop (void)
{

  // if SPI not active, clear current command
  if (digitalRead (SS) == HIGH)
    command = 0;
}  // end of loop

Test results
Testing gave the expected results:
Adding results:
25
32
48
57
Subtracting results:
2
9
25
34

So, what is different in your code?
Your slave ISR:
ISR(SPI_STC_vect)
 {
   c = SPDR;
  switch(c)
    {
      case 0:
      SPDR = 0;
      break;

     case 'a':
     SPDR = c + 15;
     break;
   }
  }

This isn't quite the same, is it? In my code you get the command in one session (one interrupt) and what to use it for in another one.
Hence I had this:
  byte c = SPDR;

  switch (command)
  {
  // no command? then this is the command
  case 0:
    command = c;
    SPDR = 0;
    break;

Sending a "command" of zero clears the current command. So the sequence being sent is like this:
0    <-- start a new command
command  (ie. 'a' or 's')
22   <-- what to add to
33   <-- what to add to
44
55

Perhaps confusingly, I didn't send in that order, because I knew that the command would be zero initially(1), so I actually sent:
command  (ie. 'a' or 's')
22   <-- what to add to
33   <-- what to add to
44
55
0    <-- start a new command

There would be other ways of achieving this, but the fact is you changed the way the slave interpreted the incoming data.

I knew it would be zero because the slave sets the command to zero in the main loop if SS is not asserted.

ISR(SPI_STC_vect);  <-- Reason 1.
 {
   byte c = SPDR;
  switch(command)   <-- Reason 2.
    {                      |
      case 0:              |
      command = c;  <------┘
      SPDR = 0;
      break;

     case 'a':
     SPDR = c + 15;
     break;
   }
  void loop(void)   <--- Reason 3.
   {
     if(digitalRead(slave)==HIGH)
     command = 0;
   }

The slave code is not going to work, for various reasons.
Reason 1:
This is a declaration of a function. Not an implementation.
The ";" is badly misplaced here.
Reason 2: You're switching on a value "command" but it's only changed after executing the case/command?
Reason 3: The loop function is still part of the previous function?
The "{" below the ISR(SPI... isn't closed right. (With another "}")

The reason 1 and 3 were a typos, sorry about that!

Oh. Thank you for pointing out reason 2. Didn't notice that. I will shift this statement outside the case and check.

I edited the slave code as shown above. But my slave code is still not executing the " SPDR = c + 15" statement for case 'a'. Its repeatedly displaying 97,97,97.... on the serial monitor. Its just a simple add operation and I cant figure whats the mistake in the code, my master code seems to look fine. Pl help me debug.

Try to go back to the basics, verify that works and build on from there.
So first, make one arduino send stuff and let the other one print it as is.
No handling, just serial out it.
From there you can build on.
I believe SPDR is only 1 byte, so sending three bytes after eachother is quite weird? Because you check on the 'a' and then send it back +15... if another byte comes in, it will not be handled by the case switch..


text:
How has Arduino been used in the classroom?
I remember seeing Primo, this robot that is based on Arduino and serves to teach kids to program. My interest in the platform comes from there, but it is always nice to learn about other cool applications.
What other applications are there that utilise Arduino for K-12 education?

This is very broad. What age range? What type of education?

Edited to mean only k-12. Is that still too broad?

There's linkbot http://www.barobo.com/

I've used Sparki from Arcbotics as a robotics platform. It's uses Arduino Sketch to program and a modified Arduino IDE.
Sensors for line following , edge detection, distance and light level sensing are built in. Also the creators are focused on education so the material and projects are teaching oriented.
The Community seems pretty active and engaged too so the material should build over time.

We have been using Arduino's to teach basic microcontroller concepts in classes focused on environmental monitoring & instrumentation, rather than just electronics:
An Arduino UNO based Datalogger for the Classroom
The IDE abstracts away enough of the low level details that you can get students into programming quickly, while still exposing them to enough of hardware side of things. I am not sure what other platform would let us take true beginners so far, so quickly.


text:
High precision timing on Arduino for serial communication
I am using an Arduino Uno to send time and voltage information over the serial port to Python to plot. However the interval timings between successive time stamps appears to be increasing over time, affecting my plotting. This is especially true when the baud rate is set to 9600, where my initial time differences maybe 1320 and increases to 16400 after a relatively short period of time. When this rate is put to maximum of 115200 bps the change is slower and less noticeable, from around 1340 to 1500 even after a relatively long run of sending. All times are given in microseconds.
I would like to know if I can reduce or eliminate this effect, and if not understand why it exists. I have read things about interrupts and delays causing this, but I do not fully appreciate the complexity of the electronics at hand and would like to know:

Can I get greater precision in the timing?
What causes this change in timing?

Here is what I currently have:
#include <eHealth.h>

extern volatile unsigned long timer0_overflow_count;
float fanalog0;
int analog0;
unsigned long time;

byte serialByte;
void setup() {
  Serial.begin(9600);
}

void loop() {
  while (Serial.available()>0){
    serialByte=Serial.read();
    if (serialByte=='S'){
      while(1){
        fanalog0=eHealth.getECG();
        // Use the timer0 => 1 tick every 4 us
        time=(timer0_overflow_count << 8) + TCNT0;
        // Microseconds conversion.
        time=(time*4);
        //Print in a file for simulation
        //Serial.print(time);
        //Serial.print(" ");
        Serial.print(fanalog0,5);
        Serial.print("\n");

        if (Serial.available()>0){
          serialByte=Serial.read();
          if (serialByte=='F')  break;
        }
      }
    }
  }
}

What do you mean by "precise"? The times given by the counter are going to be fairly precise, accurate and with a good resolution. Do you want the times to be deterministic (i.e. always the same)?

Apologies, yes I guess that is what I meant, for the difference between them to be consistent and if not, the reason why they are not

Add the timestamp at PC end rather than Arduino end, or use a RTC (real time clock) module. RTC modules are pretty cheap to find on various webstores, just ensure that the store links to the datasheet. Another method is to program a timer and use an interrupt service routine to get reasonably accurate timing.

What does eHealth.getECG() do? Does that call always last the same amount of time?

Can you specify how long a "relatively short period of time" lasts? Is it always the same after restarting the Arduino?

getECG() is calling a function which takes the ECG value from electrodes connected to a subject. It is a voltage value and a short period of time usually encompasses 10 - 15 seconds

Posting the getECG() method could help explain the behavior you observe. Is this a method you wrote yourself or you got it from a library?

Although I don't have the ECG stuff, I have tried to reproduce the behavior you describe (and replaced getECG() with a simple delay(10)). At 9600 bps, I could not observe a shift in the timing as you describe.

Timestamping at the PC end would be good to avoid accumulating errors, but will add some jitter due to the asynchronous packetization over the USB-serial.  So for precise intervals in the short term, it would be better to fix the timestamping at the source.

getECG() just converts the analog value from analog0 to a voltage value from 0 to 5, its a simple calculation.

Use a timer and ISR (interrupt service routine) to make timing more accurate.
Take a look at my 1ms timed interrupt Proof of Concept. The idea is to have a reasonably accurate 1ms 'heartbeat' in the system that can be used to trigger other events. In the PoC it is used to blink an LED at ½Hz, but having access to the new variables millisecondCounter and secondCounter enables you to trigger events in the main loop at arbitrary (but accurately timed) moments.

Your PoC is very interesting but it has a flaw (easy to fix) in the fact that it reads a 2-byte value while interrupts are enabled (in loop()), this value being modified by an ISR. It can happen that loop() reads a bad value (in the middle of a modification by the ISR). I've posted a comment on your blog about it.

@jfpoilpret interesting point you make there, never thought of an interrupt occuring half way retrieving the value from RAM. I'm going to check the disassembly this evening and update the article. Maybe a good reason to write another article too :o)

I created a sample from your PoC and could see the problem occur at least once every 10 seconds on my UNO. But of course in reality it highly depends on what you do in your loop(): my sample just got the milliseconds value, ompare it to the previous read value and if difference > 0 (other than reset counter to 0) , display a message.

@jfpoilpret never really noticed it. I just use it as a heartbeat to monitor the food buckets for my cats and make an LED flash when my cats will be potentially disappointed ... ;o) It definitely will change the way how I use ISR's in future.

@jfpoilpret code is updated. Need to sit down to write a nice blog about this. Thnx

Although an Uno easily achieves a resolution of 1ms its timebase is usually worse than 1000 ppm. With other words it typically drifts more than 1ms per second. It is not uncommon for UNOs to drift more than 1s each 10 minutes.

@UdoKlein For accurate time keeping you should use an RTC anyway, but 1000ppm is a lot for a crystal oscillator. I'd expect order of magnitude 100ppm

The UNO does not have a crystal oscillator for the controller. It only has a crystal oscillator for the serial connection. The main controller is run from a resonator. Thus the typical deviation of a UNO is >> 1000 ppm. Older Arduinos (with crystal) used to be ~30 ppm or better.

@UdoKlein http://arduino.cc/en/uploads/Main/Arduino_Uno_Rev3-schematic.pdf still shows a 16MHz crystal.

It shows a crystal connected to a block ATMEGA16U2 and a resonator connected to ATMEGA328P-PU. The 16U2 is for the serial interface the 328P is "The Arduino". Interestingly enough the 16U2 would be able to push its clock to another chip, e.g. the 328P.

@UdoKlein I searched for the part number and I stand corrected. Awkward design decision.

I can think of a few things that can impact the "consistency" of the serial write timings:

size of the data to be printout

this may be the most obvious thing to think of, but indeed the more you print, the more it'll take to handle it.
Solution: print format the string into a string of known length.

using buffered serial

on unix you can access the serial port using a buffered or an unbuffered way. Using the buffered way for a long time may make it a bit slower as the buffer fills, usually it happens when data is incoming faster than you're reading it…
Solution: use the unbuffered serial line (e.g.: on Darwin/OSX it's /dev/cu.usbmodemXXX instead of /dev/tty.usbmodemXXX)

priority of the timers

it looks like your using a TC interrupt, and AVRs have priorities in the way interrupts are handled, I don't know the order of priority for the Atmega328, and it's not one of the most documented feature around, so I don't know how safe is TC0 versus the UART interrupt.
Solution: look up further in the documentation/datasheet about interrupt priorities and change the timer if needed ; and/or do a test without having the other timer running.

the data you're reading from takes more time to read from over time

some drivers need to average or do some operations over the previous values, so the more values you measure, the longer the buffer is, and the longer it takes to calculate the value, until you've reached the maximum size of the buffer.
Solution: look at the source code of the library you're using, and either optimize it, remove the calcul if there's one or take that increasing processing time into account.

avoiding the arduino framework overhead

but if you really want to optimize serial output from the arduino, you should avoid using the arduino overhead… But it's way less elegant and comfortable to use.
I'm pretty sure there are other points I'm missing, but that's the first things that I'd check before digging further.
HTH

Your code includes the duration of the output in subsequent measurements. Thus depending on the length of the output you will measure different times. This can be fixed by formating to fixed length output.
The next issue is that the UNO has a very poor timebase. Have a look here for a comparison of different Arduino types vs. the DCF77 time reference.
Conclusion: if you need precise timing either get an Arduino with crystal or go for an RTC. I can highly recommend DS3231 / DS3232 RTCs since these usually achieve 2 ppm accuracy out of the box.


text:
Is it possible to build a 1080p OSD webcam shield?
What do I need to build a shield capable of receiving 1080p video from USB camera, timestamp each frame and send the frame to memory card?

It would require so much hardware in terms of memory, speed and specialized peripherals, that it renders adding an Arduino to the mix pointless.

You would be better off with a Raspberry Pi connected to the USB port via serial and to send when to start/stop. The YUN might be able to handle it, but you'll have to write your own device drivers. Also, the TRE (not available yet) might work.

None of the ATmega based boards have the hardware (in terms of acting as a USB host) or power (in terms of handling probably compressed 1080p video).
Potentially one of the ARM boards could do this. The Arduino Due can act as a host, but it sounds fairly experimental, and none of them will have drivers to connect to the camera.
If a shield was developed to do this, it would have so much more power than the Arduino that the Arduino would probably better be viewed as a slave to the other device.

The Arduino Due has a port that can act as a USB host. You'd still have driver issues, though.

Raspberry Pi...


text:
How to pause Arduino for 1 millisecond through MATLAB?
I have been able to connect MATLAB to my Uno with this line of code: a = arduino('COM4'); through this package: Matlab support package for Arduino.
Right now, MATLAB is my main script that will synchronize all the components [like the Arduino].
I am able to send pulses to my stepper-motor just by using:
void loop() {
    digitalWrite(2, HIGH);
    delay(1);
    digitalWrite(2, LOW);
    delay(1);
}

This works fine, and will make the motor move about once every 2 milliseconds. My problem is that I cannot find a way to produce this same delay through MATLAB's interface. I do know that MATLAB has a pause() function, but when I set up a loop in MATLAB like this:
a = arduino('COM4');
for m = 1:400
    a.digitalWrite(2, 1);
    pause(0.001);
    a.digitalWrite(2, 0);
    pause(0.001);
end

Each step takes WAY longer - about 200 milliseconds each.
What are other options for creating the pause between digital High / Low being sent to the Arduino? It would be nice if I could control the outcome from Matlab, through Arduino.

It sounds like you need something like GRBL. It's a stand-alone program for an arduino board that interprets a command language, and produces coordinated stepper motor motions. It's largely intended for CNC machining, but it can probably do what you need.

The increased in observed delay is due to the time it takes to send the command from MATLAB to the Arduino have its code execute the requested command. In your case the a.digitalWrite. So actual time between pulses using MATLAB's delay is 0.001 pause plus the time of baud rate times the packet size and decoding then execution.
I would recommend not pursuing this solution of the MATLAB controlling the timing of Step Motors, remotely. As this latent coupling will be a frustrating limitation. Noting that for step motors the timing can not afford such latent execution. Hence all the 3D printers and many CNC with Step Motors use Arduino's which get G-Code (motor move commands with destinations) and the Real-time firmware handles the stepping, within tolerances.
I would suggest using something like grbl firmware with step motor shield and then have the MATLAB send the needed G-code. Where there are others with much more features but tailored to 3d Printing. grbl is simpler and straight to the point of moving motors.

It's not clear from your question whether you are trying to get real-time execution without latency or simply want to adjust the motor delay time from MATLAB.  If the latter, a good way is to send delay data (e.g. a number that represents how long you want between pulses) vie serial, which your Arduino program will receive and update the motor delay as desired.  Or, bearing in mind RAM limitations, you can send a whole sequence of delays that can run one after another with precise timing.


text:
Difference between SoftwareSerial and Serial
From the sample code
#include <SoftwareSerial.h>
SoftwareSerial mySerial(10, 11); // RX, TX
void setup()
{
  // Open serial communications and wait for port to open:
  Serial.begin(57600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }
  Serial.println("Goodnight moon!");
  // set the data rate for the SoftwareSerial port
  mySerial.begin(4800);
  mySerial.println("Hello, world?");
}

void loop() // run over and over
{
  if (mySerial.available())
    Serial.write(mySerial.read());
  if (Serial.available())
    mySerial.write(Serial.read());
}

What is the difference between, why use 2 types of calls to make AT command calls.

SoftwareSerial mySerial (10,11)
  mySerial.begin(10,11)

and

Serial.begin(9600)

Edit, this answers my question in my own words based on @jfpoilpret response.

It is important to initialize both Serial and SoftwareSerial, since SoftwareSerial is used to send the actual commands to the GSM, and Serial is used to view all the commands and their responses on the debug port of the GSM
The pins on the GSM and Arduino are used to connect the the 2, and pass on actual commands. While the RS232 is only used for debugging. We can however connect a RS232 to USB connector so as to connect the GSM to the desktop(or laptop)
The code in the loop is essential to help convert all actual commands to the debugging RS232 port, and the other way around, so as to enable us to use a tool like cutecom (on ubuntu) to pass commands to the GSM serial input pins.

Important Note : When using cutecom ensure that you select CR line end to send commands.

All Atmel MCU, on which Arduino models are based, include special hardware for serial communication; this part of the MCU is called USART (stands for Universal Synchronous/Asynchronous Receiver/Transmitter).
Based on the Arduino model you have, you may have only one (eg on UNO) or more USART (leonardo, mega...) on the board MCU.
Each MCU USART is mapped to specific pins of the board, you cannot change those pins.
On Arduino, if you use the monitor to send debug information to your PC, then one USART is used, this is when you used Serial.
If you need more than one serial communication link (e.g. because you have some devices that communicate through serial) but your Arduino model has only one USART, then you have to use the library SoftwareSerial that "simulates" the job of an USART only by software. Hence it is much less optimized than the hardware USART.
One advantage of SoftwareSerial is that you can map it to any pair of pins you like.
Going to your code sample:
if (mySerial.available())
    Serial.write(mySerial.read());
if (Serial.available())
    mySerial.write(Serial.read());

Obviously here, Serial is used for debugging (sending info to the serial monitor of your PC), whereas mySerial is used to communciate with the GSM device.
So this sketch is used to allow you to type AT commands on the monitor, which will then be forwarded to the GSM device; conversely, any strings returned from the GSM device will be echoed to the serial monitor.

I'm using SIM808 module with Arduino Uno, one thing that I don't understand is when I use TX1 and RX0 of Arduino to communicate to GSM module, I get error on Arduino software during upload process: something like 'avrude ....' . But when I use SoftwareSerial setting tx and rx pins to pin7 and pin8, there's no problem on uploading when pins are connected. One other thing is that when different versions of Arduino is used how do you communicate to GSM device if you don't use SoftwareSerial? I've seen code for other versions of Arduino and SIM908
at which SoftwareSerial lib. is not used at all.

#include <SoftwareSerial.h>

SoftwareSerial GSMSerial(7, 8); //use pins 7 and 8 as RX and TX

void setup() {
   GSMSerial.begin(19200);               // the GPRS/GSM baud rate
   Serial.begin(19200);                 // the GPRS/GSM baud rate
}

void loop() {
    if(Serial.available()) {
       //to send commands received from Serial Monitor to GSM module
       GSMSerial.print((char)Serial.read());
    }
    else  if(GSMSerial.available()) {
       //To print data responded from GSM module to the Serial Monitor.
       Serial.print((char)GSMSerial.read());
    }
}

In the code above inside loop function first if statement is needed to talk to GMS module from Serial Monitor, e.g. when you type AT in the monitor and press enter your command gets sent to the GSM module.
The second if statement else if is to print whatever is received or responded from GSM module e.g. GSM module responds the received command like AT and its result OK after you send command AT to the module.


text:
Arduino Packet for Bluetooth
I'm having trouble figuring out how to start my project. The objective is to control a robot with four servo motors and six DC motors through bluetooth. I have a bluetooth shield from Adafruit and I'm using the Arduino UNO. Ideally, I want to control this robot by sending it packets through Processing. The problem is I don't know how to create a packet with a header, payload, and checksum. I can't find any examples; can anyone help me find something to help me get started?

One layer of this should already be being invisibly added, verified, and removed in the bluetooth subsystem, but you can do your own as well on top.  One thing which would make your life a LOT easier is to use a printable format so you can use a serial monitor for debugging.  For example you could simply have a line of readable text, and a two-digit hex checksum at the end followed by a carriage return (a bit like a line from a .hex file).  You could put a byte count at the start of the line, but don't need to.

I don't understand. What I'm saying is: I don't know what a packet is, or a header, or a payload, or how to create a checksum. Is there an example out there that helps me grasp what these are?

First, depending on the degree of reliability you need, you may not actually have to do this yourself, as the bluetooth implementation will already invisibly-to-you add, verify, and remove a packet and checksum framing around your data.  But let's assume you want to add your own as well.
A packet is a batch of data to be transmitted as a contained unit.  It may or may not contain exactly one useful message, but it is quite convenient if it does, and since you will be doing your own packetization (at this level) you can make sure that it does.  So basically you will transmit something that has a structure, for example:

Hi, I'm a packet
attention HAL
"Open the pod bay doors"
The bytes in this message should add up to xx if you ignore the overflow
That was a packet

There are countless ways you could implement this, but your life will be a lot easier if you make both the messages and the packet structure human readable, so that you can watch on the serial monitor, and perhaps even type manually.  So let's say you did something like
M1=200/BF\n

For simplicity sake, instead of having a "Hi I'm a packet" header, we just use the newline character '\n' to mark the end of a packet, and assume that whatever comes next is the start of a new packet.  Further, since bluetooth is already creating a one-to-one link, you don't need to address who you are talking to.
Now we have a message, for example "M1=200" meaning "drive motor 1 at PWM level 200" (out of 255).
I'm somewhat randomly choosing the '/' character to mark the division between the message body and it's checksum.
"BF" might be the low two hex digits of adding up all the previous bytes in this message (it's not, I just picked something random).
And finally you have your newline to mark the end of a message and the end of a packet, since in this scheme we've decided that 1 packet = 1 message.
For extra fun, if the robot itself is not dangerous, you can make a test mode where the receiver will accept messages with no '/' and checksum, and only check the checksum on those where it is present.  This would allow you to manually type messages into a terminal when you are experimenting.  Or you can make your own specialized terminal program which calculates and appends a checksum each time you press return

Start simple.

send serial data from PC. either use Arduino USB port or on real hardware serial port, needs USB to serial adaptor and a terminal software. (see diagram in below web)
for starting, no need for header. Just use simple text as defined yourself
on Arduino side, read serial input. For example, type letter 'a' on PC will blink LED, 'b' to move servo 30 degree
Replace serial communication (like RS-232 or a UART) with Bluetooth. Bluetooth supports many 'profiles', like headset, keyboard, etc. that are not suitable in your case.

See below video. You need to use the SPP profile. see https://learn.sparkfun.com/tutorials/bluetooth-basics/bluetooth-profiles
Make sure your purchased bluetooth device supports SPP. Some bluetooth device are permanently setup to do one fix action. However, many bluetooth need to be 'programmed' (told what to do) before doing the task via AT command. Set speed, pairing, etc.
https://learn.sparkfun.com/tutorials/using-the-bluesmirf/example-code-using-command-mode
http://www.instructables.com/id/Modify-The-HC-05-Bluetooth-Module-Defaults-Using-A/

Quoted from your link, "Bluefruit EZ-Link shield is a regular 'SPP' device" so you have brought the right unit. At FAQ, "There is no command mode for EZ-Link, it is designed to be used out of the box.", so, one less thing to worry. The tutorial look excellent and should have all info you need. There are may steps and 'fine points'. Make sure you follow them precisely and carefully.  Are you using one pair of "module plus Arduino"? That is, two same_brand and same_model BT modules communicating. Thinngs are more complex if different equipment is involved, like BT module communicate with phone.

If I am at your situation, I would forget my code for the time being. Just follow the Adafruit tutorial from start to end. This ensure wiring done ok and the unit is paired (need one time pairing and two modules can communicate in all future sessions)