message:
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: [![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/4RMhI.png
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:

<!-- language: lang-c -->

    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.

body: Part seems to be broken; voltage is unusually high.


sender: user

sender: assistant

body:
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.**


message:
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.

body:
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 `>=`.


body:
    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
     }
    }


body:
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...
      }

    }


body:
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
      }


body:
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);


body:
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:

```cpp
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:

```cpp
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:

```cpp
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:

```cpp
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);
}
```


message:
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?

body: There is a reference to the [accelerometer datasheet](http://ae-bst.resource.bosch.com/media/products/dokumente/bma250/bst-bma250-ds002-05.pdf) from the [Arduino Reference page](http://legacy.punchthrough.com/bean/the-arduino-reference/accelerationreading/)


body:
> 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][1] product description. There you can find a link to the [schematics and board layout][2]. On page two there is accelerometer, a BMA250 just as @Jason links to.

That took "30 seconds" web search plus writing this answer :)

Cheers!

  [1]: https://www.adafruit.com/products/2732
  [2]: https://www.adafruit.com/images/product-files/2732/Bean_revE_board_export.pdf


message:
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](https://www.sparkfun.com/products/12640). The [datasheet](http://cdn.sparkfun.com/datasheets/Dev/Arduino/Boards/ATMega32U4.pdf) 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.

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


message:
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.

body:
> 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.


body:
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 <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?

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.


message:
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**

<!-- language: C -->

    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;
         }
    }

body:
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][1] or at this special topic, [P3D by Daniel Shiffman][2].

I have not tested the code, but I think that it should work.

If you have questions, feel free to ask ;D

  [1]: https://processing.org/reference/
  [2]: https://processing.org/tutorials/p3d/


message:
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.
[![enter image description here][1]][1]
[![enter image description here][2]][2]

  [1]: https://i.stack.imgur.com/V5pdE.png
  [2]: https://i.stack.imgur.com/xKX47.png

body:
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:
[![screenshot of tkinter plot][1]][1]

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.

  [1]: https://i.stack.imgur.com/3wnW3.png


message:
Johnny Five LCD: black boxes only

I posted this also at [Stack Overflow][1]. 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.

[![enter image description here][2]][2]

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?

  [1]: https://stackoverflow.com/questions/33540095/johnny-five-lcd-black-boxes-only
  [2]: https://i.stack.imgur.com/8a9mJ.png

body:
Try changing the resistance in your 10k potentiometer. This might be a reason for the black boxes.

P.S: I.m a beginner too.


message:
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.

body:
 - 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.


body:
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.


message:
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?

body:
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


body:
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][1]. This one is controllable using the SPI bus.

There are several libaries implementing the protocol, i.e [PaulStoffregen/Tlc5940][2].

See [Playground from Arduino - TLC5940][3] for more information.

  [1]: http://www.ti.com/lit/ds/symlink/tlc5940.pdf
  [2]: https://github.com/PaulStoffregen/Tlc5940
  [3]: http://playground.arduino.cc/Learning/TLC5940


message:
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)

body:
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);


message:
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?

body:
Looks like your connection is somewhere missing.

Connect CH_PD and reset pin to high--i.e. 3.3v.


body:
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!


message:
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);
    }
    }

body: 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`.


body:
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.


message:
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);
      }
    }

body: 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.


body:
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(",");
      }

    }


message:
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 [![enter image description here][1]][1]

[IR transmiter][2]
[IR reciever][3]

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);
    }

  [1]: https://i.stack.imgur.com/KBYYf.png
  [2]: http://www.vishay.com/docs/81010/tsal6200.pdf
  [3]: http://arduino-info.wikispaces.com/file/view/IR-Receiver-AX-1838HS.pdf

body:
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.


message:
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?

body:
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.


message:
Timer (or other) interrupt happens while servicing an interrupt - how to accurately handle the second one?

This seems like a simple question but I'm not finding an answer so far: at a high level, say I have a timer interrupt and some input interrupt. The input arrives, the ISR is entered, interrupts are (automatically by default?) disabled, I service the input (quickly!), but while that's going on a timer used for some other purpose fires. I don't want to miss that timer but because interrupts are disabled my input processing won't get interrupted for it.

