text:
MPU6050, Bluetooth — FIFO Overflow and Breakdown
I am quite new to all the arduino stuff and right now I am struggling with a Problem that seems to be easy, but I have honestly no idea how to deal with it.
I would like to read the data from a gyroscop and transmit the raw values via bluetooth to another device.
I am using the arduino uno r3 (it should be quite new since I bought it yesterday), the famous MPU-6050 Gyro-GY521 and for bluetooth De-HC-06BT.
I could already manage to assemble everything and send the data via bluetooth. To read the data from the gyro I am using the famous library MPU6050, which comes with some examples and seems to be the de facto standard for this.
The whole script is based on the MPU6050_DMP6 example and utilizes a SoftwareSerial to transmit the data.
Unfortunatly has two major issues:

It just stops to send data after some time (~2 Minutes) and a restart makes it send again.
It prints FIFO Overflow ~ each 20th frame, so I guess there is an ongoing failure which might stop the system.

If anybody could give some hint how to solve the »FIFO-« and »Breakdownissue« I would be very glad and I appreciate any kind of help!
Thanks in Ahead!
The whole code:
#include <SoftwareSerial.h>

// I2Cdev and MPU6050 must be installed as libraries, or else the .cpp/.h files
// for both classes must be in the include path of your project
#include "I2Cdev.h"

#include "MPU6050_6Axis_MotionApps20.h"
//#include "MPU6050.h" // not necessary if using MotionApps include file

// Arduino Wire library is required if I2Cdev I2CDEV_ARDUINO_WIRE implementation
// is used in I2Cdev.h
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
    #include "Wire.h"
#endif

// class default I2C address is 0x68
// specific I2C addresses may be passed as a parameter here
// AD0 low = 0x68 (default for SparkFun breakout and InvenSense evaluation board)
// AD0 high = 0x69
MPU6050 mpu;
//MPU6050 mpu(0x69); // <-- use for AD0 high

//RX und TX gekreuzt vom Bluetooth board
SoftwareSerial serial2(10, 11); //RX, TX

#define OUTPUT_READABLE_YAWPITCHROLL

//#define LED_PIN 13 // (Arduino is 13, Teensy is 11, Teensy++ is 6)
//bool blinkState = false;

// MPU control/status vars
bool dmpReady = false;  // set true if DMP init was successful
uint8_t mpuIntStatus;   // holds actual interrupt status byte from MPU
uint8_t devStatus;      // return status after each device operation (0 = success, !0 = error)
uint16_t packetSize;    // expected DMP packet size (default is 42 bytes)
uint16_t fifoCount;     // count of all bytes currently in FIFO
uint8_t fifoBuffer[64]; // FIFO storage buffer

// orientation/motion vars
Quaternion q;           // [w, x, y, z]         quaternion container
VectorInt16 aa;         // [x, y, z]            accel sensor measurements
VectorInt16 aaReal;     // [x, y, z]            gravity-free accel sensor measurements
VectorInt16 aaWorld;    // [x, y, z]            world-frame accel sensor measurements
VectorFloat gravity;    // [x, y, z]            gravity vector
float euler[3];         // [psi, theta, phi]    Euler angle container
float ypr[3];           // [yaw, pitch, roll]   yaw/pitch/roll container and gravity vector

// packet structure for InvenSense teapot demo
uint8_t teapotPacket[14] = { '$', 0x02, 0,0, 0,0, 0,0, 0,0, 0x00, 0x00, '\r', '\n' };

// ================================================================
// ===               INTERRUPT DETECTION ROUTINE                ===
// ================================================================

volatile bool mpuInterrupt = false;     // indicates whether MPU interrupt pin has gone high
void dmpDataReady() {
    mpuInterrupt = true;
}

// ================================================================
// ===                      INITIAL SETUP                       ===
// ================================================================

void setup() {
    // join I2C bus (I2Cdev library doesn't do this automatically)
    #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
        Wire.begin();
        TWBR = 24; // 400kHz I2C clock (200kHz if CPU is 8MHz)
    #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
        Fastwire::setup(400, true);
    #endif

    Serial.begin(115200);
    while (!Serial); // wait for Leonardo enumeration, others continue immediately

    serial2.begin(9600);
    //serial2.println("Hello");

    // initialize device
    Serial.println(F("Initializing I2C devices..."));
    mpu.initialize();

    // verify connection
    Serial.println(F("Testing device connections..."));
    Serial.println(mpu.testConnection() ? F("MPU6050 connection successful") : F("MPU6050 connection failed"));

    // load and configure the DMP
    Serial.println(F("Initializing DMP..."));
    devStatus = mpu.dmpInitialize();

    // make sure it worked (returns 0 if so)
    if (devStatus == 0) {
        // turn on the DMP, now that it's ready
        Serial.println(F("Enabling DMP..."));
        mpu.setDMPEnabled(true);

        // enable Arduino interrupt detection
        Serial.println(F("Enabling interrupt detection (Arduino external interrupt 0)..."));
        attachInterrupt(0, dmpDataReady, RISING);
        mpuIntStatus = mpu.getIntStatus();

        // set our DMP Ready flag so the main loop() function knows it's okay to use it
        Serial.println(F("DMP ready! Waiting for first interrupt..."));
        dmpReady = true;

        // get expected DMP packet size for later comparison
        packetSize = mpu.dmpGetFIFOPacketSize();
    } else {

        Serial.print(F("DMP Initialization failed (code "));
        Serial.print(devStatus);
        Serial.println(F(")"));
    }

    // configure LED for output
    //pinMode(LED_PIN, OUTPUT);
}

void loop() {

    // if programming failed, don't try to do anything
    if (!dmpReady) return;

    // wait for MPU interrupt or extra packet(s) available
    while (!mpuInterrupt && fifoCount < packetSize) {

    }

    // reset interrupt flag and get INT_STATUS byte
    mpuInterrupt = false;
    mpuIntStatus = mpu.getIntStatus();

    // get current FIFO count
    fifoCount = mpu.getFIFOCount();

    // check for overflow (this should never happen unless our code is too inefficient)
    if ((mpuIntStatus & 0x10) || fifoCount == 1024) {
        // reset so we can continue cleanly
        mpu.resetFIFO();
        //Serial.println(F("FIFO overflow!"));

    // otherwise, check for DMP data ready interrupt (this should happen frequently)
    } else if (mpuIntStatus & 0x02) {
        // wait for correct available data length, should be a VERY short wait
        while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();

        // read a packet from FIFO
        mpu.getFIFOBytes(fifoBuffer, packetSize);

        // track FIFO count here in case there is > 1 packet available
        // (this lets us immediately read more without waiting for an interrupt)
        fifoCount -= packetSize;

        #ifdef OUTPUT_READABLE_YAWPITCHROLL
            // display Euler angles in degrees
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetGravity(&gravity, &q);
            mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);

            serial2.print(ypr[0] * 180/M_PI);
            serial2.print(",");
            serial2.print(ypr[1] * 180/M_PI);
            serial2.print(",");
            serial2.print(ypr[2] * 180/M_PI);
            serial2.print("\n");

        #endif

        delay(5);
    }
}

See if you can determine if it is the serial link that is not keeping up.  You might try increasing the baud rate.  You could also try to reduce the rate at which samples are produced, make the output more compact, or even do something as crude as only producing output for every second sample.  You could also add extra output to see where it gets "stuck"

I have the same issue. I get disconnected after a few seconds/minutes when I send data from mpu6050 via BT HC-06. Have you found your answer in 1 year ?


text:
Why is my TMP35 giving me weird values?
A TMP35/36/37 is giving very high voltage readings, which results in high temperature readings. The serial monitor looks like this:
As you can see, the sensor value is in the 900s, voltage is almost 5, and temp is in the 400s. The circuit is very simple, just a TMP connected to 5V and ground and pin A0. Here is my code:
const int sensorPin = A0;
const float baselineTemp = 20.0;

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

}

void loop() {
  int sensorVal = analogRead(sensorPin);
  Serial.print("Sensor value: ");
  Serial.print(sensorVal);

  float voltage = (sensorVal / 1024.0) * 5.0;
  Serial.print(", volts: ");
  Serial.print(voltage);

  Serial.print(", degrees C: ");
  float temperature = (voltage - .5) * 100;
  Serial.println(temperature);
  delay(1000);
}

This is a very simple program and a very simple circuit, so I'm not sure what is going on. Maybe the problem is the sensor itself. I have also tried this sensor with multiple other circuits and programs and the same thing happens.
If anyone knows anything about this, help would be great.

Can you hook up a voltmeter to the Vout of the TMP? If the voltage is actually that high, then yes, you've got a broken part. Try another TMP sensor. This is to just rule out the arduino.

When I connect a voltmeter to the TMP it says 5V. So it must be the part.

Yeah, must've gotten damaged somehow. Just for the sake of being thorough you could: 1. double check your circuit, 2. double check the the TMP orientation (I've hooked them up backwards before), 3. double check the supply voltage and make sure it's between 2.7v and 5.5v (per the data sheet). But, you probably already did these things. I just thought I should mention them just in case.

Thanks for the comment but yes, I checked all these multiple times. Too bad they only give you one TMP in the starter kit.

Just curious: where does the - .5 come from, in float temperature = (voltage - .5) * 100;? TMP35 outputs 10mv/degC, with 0v at 0degC. (Not that it would help if this is a coding error; it would make your results look 50degC higher.)

Part seems to be broken; voltage is unusually high.

Before you toss it, it's worth trying another ADC pin.  Also make a divider with some resistors and verify you can get a range of values from the ADC.  And be sure you have the sensor, not some random transistor, and that you have the wiring correct, including its ground connected.

Thanks, tried different ADC pins, all same results. It is definitely a temperature sensor and the wires are correct. I will try to make a divider to test the ADC, but the other pins were giving me the same results.

I use voltage dividers a lot and have seen this before.
In each and every case where ALL my readings are high, yet they vary predictably (like on my solar panels - they go up during day and down at night), there has always been proven to be a very simple, single cause.
Resistance in the ground lead.
Such as if it is plugged into a breadboard hole that is not holding it well, or if I have extended it and have connections along the way.
So that would be the first thing I would look for.

Having said that, if the readings are very high and do NOT vary predictably, then I would look for a disconnected ground lead.

If all the connections are good but it still misbehaves then I would swap it out with another one to make sure the part itself isn't the problem.

source: Stack Exchange

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

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

sort: votes


text:
Creating a timer using a Real Time Clock with start and stop times
I have an Arduino Uno with a motor shield, as well as a DS1307 RTC that I am using to control 2 pumps.
Ideally I would like to set a start time (startHour + startMinute) and end time (endHour + endMinute) for each pump.
I have had luck using if statements to control my timer like below (adapted from Iain Foulds):
byte startHour=8
byte startMinute=15
byte endHour= 14
byte endMinute= 20

byte startHour2=22
byte startMinute2=30
byte endHour2= 2
byte endMinute2= 45

void loop() {
  byte checkStartTime1() {
    DateTime now = RTC.now();
    // Read in what our current datestamp is from RTC
    if (now.hour() == startHour && now.minute() == startMinute) {
      validStart1 = 1;
    } else {
      validStart1 = 0;
    }
    return validStart1;
    // Return the status for powering up
  }
}