I exit the input ISR and interrupts are (automatically?) re-enabled. Assuming the timer is uncomplicated (it wouldn't overflow twice during my input ISR) how do I accurately handle the fact that it overflowed during my input ISR and I "missed" it?

Would this differ if instead of the timer I simply had a second input2 that similarly might fire during my input1 processing (but would present a useful input long enough to process after input1, presuming I knew it triggered)?

I'm not looking to nest interrupts here, just to understand what happens when an interrupt happens during another ISR which has temporarily disabled them - do they pend and fire after the blocking ISR returns, or are they just lost?

body:
Q1:
>... exit the input ISR and interrupts are (automatically?) re-enabled

Yes, the RETI (return from interrupt) instruction enables interrupts.  See third paragraph of section 7.7 in [Atmel's document #8271](http://www.atmel.com/images/atmel-8271-8-bit-avr-microcontroller-atmega48a-48pa-88a-88pa-168a-168pa-328-328p_datasheet_complete.pdf) (a 650-page spec sheet for the Atmega 48, 88, 168, 328 series), which says:

> When an interrupt occurs, the Global Interrupt Enable I-bit is cleared and all interrupts are disabled. The user software can write logic one to the I-bit to enable nested interrupts. All enabled interrupts can then interrupt the current interrupt routine. The I-bit is automatically set when a Return from Interrupt instruction – RETI – is executed.

Q2:
>Assuming the timer is uncomplicated (it wouldn't overflow twice during my input ISR) how do I accurately handle the fact that it overflowed during my input ISR and I "missed" it?

If the timer is running a clock, set the timer control bits to automatically reload the count register upon each overflow (or underflow).  That will leave a full count period for processing each timer interrupt.

That is, you can pre-load a next-timer-count (I think it can be different from the current count if necessary), so the timer can start its next interval automatically.  If the timer is used for some purpose more complicated than that, you may need a nested interrupt.

Q3:
>Would this differ if instead of the timer I simply had a second input2 that similarly might fire during my input1 processing (but would present a useful input long enough to process after input1, presuming I knew it triggered)?

If indeed input2 sticks around long enough to process after input1 processing is done, no problem.  Its interrupt will occur after the first interrupted code sequence executes one more instruction after the RETI occurs.  (See paragraph 6 of section 7.7 in doc8271.)

If input2 is brief, several different things can happen.   (a) If it is shorter than a clock cycle, in general it won't trigger an interrupt.  (b) If it is a level-interrupt-triggering event on INT0 or INT1 that ends while another interrupt is being processed, it won't trigger an interrupt.  (See discussion on page 72, section 13.2.3, of doc8271 of INTF0 and INTF1 being clear for level interrupts.) (c) If it is an interrupt-flag-setting event that sets a flag and ends while another interrupt is being processed, it will trigger an interrupt after the global interrupt flag is set, unless current processing clears its flag.

I think the above accurately states what happens on Atmega devices, but I suggest you also see doc8271 – and run tests – to see for yourself.  Here is part of what paragraphs 4 and 5 of section 7.7 in doc8271 say regarding (b) and (c):
>There are basically two types of interrupts. The first type is triggered by an event that sets the Interrupt Flag.  ... Interrupt Flags can also be cleared by
writing a logic one to the flag bit position(s) to be cleared. If an interrupt condition occurs while the
corresponding interrupt enable bit is cleared, the Interrupt Flag will be set and remembered until the interrupt is enabled, or the flag is cleared by software. Similarly, if one or more interrupt conditions occur while the Global Interrupt Enable bit is cleared, the corresponding Interrupt Flag(s) will be set and remembered until the Global Interrupt Enable bit is set, and will then be executed by order of priority.

>The second type of interrupts will trigger as long as the interrupt condition is present. These interrupts do not necessarily have Interrupt Flags. If the interrupt condition disappears before the interrupt is enabled, the
interrupt will not be triggered.


message:
How can I have two Arduino Uno's communicate wirelessly?

I'm an art student, using arduino in an Electronic Arts Class.  I have already created a skateboard speedometer, using a Hall Effect Sensor and a magnet embedded in one of my skateboards wheels.  I've attached a speaker to the arduino that plays a tone, with the pitch depending on the RPM's of the wheel.  (the faster the board is going, the higher pitch the tone being played is).  Currently the speaker is attached to the skateboard and wired directly to the arduino.  My goal is to have a speaker with an arduino wirelessly connected to the arduino on the skateboard.  The arduino on the skateboard record's the RPM's and then wirelessly send that information to the second arduino to play the tone through the speaker.  Is this possible? what hardware would yo recommend? I've been looking at the Bluetooth HC-05 but I'm not sure this will work.  Thanks for any help!

body:
ESP8266 is also a good choice. these little guys are really useful and give you a Wi-Fi connection between your Arduino boards.

Also, the cost of one ESP8266 is about $3.. super cheap!

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/R0gB7.jpg


message:
Need help converting a processing sketch for a robot arm with servo shield

I'm currently building a robotic arm. I'm using an Adafruit servo shield, 7 servos, Arduino uno, and a 5V 10A power supply.

[![Diagram of Robotic arm][1]][1]

I found a program that controls the arm with mouse movement using a processing sketch, [Fixbot][2].

However I'm using the Adafruit servo shield, and I've got no clue how to convert the program. I've found the center points for the servos, so I've managed to make the robot stand upright using my own code.

If someone could give me some pointers as to how to convert from the on-board PWM outputs to the servo shield outputs for the linked program, and how to set servo max/min, I would highly appreciate it.

  [1]: https://i.stack.imgur.com/X9efl.png
  [2]: https://github.com/mikevanis/Fixbot

body:
I use a generic servo shield, and the *servo PWM outputs* (3 pin inline connector) on the shield are labeled accordingly (`0` - `15`). Your Adafruit servo shield should be the same, see below.

[![Adafruit Servo shield][1]][1]

The link that you provide also has the *Arduino* version, see below. You should use that, instead of the *Processing* version.

The Arduino library `Servo.h`, handles all of the "Servo PWM to Arduino pin conversions" that you ask for. So, looking at the [Fixbot][2] code, it would seem that all you would need to do is change the five pins (servo PWM outputs) to which the servos are `attach`ed in `setup()`, according to which servo PWM outputs you attach each servo to.

    #include <Servo.h>

    String command;

    Servo seg0;
    Servo seg1;
    Servo seg2;
    Servo seg3;
    Servo seg4;

    void setup() {
      Serial.begin(115200);
      seg0.attach(8);            /* <--- Change Me !!! */
      seg1.attach(9);            /* <--- Change Me !!! */
      seg2.attach(10);           /* <--- Change Me !!! */
      seg3.attach(11);           /* <--- Change Me !!! */
      seg4.attach(12);           /* <--- Change Me !!! */
    }

    void loop() {
      if(Serial.available() > 0) {
        char inChar = Serial.read();
        command += inChar;
        if(inChar == '\n') {
          // clear command
          performCmd(command);
          command = "";
        }
        Serial.flush();
      }
    }

    void performCmd(String cmd) {
      int comma1 = cmd.indexOf(',');
      int comma2 = cmd.indexOf(',', comma1+1);
      int comma3 = cmd.indexOf(',', comma2+1);
      int comma4 = cmd.indexOf(',', comma3+1);

      int cmd0 = stringToInt(cmd.substring(0, comma1));
      int cmd1 = stringToInt(cmd.substring(comma1+1, comma2));
      int cmd2 = stringToInt(cmd.substring(comma2+1, comma3));
      int cmd3 = stringToInt(cmd.substring(comma3+1, comma4));
      int cmd4 = stringToInt(cmd.substring(comma4+1, cmd.length()));

      seg0.write(cmd0);
      seg1.write(cmd1);
      seg2.write(cmd2);
      seg3.write(cmd3);
      seg4.write(cmd4);

    }

    int stringToInt(String str) {
      String tmp = String(str);
      return str.toInt();
    }

Regarding your question about the maximum and minimums, again, these will be handled by the `Servo.h` library.

-----

### TL;DR

Change the five servo `attach` lines in the `setup()` routine, to reflect which servo ports your servos are connected to.

-----

**Power Requirements**

As an aside, remember that you will need to supply external power (+5V) to the Adafruit Servo board, via the blue screw terminal block, in order to have sufficient power (current) to actuate the servos. In the photo above the screw terminal block is not shown, but would be mounted half way up on the left hand side of the PCB (where it says `5-6V Servo`). It can be seen in this photo, at the top:

[![Adafruit Servo Shield, showing blue screw terminal][3]][3]

If you do not supply external power, then the Arduino board, by itself will not be able to supply enough power. Even though the code may be running, the lack of power may make it appear that there is no output, as the servos remain immobile, due to the lack of current.

  [1]: https://i.stack.imgur.com/fP171.jpg
  [2]: https://github.com/mikevanis/Fixbot
  [3]: https://i.stack.imgur.com/Mk9bK.jpg


message:
Arduino Orion Upload - Which Board When Compiling

I'm trying to compile and upload the example code for the arduino robotics starter kit (https://github.com/Makeblock-official/Makeblock-Library and https://raw.githubusercontent.com/Makeblock-official/Assembly-Instructions/master/Starter_Robot_Kit_IR_Instruction.pdf).

In the IDE to compile the code, you need to select the appropiate 'board' for the sketch, and the Arduino Orion isn't listed.  Should I just compile under the Arduino Uno, which I believe the Orion is based on?

body:
Yes, the "Orion" is just an Uno in a different shape with different connectors.  Just treat it like an ordinary Uno.

Similarly the "Baseboard" is just a Leonardo in a different shape with different connectors.


message:
Prevent reiteration of loop instruction in Arduino/Execute instruction via off switch

I'd like to make an Arduino play a (2sec).wav file once when it is powered on (via push button) and another when it is switched off i.e. when the push button is pushed there is a 2sec delay and the .wav file plays, then the arduino turns off.  What would the best way be to implement this?  So far I've come up with:

    void loop()
    {
    //play .wav file

    while(1){}
    }

or:

    void setup(){
    //play .wav file
    }

    void loop(){
    //empty
    }

body:
Neither way addresses your second requirement. I would do something like:

    void setup()
        {
        pinMode (OFF_BUTTON, INPUT_PULLUP);

        //play .wav file
        }

    void loop()
      {

      if (digitalRead (OFF_BUTTON) == LOW)  // depending on how it is wired
        {
        delay (2000);   // 2 second delay
        // play .wav file
        // power self off somehow
        }

    }


body:
An Arduino doesn't understand the concept of "powering off".  It is either on (running) or off (not able to do anything).

Your first task must be to design a system whereby the Arduino can control its own power so the Arduino can then go "I have been asked by this external stimulus to switch off. Therefore I will play this sound and then perform whatever actions are required to remove power from myself."

Only when you have worked out how you can get the Arduino to control its own power and still have the ability to manually turn the power on can you begin to think about adding things that happen "when it powers off".


message:
Hardware serial not working, SoftwareSerial is

On my Uno-equivalent Arduino, a SoftwareSerial connection (on RX, TX = 8, 9) is working*, while a hardware serial connection to the same device, set up in the same way (but on pins RX, TX = 0, 1) is not working. Why is the hardware serial setup not working?

*By working I mean receiving a byte from the external device

**Edit:** as a simple example:

    void setup() {
      Serial.begin(38000);
      pinMode(7, OUTPUT);
    }

    void draw() {
      if (Serial.available() > 0) {
        Serial.read();
        tone(7, 440, 1000);
      }
    }

The above, using `Serial`, doesn't work, whereas

    #include <SoftwareSerial.h>

    SoftwareSerial serial(8, 9);

    void setup() {
      serial.begin(38000);
      pinMode(7, OUTPUT);
    }

    void draw() {
      if (serial.available() > 0) {
        serial.read();
        tone(7, 440, 1000);
      }
    }

does work.

***

I don't know if this helps, but connecting RX/TX through an LED to ground gave me the following, using Serial on (0, 1) and SoftwareSerial on (8, 9):

**Serial**
RX: bright
TX: bright
**SoftwareSerial**
RX: dim (but still lit)
TX: bright

Is the fact that RX is dim using SoftwareSerial significant?

body:
There may be several reasons

 1. Be sure uC pin connect pin header
 2. In setup part, you write Serial.begin(xxxx);
 3. After serial begin, don't change this pins IO features(Input, output)

Please check that after if not solve, please share code


body:
I would check if the arduino you are using supports your selected baudrate.

38000 is not a standard rate and it could be, that the hardware is not able to work at it with the needed precision.
The software serial (and most USB serial dongles) could use any baudrate, but not the limited hardware within most arduinos.


message:
Sending serial data to Arduino from Matlab(not using support package)

I am learning Arduino and trying to understand how integers and strings are sent across the serial port.
I tried a small program in arduino which reads a number as a string and tries to blink led 13 according to that number. Below is the arduino side of code.

    const int ledpin = 13;
    int value = 0;
    int blinkrate;
    void setup()
    {
       Serial.begin(9600);
       pinMode(ledpin,OUTPUT);

    }

    void loop()
    {
        if (Serial.available())
          {
             char ch = Serial.read();
             if (isDigit(ch))
                {
                   value = (value*10) + (ch - '0');
                }
             else if (ch == 10)
                {
                   blinkrate = value;
                   Serial.println(blinkrate);
                   value = 0;
                }
          }
        blinkled(blinkrate);
    }

    void blinkled(int blinkrate)
     {
       digitalWrite(ledpin,HIGH);
       delay(blinkrate);
       digitalWrite(ledpin,LOW);
       delay(blinkrate);
     }

When i try to send a string from MATLAB, the RX led blinks once indicating something is coming, but the LED on pin 13 is not behaving accordingly(it should blink according to the number i send). Here is the matlab side of code.

    pre_open = instrfindall;
    delete(pre_open);
    serial_port = serial('COM3');
    set(serial_port,'Terminator','CR');
    set(serial_port,'BaudRate',9600);
    set(serial_port,'DataBits',8);
    set(serial_port,'StopBits',1);
    set(serial_port,'Parity','none');
    fopen(serial_port);
    num = 200;
    fwrite(serial_port,int2str(num));
    data = fscanf(serial_port,'%d');
    pause(2);
    fclose(serial_port);

When i try to read the return string from arduino, MATLAB shows me a timeout error.

I would be grateful if anybody points me to the right solution.
Thank you.

body:
You're setting the terminator to be 'CR'.  CR, or Carriage Return, is character 13.  In your Arduino program you are looking for character 10.  That is 'LF' or Line Feed.

Either are commonly used to denote a line ending, but both ends must agree on which it is.

For instance, Unix files use a single LF for a line ending.  Windows files use the combination of both a CR and an LF.  Many networking protocols use a single CR for the line ending.  It really doesn't matter what is used *as long as it is consistent.*


body:
Got it, instead of depending on the Serial object, i sent the line feed to arduino. All this time it has been waiting for the Line feed that never arrived.

    delete(instrfindall)
    s = serial('COM3', 'BaudRate', 9600); 8400
    fopen(s);
    pause(0.1);
    text = input('enter','s');
    fprintf(s,'%s\n',text,'sync');
    pause(0.1);
    d = fscanf(s,'%s');
    pause(0.1);
    delete(instrfindall)


message:
Why serial communication does not work on atmega168/328p?

I expect from the following program `serial.c` to light the led on if I send key `1` from terminal, and light the led off when I send key `0` from terminal:

    #define F_CPU 16000000UL
    #define BAUD 9600
    #include <avr/io.h>
    char data;
    void main(void) {
      #include <util/setbaud.h>
      UBRR0H = UBRRH_VALUE;
      UBRR0L = UBRRL_VALUE;
      UCSR0B |= (1<<RXEN0);
      UCSR0C |= (1<<UCSZ01)|(1<<UCSZ00);
      DDRB |= (1<<PB1);
      while(1) {
        while(!(UCSR0A&(1<<RXC0)));
        data = UDR0;
        if (data=='0') PORTB &= ~(1<<PB1);
        if (data=='1') PORTB |= (1<<PB1);
      }
    }

I use the following commands to compile and burn all the programs:

    avr-gcc -Os -mmcu=atmega328p -c -o serial.o serial.c
    avr-ld -o serial.elf serial.o
    avr-objcopy -O ihex serial.elf serial.hex
    avrdude -c usbasp -p atmega328p -U flash:w:serial.hex

The output of avrdude is the following:

    $ avrdude -c usbasp -p atmega328p -U flash:w:serial.hex

    avrdude: AVR device initialized and ready to accept instructions

    Reading | ################################################## | 100% 0.00s

    avrdude: Device signature = 0x1e950f
    avrdude: NOTE: "flash" memory has been specified, an erase cycle will be performed
             To disable this feature, specify the -D option.
    avrdude: erasing chip
    avrdude: reading input file "serial.hex"
    avrdude: input file serial.hex auto detected as Intel Hex
    avrdude: writing flash (12 bytes):

    Writing | ################################################## | 100% 0.03s

    avrdude: 12 bytes of flash written
    avrdude: verifying flash memory against serial.hex:
    avrdude: load data flash data from input file serial.hex:
    avrdude: input file serial.hex auto detected as Intel Hex
    avrdude: input file serial.hex contains 12 bytes
    avrdude: reading on-chip flash data:

    Reading | ################################################## | 100% 0.02s

    avrdude: verifying ...
    avrdude: 12 bytes of flash verified

    avrdude: safemode: Fuses OK (E:07, H:DE, L:FF)

    avrdude done.  Thank you.

For serial connection I tried PL2302 and FT232RL usb-com adapters - the effect is always the same.

Terminal settings on the computer are correct (9600,8N1).

avr-gcc version 4.8.1
avrdude version 6.1

Why the very first program in this question does not work as needed and what should be changed in it to achieve the desired behavior?

body:
The problem you have is that your baud rate is not being set right.

You only have part of the settings you need.  There is a third macro in the setbaud.h file that you need to take account of:  `USE_U2X`.

That defines whether or not you need to set or clear the U2X0 bit of UCSRA0.  If that is set wrong then your baud rate will be either twice or half what you want it to be - in this case it's coming out as twice.

Modify your code to assign the baud rate like this:

    #include <util/setbaud.h>
    UBRR0H = UBRRH_VALUE;
    UBRR0L = UBRRL_VALUE;
    #if USE_U2X
    UCSR0A |= (1<<U2X0);
    #else
    UCSR0A &= ~(1<<U2X0);
    #endif
    UCSR0B |= (1<<RXEN0);
    UCSR0C |= (1<<UCSZ01)|(1<<UCSZ00);

Then you should be able to receive characters.

In the actual header file in question there is a large number of comments and instructions, including this:

>   Assuming that the requested BAUD is valid for the given F_CPU then
   the macro UBRR_VALUE is set to the required prescaler value.  Two
   additional macros are provided for the low and high bytes of the
   prescaler, respectively: UBRRL_VALUE is set to the lower byte of
   the UBRR_VALUE and UBRRH_VALUE is set to the upper byte.  **An
   additional macro USE_2X will be defined.  Its value is set to 1 if
   the desired BAUD rate within the given tolerance could only be
   achieved by setting the U2X bit in the UART configuration.  It will
   be defined to 0 if U2X is not needed.**

My resulting UART configuration, which may be being affected by the bootloader, is:

    UBRR0H: 0x00
    UBRR0L: 0x67
    UCSR0A: 0x20
    UCSR0B: 0x10
    UCSR0C: 0x06

That equates to `data register empty`, `RX enabled`, `8-bit`.

To my mind that is equal to the values being manually set in the code, so shouldn't be a problem.


message:
Controlling Servo Motors with push button. Problem though

I have this setup where I have and Arduino Uno, a mini servo motor, and a pushbutton. I use a single pushbutton to control the servo motor to go to one position, then push it again to go back. It first goes to 0 degrees, then if you push it it goes to 180 degrees then vice versa. The problem is that in its initial state (which is 0 degrees), the servo motor makes noise. Like it's running or something then it gets hot.

I've seen other servo motors that never do this. Here is my code by the way:

    #include <Servo.h>

    const int buttonPin = 8;
    const int servoPin = 9;
    int buttonState = 0;
    int directionState = 0;
    Servo servoOne;
    int pos = 0;

    void setup() {
      servoOne.attach(9);
      servoOne.write(directionState);
      pinMode(buttonPin, INPUT);
    }

    void loop() {
      buttonState = digitalRead(buttonPin);
      if (directionState == 0) {
        if (buttonState == HIGH) {
          directionState = 1;
          for (pos = 0; pos < 180; pos = pos + 1) {
            servoOne.write(pos);
            delay(5);
          }
        }
      } else if (directionState == 1) {
        if (buttonState == HIGH) {
          directionState = 0;
          for (pos = 180; pos > 1; pos = pos - 1) {
            servoOne.write(pos);
            delay(5);
          }
        }
      }
    }

I really need all the help I can get.

body: You might need to add more time to the delay. Also, check how your powering the servo. If you're powering from the Arduino, it might be drawing to much current and causing issues. If it's a bigger servo, try to hook it up to an external power source and just connect the PWM line and it's ground.


body:
Looks like your delay is too short. If the delay gets over before the servo can reach the set postion, it will skip that command and execute the next one.

Also I agree with @julio about how are you powering your servo. By "mini" servo I assume that you are using a micro servo. I have a Tower Pro 9G micro servo (which I use as steering servo btw, small but pretty decent), and it works fine if I power it with the Arduino UNO, but torque is a bit less. Anyways, check your servo's datasheet, your servo might need more power. Just hook it up to a power supply and make sure the grounds are common. The jitter might just be the result of inappropriate power.


body: The most basic issue with servo motors is wrong cabling and then insufficient motor driver in terms of amperage. And then, PWM duty cycle must be set correctly. If you don't treat those things properly, you may hear noises such as humming, vibration instead of turning the motor.


body: The code was absolutely ok but position 180 was a problem sometimes. Those servos simply can't reach position 180 because the end is on 178 or nearby. But the servo was trying to go on that position. The solution is simple: try a different position (179 or less).


message:
Computer to multiple arduino bluetooth modules

Im going to take part in a competition called IEEE Very Small Soccer and I need to set up a communication between my computer, that will run visual and strategy algorithms, and send some commands to 3 Arduinos, which will be the players. Most people use the Xbee module to send data to the Arduinos, so I was wondering why not use the Bluetooth module instead, once it is so much cheaper and the difference in power consumption isn't so big, the only drawback would be the working range, which is 10m, if Im correct... However, if the distance is really 10m, not 5m It will be ok, because the computer is always close to the robots.

Summing up, my questions are:

 1. Can I use a computer to send data to 3 Arduinos at the same time?
 2. What is the real working range of the Bluetooth module?
 3. Any suggestions or tips? =D

[![IEEE Very Small Size Soccer schematic][1]][1]?

[1]: https://i.stack.imgur.com/0fjsE.png

body:
 1. yes, you can, this is what happens normally in a crowded area where multiple people use their phones with bluetooth headsets, for example.
 2. if you believe [the claims][1] typical 10m max 100m but in practice there are a number of factors:

 - Quality of the HW design of the antennas
 - Signal to noise ratio due to other radios operating in the same area
 - Obstacles in the path
 - Responsiveness and throughput required by your application
 - etc.

 3. you could consider other options, like [this module][2], which is basically the same, from the perspective of transferring data. Also [wifi][3] could work, if you are allowed to setup your own access point.

  [1]: https://en.wikipedia.org/wiki/Bluetooth
  [2]: http://hallard.me/nrf24l01-real-life-range-test/
  [3]: http://www.esp8266.com/


message:
Connect HX711 to a three wire load cell

I have the following load cells:

[![Load Cell three wires][1]][1]

I'm using the following HX711 amplifier [![enter image description here][2]][2]

  [1]: https://i.stack.imgur.com/JfBSd.jpg
  [2]: https://i.stack.imgur.com/fVy0H.jpg

Every guide i can find on the internet describes how to connect a load cell with four wires to the amplifier. How can i connect a load cell with three wires to the amplifier?

Thanks in advance.

body:
It seems like that module is used to connect the 4 wire load cell, but on the internet I found other schematics that might help you out how to wire it up.

This is one way (http://i46.tinypic.com/30j0d2t.jpg):

[![Schematic A][1]][1]

Otherwise try this way:

[![Schematic B][2]][2]

I am not an expert on load cells but it seems like you just need to give it a try and see if it works.

  [1]: https://i.stack.imgur.com/xYqBx.jpg
  [2]: https://i.stack.imgur.com/9vDyI.jpg


body:
A datasheet for the HX711 is https://cdn.sparkfun.com/datasheets/Sensors/ForceFlex/hx711_english.pdf  (On your board, it looks like E+ is AVDD and E- is AGND.)

Each of your two load cells could be a half-bridge of a wheatstone bridge, with excitation on the white and black, and sensing on the red like: [![https://i.stack.imgur.com/PrHOR.jpg][1]][1]

I have a similar loadcell with the colors as Blue-Red-Black, (instead of White-Red-Black as above, or the Red-White-Black in your image) with my red sensing wire in the middle.  The positive strain resistance (increasing resistance with increasing load) is between the Blue and Red, while the negative strain (decreasing resistance with decreasing load) is between the Red and the Black. The ~1000 ohm resistance in each leg changes by tenths of an ohm with hand pressure on the button, when the outer portion is supported, but the inner portion is not supported.  Your cells do not have the bridge-button part that create a balanced twist along the center portion, so it might be hard to reliably apply a load your cell.

To make positive deflections of the cells combine to unbalance the Wheatstone bridge, wire one cell's white and black opposite to the other cell, and attach them to E+ and E-, with the reds connected to A+ and A- like this:

       HX711.E+ : Cell1.White + Cell2.Black
       HX711.E- : Cell1.Black + Cell2.White
       HX711.A+ : Cell1.Red
       Hx711.A- : Cell2.Red

[![enter image description here][2]][2]

The labelling on the schematic isn't quite right-- the "Reference 1K" are actually the negative-strain portions of the cells, and might be better labelled as "-Active 1k Ohm".

If it moves in the wrong direction/wrong sign with increasing force, switch the reds or multiply by -1.

If you have only one three-wire cell, use a couple 1K resistors, or a 2K potentiometer to balance the existing cell as the other half of the Wheatstone bridge.  One issue with using discrete (10%, 5%, 1%?) resistors is that the precision and tolerances when configured as a voltage divider may produce a significantly different result as compared with the balance in a lead cell and its full-scale signal (+/-0.1%) in a loadcell.  A the center tap of a potentiometer can provide for tuning to match the load cell voltage.  For the HX711's 32x, 64x, or 128x gain, you need to keep the voltage differences between the sense terminals  between +/-80mV, +/-40mV, or +/-20mV to stay within the limits of the HX711.

Per @wirewrap's comment, the colors on the wire could be different than the picture I posted.  You can make certain by measuring the resistances between the wires and exciting on the pair with the greatest resistance, and sensing on the middle terminal.

  [1]: https://i.stack.imgur.com/PrHOR.jpg
  [2]: https://i.stack.imgur.com/sUqcE.png


body:
When you have four half bridges I think that you will need to read them separately as pairs and then sum the result in software.  I would be interested in hearing how multiple hx711 modules should be best handled by a Nano.

Update.  I have discovered that sparkfun produce a load cell combinator board that assists wiring four half bridge load cells to appear as a full bridge.  I have still not understood how that works yet.


body:
> How can i connect a load cell with three wires to the amplifier?

it is one-side of the bridge.

the other side can be another load cell or a resistor bridge.


message:
Burning arduino generate hex file to blank atmel chip

Is it possible to burn the hex file to a blank chip, generated by Arduino to burn using USBASP to that particular chip without using Arduino board ? Will the program work ?

---

My main goal is to use Atmega328P for low power. Should I select Arduino pro mini in the arduino IDE ?

Ater successful testing I will just burn the hex file to another 50 chips. thats why I dont want to use arduino board.

body: Yes. The binary generated by the Arduino IDE in no way requires the presence of the Arduino bootloader in order to operate. Note that certain characteristics such as the MCU and clock rate are set at build time and cannot be changed in the final binary.


body:
Yes that's no problem as long as you check your fuse bytes. And the connections to the 6pin ISP header.
Make sure you study the avrdude command line and the manual for the particular Atmel chip.

I'm assuming the programmer you are using must use avrdude to be able to work.

I often use a nice GUI called "avrdudess" which is freeware. Great for avr beginners, and takes some of the effort out of writing directly into the command prompt.


message:
How to measure relay current draw from Arduino

How does one measure the amount of current a relay is drawing from an Arduino?

Do I connect a multimeter in series with the digital pin to which the relay 'IN1' is connected (in this case pin 7), the 5V pin or GND pin?

Provisional testing gives me the following results (when the relay is ON):

 1. Pin 7: **3.93 mA**
 2. 5V pin: **70.2 mA**
 3. GND pin: **66.8 mA**

Also, assuming I pull more than 40 mA through digital pin 7 for a number of seconds, is the pin likely to fail immediately? Or slowly degrade over time?

body:
Have you noticed how the 5V current is, give or take a little inaccuracy on the part of your ammeter, the sum of the other two currents?

Without knowing what relay you are talking about, my guess is it is one of the SainSmart 5V relay modules with opto-coupler. Those, by default, use a common 5V input and split it between the opto-coupler (and then into your digital pin to be sunk through ground) and the relay to ground.  Therefore the 70mA is split between 66mA through the relay and 4mA through the digital IO pin.

So the correct place to measure the total current in this instance is the 5V pin since that is the common point for the circuit.

In answer to your second question, *read the datasheet*.  It quite clearly states:

> Although each I/O port can sink more than the test conditions (20 mA at VCC = 5V, 10 mA at V CC = 3V) under steady state conditions (non-transient), the following must be observed:
>
>ATmega48PA/88PA/168PA/328P:
>
> 1. The sum of all I OL , for ports C0 - C5, ADC7, ADC6 should not exceed 100 mA.
> 2. The sum of all I OL , for ports B0 - B5, D5 - D7, XTAL1, XTAL2 should not exceed 100 mA.
> 3. The sum of all I OL , for ports D0 - D4, RESET should not exceed 100 mA.
>
> If IOL exceeds the test condition, VOL may exceed the related specification. Pins are not guaranteed to sink current greater than the listed test condition.

And also a similar note for sourcing current.

So although they *can* sink or source more than 20mA, and theoretically up to 40mA, anything more than 20mA is not guaranteed and should be avoided.

Basically overcurrents cause increased heat dissipation in the MOSFETs which causes the internals to break down.  Hence the note about *under steady state conditions*.

So sourcing or sinking more than 20mA for longer than a few ms is asking for trouble. More than 40mA is just being irresponsible.

Furthermore, the MOSFETs in the IO pins act like resistors when turned on.  As you should know, according to Ohm's Law, the voltage across a resistor is proportional to the current through the resistor.  Increase the current and you increase the voltage across the resistor.  Since that resistance is in series with your circuit that voltage gets subtracted from your available voltage on the IO pin - so drawing too much current will cause the voltage to drop (or rise for sinking) below (above) the specifications for the logic voltage for that IO pin.  So not only do you risk damage to the IO pin and other parts of the chip through overheating, but you also then operate outside the specifications for the logic levels which can cause things that you are communicating with to not work right.


message:
Why were Atmel MCUs used for Arduino?

Atmel microcontrollers are not cheap compared to STM and Microchip. Why did Arduino select Atmel MCUs such as atmega328 and atmega2560 on their board out of so many alternatives?

body:
Simply because the Wiring system that Arduino stole was written for the Atmel chips.

Arduino didn't "invent" the Arduino system - they just took an existing system called Wiring and adapted it slightly and branded it Arduino.


message:
Arduino UNO, using 5V and 3.3V

I am newbie in Arduino (using UNO) and as I have 2 components that I wish to connected that one needs 5V and the other need the 3.3V, is it safe to connected them together next to each other?

body:
If a component needs 5V it must be connected to 5V. If it needs 3.3V it must be connected to 3.3V.  Connecting a 3.3V component to a 5V supply is a sure fire way of destroying it.

Furthermore, since the Arduino's main chip is a 5V device, if you want to connect it to a 3.3V device you must use some form of *level translation* so that the 5V signals from the Arduino don't damage the 3.3V device. Also it may (though not always) be necessary to convert the signals from the 3.3V device to a level that the Arduino can understand (5V).


message:
Can't get Ubuntu to see FTDI cable for breadboarding Arduino project

I am in the process of breadboarding an Arduino for a project and am using my FTDI Serial cable [Adafruit FTDI Cable][1] (tested working on Windows 7). I have also tested the breadboarded Arduino successfully on Win7.

When I plug the FTDI Serial cable into my Linux (Ubuntu 14.04 with Mint Desktop) laptop and the other end to my project (exactly as I did for Windows and it works for Win7), the Tools, Port is grayed out when in Linux.

I have tried running Arduino as root, with no success.

The output of : dmesg | tail is

    sudo dmesg | tail
    [  729.069015] usb 4-1.2: New USB device strings: Mfr=1, Product=2,     SerialNumber=3
    [  729.069019] usb 4-1.2: Product: TTL232R-3V3
    [  729.069022] usb 4-1.2: Manufacturer: FTDI
    [  729.069024] usb 4-1.2: SerialNumber: FTF50VXW
    [  729.487689] usb 4-1.2: USB disconnect, device number 4
    [  729.615330] usbcore: registered new interface driver usbserial
    [  729.615384] usbcore: registered new interface driver usbserial_generic
    [  729.615432] usbserial: USB Serial support registered for generic
    [  729.621997] usbcore: registered new interface driver ftdi_sio
    [  729.622057] usbserial: USB Serial support registered for FTDI USB Serial Device

When I type "lsusb" into the terminal, there is no difference between when the FTDI is plugged in and not plugged in.
I have tried switching ports with no success.

Any suggestions?

  [1]: http://www.adafruit.com/products/70

body:
Check if the driver is loaded, in Terminal type:

    lsmod | grep  ftdi_sio

If you get no answer then it's not loaded, load it using:

    sudo modprobe ftdi_sio

I hope this helps.


message:
creating array using string name

I appreciate if someone can help me.
I have a function that counts the time and I would like to store values according to the day.

`For example: day_7.11.2015 = [gain = 100.23, cost = 78.0 ...]
              day_8.11.2015 = ...`

I do not know how can I create an array with these values taking as input the day, month and year. Does anyone have any idea?

`String test = "day_" + String(day) + "." + String(month) + "." + String(year);
float String(test)[] = {11.2, 10, 20, 31.2};
 Serial.println(test);`

Thanks a lot!

body:
What you're talking about is often called a *Hash* or a *Map* or sometimes both together as a *HashMap*.

Unfortunately it's a facility that isn't supported in the Arduino C++ language

There are `map` objects available in normal C++, but they are incredibly expensive to use with regards to memory and they just aren't practical for use on a small microcontroller with memory measured in the kilobytes.

The closest you can probably get is to "invert" the storage, so you have a list of values that happen to be in date order (because that's when you added them) but the "key", a simple sequential number, doesn't define the date.  Instead you store the date inside the array along with the data - assuming you really need to know the date.

A good concept to get to grips with for this is the *struct*.  This is a custom data type which you define and can store a number of other different data types within itself.  You can then make an array or linked list out of those new data types.

For instance, you may have:

    typedef struct {
        int year;
        byte month;
        byte day;
        float gain;
        float cost;
    } Data;

You can then create variables of type "Data" and assign values to the items within it:

    Data myEntry;
    myEntry.year = 2015;
    myEntry.month = 11;
    myEntry.day = 7;
    myEntry.gain = 100.23;
    myEntry.cost = 78.0;

Or assign them directly at creation time:

    Data myEntry = {2015, 11, 7, 100.23, 78.0};

If you wanted to store 100 days' worth of data you could use an array:

    Data myArray[100];

Then you access each slice:

    myArray[0].year = 2015;
    ... etc ...

I mentioned above "assuming you really need to know the date".  Most of the time with this kind of method you really don't need to store the date.  If you have one entry per day and you know *when you started gathering data* then you know that each entry is one day more than the one before it - so you know that the tenth entry is ten days later than when you started gathering data.  Alternatively, if you have a 100 entry circular array (that is, when you reach the end of the array you start filling from the bottom again, so you keep the last 100 days' worth of data) and you know what the date is *today* you can count backwards from today to work out what date each entry is.