But my concern is that this only checks for equivalency at the moment, and if I lost power when my start time came up my pump would not come on. So I was hoping to set up an if statement that can deal with ">=" as opposed to just "==".
Which I can use if I only deal with the hour section:
if (now.hour() >= startHour && <= endHour)

But things get complicated when I try to add in minutes to the control structure. I end up with a series of nested for loops that do not work.
I'm hoping someone can help me write an if statement (or switch case) that can accommodate hours and minutes. So that any time between 8:15-14:20
validStart1=1

and anytime other time
validStart1=0

And please note the addition of the second set for this timer (StartHour2)- which I threw as my second pump will need to deal with the switch over past midnight.

May I know how to change this code working for midnight time range?
As an example, 23.30 to 01.30. byte startHour=8
byte startMinute=15
byte endHour= 14
byte endMinute= 20 void loop()
{ DateTime now = RTC.now(); // Read in what our current datestamp is from RTC if ( ( (now.hour()==startHour && now.minute()>= startMinute) || (now.hour()>startHour) && ( (now.hour()==endHour && now.minute()< endMinute) || (now.hour()<endHour) ) { validStart1 = 1; } else { validStart1 = 0; // }

I had a similar problem when i tried to control some heating source here at home.This was how I made my steps to get it working.
First I will assume you are using the library time.h and DS1307RTC.h (check here for info: https://www.pjrc.com/teensy/td_libs_Time.html).
Assuming that you will need 3 variables of the type tmElements_t.
tm will store your current time( the one you get from DS1307). The other two are auxiliary for defining time you start and time you stop the pump.
In similar way, you will need 3 variables of type time_t for the same reasons.
time_t variables store a the timestamps since 01/01/1970 (Unix epoch) which are easier to work with but tmElements structures are more human friendly.
tmElements_t tm, tm_hour_start, tm_hour_end;
time_t now, t_hour_start, t_hour_end;

Now in your loop you need to get the current time from rtc:
time_t now = RTC.get();

after, use the breaktime funtion to convert the timestamp value to tmElements struture:
breakTime(now, tm);

Next step is to copy contents of tm to the other auxiliary structures, use the memcpy function:
memcpy(&tm_hour_start, &tm, sizeof(tm));
memcpy(&tm_hour_end, &tm, sizeof(tm));

after, change the the auxiliaries vars to meet your correct schedule of start and stop (are seconds important? if so, do similar way):
tm_hour_start.Hour = startHour;
tm_hour_start.Minute = startMinute;
tm_hour_start.Second = 0;
tm_hour_end.Hour = endHour;
tm_hour_end.Minute = endMinute;
tm_hour_end.Second = 0;

Ok, we have the more human friendly start and end structures, lets get the timestamps from them. To do soo we use the makeTime function that converts tmElements_t structures to time_t:
t_hour_start = makeTime(tm_hour_start);
t_hour_end = makeTime(tm_hour_end);

All you need to do now, is check if your current timestamp (now) is between this newly created timestamps:
if ((t_hour_start <= now) && (now <= t_hour_end)){
   //do something is soo...
}else{
   // do something if not...
}

Extra tip: In case your stop hour goes past midnight, add one more day to the timestamp:
if (startHour > endHour) //past midnight correction
   t_hour_end = t_hour_end + SECS_PER_DAY;

clean code:
#include <time.h>
#include <DS1307RTC.h>
#include <stdio.h>
// other includes etc...

byte startHour=8
byte startMinute=15
byte endHour= 14
byte endMinute= 20

tmElements_t tm, tm_hour_start, tm_hour_end;
time_t now, t_hour_start, t_hour_end;

// setup function and other needed things...

void loop(){
  //get current timestamp
  time_t now = RTC.get();
  // make current date and time structure
  breakTime(now, tm);
  // make auxiliary structures to be more human editable and friendly
  memcpy(&tm_hour_start, &tm, sizeof(tm));
  memcpy(&tm_hour_end, &tm, sizeof(tm));
  // change auxiliary structures to meet your start and end schedule
  tm_hour_start.Hour = startHour;
  tm_hour_start.Minute = startMinute;
  tm_hour_start.Second = 0;
  tm_hour_end.Hour = endHour;
  tm_hour_end.Minute = endMinute;
  tm_hour_end.Second = 0;
  // reverse process to get timestamps
  t_hour_start = makeTime(tm_hour_start);
  t_hour_end = makeTime(tm_hour_end);
  // check if end time is past midnight and correct if needed
  if (startHour > endHour) //past midnight correction
       t_hour_end = t_hour_end + SECS_PER_DAY;

  //final part
  if ((t_hour_start <= now) && (now <= t_hour_end)){
          //do something is soo...
  }else{
          // do something if not...
  }

}

EDIT: to correct the thing about midnight checks spotted in comments. New code:
#include <Wire.h>
#include <Time.h>
#include <DS1307RTC.h>
#include <stdio.h>
// other includes etc...

byte startHour = 8;
byte startMinute = 15;
byte endHour = 14;
byte endMinute = 20;

tmElements_t tm, tm_hour_start, tm_hour_end;
time_t now_, t_hour_start, t_hour_end;
boolean update_tm = 1;

// setup function and other needed things...
void setup(){};

void loop(){
  //get current timestamp
  time_t now_ = RTC.get();
  // make current date and time structure
  breakTime(now_, tm);
  // make auxiliary structures to be more human editable and friendly
  if(update_tm){
    memcpy(&tm_hour_start, &tm, sizeof(tm));
    memcpy(&tm_hour_end, &tm, sizeof(tm));
    // change auxiliary structures to meet your start and end schedule
    tm_hour_start.Hour = startHour;
    tm_hour_start.Minute = startMinute;
    tm_hour_start.Second = 0;
    tm_hour_end.Hour = endHour;
    tm_hour_end.Minute = endMinute;
    tm_hour_end.Second = 0;
    // reverse process to get timestamps
    t_hour_start = makeTime(tm_hour_start);
    t_hour_end = makeTime(tm_hour_end);

    // check if end time is past midnight and correct if needed
    if (startHour > endHour) //past midnight correction
      t_hour_end = t_hour_end + SECS_PER_DAY;
  }
  //final part
  if ((t_hour_start <= now_) && (now_ <= t_hour_end)){
    /* if we got a valid schedule, don't change the tm_hour structures and the
    respective t_hour_start and t_hour_end timestamps. They should be updated
    after exiting the valid schedule */
    if(update_tm)
      update_tm = 0;

    //do something is soo...
  }else{
    if(update_tm == 0)
      update_tm = 1;
    // do something if not...
  }

}

Thanks so much for such a well thought out, well explained, and well complemented code. But I do seem to be having an issue with the midnight correction. When I use the above code, when the clock strikes midnight my pumps stop. There seems to be some funky math going on when at midnight, so I even tried (SECS_PER_DAY*2) to make sure I'm well into the next day. But my pump is still shutting down at midnight. But other than this issue, the code works well

try to replace SEC_PER_DAY with the real number (24hours * 3600 sec per hour = 86400) to see if there is no buggy problem with that macro or something. The macro itself is defined in time.h (https://github.com/PaulStoffregen/Time/blob/master/Time.h).
Have you printed time_t variables t_hour_start, t_hour_end and now? Are they correct?

@Vinterwoo ignore my last comment, I think I figured it out, however I can not test it at the moment. I think the problem is we are constantly refreshing the 'tmElements_t' structures of 'tm_hour_start' and in 'tm_hour_end'. Once we past over midnight, this structures also will change and cause the failure (because the 'tm_hour_start.day' will reflect the change over new day). Once we get a valid start, we must fix this structures until turn off hour is passed. Check the edit

What you need to do is convert the time into some standard single number and then compare those numbers.
A popular method is to calculate the number of seconds since an epoch.  An epoch is an arbitrary point in time that you measure time since.  Microsoft chose 01/01/0000 for their epoch - Unix chose 01/01/1970.
The Time.h library contains functions for manipulating time values - one of the functions in it can convert a full date and time specification into the number of seconds since 01/01/1970 (Unix epoch).  If you want ideas then look at the source code for that.
A similar approach can be used to just work on the hours and minutes within a day.  One hour is 60 minutes, so you can create a number that is the number of hours multiplied by 60 plus the number of minutes in the current hour.  That will give you the number of minutes since midnight.  You can even add in the seconds if you want even more accuracy.
Once you have that single value it's very easy to compare it with a >=.

Gerben, thanks for your code. I took it and added seconds to the check, and tidied up a few typos. This isn't as sophisticated as other methods, but might be good for beginners to follow logic. hope it helps
#include <TimeLib.h>
#include <Wire.h>
#include <DS1307RTC.h>  // a basic DS1307 library that returns time as a time_t

int openHH = 9;
int openMM = 10;
int openSS = 0;
int closeHH = 9;
int closeMM = 40;
int closeSS = 0;

bool isOpenTime()
{
  time_t t = now(); // Read in what our current datestamp is from RTC
//  DateTime now = RTC.now();  // if using timeRTC lib, i think

  int nowHH = hour(t); int nowMM = minute(t); int nowSS = second(t);  // put into local variables for easier read

  if ((
        (nowHH>openHH)                        // check hours first
        || ((nowHH==openHH) && (nowMM>openMM))             // check minutes if in same hour
        || ((nowHH==openHH) && (nowMM==openMM) && (nowSS>=openSS))    // check seconds if in same hour & minute
      )
      &&                                  // both conditions must be valid
      (
        (nowHH<closeHH)                       // check hours first
        || ((nowHH==closeHH) && (nowMM<closeMM)))             // check minutes if in same hour
        || ((nowHH==closeHH) && (nowMM==closeMM) && (nowSS<=closeSS)) // check seconds if in same hour & minute
      )
  { return true; } else { return false; }
}

  // usage
  if (isOpenTime) {
    // ... do something, eg open door
  } else {
    // ... do something, eg close door
  }

byte startHour=8
byte startMinute=15
byte endHour= 14
byte endMinute= 20

byte startHour2=22
byte startMinute2=30
byte endHour2= 2
byte endMinute2= 45

void loop()
{
  DateTime now = RTC.now();  // Read in what our current datestamp is from RTC

  if (
    ( (now.hour()==startHour && now.minute()>= startMinute) || (now.hour()>startHour)
    && ( (now.hour()==endHour && now.minute()< endMinute) || (now.hour()<endHour) ) {
    validStart1 = 1;

  } else {
    validStart1 = 0;  //
  }

return validStart1; // Return the status for powering up
 }
}

Use the time in number of seconds total.
ontime=((sethour*60)+(setmin*60)+setsec);
offtime=((ofsethour*60)+(ofsetmin*60)+ofsetsec);
currenttime=((t.hour*60)+(t.min*60)+(t.sec);
if ((currenttime>ontime)&&(currenttime<offtime));
  {
  pumpon();
  }
else
  {
  pumpoff();
  }
delay(1000);

small correction ... one hour has 3600 seconds ... so ontime=((sethour3600)+(setmin60)+setsec);
offtime=((ofsethour3600)+(ofsetmin60)+ofsetsec);
currenttime=((t.hour3600)+(t.min60)+(t.sec);

A simple and effecient way is to use relative days and make use of the fact that the days, hours, minutes, and seconds are byte-sized data types that can fit into a single 32-bit data type.

byte 3
byte 2
byte 1
byte 0

Day
Hour
Minute
Second

This can be achieved with the following function:
constexpr uint32_t MakeTimestamp(const byte day, const byte hour, const byte minute, const byte second)
{
  // Pack the 4 individual bytes into a single 4-byte data type in order of precedence.
  return uint32_t(day) << 24 | uint32_t(hour) << 16 | uint32_t(minute) << 8 | uint32_t(second);
}

This 32-bit timestamp can be easily compared with other ones to test whether a timestamp is within a timespan:
bool WithinTimespan(const uint32_t& timestamp, const uint32_t& begin, const uint32_t& end)
{
  if (end < begin)
  {
    // Crossing midnight.
    return timestamp >= begin || timestamp <= end;
  }
  // Single day.
  return timestamp >= begin && timestamp <= end;
}

By using relative days to declare the motor start and stop times, the comparison takes care of the rollover to tomorrow:
const byte motor1_start_hour = 8;
const byte motor1_start_minute = 15;
const byte motor1_stop_hour = 14;
const byte motor1_stop_minute = 20;

const byte motor2_start_hour = 22;
const byte motor2_start_minute = 30;
const byte motor2_stop_hour = 2;
const byte motor2_stop_minute = 45;

const uint32_t motor1_start_time = MakeTimestamp(0, motor1_start_hour, motor1_start_minute, 0);
const uint32_t motor1_stop_time = MakeTimestamp(0, motor1_stop_hour, motor1_stop_minute, 0);

const uint32_t motor2_start_time = MakeTimestamp(0, motor2_start_hour, motor2_start_minute, 0);
const uint32_t motor2_stop_time = MakeTimestamp(0, motor2_stop_hour, motor2_stop_minute, 0);

Then the loop() is simply something like this:
void loop()
{
  const DateTime now = rtc.now();
  const uint32_t timestamp = MakeTimestamp(0, now.hour(), now.minute(), now.second());

  bool motor1_on = WithinTimespan(timestamp, motor1_start_time, motor1_stop_time);
  bool motor2_on = WithinTimespan(timestamp, motor2_start_time, motor2_stop_time);

  UpdateMotor1(motor1_on);
  UpdateMotor2(motor2_on);
}

I recommend you to read Majenko's answer

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

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


text:
Can anyone tell me about the onboard accelerometer of LightBlue Bean?
I would like to know the specs of the accelerometer used on a LightBlue Bean before buying one, but I couldn't find any info online. Anybody has an idea?

They seem to have a web site. How about asking on that?

There is a reference to the accelerometer datasheet from the Arduino Reference page

I would like to know the specs of the accelerometer used on a LightBlue Bean before buying one, but I couldn't find any info online. Anybody has an idea?

Start by checking the Adafruit LightBlue Bean product description. There you can find a link to the schematics and board layout. On page two there is accelerometer, a BMA250 just as @Jason links to.
That took "30 seconds" web search plus writing this answer :)
Cheers!


text:
Using Analog Comparator on ATmega32u4
I am (currently) parsing a PPM analog signal using an Arduino Uno R3 using the analog comparator ASCR and analog hardware interrupts using AIN0 and AIN1. I am applying a specific negative comparison voltage using a linear voltage regulator on AIN0 and the signal on AIN1.
Code snippets:
setup
  ACSR  = B00011011;

outside other closures
ISR(ANALOG_COMP_vect) {
   CRCArduinoPPMChannels::INT0ISR();
}

I am trying to move this project to an Arduino (compatible) Pro Micro from SparkFun. The datasheet specifies AIN0 on ATmega32u4 pin 1 but do not see a reference to AIN1.
The datasheet outlines use of the analog comparator on page 289:

AIN+ can be connected either to the AIN0 (PE6) pin, or to the internal
  Bandgap reference. AIN- can only be connected to the ADC multiplexer.

I have connected the signal to Arduino pin 7, the comparison voltage to Arduino pin 20 (analog 2) and set the following options of the ADMUX register:
ADMUX = B11000101;

The interrupts trigger but the comparator voltage (AIN-) is not being observed. Any help would be appreciated.

Did you forget to set ACME?

Yes! Setting ACME bit to 1 and ADEN to 0 did it. Thank you

3 years 9 months later, do you still happen to have your code handy by chance, would you mind to share the whole analog comparator setup please? (This is of course not an answer, sorry, I'm unable to just write a comment, I get "You must have 50 reputation to comment".)

Actually... I do. https://github.com/jjluebke/PigeonPPM/blob/master/PigeonPPM.ino

AIN- won't be connected to the ADC mux unless ACME is set and ADEN is cleared. Don't forget to do so.


text:
Question about include statements and details in Arduino.h file from core library
This is more of a C/C++ question. However the files I am asking about are a part of the Arduino library.
In /arduino-1.6.5-r5/hardware/arduino/avr/cores/arduino/Arduino.h :
#ifndef Arduino_h
#define Arduino_h

#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <math.h>

#include <avr/pgmspace.h>
#include <avr/io.h>
#include <avr/interrupt.h>

#include "binary.h"

#ifdef __cplusplus
extern "C"{
#endif

How are these blocks found at compile time in the main sketch?
#include <avr/pgmspace.h>
#include <avr/io.h>
#include <avr/interrupt.h>

Does #include <avr/somelibrary.h> mean that this is a standard library from either avr-g++ or avr-gcc? As opposed to a standard g++ or gcc compiler?
One last question, how can there be an Arduino.h without an Arduino.c? I searched through the project but could not find an Arduino.c. All of these are probably stupid questions, as I am in the process of learning C/C++. I am completely new to it.

why the two down-votes on this recently? And 3 months later...

Does #include <avr/somelibrary.h> mean that this is a standard library from either avr-g++ or avr-gcc? As opposed to a standard g++ or gcc compiler?

No. It simply means that the compiler should check both its built-in include paths as well as any passed via the -I command line option (or its local equivalent) for a file called "avr/somelibrary.h". That AVR GCC knows where AVR Libc is located is incidental.

One last question, how can there be an Arduino.h without an Arduino.c?

There is no obligation to match each header file with a .c/.cc/.cpp file, or vice versa.

So the function signatures within Arduino.h are defined by the libraries referenced, via the include statements shown in OP?

The headers referenced, yes.

Suppose there is an include in an include, so to speak. Would the header file pick up functions to the second level?

Does avr/someLibrary.h mean to that someLibrary.h is contained in a directory called avr?

@skywalker: That is correct.

Maybe there is no obligation to match a header file with a .c/.cc/.cpp file, but the functions have to exist somewhere when you call them

I think after all this time, you may found the answers for your question.
But to add some information to this topic incase if anyone opened this question.

Does #include  mean that this is a standard library
  from either avr-g++ or avr-gcc? As opposed to a standard g++ or gcc
  compiler?

Yes, what is included with avr/ is related to avr standard libraries, which is also found in avr standard compilers.

One last question, how can there be an Arduino.h without an Arduino.c?

Because, as Mr @Ignacio Vazquez-Abrams answered that there's no obligation for connecting the header file for anything else. You can write multiple header files and use them for one source file.


text:
Graph plotting on Processing from Arduino sensor data
I am trying to plot a graph on processing but I'm having challenges going about it. The processing sketch below does work for plotting only one axis, and I'm trying to plot all three axis on the same sketch. Does anyone have an idea on how I could go about it. Below are the Arduino and Processing sketches.
Arduino
AcceleroMMA7361 ski;
int x;
int y;
int z;

void setup()
{
   Serial.begin(115200);
   ski.begin(13, 12,11,10, A0, A1, A2);
   ski.setARefVoltage(3.3);
   ski.setSensitivity(HIGH);
   ski.calibrate();
}

void loop()
{
    x = ski.getXRaw();
    y = ski.getYRaw();
    z = ski.getZRaw();
   //Serial.print("\nx: ");
     Serial.println(x);
   //Serial.print("\ty: ");
   //Serial.print(y);
   //Serial.print("\tz: ");
   //Serial.print(z);
   delay(10);                                     //(make it readable)
}//End of Arduino Sketch

Processing
import processing.serial.*;

Serial myPort;        // The serial port
int xPos = 1;         // horizontal position of the graph

float fValue;
boolean newVal = false;

void setup () {
   size(800, 630);
   println(Serial.list());
   myPort = new Serial(this, Serial.list()[0], 115200);
   myPort.bufferUntil('\n');
   background(2);
   stroke(127, 34, 255);
}

void draw () {
    if (newVal) {
       line(xPos, height, xPos, height - fValue);
       if (++xPos >= width) {
         xPos = 0;
         background(2);
       }
       newVal = false;
    }
}

void serialEvent (Serial myPort) {
   String inString = myPort.readStringUntil('\n');
   if (inString != null) {
       inString = trim(inString);
       fValue = float(inString);
       fValue = map(fValue, 0, 1023, 0, height);
       newVal = true;
     }
}

I have edited your serialEvent() method a little bit, so it could handle the data from the Arduino, when split by a tab.
void serialEvent (Serial myPort) {
   String inString = myPort.readStringUntil('\n');

   if (inString != null) {
     values=split(inString,"\t");  //Splitting the output of the arduino into a String Array
     for(int i=0;i<values.length;i++){
       values[i]=trim(values[i]); //deleting the whitespaces as before
       float_values[i]=float(values[i]); //cast the string to a float as before
     }
       x = map(float_values[0], 0, 1023, 0, height); //map the value as before
       y = map(float_values[1], 0, 1023, 0, height);//map the value as before
       z = map(float_values[2], 0, 1023, 0, height);//map the value as before
       newVal = true;
     }
}

so your sending on the Arduino has to look like this:
void loop()
{
    x = ski.getXRaw();
    y = ski.getYRaw();
    z = ski.getZRaw();
    Serial.print("\n");
    Serial.print(x);
    Serial.print("\t");
    Serial.print(y);
    Serial.print("\t");
    Serial.print(z);
    delay(10);                                     //(make it readable)
}

You still have to make the drawing in the draw() method of processing, but I think that this is not the problem.
For the 3d draw you should have a look on the Processing reference or at this special topic, P3D by Daniel Shiffman.
I have not tested the code, but I think that it should work.
If you have questions, feel free to ask ;D

+1 - for taking the time to make the correction - however, you should test your code before posting it, as some people may just copy and paste the code without even thinking of testing it, which may have some unforeseen outcome.

There are two problems, why I have not tested my code: the first is, that I have no arduino avaible, because i have lend all of mine to the school for a group of robots acting together and the second reason is, that I have the final exams (i am from germany) in next tuesday


text:
Graph plotting on Python using Tkinter Canvas
I'm trying to plot a graph with python using the canvas widget, I'm currently sending data in from an arduino sensor sketch ..does anyone have an idea on how I can plot this graph in real time on Python using canvas. I've read up on it but I'm having problems with unpacking the x , y and z axis data and looping it to updating in real time. Below is the arduino sketch.And also the skeleton of the Tkinter canvas sketch. Thanks!!
AcceleroMMA7361 ski;
int x;
int y;
int z;

void setup(){
    Serial.begin(115200);
    ski.begin(13, 12,11,10, A0, A1, A2);
    ski.setARefVoltage(3.3);
    ski.setSensitivity(HIGH);
    ski.calibrate();
}

void loop(){
    x = ski.getXRaw();
    y = ski.getYRaw();
    z = ski.getZRaw();
    Serial.print("\nx: ");
    Serial.println(x);
    Serial.print("\ty: ");
    Serial.print(y);
    Serial.print("\tz: ");
    Serial.print(z);
    delay(10);                                     //(make it readable)
}//End of Arduino Sketch

  from Tkinter import *
  import serial #import Serial Library
  import numpy as np # Import numpy

  ardoData = serial.Serial('COM4', 115200)
  accelX1 = []     #to hold the incoming axis data from the arduino
  accelY1 = []
  accelZ1 = []

  class GraphException(Exception):
      def __init__(self, string):
         Exception.__init__(self, string)

  class Smoking(Canvas):
     def __init__(self, master, FrameTitle, Col, Row, Height):
        Canvas.__init__(self, master)
          self.FrameTitle = FrameTitle
          self.x1Axis = range(1001)
          self.y1Axis = range(1001)
          self.z1Axis = range(1001)
          self.Line1 = range(1001)
          self.Line2 = range(1001)
          self.Line3 = range(1001)
          self.configure(height=Height, width=750, bg='grey', bd=3, relief=GROOVE)
         self.grid()
         self.grid_propagate(0)
         self.Col = Col
         self.Row = Row
         self.place(y=Col, x=Row)
         self.create_text(380, 20, text=self.FrameTitle, fill = 'black')
         for i in range(0, 1001):
            self.Line1[i] = self.create_line(-10+(i*10), 90, 0+(i*10), 90, fill='blue', width=0)
            self.Line2[i] = self.create_line(-10+(i*10), 90, 0+(i*10), 90, fill='red', width=0)
            self.Line3[i] = self.create_line(-10+(i*10), 90, 0+(i*10), 90, fill='yellow', width=0)

     def LiveValues(self,accelX1, accelY1, accelZ1, Centerline = False, Dritter = False):
          for x in range(1, 59):
             for i in np.arange(1, 1001, 1):
                  while(ardoData.inWaiting() == 0):
                      pass #do nothing
                  ardoString = ardoData.readline()
                  dataArray = ardoString.strip().strip('\n')   #Split into an array called dataArray and strip off any spaces
                # Ensure that you are not working on empty line
               if ardoString:
                   dataArray = ardoString.split(",")
               if len(dataArray) > 1:
                   self.x1Axis = int(dataArray[0])
                   self.y1Axis = int(dataArray[1])
                   self.z1Axis = int(dataArray[2])
                   accelX1.append(self.x1Axis)
                   accelY1.append(self.y1Axis)
                   accelZ1.append(self.z1Axis)
              for x in range(0, 1001):
                 self.coords(self.Line1[x], -10+(x*10), self.accelX1[x], (x*10), self.accelX1[x+1])
                 self.coords(self.Line2[x], -10+(x*10), self.accelY1[x], (x*10), self.accelY1[x+1])
                 self.coords(self.Line3[x], -10+(x*10), self.accelZ1[x], (x*10), self.accelZ1[x+1])

   # Create and run the GUI
   root = Tk()
   app = Smoking(root, "Smooth Sailing", 1000, 1000, 1000)
   app.mainloop()

So after working with the answer given on the post I ended up with a Line graph that is not reactive, I understand that I have to tweak the code to suit the range of values I am getting which is shown below. I increased the limit as indicated by @patthoyts but I still couldn't get either lines to show up on the canvas and to even be reactive ( what i mean by that is to respond to the movement of the sensor). Also, do bear with me Editors!, if I'm going about editing this question the wrong way, is just that I'm quite desperate to have this issue resolved. Does anyone have any clue as to how I could resolve this issue. Thanks PS: I added both images , that of my data stream and the image on the canvas.

You should show at least part of your python code. Really this is not about arduino but about plotting a graph from a stream of 3 decimal numbers, 1 per line, output every 10 ms. Create a canvas and put a line on it. Read 3 lines and parse the numbers then convert into canvas coords and update the line configuration coords property.

@patthoyts.....please do bear in mind THIS is a NEWBIE alert!!!!! I have limited idea on how to go about it...The idea I had going was simply inculcated in this sketch below

To generate a useful example I've setup an Arduino Nano with a magnetic orientation sensor and have it output 3 values per line for the X, Y and Z field strengths. It prints 1 line every 50ms and the following python tkinter script plots this. It started as your python code above but it has been reworked to be more pythonic. The result looks like this:

Call the script with the comport and speed. eg: python magplot.py COM21 19200
#!/usr/bin/python
#
# Read stream of lines from an Arduino with a magnetic sensor. This
# produces 3 values per line every 50ms that relate to the orientation
# of the sensor. Each line looks like:
# MAG   1.00    -2.00   0.00
# with each data line starting with "MAG" and each field separated by
# tab characters. Values are floating point numbers in ASCII encoding.
#
# This script supports both Python 2.7 and Python 3

from __future__ import print_function, division, absolute_import
import sys
if sys.hexversion > 0x02ffffff:
    import tkinter as tk
else:
    import Tkinter as tk
from serial import Serial

class App(tk.Frame):
    def __init__(self, parent, title, serialPort):
        tk.Frame.__init__(self, parent)
        self.serialPort = serialPort
        self.npoints = 100
        self.Line1 = [0 for x in range(self.npoints)]
        self.Line2 = [0 for x in range(self.npoints)]
        self.Line3 = [0 for x in range(self.npoints)]
        parent.wm_title(title)
        parent.wm_geometry("800x400")
        self.canvas = tk.Canvas(self, background="white")
        self.canvas.bind("<Configure>", self.on_resize)
        self.canvas.create_line((0, 0, 0, 0), tag='X', fill='darkblue', width=1)
        self.canvas.create_line((0, 0, 0, 0), tag='Y', fill='darkred', width=1)
        self.canvas.create_line((0, 0, 0, 0), tag='Z', fill='darkgreen', width=1)
        self.canvas.grid(sticky="news")
        self.grid_rowconfigure(0, weight=1)
        self.grid_columnconfigure(0, weight=1)
        self.grid(sticky="news")
        parent.grid_rowconfigure(0, weight=1)
        parent.grid_columnconfigure(0, weight=1)

    def on_resize(self, event):
        self.replot()

    def read_serial(self):
        """
        Check for input from the serial port. On fetching a line, parse
        the sensor values and append to the stored data and post a replot
        request.
        """
        if self.serialPort.inWaiting() != 0:
            line = self.serialPort.readline()
            line = line.decode('ascii').strip("\r\n")
            if line[0:3] != "MAG":
                print(line) # line not a valid sensor result.
            else:
                try:
                    data = line.split("\t")
                    x, y, z = data[1], data[2], data[3]
                    self.append_values(x, y, z)
                    self.after_idle(self.replot)
                except Exception as e:
                    print(e)
        self.after(10, self.read_serial)

    def append_values(self, x, y, z):
        """
        Update the cached data lists with new sensor values.
        """
        self.Line1.append(float(x))
        self.Line1 = self.Line1[-1 * self.npoints:]
        self.Line2.append(float(y))
        self.Line2 = self.Line2[-1 * self.npoints:]
        self.Line3.append(float(z))
        self.Line3 = self.Line3[-1 * self.npoints:]
        return

    def replot(self):
        """
        Update the canvas graph lines from the cached data lists.
        The lines are scaled to match the canvas size as the window may
        be resized by the user.
        """
        w = self.winfo_width()
        h = self.winfo_height()
        max_X = max(self.Line1) + 1e-5
        max_Y = max(self.Line2) + 1e-5
        max_Z = max(self.Line3) + 1e-5
        max_all = 200.0
        coordsX, coordsY, coordsZ = [], [], []
        for n in range(0, self.npoints):
            x = (w * n) / self.npoints
            coordsX.append(x)
            coordsX.append(h - ((h * (self.Line1[n]+100)) / max_all))
            coordsY.append(x)
            coordsY.append(h - ((h * (self.Line2[n]+100)) / max_all))
            coordsZ.append(x)
            coordsZ.append(h - ((h * (self.Line3[n] + 100)) / max_all))
        self.canvas.coords('X', *coordsX)
        self.canvas.coords('Y', *coordsY)
        self.canvas.coords('Z', *coordsZ)

def main(args = None):
    if args is None:
        args = sys.argv
    port,baudrate = 'COM4', 115200
    if len(args) > 1:
        port = args[1]
    if len(args) > 2:
        baudrate = int(args[2])
    root = tk.Tk()
    app = App(root, "Smooth Sailing", Serial(port, baudrate))
    app.read_serial()
    app.mainloop()
    return 0

if __name__ == '__main__':
    sys.exit(main())

Update
Looking at the updated question it is clear that the new Tkinter code is not updating the display. In all windowing systems it is essential that the application thread is allowed to process events regularly. This is why the example code above uses the Tk after() method to add calls to the event queue. The read_serial() function checks to see if any data is available and if not schedules a retry later. This is done by using after() to request the same method is called again in 10ms time. During that 10ms delay the Tk application processes all the other windowing system events like mouse movement, keyboard input and crucially expose and painting events.
The same method is used to call the replot() method once we have updated the list of data items. In this case after_idle() has been used which means schedule this function call as soon as nothing else is happening.
The act of changing the canvas line coordinates will cause further events to be raised by Tk which affect the display only once they are processed by the event loop. If we never process the events, nothing will appear on screen.

I suggest adding some print() statements in read_serial to check you are reading values and splitting them right. Then check the scaling in replot. I've offset by 100 and scaled to 200 so the values must be -100 < x < 100. If your values lie outside that range they'll be offscreen. You could use max_all = max([max_X, max_Y, max_Z]) to range dynamically.

@pattyhoyts from your update, I garner that even though the structure of the sketch is correct, it's compilation/execution is the problem . Would you advise I continue to find ways for it to work on my system (Windows) or ditch it for something else?


text:
Johnny Five LCD: black boxes only
I posted this also at Stack Overflow. I have tested the Johnny Five LED example on my Arduino Uno, and it worked fine. Now I need to test Johnny Five LCD. I connected all wires correctly.

The code:
var five = require("johnny-five"), board, lcd;

board = new five.Board();
board.on("ready", function() {
  lcd = new five.LCD({
    // LCD pin name  RS  EN  DB4 DB5 DB6 DB7
    // Arduino pin # 7    8   9   10  11  12
    pins: [7, 8, 9, 10, 11, 12],
    backlight: 6,
    rows: 2,
    cols: 20
    // Options:
    // bitMode: 4 or 8, defaults to 4
    // lines: number of lines, defaults to 2
    // dots: matrix dimensions, defaults to "5x8"
  });

  // Tell the LCD you will use these characters:
  lcd.useChar("check");
  lcd.useChar("heart");
  lcd.useChar("duck");

  // Line 1: Hi rmurphey & hgstrp!
  lcd.clear().print("rmurphey, hgstrp");
  lcd.cursor(1, 0);

  // Line 2: I <3 johnny-five
  // lcd.print("I").write(7).print(" johnny-five");
  // can now be written as:
  lcd.print("I :heart: johnny-five");

  this.wait(3000, function() {
    lcd.clear().cursor(0, 0).print("I :check::heart: 2 :duck: :)");
  });

  this.repl.inject({
    lcd: lcd
  });
});

But it doesn't output as expected. It is showing one row of black boxes only. what have I missed?

Look at this answer here: http://arduino.stackexchange.com/a/17472/11174 . I'm still studying about it, otherwise I would've posted more.

Try changing the resistance in your 10k potentiometer. This might be a reason for the black boxes.
P.S: I.m a beginner too.


text:
avrdude: ser_open(): can't open device "\\.\COM4": Access denied
I installed the new IDE Environment 1.6.6 and I got this error when compiling a program. I am using an Arduino Uno
avrdude: ser_open(): can't open device "\\.\COM4": access denied

I need your help.

finnaly, it works after restarting my computer

If you have solved the issue, please post the solution as an answer.

I think you used "Eclipse" and "Arduino" at the same time. so, I guess that a "com4 Port" conflict has occurred and the upload could not was done.

restart  your computer and try to open "Arduino" first and upload. not open "Eclipse" at the same time.

I had this very same issue. I solved the problem by shutting down my outside cameras. Once cameras were off (the software) the program worked. It was the camera software that was using the port.
So if you have a lot of other software or equipment running in the background this may be your problem. Just try shutting down things one at a time. That's what I did until I found that the camera software was my problem.


text:
I2C — set int pin
I am using a blend micro board, where the digital pins 4, 6 and 7 are reserved.
I have connected a MPU6050 which uses the I2C protocol, so there is the need for the i2cdev lib to handle that.
The example I am using tells me to use pin 7 as int pin for the mpu6050, but that is not possible, since it is reserved.
Does anybody know how I could set this Pin to some other?
Thanks in Ahead!

Could you link to your example? The only other hardware interrupt pins on the ATMega32u4 are 0,1,2 and 3 (RX, TX, SDA SCL). So 2 and 3 are not available. That leaves 0, and 1, unless you are using serial for some other module. But maybe the example doesn't necessarily need a hardware interrupt pin at all.

All I want to setup is based on this project https://edtracker.org.uk/index.php

this is the very template I am using https://github.com/brumster/EDTracker2/blob/master/EDTracker2_6050/EDTracker2_6050/EDTracker2_6050.ino

board setup here: https://edtracker.org.uk/index.php/diy/build-it/breadboard

You need to change the code in that project. Change INT6 to e.g. INT2 if you  are using pin 0 instead.

@Gerben Could you please drop a line of code that shows that? I guess that is what I am looking for…

Change EIMSK &= ~(1 << INT6);, EIMSK |= (1 << INT6);, and ISR(INT6_vect) { from 6 to 2.


text:
How to use Due PB0-PB7 pins as an external interrupt
In my board I need to use PB0-PB7 ports as an external interrupt sources.
Is it possible?
I spent a lot of time to understand that. Seems the easiest way is to update variant.cpp file by adding these pins.
Unfortunately this is not the solution I'm looking for (actually this can be a solution if I'm able to add pins from the sketch, but it is not possible to update cons dynamic array after declaration ).
Another way is to create my own interrupt handler. But I didn't find how should I do that.


text:
How to build a high-frequency (>20kHz) driver for LEDs?
I'd like to build a LED lighting for my house. I've made preliminary tests and I've realized that my 12V transformer emits a considerable electric hum at the Arduino's PWM frequency range (PWM signal from Arduino gets amplified by external amplifier powered by the transformer).
I know, that I can reduce the audible noise if I will drive the PWM at higher frequency, beyond the human ear's audible range.
AFAIK Arduino itself is not able to give me 8-bit PWM at the >20kHz range. Do you know any feasible hardware high frequency PWMs that will work with the Arduino?

An "amplifier" for a PWM signal need not be more than an nFET, and the PWM signal should not couple into the power the nFET switches.  Ie, there may be some problem with your design other than the PWM frequency.  Perhaps ask on electronics SE about the circuit design

"AFAIK Arduino itself is not able to give me 8-bit PWM at the >20kHz range." Yes it is. 16MHz / 256 = 62.5kHz

I am not into hardware but the way we handle it was by using a external PWM designed for LEDs and control that, using an Arduino. The LED driver we used was a TLC5940, see TLC5940 16-Channel LED Driver With DOT Correction and Grayscale PWM Control. This one is controllable using the SPI bus.
There are several libaries implementing the protocol, i.e PaulStoffregen/Tlc5940.
See Playground from Arduino - TLC5940 for more information.

Actually this is the one, I settled to use. I got one from China for ca. $10.

Just change the timer prescaler to a lower value.
E.g. timer2 (PWM pins 3 and 11) has the prescaler set to clock/64 and runs at around 500Hz. So changing it to clock/8 will result in 4kHz. (Sorry, no clock/16 available).
TCCR2 &= ~_BV(CS22);//clear CS22 bit
TCCR2 |= _BV(CS21);//set CS21 bit


text:
Having problems with HC-05 and three relays
I'm trying to control three relays with the Arduino Uno rev3 and a HC-05 bluetooth module from Elecfreaks.
I've wrote this code:
// the comments are the part of the code that I use to replace the Serial by default to be able to use the HC-05 module
//#include <SoftwareSerial.h>
int relay1 = 2;
int relay2 = 3;
int relay3 = 4;
int relay1estatus = 0;
int relay2estatus = 0;
int relay3estatus = 0;
char command;
//SoftwareSerial bluetooth(5,6);

void setup() {
 Serial.begin(9600); //bluetooth.begin(9600);
 pinMode(relay1, OUTPUT);
 pinMode(relay2, OUTPUT);
 pinMode(relay3, OUTPUT);
 digitalWrite(relay1, LOW);
 digitalWrite(relay2, LOW);
 digitalWrite(relay3, LOW);
}

void loop() {
 while(Serial.available() > 0){ //bluetooth.available()
  command = (byte)Serial.read(); //(byte)bluetooth.read();
  Serial.println(command); //bluetooth.println(command)

  if (command == 'a'){
   if (relay1estatus == 0){
    digitalWrite(relay1, HIGH);
    relay1estatus = 1;
   }else{
    digitalWrite(relay1, LOW);
    relay1estatus = 0;
   }
  }

 if (command == 'b'){
  if (relay2estatus == 0){
   digitalWrite(relay2, HIGH);
   relay2estatus = 1;
  }else{
   digitalWrite(relay2, LOW);
   relay2estatus = 0;
  }
 }

 if (command == 'c'){
  if (relay3estatus == 0){
   digitalWrite(relay3, HIGH);
   relay3estatus = 1;
  }else{
   digitalWrite(relay3, LOW);
   relay3estatus = 0;
   }
  }
 }
}

The problem is that this code works perfectly using the Arduino IDE serial monitor, but when I try it using instead of the default serial methods, the SoftwareSerial ones it doesn't work.
Doesn't work in a very strange way because I can switch one by one the relays between on or off but, when I have two of them activated seems like freezes, I can't switch the third one on or off and neither I can switch the other two again.
To send the 'commands' through bluetooth I use the Bluetooth Terminal app available in the PlayStore.
(I've just posted the same question in stackoverflow but now I think here's the best place to ask it)

I don't see a problem with the code indicated for bluetooth; if that code is indeed ok, then probably you should look for hardware issues;  first, look for low +5V when multiple relays are turned on.  (Attach a voltmeter or a scope to +5, see if it changes when a second relay comes on, etc.)  Second, look (with a storage scope) for glitches when the relays switch.  If you don't have a storage scope, try testing with a separate power supply for the relays.  (Tie the grounds of things together, but give the Arduino and the HC-05 +V that's isolated from relay +V.)
More seriously, your code is overweight.  For example, replace
   if (relay1estatus == 0){
    digitalWrite(relay1, HIGH);
    relay1estatus = 1;
   } else {
    digitalWrite(relay1, LOW);
    relay1estatus = 0;
   }

with
    relay1estatus = 1 - relay1estatus;
    digitalWrite(relay1, relay1estatus);

Thanks a lot! This issue have been driving me mad for some days because I was sure it wasn't a software problem.. also I had the module connected at 3V and that cause some problems with the power as I saw, so I've connected the relays and the bluetooth in  parallel to 5V and I've also added two capacitors just in case.


text:
Error in sending AT commands in esp8266 connecting to arduino IDE
I am working on esp8266 with Arduino.
I have connected pins like arduino-esp 3.3-vcc
gnd-gnd 3.3-CH_PD RX-TX TX-RX  and reset to gnd using 3k resistor.
I couldn't send AT commands in serial monitor in Arduino IDE.
Later I connected a capacitor between Vcc and Gnd. Now I could send AT commands and I am getting same commands back. Whatever I entered, I am getting the same back.
I didn't get reply as OK. And I got some random characters too. Can anyone help me with this?

I think TX needs to go to TX and RX to RX, if you are sending the command via the computer instead of the arduino-sketch. You also need to convert the 5v to 3.3v on the RX line.

You also need to convert the 5v to 3.3v on the RX line. - s/he needs to do what?

I have connected pins like arduino-esp 3.3-vcc gnd-gnd 3.3-CH_PD RX-TX TX-RX and reset to gnd using 3k resistor. - you connected what to what? This is very unclear. Please edit your question and clarify what you have done. Also try to write proper English if possible. Sentences start with a capital letter.

Looks like your connection is somewhere missing.
Connect CH_PD and reset pin to high--i.e. 3.3v.

Please do not insert advertisements into your post. You are welcome to add this to your profile page, but not into the post itself. I've edited it out. Thanks!

I made the following connection with Arduino Mega 2560 and AT commands was working perfectly well.
Connection:
ESP8266 - Arduino Mega 2560
Vcc, CH_PD, RST - 3.3V pin
GND - GND
Rx - Tx(18)
Tx - Rx(19)
Program:
void setup() {
  Serial.begin(115200);   // USB serial port of Due (PROGRAMMING)
  Serial1.begin(115200);  // ESP8266 on Serial Port 1 of Due (UART 1)
}

char rx_byte = 0;

void loop() {
  // send terminal byte to ESP8266
  if (Serial.available() > 0) {
    rx_byte = Serial.read();
    Serial1.print(rx_byte);
  }
  // send ESP8266 byte to terminal
  if (Serial1.available() > 0) {
    rx_byte = Serial1.read();
    Serial.print(rx_byte);
  }
}

Select Tools>Board> Arduino/Genuino Mega or Mega 2560. Upload the code. In serial monitor, select 115200 baud rate and Both NL & CR option.
Enter the AT command and it works!


text:
Error in my Arduino code " error: expected unqualified-id before ‘if’ "
I cant seem to find this error is:
elevator_bug_2.ino:38:1: error: expected unqualified-id before ‘if’

Here is the code:
// these constants won't change. They are the
// lowest and highest readings you get from your sensor:
const int sensorMin = 0;      // sensor minimum, discovered through experiment
const int sensorMax = 600;    // sensor maximum, discovered through experiment

void setup() {
  // initialize serial communication:
  Serial.begin(9600);
}

void loop() {
  // read the sensor:
  int sensorReading = analogRead(A0);
  // map the sensor range to a range of four options:
  int range = map(sensorReading, sensorMin, sensorMax, 0, 3);

  // do something different depending on the
  // range value:
  switch (range) {
    case 0:    // your hand is on the sensor
      Serial.println("dark");
      break;
    case 1:    // your hand is close to the sensor
      Serial.println("dim");
      break;
    case 2:    // your hand is a few inches from the sensor
      Serial.println("medium");
      break;
    case 3:    // your hand is nowhere near the sensor
      Serial.println("bright");
      break;
  }
  delay(1);        // delay in between reads for stability
}

if (Serial.println("dark") == true)   // LINE 38
{

int led = 9;           // the PWM pin the LED is attached to
int brightness = 0;    // how bright the LED is
int fadeAmount = 5;    // how many points to fade the LED by

// the setup routine runs once when you press reset:
void setup() {
  // declare pin 9 to be an output:
  pinMode(led, OUTPUT);
}

// the loop routine runs over and over again forever:
void loop() {
  // set the brightness of pin 9:
  analogWrite(led, brightness);

  // change the brightness for next time through the loop:
  brightness = brightness + fadeAmount;

  // reverse the direction of the fading at the ends of the fade:
  if (brightness == 0 || brightness == 255) {
    fadeAmount = -fadeAmount ;
  }
  // wait for 30 milliseconds to see the dimming effect
  delay(30);
}
}

Check where the function loop() ends. Seems likes there is a } too many or a function declaration is missing.

C is procedural language and code is compiled. You cannot put code beyond procedure as you try to do in mentioned if. Remaining code following this point is nonsense. Do you mean you can put second loop() based on if condition ? I recommend to start learning programming C before using Arduino. In C you can do such a idea using preprocessor directives IF, ELSE, ENDIF.

As Tma mentioned earlier, C is a procedural language. That means that all the code must be part of a defined function. So in your code you have the functions void loop() and void setup(). Wich are two functions you must always have in an arduino sketch, but you can also define others. What you cannot do is having two functions with the same name and type in C like you have there, because there is no way to tell them apart from each other. You have two functions called loop and setup...
One basic thing about Arduino code that you must know is the way it runs your code. Every arduinos sketch must have a setup and a loop function. Then when you start the program, it wil first execute the code in your setup function ONCE and then start at your loop function. The name of the loop function already indicates that it will LOOP all the code inside it, so when your program reaches the end of loop() is starts again at the top of loop(). Your program will never reach any point below loop, because you need to specifically call a function to redirect your program to another point. I think the best way to learn Arduino is to study some C first.


text:
I2C send and read 2 bytes many slave
I've already sent you the code but you told me to format it, so I tried this way ..
the problem I got is it doesn't read good the 2 slave (sender) to the master
(reader) ...you told me LAST TIME (DON'T DO SERIAL PRINTLN IN THE CALLBACK
ROUTINE) so I tried this code (I've got some data from both but not in order)
here's the slave 1 and 2 code (I only change the  slavedeviceId address)
#include "Wire.h"

//
// i2c_test_01

//
// This demonstrates a master transmitting to a slave.
//

// The master transmits a value read from an analogue port.

// The slave sends the value to the serial device.
//

byte x = 0;
//
const byte AnalogueInputPin = 0;

const byte SlaveDeviceId = 2;

void setup() {
  // Start I2C bus as master
  Wire.begin();
}

void loop() {
  int input0 = analogRead(x);
  // Send two bytes to slave.
  Wire.beginTransmission(SlaveDeviceId);
  Wire.write(input0 >> 8);
  Wire.write(input0 & 255);
  Wire.endTransmission();

  delay(10);

  x++;
  if (x == 4) {
    x = 0;
  }

  delay(40);

}

here's the master (reader)
thanks for your time it is realy intructive for me !!!
#include "Wire.h"

const byte SlaveDeviceId = 1;
const byte SlaveDeviceId2 = 2;
int S1;
int S2;
int c;
int cc;

void setup() {
  // Start I2C bus as a slave
  Wire.begin();
  Wire.onReceive(receiveCallback);
  Serial.begin(9600);
}

void SLAVEone() {
  Wire.begin(SlaveDeviceId);
  delay(5);
  Wire.onReceive(receiveCallback);
  delay(5);
}

void SLAVEtwo() {
  Wire.begin(SlaveDeviceId2);
  delay(5);
  Wire.onReceive(receiveCallback2);
  delay(5);
}

void receiveCallback(int aCount) {
  if(aCount == 2) {
    int receivedValue  = Wire.read() << 8;
    receivedValue |= Wire.read();
    //Serial.print(c);
    //Serial.print(" S1 = ");
    //Serial.println(receivedValue);
    S1 = receivedValue;
  } else {
    Serial.print("Unexpected number of bytes received: ");
    Serial.println(aCount);
  }
  c++;
  if (c == 4) {
    c = 0;
  }
}

void receiveCallback2(int aCount2) {
  if (aCount2 == 2) {
    int receivedValue2  = Wire.read() << 8;
    receivedValue2 |= Wire.read();
    // Serial.print(cc);
    //Serial.print(" S2 = ");
    //Serial.println(receivedValue2);
    S2 = receivedValue2;
  } else {
    Serial.print("Unexpected number of bytes received: ");
    Serial.println(aCount2);
  }
  cc++;
  if (cc == 4) {
    cc = 0;
  }
}

void loop() {
  for(int y = 0; y <= 3; y++) {
    SLAVEone();
    Serial.print(c);
    Serial.print(" = S1 = ");
    Serial.println(S1);
    delay(10);
  }
  for(int y = 0; y <= 3; y++) {
    SLAVEtwo();
    Serial.print(cc);
    Serial.print(" = S2 = ");
    Serial.println(S2);
    delay(10);
  }
}

I have formatted your code, without changing anything else.
Please take a moment to check how it is done. Just hit edit on your question.

Don't do serial prints in an ISR (callback).

There are so many mistakes in your code. I'll do my best to correct them using comments. The code for the slaves should be as follows:
#include "Wire.h"

//
// i2c_test_01

//
// This demonstrates a master transmitting to a slave.
//

// The master transmits a value read from an analogue port.

// The slave sends the value to the serial device.
//

int inp = 0;  // input pin

const byte SlaveDeviceId = 2;

void setup() {
  Wire.begin(SlaveDeviceId);  // here the slave joins the bus, with its address as argument to begin()
  Wire.onRequest(callback);  // here you indicate what the slave should do if a bus master queries it
}

void callback() {
  int input0 = analogRead(inp);
  // Send two bytes to master
  Wire.write(input0 >> 8);
  Wire.write(input0 & 255);

  inp++;
  if (inp == 4) {
    inp = 0;
  }

}

void loop(){}

This is the master's code:
#include "Wire.h"

const byte SlaveDeviceId = 1;
const byte SlaveDeviceId2 = 2;
char inputDev = 4;  // number of devices connected to slave analog inputs

void setup() {
  Wire.begin();   // no argument here since its a master
  Serial.begin(9600);
}

//the onReceive() method is for slaves receiving from a master, so we dont use it here

void loop() {
  Serial.println("\r\nSlave 1: ");
  for (char i = 0; i < inputDev; i++){
    Wire.requestFrom(SlaveDeviceId, 2);
    delay(1);  // more than enough time for all the data to come in
    int val = Wire.read() << 8;
    val |= Wire.read() & 0xFF;
    Serial.print(val);
    Serial.print(",");
  }
  Serial.println("\r\nSlave 2: ");
  for (char i = 0; i < inputDev; i++){
    Wire.requestFrom(SlaveDeviceId2, 2);
    delay(1);  // more than enough time for all the data to come in
    int val = Wire.read() << 8;
    val |= Wire.read() & 0xFF;
    Serial.print(val);
    Serial.print(",");
  }

}

I don't quite see how your code is supposed to work.  It seems like your "slave" devices are trying to write to your "master" as if they were master devices not slaves, and your "master" is rapidly switching between thinking it is one of two slaves. The whole methodology is backwards.  The "master" should connect to a "slave" and request the data not wait for a "slave" to randomly throw data at it.


text:
IR receiver transmitter High frequency
I build photo gate, to detect throwing ball.
It works fine when delay time in main loop for max 40 milliseconds.
Problems start when I delay every loop only for 20 milliseconds, now my LED which indicates if something broke path between IR led and IR receiver, blinks occasionally, if I set delay for 10 milliseconds and turn on, then LED is off for 2 seconds, then start blinking very fast and is ON for rest time, until I break IR path. I think some physics is going on here which I don't understand.
I also would like to ask if it is possible to narrow IR wave path to be more like laser (going strait into one direction) and how I can control sensitivity of IR detection
This is schematic
IR transmiter
IR reciever
Code:
//define pins. I used pins 4 and 5
#define irLedPin 4          // IR Led on this pin
#define irSensorPin 5       // IR sensor on this pin
#define buzzerPin 2       // buzzer on this pin

int irRead(int readPin, int triggerPin); //function prototype

void setup()
{
  pinMode(irSensorPin, INPUT);
  pinMode(irLedPin, OUTPUT);
  pinMode(buzzerPin, OUTPUT);
  Serial.begin(9600);
  // prints title with ending line break
  Serial.println("Program Starting");
  // wait for the long string to be sent
  delay(100);
}

void loop()
{

  bool isOn = irRead(irSensorPin, irLedPin);
  //Serial.println(isOn); //display the results
  if(isOn == true)
  {
    digitalWrite(buzzerPin, HIGH);
  }
  else
  {
     digitalWrite(buzzerPin, LOW);
  }
  delay(10);
}

int irRead(int readPin, int triggerPin)
{
  int halfPeriod = 13; //one period at 38.5khZ is aproximately 26 microseconds
  int cycles = 23; //26 microseconds * 23 is more or less 600 us
  int i;
  for (i=0; i <=cycles; i++)
  {
    digitalWrite(triggerPin, HIGH);
    delayMicroseconds(halfPeriod);
    digitalWrite(triggerPin, LOW);
    delayMicroseconds(halfPeriod - 1);     // - 1 to make up for digitaWrite overhead
  }
  return digitalRead(readPin);
}

You can get IR laser diodes if you want a beam.

Or you can use red laser beam and use that as a IR source.

@Avamander, wow that's strange, I just checked and it works, but how? my red laser has 570 nm and IR reciver 950nm and it works, how ?

The laser has close enough wavelength, the same thing works with red LEDs too.

While you are doing a delay() you can't be doing anything else - that includes looking to see if the beam has been broken by the ball.
You must not use delay() in your sketch, instead use millis() as in the BlinkWithoutDelay example sketch in the IDE's File -> Examples menu.
Also how you are dealing with your IR system is incorrect.  You are first generating a brief square wave and then afterwards you are looking to see what was received.  Instead you need to be generating the square wave and at the same time see if that square wave is being received.  Normally that is achieved by using one of the PWM outputs of the Arduino set to the right frequency to generate a constant waveform which the receiver then senses all the time.


text:
Using Arduino UNO as FTDI programmer for 9DOF Razor IMU
I am trying to upload some code to the ATmega328 on Sparkfun's 9DOF Razor IMU. Because I don't have an FTDI board at hand I was trying to use my UNO by "grounding" the RESET pin. Communicating with the 9DOF works well (it has some sample firmware loaded):

So here's the problem:
When I try to program the ATmega328, the Arduino IDE gives e the following error:
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x0d

What am I doing wrong?

What you're missing is the signal that resets the ATMega so it can enter the bootloader.  That signal is the one that goes to the DTR pin of the 9DOF and would normally be sent to the reset pin on your Arduino (that you are grounding).
What you need to do is reset the 9DOF just as it's about to start trying to upload the code.  Timing is critical - you get about a second or so of leeway where the bootloader is actually available for avrdude to talk to.
Alternatively you can try and find a point on your Arduino board where the DTR signal from the USB interface chip is available before it passes through the capacitor to the RESET pin of the Arduino and take a wire from there (wherever that may be) to the DTR pin of the 9DOF.

Perfect, thank you for the quick answer! I  won't get around to trying anything, but I'll verify it as soon as I can! Thanks again!

I simply removed the ATMega and connected RESET and DTR, works well! Thanks again!


text:
Why won't the slide switches control the motor in this 123d simulation?
int guard = 7;
int switchPin = 6;
int motorPin = 9;

void setup(){
  pinMode(guard,INPUT);
  pinMode(switchPin,INPUT);
  pinMode(motorPin,OUTPUT);
}

  void loop(){
   if (digitalRead(guard==HIGH)&&digitalRead(switchPin==HIGH))              //&&

   {

     digitalWrite(motorPin,HIGH);
    delay(500);
    digitalWrite(motorPin,LOW);
    delay(1000);
   }
        else {

     digitalWrite(motorPin,LOW);
   }

  }

This should be written like this:
if ( digitalRead(guard)==HIGH && digitalRead(switchPin)==HIGH ) {

// Rest of the code..

}


text:
The difference between "time_t" and "DateTime"
I've run into an issue trying to combine 2 different Arduino timer projects I've found online.
For both projects I'm using a DS3231 RTC, but have been able use the DS1307 library just fine in my code.
The first set of code I picked up started with:
#include <DS1307RTC.h>

The second set of code I tried to combine did not have this 'include', but instead used
RTC_DS1307 RTC;

as found here:
https://learn.adafruit.com/ds1307-real-time-clock-breakout-board-kit/understanding-the-code
As a novice coder, I'm not really sure what the difference between the above two ways to call this library. But I do know the first way using "include", if I want to access the current time on the RTC I use
RTC.get();

as opposed to the second method which requires:
RTC.now();

And while it was easy to find documentation to sync the RTC to computer time over the USB cable using this handy bit of code:
// Notify if the RTC isn't running
    if (! RTC.isrunning()) {
    Serial.println("RTC is NOT running");
  }

   // Get time from RTC
  DateTime current = RTC.get();
  DateTime compiled = DateTime(__DATE__, __TIME__);
  if (current.unixtime() < compiled.unixtime()) { //CHECKS AGAINST COMPUTERTIME
    Serial.println("RTC is older than compile time! Updating");
    RTC.adjust(DateTime(__DATE__, __TIME__));  //UPDATES FROM COMPUTER IF OLD TIME IS OFF
  }

I can find no easy alternative using "#include DS1307RTC"
I first thought that the difference between RTC.now() and RTC.get() was just a matter of word substitution. But later on when I want to use a "time_t" call after initializing with "RTC_DS1307 RTC;"
 time_t timeNOW = RTC.now();

I get the error "cannot convert 'DateTime' to 'time_t {aka long unsigned int}' in initialization"
So I'm assuming one method uses "DateTime" and one method uses "time_t". But I'm not sure if this is the case, and if so, how to convert a "DateTime" value to a "time_t" value.
I have two goals in writing this post.
1- Can someone please explain to me the difference between "#include DS1307RTC.h" and "RTC_DS1307 RTC;" and how it impacts my code.
2- I'd like to stick with using ""RTC_DS1307 RTC;", only because it seems easy to sync my RTC to my computer. But if I do, I get the above error. So can someone please tell me how to convert a "RTC now()" call to a "time_t" value? Or is the issue more complicated than just a mere conversion between data types?

A DateTime is a full class with lots of methods to it - a time_t is just an unsigned long.
time_t is used to store the number of seconds since the epoch (normally 01/01/1970)
The Arduino Time library returns a time_t to the now() function - but RTCLib return s a DateTime object.
The DateTime object, though, has a unixtime() method which will return a time_t representation of the time stored in the DateTime object.
So you can do:
DateTime dt = RTC.now();
time_t time = dt.unixtime();


text:
Interfacing Arduino UNO with TFT LCD and WiFi Shield
I'm trying to interface my Arduino UNO with both a 1) TFT LCD screen and 2) WiFi Breakout board/shield.
The WiFi breakout board uses many of the same Digital pins as the LCD screen so is it possible for the arduino to interface with both devices simultaneously?
I also noticed that the shield goes over the arduino, but covers the header pins. Does this mean that I can't use these pins?
I've never worked with shields or breakout boards and would like some advice before I purchase either component.
If neither of these solutions will work, please provide me with alternate methods.
Your time/feedback is greatly appreciated :)
-Vip

This isn't a very well matched selection of parts - even if you get the wiring to work (there are probably ways) both an LCD display and wifi tend to need a fair amount of RAM to use effectively, and your Uno has a mere 2048 bytes which will require very careful budgeting.  You would do much better with a processor having both more memory as well as more pins.

I agree with Chris on this. The uno is limited where it comes to pins and and ram, you should probably look at a mega, or similar.
As far as running both at once, i don't think it would be possible with the uno, with the ram limitations, as well as pin limitations, you'll be hard pressed to get them going at the same time, within the same sketch.
While technically it is possible to use alternative pins, i doubt there will be enough unused pins to shift an entire shield over to on the Uno
If you're looking for a cheaper rout, you may look at adding a secondary Uno to run the wifi, and send any data you need displayed to the uno running the tft via serial coms.

Thank you both for the great feedback. @ArcAIN6 Is there a link to a tutorial where I can interface two Uno's like you mentioned?
Thanks again.


text:
Instead of 1 and 0, make display say On or Off
So for my project, I am making a button that turns on and off an LED, but also display the state of the led on an LCD and by Serial.  But my issue is, I don't want it to just show a 0 or a 1, I want it to say On or Off.
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

int inPin = 22;         // the number of the input pin
int outPin = 13;       // the number of the output pin

int state = HIGH;      // the current state of the output pin
int reading;           // the current reading from the input pin
int previous = LOW;    // the previous reading from the input pin

// the follow variables are long's because the time, measured in miliseconds,
// will quickly become a bigger number than can be stored in an int.
long time = 0;         // the last time the output pin was toggled
long debounce = 200;   // the debounce time, increase if the output flickers

void setup(){
    // set up the LCD's number of columns and rows:
    lcd.begin(16, 2);
    // Print a message to the LCD.
    lcd.print("System Activated");
    //
    lcd.setCursor(0, 1);
    lcd.print("Ready...");

    pinMode(inPin, INPUT);
    pinMode(outPin, OUTPUT);

    Serial.begin(9600);
    Serial.println("System Activated");
    Serial.println("Made by Mateo Holguin");
    Serial.println("0 = Light is Off | 1 = Light is On");
    Serial.println("=======================================");
}

void loop(){
    reading = digitalRead(inPin);

    if (reading == HIGH && previous == LOW && millis() - time > debounce) {
        Serial.println("Button Switch State Change:");
        if (state == HIGH)
            state = LOW;
        else
            state = HIGH;

        Serial.println(state);
        Serial.println("");
        lcd.clear();
        lcd.print("State: ");
        lcd.print(state);

        time = millis();
    }

    digitalWrite(outPin, state);

    previous = reading;
}

Both of these 2 answers works well, I just used the second one as I am a bit of a noob so I used one that I can understand more.

Another option: use the "inline" if construct:
lcd.print(state ? F("On") : F("Off"));

The format is:
<if comparison> ? <true result> : <false result>

Note the use of F(...) to force the strings to stay in flash memory.

I am going to try this option as well, as it makes a lot of sense to me.  Thank you very much!

When I use that line I get " '_F' was not declared in this scope"

@MateoHolguin Sorry, wasn't thinking straight that day - it's F() not _F()

I uploaded it to the Arduino, and it works perfectly the way I needed it to! Thanks again

Put the strings to display in an array, and output them instead.
char const * const stateDisplay[] = {"Off", "On"};

 ...

lcd.print(stateDisplay[state]);

Could you please explain why "const" is used twice there? I've never seen that before and don't know how to look it up.

@Jerry: One is for stateDisplay (i.e. the pointer is constant), and the other is for *stateDisplay (i.e. the contents are constant as well).

Thanks! I can actually use that in a sketch I'm working on now.

Thank you very much!  I can finally get that one issue fixed!


text:
HX711 Load Cell application strange behaviour
I have an application where an HX711 ADC is used with 4 load cells. (in wheatstone bridge configuration, rated at 50kg each).
The thing is that I am trying to sense 30~ish gram changes with it accurately, while the cells will be loaded with 10 to 40 kilograms.
I have built up the circuitry and placements properly, calibrated and tested etc. but I have 2 questions that I couldn't come up with a solution.
1st question:
When powering arduino from USB cable the readings are much more stable (they are fluctuating like +-5 grams only) but when I connect a 12V power source (with 5A output) to the arduino, the readings start to fluctuate much more. (+-30 grams or so). The HX711 is powered from arduino 5v out pin but even though i tried to power it from a 5v adapter the fluctuations seemed to happen.
I should also note that the HX711 is connected to the analog pins A0 and A1, and there are 8 other sensors connected to the pwm pins of the arduino.
Now any ideas why does that happen? Any way to prevent this fluctuation?
2nd question:
If I calibrate with a load close to the max. weight (as suggested in many papers) the small changes seems to be very unreliable. If I calibrate it with a small weight (like around 200g) I can sense small weights properly but this time when a 2 kg weight is put it is read like 2.3kg or something. Is this normal?
I know that my load cells are not the proper ones for the application but I would like to push them as much as i can.
Thanks for your time

Try a few different adapters. Some generate very noisy power. Secondly, you could add multiple calibration points. Cause the output, as you noticed, is not linear.

I will try different sources and return an answer asap, thank you.

1) Put your power source on an oscilloscope and check it. I assume what's happening is you don't have a clean sine, and the power fluctuates, whereas power from a PC USB port is usually very well regulated. This may be causing issues in your sensor due to under/over voltage at a minuscule level.
2) Because you're pushing your sensors to the edge of their capabilities, you're going to have to work around them, so the normal scenario's don't really offer much help, as they are usually based on working within the middle ground of capabilities.
You said that factoring based on low load vs high load created unreliable  variances in your measurements, i would personally suggest calibrating not for max load, nor min load, but 2/3 of max, or 1/3 max, and see if that stabilizes you, or at least gets you somewhere to the middle of the road where your differences are nominal, or something you can live with.

Thank you for your comments and suggestions! I did not have an oscilloscope at hand, i had to assume the power source was working clean as it was somewhat commercial design but I guess i'll have to check it, it really seems to be the problem.


text:
RS-232 is a protocol or a cable?
RS-485 and RS-232 are a type of communication protocol or a type and cable?
I studying these serial communication protocols and each place refers to the RS-232 / RS-485 in different ways. Some articles mention that it is a cable, the other a protocol, so I was in doubt.

RS-232 etc mean different things in different contexts.  More specifically it is called TIA/EIA-232.
It refers to both the electrical characteristics of an NRZ signalling system, and at the same time it refers to the packet format for the transmission of data through such a system.
It also refers to the connectors that are used with such a system and, by extension, the cables that have those connectors on them.

The standard defines the electrical characteristics and timing of signals, the meaning of signals, and the physical size and pinout of connectors. The current version of the standard is TIA-232-F Interface Between Data Terminal Equipment and Data Circuit-Terminating Equipment Employing Serial Binary Data Interchange, issued in 1997.

RS-485, or TIA/EIA-485, in contrast only specifies the electrical characteristics and not the data that is sent down the line. It doesn't specify any connectors to use, nor what format the data should take. For instance you can use RS-232 formatted packets, or you could use a MODBUS-RTU format that uses completely different packets. It only refers to the drivers and voltages used.

TIA-485-A, also known as ANSI/TIA/EIA-485, TIA/EIA-485, EIA-485 or RS-485, is a standard defining the electrical characteristics of drivers and receivers for use in balanced digital multipoint systems.


text:
Arduino Due uploading error using Eclipse plugin "avrdude: stk500_recv(): programmer is not responding"
I have a Arduino Due that I'm trying to upload a sketch to. I follow the tutorial http://playground.arduino.cc/Code/Eclipse to get the board running with the Eclipse plugin.
However uploading the sketch gives me the error
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x03

If I use the Arduino IDE everthing works fine. I'm using Eclipse mars with Arduino 1.6.5
What could have gone wrong?

avrdude: stk500_recv(): programmer is not responding
  avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x03

There's your clue.
1) programmer is not responding - This usually means the device isn't connected, or powered, or reachable by the IDE, make sure you have eclipse configured correctly for your device, and it's location.
2) not in sync - This is a redundant, or overlapping error, of course it's not going to sync if it can't connect.

The weird thing is if I press erase and reset on the Due before uploading the sketch it runs without any problems! I thought the Due has auto reset functionality?

I searched for a solution to this problem but it seems to be that I'm not the only one who struggles with that: https://forum.arduino.cc/index.php?topic=167492.0. They found some fix but these are a little bit ugly. I'm also worried about damaging my board if I press each time erase when uploading my sketch.

You are using the wrong upload tool.
The due is not using avr dude as upload tool.
You need to use bossac.
If you turn on verbose upload in the arduino ide preferences you will see
...arduino\tools\bossac\1.6.1-arduino/bossac.exe ...


text:
Matlab and Arduino Serial communication
I'm new to Arduino and am learning how Serial communication works. I am trying to send a value from Matlab to Arduino, but it seems to be partly fruitful. If anyone can explain the difference between the acquiring input and predefined strings in Matlab
Here is the program I tried, and it is successful.
Arduino :
 %This program receives an array of chars and stores them in array and transmits them back

 const int no_of_fields = 3;
 int field_index = 0;
 int vec_to_hold[no_of_fields]; //Array to hold the numbers

void setup()
{
   Serial.begin(9600);
}
void loop()
{
   if(Serial.available())
    {
     char ch = Serial.read();
     if(ch >= '0'&& ch<= '9') //check if the received chars are digits
      {
         if(field_index<no_of_fields)
           {
              vec_to_hold[field_index] = (vec_to_hold[field_index] * 10) + (ch -'0'); //accumulate values to form and integer
           }
      }
     else if(ch == ',')
     {
       field_index++;
     }
     else if(ch == '\n')
     {
        for (int i = 0;i<min(no_of_fields,field_index+1);i++)
         {
         Serial.print(vec_to_hold[i]);
         vec_to_hold[i] = 0;
         }
        Serial.println();
        field_index = 0;
      }
   }
}

Here is the Matlab side of Code :
delete(instrfindall)
S = serial('COM3', 'BaudRate', 9600,'Terminator','LF'); %38400
fopen(S);
pause(0.1);
vec_sent = input('Enter : ','s');
fprintf(S,'%s\n',vec_sent);
pause(0.1);
t_value = fscanf(S,'%d');
disp(t_value);
delete(instrfindall)

The above code is working, but what if i don't want to enter the string. I want to be predefined.
For example in the above matlab code
vec_sent = '200,300,400';

If i convert this line
 vec_sent = input('Enter : ','s');

to
 vec_sent = '200,300,400';

it does not work. The RX pin on the Arduino blinks indicating something is coming on the serial, but TX pin is not at all blinking, and nothing appears in MATLAB except an error stating
 Warning: Unsuccessful read: A timeout occurred before the Terminator was reached..

I would be grateful if anybody points out what I am doing wrong.
Thanks in advance.

To confirm that the cause of the connection problem is not the software, you can try to connect using reliable software. Do do this, download and install the MATLAB support package for Arduino hardware: http://www.mathworks.com/hardware-support/arduino-matlab.html

The Arduino parsing code seems to function correctly. If I just use the IDE Serial Monitor window and enter "200,300,400", the Arduino replies "200300400".
The error message says that you either did not get the LF, or the LF did not arrive within 0.1 seconds.
One thing to try, as I do not have MATLAB, is to change how the Arduino replies.  On the Arduino, Serial.println will send a CR and a LF at the end.  Perhaps you should just do the LF explicitly instead:
for (int i = 0;i<min(no_of_fields,field_index+1);i++)
{
  Serial.print(vec_to_hold[i]);
  vec_to_hold[i] = 0;
}
Serial.print( (char)10 ); // just LF, not CR/LF with println
field_index = 0;

This will test whether the CR is causing a line termination problem in MATLAB.
Another possibility is that the pause(0.1) is too short.  The documentation states that this is highly dependent on the OS timer resolution.  Try pause(1).  This will test whether the time is too short.  At 9600, 0.1s is only 100 character times.

Yes i thought of it and tried it yesterday, but with  pause(2). It works perfectly when i put a pause of 2 seconds in MATLAB, but i couldn't come up with the reason. Since you just said that it(pause) might be the reason, would you care to explain why i have to extend the pause time when i am connecting it to Arduino.
I tried with pause(1) but not fruitful, the thought is killing me from yesterday why pause(2)??

Because MATLAB runs on so many OS's, it will exhibit slight differences between platforms.  In this case, the resolution of the timers used by MATLAB is only 1 second: pausing (0,1] could be no pause, pausing (1,2] is <= 1s, etc.  Because there are so many things going on in the background in Windows, and it's not a Real Time OS, the MATLAB developers may have simply said, "Windows Update might be running... Close enough!" :P  I have found MATLAB examples that use pause(1), so sub-second resolution isn't something you should count on.  Answered?  :)

Yes, i agree, it might be one of the reason. Do you think the (DTR - Data Terminal Ready) of the arduino might be the culprit here?
I have obeserved some scenarios arduino taking some time to print to serial monitor.

DTR is probably not the culprit. On the PC side, you must go out of your way to enable DTR handshaking. On the Arduino side, there's nothing in the HardwareSerial class that does hardware handshaking. I don't know which Arduino you're using, so I don't know what's handling the USB interface. If it's using an FTDI chip, it can do DTR/DSR handshaking. More likely, it's just waiting a little bit to gather serial data to send to the PC in a packet. Below some threshold (64 bytes?), it will wait to see if more data is coming.


text:
Read Voltage at PWM off time, and Current at PWM on time
For a battery charging project, i am using an ARDUINO UNO which is driving a buck converter to provide the battery with the charging current. I am using external ADCs to measure the battery's charging voltage and current. The test setup is working fine, but right now i am just measuring the voltage and current at random time instants. However to measure it correctly, battery voltage reading should be done at an instant when the controller's PWM output is LOW (OFF duty cycle), and battery current reading should be done when PWM output is HIGH (ON duty cycle). So i was thinking how i can do that, since i am using analogueWrite() function to give PWM output, i thought if i could access analogueWrite() fucntion, may be i could there insert the function of read_ADC_Voltage() during the LOW time, and read_ADC_Current() during the HIGH time.
Is my approach right ? If yes then can please anyone tell me how can i access and use this analogueWrite() function ? And if someone has any other idea to do the readings correctly, please suggest. I shall be grateful.

Add a pin-change-interrupt (PCI) handler (See eg PinChangeInt at arduino.cc); clear the flag and enable the interrupt whenever you want to take readings, and disable that PCI after you have the reading.  As noted in the link, PCIs are available on all signal pins (possibly not on A6 and A7 on the 328), so are available on any of the PWM pins.

i tried to, but i am confused as the code isnt working as it is supposed to, in my opinion, so i posted my problem as an answer, as the code wont fit in comment box. Can you please tell what i am doing wrong?

I suggest that you copy your 'answer' to a new question.  I'm not going to evaluate that 'answer' here because use of comments for such evaluation is cumbersome -- comments can't be edited after their first five minutes -- and it does not tie into the stackexchange reputation system.  Anyhow, post that as a separate question and I'll be glad to answer.  Note, when you get another 5 points of reputation, you can start upvoting answers you find useful.  Also, you can accept answers that best address questions you ask.  Accepting and upvoting answers gives more people incentive to answer well.

i just did..here is the link to it.

P.S I am writing it as an answer since my code wont fit in comment
I looked into interrupts and learned about them that there are 2 types of interrupts in Arduino namely "external", and "pin change". So i downloaded the "PinChangeInt Library" to test it. I wrote a small program where a PWM of 62.5kHz is being generated on pin3, and i am calling rising and falling edge triggered interrupts on this pin, i.e to display one value when rising edge occurs, and other value when falling edge occurs. My code looks like following:
    #include <PinChangeInt.h>
    #define pw 3
    int pwm;

    void setup() {
      // put your setup code here, to run once:
      pinMode(pw, OUTPUT) ;
      pwm_setup();             // Set PWM to a frequency of 62.5kHz

      PCintPort::attachInterrupt(pw,rise,RISING);    // call void rise() when PWM is HIGH
      PCintPort::attachInterrupt(pw,fall,FALLING);   // call void fall() when PWM is LOW

      Serial.begin(9600);
    }

    void loop() {
      // put your main code here, to run repeatedly:
      pwm = 127;                                                // 50% duty cycle
      pwm_on(pwm);

    }
    void pwm_setup()
    {

      TCCR2A = 0x23 ;
      TCCR2B = 0x09 ; // mode 7, clock prescale by 1
      OCR2A = 256-1 ;  // 256 clock periods = 16us per cycle
      OCR2B =0 ;
      TCNT2 =0 ;

    }
    void pwm_on(double)
     {
        OCR2B = pwm ;
     }

    void rise()
    {
      Serial.println("RISE");
    }

void fall()
{
  Serial.println("fall");
}

But it is not working the way i think it should. It keeps on displaying "fall" every time, whereas according to me it should display "RISE" and "fall" alternatively, right ? However if i remove the "PCintPort::attachInterrupt(pw,fall,FALLING); " line, it starts to display "RISE" as it is supposed to.
Since its my first time programming with Arduino, and i am just a beginning level programmer, i might be making some stupid mistake here. So can you point it out please ?

No, in my opinion changing functions in the Arduino Core is not a good approach. You would have to change it back for any other project you are going to do and secondly, if you insert a function in the part where analogWrite is low it will result in a change in the duty cycle. Which may not be a big problem, but just don't.
My advice would be to use a timer to run a callback function every x seconds. Then in that function temporarily set the PWM to 0 and read your values. This is indeed not the most efficient approach, but we're talking about microseconds here... This approach is completely intterupt driven so you could run other things while it is running it's PWM and checking the voltage periodically.
It sounds as if you have gotten pretty far by yourself, so I'm not going to write you example code. You can a tutorial on how to use a timer to periodically call a function here.