message:
Standalone Arduino

I have an Arduino Uno and I am using arduino 1.0.5 IDE. I followed he procedures for bootloading an atmega328P-PU on a breadboard using an Arduino Uno from the link:

https://www.arduino.cc/en/Tutorial/ArduinoToBreadboard

I uploaded the ArduinoISP sketch first, made the connections(using the External Oscillator) and then wired it up. Then, I selected the programmer as Arduino as ISP, selected the board as Arduino duemilanove w/ Atmega328P . Then I selected the correct serial port and clicked Burn Bootloader. I got the following errors:

    avrdude.exe: stk500_program_enable(): protocol error, expect=0x14,
    resp=0x50avrdude.exe: initialization failed, rc=-1 Double check
    connections and try again, or use -F to override this
    check.avrdude.exe: stk500_disable(): protocol error, expect=0x14,
    resp=0x51

How to solve this issue? Also, can I upload the bootloader directly by using it on the Uno in place of the original chip. If so, how?

body:
See [How to make an Arduino-compatible minimal board](http://www.gammon.com.au/breadboard).

> Also, can I upload the bootloader directly by using it on the Uno in place of the original chip.

No, a blank chip cannot install its own bootloader. You use a second chip. My page above describes how to do that. An alternative is a stand-alone ICSP programmer, which can be purchased for around $20. The tutorial page you linked uses your Uno as a stand-alone programmer.

I think my method of [using a Uno as a programmer](http://www.gammon.com.au/bootloader) is easier, frankly.


sender: user

sender: assistant

body: I had the same problem; I never figured it out. I eventually threw down some cash for am ICSP (I got the FreeTronics USBASP), and have never looked back. In fact, with an ICSP, you don't even need a bootloader. It's also real easy to solder a 6-pin header onto your custom soldered board; then you will realize you don't need an Arduino at all, just an Atmel chip.


message:
Reading from a KY-040 rotary encoder with Digispark

I have a rotary encoder KY-040 connected to a Digispark like this:

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

CLK go to p0 and and DT go to p2, SW is disconnected for now (it's just a button).

I did everything like the instructions here: http://henrysbench.capnfatz.com/henrys-bench/keyes-ky-040-arduino-rotary-encoder-user-manual/

    #include <DigiKeyboard.h>

     int pinA = 0;  // Connected to CLK on KY-040
     int pinB = 2;  // Connected to DT on KY-040
     int encoderPosCount = 0;
     int pinALast;
     int aVal;
     boolean bCW;

     void setup() {
       pinMode (pinA,INPUT);
       pinMode (pinB,INPUT);
       /* Read Pin A
       Whatever state it's in will reflect the last position
       */
       pinALast = digitalRead(pinA);
       Serial.begin (9600);
     }

     void loop() {
       aVal = digitalRead(pinA);
       if (aVal != pinALast){ // Means the knob is rotating
         // if the knob is rotating, we need to determine direction
         // We do that by reading pin B.
         if (digitalRead(pinB) != aVal) {  // Means pin A Changed first - We're Rotating Clockwise
           encoderPosCount ++;
           bCW = true;
         } else {// Otherwise B changed first and we're moving CCW
           bCW = false;
           encoderPosCount--;
         }
         Serial.println("Rotated: ");
         if (bCW){
           //Serial.println ("clockwise");
           DigiKeyboard.sendKeyStroke(KEY_V); //or DigiKeyboard.write("1");
         }else{
           //Serial.println("counterclockwise");
            DigiKeyboard.println("cc");
         }
         Serial.print("Encoder Position: ");
         Serial.println(encoderPosCount);

       }
       pinALast = aVal;
     }

I only changed the pin numbers in the code and the `Serial.println (...` to any of the following:

    DigiKeyboard.write("1");
    DigiKeyboard.println("1");
    DigiKeyboard.sendKeyStroke(KEY_V);

All of them didn't do anything when rotating the knob...

Any ideas?
Maybe the 10K resistors are too much?

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

body:
     int pinA = 0;  // Connected to CLK on KY-040
     ...
       Serial.begin (9600);

Hardware Serial uses pins 0 and 1. I would try other pins. (Oh, it's an ATtiny - well I'm not sure about HardwareSerial on that, but it looks suspicious).

See [my page about rotary encoders](http://www.gammon.com.au/forum/?id=11130) for more ideas.

---

> I only changed the pin numbers in the code and the Serial.println (... to any of the following:

Maybe post the code you actually used, that would be helpful. Not some code you didn't use.

---

> Maybe the 10K resistors are too much?

No, that looks fine.


body:
Shown below is a KY-040 test program that in my tests doesn't lose any counts and is more accurate than some other software; it picks up the counts between detents as well as those at detents.  You may be able to adapt it to your DigiKeyboard ATtiny system.

    /*  roto_jw4.ino -- JW, 29 September 2015 --
     *  A 4-state state-machine implementation of rotary
     *  encoding for KY-040 rotary knobs.  The state-machine picture at
     *  https://e2e.ti.com/support/microcontrollers/hercules/f/312/t/318762
     *  in a Feb 4, 2014 7:40 PM post by Anthony Seely shows counts
     *  increasing on transitions 10 -> 11 -> 01 -> 00 -> 10 and
     *  decreasing on transitions the other way.  Transitions between 00
     *  and 11 or 10 and 01 are invalid.  This code detects valid
     *  transitions by (abOld xor abNew) equaling 1 or 2.  It detects
     *  up-count events by the tri-bit value ABA' (where A' is the new
     *  reading on pin A) being equal to 1, 2, 5, or 6 (a bit mask of
     *  0x66), and down-count events by ABA' being equal to 0, 3, 4, or 7
     *  (a bit mask of 0x99).
     *
     *  On a KY-040 unit I tested, there are 30 detent positions per turn.
     *  With this unit the code generates 60 counts per turn, which can be
     *  seen individually as one turns the rotor slowly.  Odd counts
     *  appear between detents, even counts at detents.
     *
     *  Set quadrature-signal pin numbers, via PinA and PinB constants.
     *  Set IPINMODE to INPUT_PULLUP if there are no external pull-ups
     *  on encoder AB pins, else set IPINMODE to INPUT
     */
    enum { PinA=2, PinB=3, IPINMODE=INPUT };

    static  byte abOld;  // Initialize state
    volatile int count;  // current rotary count
             int old_count;  // old rotary count

    void setup() {
      pinMode(PinA, IPINMODE);
      pinMode(PinB, IPINMODE);
      attachInterrupt(0, pinChangeISR, CHANGE); // Set up pin-change interrupts
      attachInterrupt(1, pinChangeISR, CHANGE);
      abOld = count = old_count = 0;
      Serial.begin(115200);
      Serial.println("Starting Rotary Encoder Test");
    }

    // On interrupt, read input pins, compute new state, and adjust count
    void pinChangeISR() {
      enum { upMask = 0x66, downMask = 0x99 };
      byte abNew = (digitalRead(PinA) << 1) | digitalRead(PinB);
      byte criterion = abNew^abOld;
      if (criterion==1 || criterion==2) {
        if (upMask & (1 << (2*abOld + abNew/2)))
          count++;
        else count--;  // upMask = ~downMask
      }
      abOld = abNew;  // Save new state
    }

    void loop() {
      if (old_count != count) {
        Serial.print(millis());
        Serial.print("  ");
        Serial.println(count);
        old_count = count;
      }
    }

Since some ATtiny's only have one external-interrupt pin, it may be necessary to use two pin-change interrupts instead of two external-interrupt pins.
(Six of the pins on an ATtiny45, for example, support pin-change interrupts, and only one is an external-interrupt pin.) Change PinA and PinB to appropriate pin numbers, and replace

      attachInterrupt(0, pinChangeISR, CHANGE); // Set up pin-change interrupts
      attachInterrupt(1, pinChangeISR, CHANGE);

with

      enableInterrupt(PinA, pinChangeISR, CHANGE); // Set up pin-change interrupts
      enableInterrupt(PinB, pinChangeISR, CHANGE);

and add the following `#include` near the beginning:

    #include <EnableInterrupt.h>

To install the .h file for use via the Arduino IDE, unpack an `EnableInterrupt` zip file (for example, `enableinterrupt-0.8.2.zip` from [bintray.com/greygnome](https://bintray.com/greygnome/generic/EnableInterrupt/view#files)) in the directory `~/sketchbook/libraries`.  I think the package works with ATtiny's as well as more-standard Arduinos.


message:
RGBs, photoresistors, and delays

I am having a little trouble with a program of mine. My circuit consists of (mainly) an arduino UNO, two RGB LEDs, and a photoresistor. My current code(programmed in c#) operates the hardware as so: When the lights in the room are on, the two LEDs alternate blue/off once per second in a loop. When the lights are off, or the photoresistor is not sensing any light, both LEDs turn on, and stay on, red.
My code:

    int prPin = A0;

    void setup()
    {
      pinMode(5,OUTPUT);
      pinMode(6,OUTPUT);
      pinMode(7,OUTPUT);
      pinMode(8,OUTPUT);
      pinMode(9,OUTPUT);
      pinMode(10,OUTPUT);
      pinMode(prPin,INPUT);
      Serial.begin(9600);
    }

    void loop()
    {
      int prVal = analogRead(prPin);
      Serial.write(prVal);
        if(prVal>450)
        {
          digitalWrite(5,HIGH);
          digitalWrite(6,HIGH);
          digitalWrite(7,HIGH);
          digitalWrite(8,LOW);
          digitalWrite(9,HIGH);
          digitalWrite(10,HIGH);
          delay(1000);
          digitalWrite(5,LOW);
          digitalWrite(6,HIGH);
          digitalWrite(7,HIGH);
          digitalWrite(8,HIGH);
          digitalWrite(9,HIGH);
          digitalWrite(10,HIGH);
          delay(1000);
        }
        else
        {
          digitalWrite(5,HIGH);
          digitalWrite(6,HIGH);
          digitalWrite(7,LOW);
          digitalWrite(8,HIGH);
          digitalWrite(9,HIGH);
          digitalWrite(10,LOW);
          delay(10);
        }
    }

The problem I am having is when the lights turn off, the LEDs will not operate according to the "else" statement/loop until it finishes going through the "if" statement/loop.
Any suggestions or answers are appreciated. I'm an open book, so I'll take anything you guys give me.

body:
Instead of the two delays of one second, have the program check if the current time is an even or odd number of seconds.

    int prPin = A0;

    void setup()
    {
      pinMode(5,OUTPUT);
      pinMode(6,OUTPUT);
      pinMode(7,OUTPUT);
      pinMode(8,OUTPUT);
      pinMode(9,OUTPUT);
      pinMode(10,OUTPUT);
      pinMode(prPin,INPUT);
      Serial.begin(9600);
    }

    void loop()
    {
        int prVal = analogRead(prPin);
        Serial.write(prVal);
        if(prVal>450)
        {
          if( (millis()/1000)%2 == 0 ) // check if even or odd number of seconds have passes since the program started
          {
            digitalWrite(5,HIGH);
            digitalWrite(6,HIGH);
            digitalWrite(7,HIGH);
            digitalWrite(8,LOW);
            digitalWrite(9,HIGH);
            digitalWrite(10,HIGH);
          }
          else
          {
            digitalWrite(5,LOW);
            digitalWrite(6,HIGH);
            digitalWrite(7,HIGH);
            digitalWrite(8,HIGH);
            digitalWrite(9,HIGH);
            digitalWrite(10,HIGH);
          }
        }
        else
        {
          digitalWrite(5,HIGH);
          digitalWrite(6,HIGH);
          digitalWrite(7,LOW);
          digitalWrite(8,HIGH);
          digitalWrite(9,HIGH);
          digitalWrite(10,LOW);
          delay(10);
        }
    }


message:
Identical statements, different outcome

First a little background on me and my project. Most of my programming experience is with PHP and javascript. I have just recently started looking at C and C++ for this Arduino project. My project is a weather station that feeds its data to a web based database in real time. I will be writing the code for a web site that will access this data base and present the data in realtime. I am currently working on the temperature section of my weather station. It is an RTD coupled to a constant current circuit and feeds a varying voltage to analog pin 5 on my Arduino Uno. My problem is with the code. I have a working code but I decided to make it object oriented so that I could reuse it in other projects. Here is the code that works.

    const unsigned int RTD_PIN = A5;
    const float MVOLTS_CTS = 4.882813;
    const float OHMS_DEGREE = 0.3851;
    const unsigned int SAMPLES = 10;
    const float MILLI_AMPS = 19.125;
    unsigned long currentMillis;
    unsigned long oldMillis = 0;
    unsigned long timeBetweenSamples = 1000; // milliseconds between samples
    int measurement[SAMPLES];
    int read_index = 0;
    int total = 0;
    int average_cts = 0;
    boolean initialized = false;
    float degC = 0;
    float degF = 0;

    void setup() {
      Serial.begin(9600);
      for (int i = 0; i < SAMPLES; i++) {
        measurement[i] = 0;
      }
    }

    void loop() {

      // Reset the counter when we go over the
      // set number of samples
      if (read_index >= SAMPLES) {
        read_index = 0;
        initialized = true;
      }

      // only take a measurement if one second has passed
      currentMillis = millis();

      if (currentMillis - oldMillis >= timeBetweenSamples) {
        // subtract one element from the total
        total = total - measurement[read_index];

        // take a measurement
        measurement[read_index] = analogRead(RTD_PIN);

        // add the new measurement back into the total
        total = total + measurement[read_index];

        // take an average of the readings
        average_cts = total / SAMPLES;

        // calculate degrees
        degC = (average_cts * MVOLTS_CTS / MILLI_AMPS -100) / OHMS_DEGREE;
        degF = degC * 1.8 + 32;

        // print results only if all elements of measurement[] are filled
        if (initialized) {
          Serial.print(degC);
          Serial.print(" degrees C ");
          Serial.print(degF);
          Serial.print(" degrees F ");
          Serial.println(average_cts);
        }

        read_index++;
        oldMillis = currentMillis;

      }
    }

And this is the code that doesn't work.

    #include "Arduino.h"
    #include "Sensor.h"

        Sensor::Sensor (int analogPin, int numSamplesInAverage, unsigned long sampleRate) {

         sensorPin = analogPin;
         samples = numSamplesInAverage;
        _sampleRate = sampleRate;
         int measurement[samples];

         // initialize the measurement array
         for (int i = 0; i >= samples; i++) {
           measurement[i] = 0;
         }

      }

      int Sensor::update() {

     if (read_index >= samples) {
           read_index = 0;
         }

         // only take a measurement if sample rate has been exceeded
         // and return a rolling average
         currentMillis = millis();

         if (currentMillis - oldMillis >= _sampleRate) {
        //subtract one element from the total
           total = total - measurement[read_index];

           // take a measurement
         measurement[read_index] = analogRead(sensorPin);

           // add the new measurement into the total
           total = total + measurement[read_index];

           // take an average of the readings
           average_cts = total / samples;

        // increment the read_index
        read_index++;
        oldMillis = currentMillis;

       return average_cts;
         }

         // return false if the sample rate has not expired
         return false;

      }

It seems like the issue is with this one line of code on line 34.

    measurement[read_index] = analogRead(sensorPin);

When this line has not been remarked out the read_index only goes to 4 before it resets to 0 and it does it at the rate of program execution instead of every second like expected.

If this line is remarked out the the read_index is incremented from 0 to 9 once every second as expected.

Here is where the read_index is defined.

    #ifndef Sensor_h
    #define Sensor_h

    #include "Arduino.h"

    class Sensor
    {
       public:
         Sensor(int analogPin, int numSamplesInAverage, unsigned long sampleRate);
         int update();

       private:
         unsigned int sensorPin;
         unsigned long currentMillis;
         unsigned long oldMillis;
         unsigned long sampleRate; // milliseconds between samples
         int read_index = 0;
         int total = 0;
         int average_cts = 0;
         int samples;
         unsigned long _sampleRate;
         int measurement[];
    };

    #endif

and this is the Arduino sketch that calls update()

    #include <Sensor.h>

    Sensor rtd(4, 10, 1000);  // instantiate a Sensor object
    int cts;

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

    void loop() {

      rtd.update();

      Serial.println(rtd.read_index);
    }

can anyone tell me why this works in my procedural code but not the objected oriented code?

body:
You have made a few fundamental errors with your class.

Firstly you have not provided a storage size (number of elements) for the `measurement` array class member variable:

    class Sensor
    {
       public:
         Sensor(int analogPin, int numSamplesInAverage, unsigned long sampleRate);
         int update();

       private:
         // ... cut ...
         int measurement[];           // <<-- How big is this?!
    };

Then it seems like you try to dynamically allocate the space for it in your constructor:

    Sensor::Sensor (int analogPin, int numSamplesInAverage, unsigned long sampleRate) {

        sensorPin = analogPin;
        samples = numSamplesInAverage;
        _sampleRate = sampleRate;
        int measurement[samples];    // <<-- Here
        // ... cut ...
    }

BUT that's *not* what you are doing.  What you are doing there is creating a *new* local variable (local to *just that one single function*) called `measurement` with an array size of `samples`.  As soon as you leave the constructor that variable is thrown away.

You haven't touched the class member variable `measurement` at all.  So, when you do:

    measurement[read_index] = analogRead(sensorPin);

you are storing the read value into an array of no size that points nowhere.  And of course that then causes a crash because you're writing to memory that you shouldn't be writing to.

If you want to be specifying the number of array elements in the constructor you need to be learning about *dynamic memory allocation* using `malloc()` and `free()` and all the pitfalls that go along with using those on a small microcontroller with very tight RAM constraints.

For an example of how it can be done you should take a look at my [Average Library](https://github.com/MajenkoLibraries/Average) which uses dynamic allocation to allocate the array memory in the constructor and free it in the destructor.


body:
I was going to add to Majenko's excellent answer, but what I want to say is too long. :)

---

Change:

    int measurement[];

to:

    int * measurement;

and then in the constructor do:

    measurement = new int [samples];

And check that measurement is not NULL, in case there is not enough memory.

---

Also, this is wrong in two ways:

    // initialize the measurement array
    for (int i = 0; i >= samples; i++) {
      measurement[i] = 0;

It should be:

    // initialize the measurement array
    for (int i = 0; i < samples; i++) {
      measurement[i] = 0;

You need to test less than, and you don't test equals (that would initialize one too many).

---

You should also have a destructor that frees the memory, ie.

    delete [] measurement;

---

> When would this destructor come into play? How and when should I call it?

The destructor is automatically called when an instance of the class is destroyed. This is when you do things like free memory you allocated. You don't call it directly.

An example:

    class Sensor
    {
    public:
      // constructor
      Sensor(int analogPin, int numSamplesInAverage, unsigned long mysampleRate);
      // destructor
      ~Sensor ();
      // call to update samples
      int update();

    private:
      unsigned int sensorPin;
      unsigned long currentMillis;
      unsigned long oldMillis;
      unsigned long sampleRate; // milliseconds between samples
      int read_index;
      int total;
      int average_cts;
      int samples;
      int * measurement;
    };

    Sensor::Sensor (int analogPin, int numSamplesInAverage, unsigned long mysampleRate)
      {
      sensorPin = analogPin;
      samples = numSamplesInAverage;
      sampleRate = mysampleRate;
      read_index = 0;
      total = 0;
      average_cts = 0;
      measurement = new int [samples];

      if (measurement == NULL)
        exit (1);  // can't continue

      // initialize the measurement array
      for (int i = 0; i < samples; i++) {
        measurement[i] = 0;
      }

    }  // end of constructor

    // destructor
    Sensor::~Sensor ()
      {
      delete [] measurement;
      }  // end of destructor

---

> Can you please explain how these two line of code work `int * measurement` and `measurement = new int [samples];`

`int * measurement` creates a pointer to an int (called `measurement`). However pointers can also point to the start of an array (or indeed, to the middle of an array) of ints. So this variable will hold the start of your array of ints.

`measurement = new int [samples];` allocates the memory for this array - in this case "samples" lots of ints.

Once the memory is allocated you can treat the pointer as an array, eg.

    measurement [5] = 42;

For more detail about this see [So what is meant by the "equivalence of pointers and arrays" in C?](http://c-faq.com/aryptr/aryptrequiv.html) and also Google: `pointer vs array`.

Also Google: `new` and `delete` with reference to the C++ language.


message:
Interrupt not firing on motion

I'm trying to get [MMA8452Q](http://www.freescale.com/files/sensors/doc/data_sheet/MMA8452Q.pdf) to trigger an interrupt when motion is detected and wonder if I'm missing something very obvious here.

So I setup CTRL_REG4 to 0x0B with

    void MMA8452Q::setupISR()
    {
     writeRegister(CTRL_REG4, 0x0B);
    }

then I setup FF_MT with

    void MMA8452Q::setupFF_MT()
    {
     writeRegister(FF_MT_CFG, 0xF8);
     writeRegister(FF_MT_THS, 0x0F);
     writeRegister(FF_MT_COUNT, 0x00);
    }

and I read ISR with

    #define SRC_PULSE 2
    #define SRC_FF_MT 1

    byte MMA8452Q::readISR()
    {
     byte intStat = readRegister(INT_SOURCE);

     if (intStat & 0x0B)
     {
      readRegister(FF_MT_SRC);
      return intStat & 0x0B;
     }
     else
      return 0;
    }

    void printISR()
    {
      byte isr = (accel.readISR() >> 2);
      if (isr & SRC_PULSE)
        Serial.print("(ISR) Tap");
      else
        Serial.print("(ISR) No Tap");

      Serial.print("\t");

      if (isr & SRC_FF_MT)
        Serial.print("(ISR) Motion");
      else
        Serial.print("(ISR) No Motion");

      Serial.print("\t");
    }

AFAIK, that should already have FF/MT interrupt enabled. Even when I'm getting readings in `FF_MT_SRC`, I'm not picking up an interrupt in `INT_SOURCE`.

Interrupts are fired on (most) taps, but not on motion at all.

Am I missing something here?

Thanks

body:
Here's an extract from page 39 of MMA8452Q-rev8.1.pdf, the MMA8452 spec sheet:

[![interrupt enable bits][1]][1]

Rather than saying `writeRegister(CTRL_REG4, 0x0B);` in `MMA8452Q::setupISR()`, try `writeRegister(CTRL_REG4, 0xD);`.

0xB is 1011 in binary, while 0xD is 1101, which turns on INT_EN_FF_MT to enable freefall/motion interrupts.

The above should answer your question as asked.  The following expands on my earlier comment which said
>Absent other info, it looks like MMA8452Q::readISR() is not an interrupt processing routine, but instead a routine that polls an interrupt-source register to find out what source would have triggered an interrupt if correctly wired and initialized.

"Interrupt" as used in your question (and code) refers to when the MMA8452 signals (via an I1 or I2 output line) that an interrupt-worthy condition has occurred.

"Interrupt" as in the question does not refer to an interrupt from the Uno's point of view, because (per diagram) neither of I1 or I2 connects to the Uno.

If speed of response becomes important, you may wish to hook I1 or I2 to one of the Uno's Digital Pins With Interrupts, ie pin 2 or 3, as noted in the [AttachInterrupt](https://www.arduino.cc/en/Reference/AttachInterrupt) page at arduino.cc.  Then you'd replace the polling loop that now periodically reads the MMA8452's ISR (interrupt status register) to check for set bits, with an interrupt service routine which would set a flag to cause loop() to use Wire.read to get ISR data.

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


message:
Help with socketIO Example

I'd like to get a TCP based connection from an arduino to a node.JS server. I found an example, I've tried to run it but its throwing the errors below, would appreciate any help.

Error Messages
    Arduino: 1.6.6 Hourly Build 2015/09/24 05:43 (Windows 7), Board: "Arduino/Genuino Uno"

    WARNING: Category '' in library ArduinoJson is not valid. Setting to 'Uncategorized'
    socketio.ino: In function 'void hello(Client&, const char*)':

    socketio:19: error: expected unqualified-id before '.' token

    socketio.ino: In function 'void setup()':

    socketio:38: error: invalid conversion from 'void (*)(Client&, const char*)' to 'void (*)(Client&, ArduinoJson::JsonArray&)' [-fpermissive]

    In file included from socketio.ino:6:0:

    C:\arduino_1.6.6\libraries\socket.io-arduino-client.2/SocketIOClient.h:56:8: error:   initializing argument 2 of 'void SocketIOClient::setEventHandler(const char*, void (*)(Client&, ArduinoJson::JsonArray&))' [-fpermissive]

       void setEventHandler(const char* eventName, void (*handler)(Client& client, JsonArray& data));

            ^

    socketio:39: error: invalid conversion from 'void (*)(Client&, const char*)' to 'void (*)(Client&, ArduinoJson::JsonArray&)' [-fpermissive]

    In file included from socketio.ino:6:0:

    C:\arduino_1.6.6\libraries\socket.io-arduino-client.2/SocketIOClient.h:56:8: error:   initializing argument 2 of 'void SocketIOClient::setEventHandler(const char*, void (*)(Client&, ArduinoJson::JsonArray&))' [-fpermissive]

       void setEventHandler(const char* eventName, void (*handler)(Client& client, JsonArray& data));

            ^

    exit status 1
    expected unqualified-id before '.' token

      This report would have more information with
      "Show verbose output during compilation"
      enabled in File > Preferences.

Arduino Code
    #include <SPI.h>
    #include <Ethernet.h>

    #include <ArduinoJson.h>
    #include <SocketIOClient.h>

    EthernetClient ethClient;
    SocketIOClient client(ethClient);

    byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
    char hostname[] = "192.168.100.40";
    int port = 3000;

    // Socket.io "hello" EVENT handler
    void hello(Client& client, char const * data) {
        Serial.print("[hello] event happening: ");
        Serial.println(data);
        Client.emit("goodbye", "Arduino here, goodbye!");
    }

    // Socket.io "goodbye" EVENT handler
    void goodbye(Client& client, char const * data) {
        Serial.print("[goodbye] event happening: ");
        Serial.println(data);
        Serial.println("That is all.");
    }

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

        if(!client.connect(hostname, port)) {
            Serial.println(F("Not connected."));
        }

        //Event hanlders
        client.setEventHandler("hello", hello);
        client.setEventHandler("goodbye", goodbye);

        //Say hello to the server
        client.emit("hello", "Arduino here, hello!");
    }

    void loop() {
        client.monitor();
    }

SocketIO.h

    /*
     socket.io-arduino-client: a Socket.IO client for the Arduino

     Based on Bill Roy's Arduino Socket.IO Client (which is based on
     Kevin Rohling's Arduino WebSocket Client) with event handling by
     @dantaex

     Copyright 2014 Quentin Pigné

     Permission is hereby granted, free of charge, to any person
     obtaining a copy of this software and associated documentation
     files (the "Software"), to deal in the Software without
     restriction, including without limitation the rights to use,
     copy, modify, merge, publish, distribute, sublicense, and/or sell
     copies of the Software, and to permit persons to whom the
     Software is furnished to do so, subject to the following
     conditions:

     The above copyright notice and this permission notice shall be
     included in all copies or substantial portions of the Software.

     THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
     EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
     OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
     NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
     HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
     WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
     FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
     OTHER DEALINGS IN THE SOFTWARE.
    */

    #ifndef SocketIOClient_H
    #define SocketIOClient_H

    #include <Arduino.h>
    #include <Client.h>
    #include <SPI.h>

    #include <ArduinoJson.h>

    #include "HashMap.h"

    //Length of static data buffers
    #define DATA_BUFFER_LEN 200
    #define SID_LEN 24

    //Max size of the HashTable
    #define HASH_SIZE 20

    class SocketIOClient {
     public:
      SocketIOClient(Client& client);
      //Public connection methods
      bool connect(const char* hostname, int port = 80, const char* resource = "socket.io", const char* nsp = "/");
      //Public event handling methods
      void setEventHandler(const char* eventName, void (*handler)(Client& client, JsonArray& data));
      //Public data emitting methods
      void emit(const char* event, const char* data);
      //Monitoring for incoming data
      void monitor();

     private:
      //Connection attributes
      Client& client;
      char* hostname;
      int port;
      char* resource;
      char* nsp;
      char sid[SID_LEN];
      //Incoming data reading attributes
      char databuffer[DATA_BUFFER_LEN];
      char* dataptr;
      //Event handling attributes
      int nbEvent;
      static HashType<const char*, void(*)(Client& client, JsonArray& data)> hashRawArray[HASH_SIZE];
      static HashMap<const char*, void(*)(Client& client, JsonArray& data)> eventHandlers;

      //Private incoming data reading methods
      bool waitForInput();
      void eatHeader();
      void readInput();
    };

    #endif

body: Make your `char *` parameters `const char *`.


message:
Sketch will not start with external power source

NOOB Question: when my Uno is connected to an external power source it will not start running the uploaded sketch. The Arduino web site says it's because the RX pin is not connected and then gets random data.

The site suggests grounding the RX pin using a resistor (granted it suggests a 10K and I used a smaller one ) or connecting it to the TX pin.

From [Why doesn't my sketch start when I power up or reset the Arduino board?][1]

> Most likely because you are sending serial data to the board when it
> firsts turns on. During the first few seconds, the bootloader (a
> program pre-burned onto the chip on the board) listens for the
> computer to send it a new sketch to be uploaded to the board. After a
> few seconds without communication, the bootloader will time out and
> start the sketch that's already on the board. If you continue to send
> data to the bootloader, it will never time out and your sketch will
> never start. You'll either need to find a way to stop serial data from
> arriving for the first few seconds when the board powers (e.g. by
> enabling the chip that sends the data from within your setup()
> function) or burn your sketch onto the board with an external
> programmer, replacing the bootloader.

From [Why doesn't my sketch start when I'm powering the board with an external power supply? (Arduino Diecimila or earlier)][2]

> Because the RX pin is unconnected, the bootloader on the board may be
> seeing garbage data coming in, meaning that it never times out and
> starts your sketch. Try tying the RX pin to ground with a 10K resistor
> (or connecting RX directly to the TX pin).

Both failed for me.

What should I do?

  [1]: https://www.arduino.cc/en/Guide/Troubleshooting#toc19
  [2]: https://www.arduino.cc/en/Guide/Troubleshooting#toc6

body: The problem was, as Gerben said, the battery was too weak to run the engine.


body:
I also had a similar problem running with an external power supply.  In my case the sketch ran but totally incorrectly .  Conected RX to ground with a 10K Ohm resistor and solved the problem.

Thanks for the info!!  Others have spent a lot more time solving this problem than I did.


body:
I will add my little drop of experience here...   So I am using a display tm1637, having CLK in 6 and DIO in 5. When connecting the Battery (12V 3s lipo 4000mA) to Vin, the arduino will freeze, even connected to the USB, will still freeze.

Short version, Moving DIO from 5 to 7 corrected the problem, now i have my device running from USB and or battery with no problem.

Long version: after 3 hours of trying different mods, including resistor to RX,TX, to GND, even removing the ch340 chip and connecting Rts and others to GND/VCC..  Nothing, so i decided to move the different devices from One nano to Other but testing after each connection. When the display was connected, the Nano will freeze while running on battery power. So... i moved DIO first to a different pin, and the device started working.  I know is a very particular case, but one more thing to try if you are like me, stock without knowing what to do.... moving some pins (maybe skipping 5?)...


message:
Connect GPS module with GPS antenna SIM39EA to Arduino Uno

I bought a GPS module with GPS antenna SIM39EA online.

The manual for the GPS module is here:

http://www.vis-plus.ee/pdf/SIM39EA_Hardware_Design_V1.00.pdf

I have an Arduino board. It has 3 ground pin, one Vcc and two input/output pin.

I want to know how can I connect this module to Arduino GPS module and get GPS coordinates?

body:
Your data comes back via the GPS's UART port.
Use the softserial library to create a second serial port on your Arduino (means you can still use the normal serial to read the console).

Then write a program that sucks data from the GPS and squirts it out of the Arduino serial port back to your PC using printf.

I only had a quick flick through and didn't see the default serial speed, so start with 9600 and experiment.

What should come out is probably a line of comma separated values which is in NEMA format.  Google for the specification and you will be able to find out the bits of interest.

Hope that helps.


message:
Can send AT+ commands, but can't upload sketch to ESP8266 via Arduino Uno

Connected a generic ESP8266 to an Arduino Uno.

I can send AT commands fine and generate a normal response, but cannot upload sketches to the ESP8266. I have "Generic ESP8266 Module selected as the board. Tried everything e.g. switching Tx and Rx, connecting GPIO0 and GPIO2 to to Vcc or ground, but to no avail.

Arduino IDE spits this out -

    esptool v0.4.5 - (c) 2014 Ch. Klippel <ck@atelier-klippel.de>
     setting board to ck
     setting baudrate from 115200 to 115200
     setting port from COM1 to COM3
     setting address from 0x00000000 to 0x00000000
     espcomm_upload_file
     stat C:\Users\Michael\AppData\Local\Temp\build7227402767538495982.tmp/wifi_setup.cpp.bin success
     setting serial port timeouts to 1000 ms
    opening bootloader
    resetting board
    trying to connect
     flush start
     setting serial port timeouts to 1 ms
     setting serial port timeouts to 1000 ms
     flush complete
     espcomm_send_command: sending command header
     espcomm_send_command: sending command payload
     read 0, requested 1
    trying to connect
     flush start
     setting serial port timeouts to 1 ms
     setting serial port timeouts to 1000 ms
     flush complete
     espcomm_send_command: sending command header
     espcomm_send_command: sending command payload
     espcomm_send_command: receiving 2013 bytes of data
     read 0, requested 1
    error: failed reading byte
    warning: espcomm_send_command: cant receive slip payload data
    trying to connect
     flush start
     setting serial port timeouts to 1 ms
     setting serial port timeouts to 1000 ms
     flush complete
     espcomm_send_command: sending command header
     espcomm_send_command: sending command payload
     espcomm_send_command: receiving 2013 bytes of data
     read 0, requested 1
    error: failed reading byte
    warning: espcomm_send_command: cant receive slip payload data
    resetting board
    trying to connect
     flush start
     setting serial port timeouts to 1 ms
     setting serial port timeouts to 1000 ms
     flush complete
     espcomm_send_command: sending command header
     espcomm_send_command: sending command payload
     read 0, requested 1
    trying to connect
     flush start
     setting serial port timeouts to 1 ms
     setting serial port timeouts to 1000 ms
     flush complete
     espcomm_send_command: sending command header
     espcomm_send_command: sending command payload
     espcomm_send_command: receiving 2013 bytes of data
     read 0, requested 1
    error: failed reading byte
    warning: espcomm_send_command: cant receive slip payload data
    trying to connect
     flush start
     setting serial port timeouts to 1 ms
     setting serial port timeouts to 1000 ms
     flush complete
     espcomm_send_command: sending command header
     espcomm_send_command: sending command payload
     espcomm_send_command: receiving 2013 bytes of data
     read 0, requested 1
    error: failed reading byte
    warning: espcomm_send_command: cant receive slip payload data
    resetting board
    trying to connect
     flush start
     setting serial port timeouts to 1 ms
     setting serial port timeouts to 1000 ms
     flush complete
     espcomm_send_command: sending command header
     espcomm_send_command: sending command payload
     read 0, requested 1
    trying to connect
     flush start
     setting serial port timeouts to 1 ms
     setting serial port timeouts to 1000 ms
     flush complete
     espcomm_send_command: sending command header
     espcomm_send_command: sending command payload
     espcomm_send_command: receiving 2013 bytes of data
     read 0, requested 1
    error: failed reading byte
    warning: espcomm_send_command: cant receive slip payload data
    trying to connect
     flush start
     setting serial port timeouts to 1 ms
     setting serial port timeouts to 1000 ms
     flush complete
     espcomm_send_command: sending command header
     espcomm_send_command: sending command payload
     espcomm_send_command: receiving 2013 bytes of data
     read 0, requested 1
    error: failed reading byte
    warning: espcomm_send_command: cant receive slip payload data
    warning: espcomm_sync failed
    error: espcomm_open failed

body: I have been hooking the ESP8266 straight up to my PC and programming it in NodeLua.  Of course it depends on what you want to do, but consider dropping the Arduino and just using the ESP8266.


body:
You mention:

> connecting GPIO0 and GPIO2 to to Vcc or ground

I've had success with this sequence:

 - GPIO0 to gnd (and hold momentarily)
 - RST to gnd (then let go, while holding GPIO0 to gnd)
 - let go of GPIO0 from gnd (e.g. let it float again)

To do a firmware flashing, you need to hold GPIO0 to ground for the duration of the flashing process, so the sequence would be slightly different.

You can do this just prior to "build and upload" in the Arduino IDE—provided the build process doesn't take too long.  It will sometimes still fail, in which case reset the ESP8266 (RST to gnd momentarily) and restart the sequence.

I've found a little test/development harness (like this one http://www.buildcircuit.com.au/esp8266-test-board) is very handy for doing this repeatedly.


body:
You don't need an Arduino UNO to program the ESP. You just need an USB to UART adapter (CP210x or FTDI one) and the Arduino IDE. Hook the ESP rx and tx to the tx an rx of the adapter and you are ready to go.
Here is an detailed explanation [how to program ESP using arduino][1]

If you don't have an USB to UART bridge you can use the Arduino board as bridge: [check this][2]

  [1]: http://ezbitz.com/program-esp8266-using-arduino-ide/
  [2]: http://microcontrollerkits.blogspot.ro/2015/05/esp8266-firmware-update-with-arduino.html


message:
How to make an Arduino USB programming circuit?

I am designing a PCB in which I am using the MCU used in **`Arduino UNO`** which is **`Atmega328P`** and some other components as per my project requirements. I have almost designed the circuit but I am confused with the USB programming part. I want my MCU to be programmed using **`USB B Type`** just like we do it in **`Arduino UNO`**. My friend suggests me to purchase an **`Arduino UNO`** device and program that MCU and then put it in my circuit. But I don't want to do it like this. I have found the [**schematic design**](https://www.arduino.cc/en/uploads/Main/arduino-uno-schematic.pdf) but its very confusing. Can anyone help me out with this.?

body: Looking at the schematic design, you need atmega8 to make a usb programming connection. Design your circuit exactly like in the schematic.You will also need bootloader for it, so use any programmer like usbasp, connect its pins to mosi, miso sck, rst,vcc,gnd and click on burn boot loader in arduino ide


body:
It is quite a lot simpler to obtain an [FTDI USB - TTL Serial cable][1]. (The link goes to the American supplier, Sparkfun, but such cables are available from many online suppliers.) They are typically made with a 6-pin female header instead of a USB B connector; you may have to make up that part yourself, if it is important to you. If you only need USB functionality for programming, one cable can serve any number of boards (one at a time, of course), no need to build it into each board.

  [1]: https://www.sparkfun.com/products/9718


body: If you wanted a more permanent option on the board, you could also add a USB to FTDI chip like this: http://www.mouser.com/Search/m_ProductDetail.aspx?FTDI/FT232RL-REEL/&qs=D1/PMqvA103RC6OU6bKtoA==&gclid=CNmDjr7dvssCFYZefgod9jgPeQ


message:
Arduino coding of producing frequency

Im new here. Anyone that could give a code or sample that would generate I wanted to use a frequency in range of 35k-43kHz. Please help me.

body:
use the 'tone' function:
[arduino tone function][1]

  [1]: https://www.arduino.cc/en/Reference/Tone
example:

    //tone(pinNumber, FrequencyInHertz);
    tone(6, 35000); //generate a 35kHz tone on pin 6
    delay(10);
    tone(6, 43000); //generate a 43kHz tone on pin 6


body:
The code below generates 38 kHz and modulates its duty cycle.

    // Example of modulating a 38 kHz frequency duty cycle by reading a potentiometer
    // Author: Nick Gammon
    // Date: 24 September 2012

    const byte POTENTIOMETER = A0;
    const byte LED = 10;  // Timer 1 "B" output: OC1B

    // Clock frequency divided by 38 kHz frequency desired
    const long timer1_OCR1A_Setting = F_CPU / 38000L;

    void setup()
     {
      pinMode (LED, OUTPUT);

      // set up Timer 1 - gives us 38.005 kHz
      // Fast PWM top at OCR1A
      TCCR1A = bit (WGM10) | bit (WGM11) | bit (COM1B1); // fast PWM, clear OC1B on compare
      TCCR1B = bit (WGM12) | bit (WGM13) | bit (CS10);   // fast PWM, no prescaler
      OCR1A =  timer1_OCR1A_Setting - 1;                 // zero relative
      }  // end of setup

    void loop()
      {
      // alter Timer 1 duty cycle in accordance with pot reading
      OCR1B = (((long) (analogRead (POTENTIOMETER) + 1) * timer1_OCR1A_Setting) / 1024L) - 1;

      // do other stuff here
      }


message:
Basic Serial Transmission Protocol

I have a small piece of code here that I hope to run on Arduino. Basically what this code is doing is, it takes a nibble from the user, appends a `startbit` to it, and transmits the code through a transmitter module. The receiver end receives the bits and checks if `startbit` is being received. If `startbit` is not being received, then it prints out whatever was transmitted. If `startbit` is received, then it doesn't print the startbit, just the nibble all in one line.

My question is: is it convention/clever to use the bool array or should I not do that? Second, is there a way to make my code more efficient? Where can I clean it up? Also, is my code legible or very convoluted?

    #include <Arduino.h>
    #include <WirelessComm.h>

    int tx_pin;
    int rx_pin;
    WirelessComm::WirelessComm(int rxPin, int txPin)
    {
        pinMode(rxPin, INPUT);
        tx_pin = txPin;
        rx_pin = rxPin;
    }

    int countDigit(long n)
    {
        int count = 0;
        while (n > 0)
        {
            n /= 10;
            count++;
        }
        return count;
    }

    void getDigit(bool *data, long num)
    {
        int cd = countDigit(num);
        long shift = 1;
        for (int i = 0; i < cd; i++)
        {
            data[i] = (num / shift) % 10;
            shift *= 10;
        }
    }

    int WirelessComm::writeTx(long nibble)
    {
        int i;
        bool data[11]; // warning: I didn't check for buffer overrun!
        int32_t startBit = 110101L; // larger than 32767, so cannot be in int
        if(nibble != 0)
        {
            int sbLen = countDigit(startBit);
            for (int i = 0; i < (int)(sizeof(data) / sizeof(data[0])); i++)
                data[i] = 0;
            getDigit(data, startBit);
            getDigit(data + sbLen, nibble);
        }
        else
            return -1;

        for(i = 0; i < 10; i++)
        {
            if(data[i] == 1)
            {
                digitalWrite(tx_pin, HIGH);
            }
            else
            {
                digitalWrite(tx_pin, LOW);
            }

        }
        return 1;
    }

    int WirelessComm::readRx(long nibble)
    {
        bool first = 0;
        bool second = 2; //initially set to some random value
        bool third = 2;
        bool fourth = 2;
        bool fifth = 2;
        bool sixth = 2;
        bool counter = 0;
        bool val = 0;
        while(true)
        {
            first = digitalRead(rx_pin);
            if(first == 1);
            {
                second = digitalRead(rx_pin);
                if(second == 1)
                {
                    third = digitalRead(rx_pin);
                    if(third == 0)
                    {
                        fourth = digitalRead(rx_pin);
                        if(fourth == 1)
                        {
                            fifth = digitalRead(rx_pin);
                            if(fifth == 0)
                            {
                                sixth = digitalRead(rx_pin);
                                if(sixth == 1)
                                {
                                    while(counter < 4)
                                    {
                                        val = digitalRead(rx_pin);
                                        Serial.print(val);
                                        counter++;
                                    }
                                    Serial.println();

                                }
                                else
                                    Serial.println(first);
                                    first = digitalRead(rx_pin);
                            }
                            else
                                Serial.println(first);
                                first = digitalRead(rx_pin);
                        }
                        else
                            Serial.println(first);
                            first = digitalRead(rx_pin);
                    }
                    else
                        Serial.println(first);
                        first = digitalRead(rx_pin);
                }
                else
                    Serial.println(first);
                    first = digitalRead(rx_pin);
            }
            else
                Serial.println(first);
                first = digitalRead(rx_pin);
        }
    }

body:
What you are doing is called "bit-banging" [(wikipedia link)](https://en.wikipedia.org/wiki/Bit_banging) but you have no guarantees about the timing of your bits.

In your `writeTx` routine you are changing `tx_pin` at some rate which depends on:

1. the clock speed of your MCU
2. the code that the C compiler generates

Moreover, the timing will be all screwed up if you happen to get an interrupt while sending the bits.

The same applies to your read routine.

The Arduino (really the Atmel MCU) has special hardware to perform both synchronous and asynchronous serial IO. The set up is rather complex because the hardware
is very versatile and capable of a lot of different functions.
In particular, it can deliver the bits at a specific baud rate for you so your code doesn't have to do it. It can also read in a serial stream and set a flag or invoke an interrupt when a complete word has been received.

This article can give you an idea of what the USART in an Atmel processor is capable of:

http://maxembedded.com/2013/09/the-usart-of-the-avr/


body:
<!-- language-all: lang-C++ -->

> So to clarify, SoftwareSerial uses bit-bang? How are you able to tell?

By reading the code. For example, this is how it reads 8 bits. It does a delay (which you don't) for the exact amount of time, and then reads the pin, and "ors" it into the variable which is the assembled byte.

    // Read each of the 8 bits
    for (uint8_t i=0x1; i; i <<= 1)
    {
      tunedDelay(_rx_delay_intrabit);
      DebugPulse(_DEBUG_PIN2, 1);
      uint8_t noti = ~i;
      if (rx_pin_read())
        d |= i;
      else // else clause added to ensure function timing is ~balanced
        d &= noti;
    }

---

And to write the 8 bits:

    // Write each of the 8 bits
    for (byte mask = 0x01; mask; mask <<= 1)
    {
      if (b & mask) // choose bit
        tx_pin_write(HIGH); // send 1
      else
        tx_pin_write(LOW); // send 0

      tunedDelay(_tx_delay);
    }

---

Your rather elaborate nested `if` just seems complete overkill, when you see how SoftwareSerial does it in half a dozen lines.

---

Another typo:

    if(first == 1);

You don't want that semicolon.

---

> Second, is there a way to make my code more efficient?

Use loops, like SoftwareSerial does.

> Also, is my code legible or very convoluted?

Very convoluted.

> Where can I clean it up?

I suggest you browse through the SoftwareSerial library for ideas.

Meanwhile, HardwareSerial is available, so you don't need to write any of this. For that matter, SoftwareSerial is available too. If you are just doing it to learn, well and good.

---

You really should read about loops. Whenever I have to do something 8 times I have a loop of 8 (or even for "x" times, a loop of "x"). Unrolling into 8 different variables is just confusing and prone to errors. As you had, before you fixed it, doing `if(fourth = 1)` instead of `if(fourth == 1)`.


message:
Arduino Pro Micro Analog Pinouts

I have the Arduino Pro Micro and I would like to use all the **analog** pins that I can on it.

It currently looks like it has a total of **9 Analog pins** that can be used.
[![enter image description here][1]][1]

A0, A1, A2, A3, A6, A7, A8, A9 and A10.

However, I am unsure how to call these pins since all of those are also **digital pins**.

Would A0-A3 be defined as:

    #define analog1 A0;
    #define analog2 A1;
    #define analog3 A2;
    #define analog4 A3;

While the other pins would be this?:

    #define analog5 4;
    #define analog6 6;
    #define analog7 8;
    #define analog8 9;
    #define analog9 10;

Then just call:

    analogRead(analog1);
    analogRead(analog2);
    .....
    analogRead(analog8);
    analogRead(analog10);

Would that be the correct way of defining the 9 analog pins?

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

body: Assuming you have the Pro Micro core, they are called A0, A1, A2, A3, A6, A7, A8, A9 and A10. There is no need to "special case" the others, since the pins are known as both.


message:
How to fix baud rate when hardware capacity has a low limit?

I have a transmitter(simple [433 MHz transmitter][1]) connected via digital pins on the Arduino. The receiver is connected to another arduino.
Now, I kept that pin on HIGH for 1 second, and it transmits only 1000 ones.
But I've seen different example transmitter sketches having baud rates of 1200, 9600, etc.
So the situation is, when the transmitter is transmitting at maximum capacity(just HIGH for a whole second), it can only transmit 1000 ones.

I am able to read that it only transmits 1000 ones because my receiver just has a simple read function that reads and prints the data. and it prints 1000 ones every second. Give or take one or two.
So when you specify a baud rate of 1200, is it useless? how will it transmit 1200 bits/sec?
Does the baud rate actually increase the hardware limit or what exactly is going on? Can someone please provide me some insight into this? I'd be glad to clarify this question more if need be.

  [1]: http://www.ebay.com/itm/433Mhz-RF-transmitter-and-receiver-kit-for-Arduino-ARM-MCU-WL-/261041100836

body:
The transmitter you're using is very basic, and only transmits "on" and "off". As such it is *protocol-agnostic*. In order to use it effectively we use it with a protocol that uses "on" and "off" as its signalling, but also includes framing information so that we can know when the data flow starts and stops.

One such protocol is the UART protocol consisting of 1 start bit, 5 to 9 data bits, an even, odd, or no parity bit, and 1, 1.5, or 2 stop bits, all being generated at a specific rate. This rate is the "baud rate", and must match in both the sending device's and the receiving device's UART in order for them to communicate. This is true whether the devices are connected by a wire, an optical link, or a radio link.

The TX and RX pins on an Arduino are connected to a hardware UART which will handle the framing and signal generation for you. The hardware UART(s) can be accessed via `Serial` on non-USB-native Arduinos as well as `Serial1`, `Serial2`, and `Serial3` on Arduinos where they are present.

Additionally, `SoftwareSerial` can be used to generate a UART signal on arbitrary pins in software, but you're almost always better off using a hardware UART when possible.


message:
How do you make the arduino go forward,backward and stop using Infrared?

Please give me a code and diagram use makeblock i.r sensor V2.1 and makeblock remote. It should be connected to a d.c motor that works with a h-bridge.It also has to be a dual motor which combines these two codes:

1:This one for the movement

    const int controlPin1 = 2; // connected to pin 7 on the H-bridge
    const int controlPin2 = 3; // connected to pin 2 on the H-bridge
    const int enablePin = 9; // connected to pin 1 on the H-bridge
    const int directionSwitchPin = 4; // connected to the switch for direction
    const int onOffSwitchStateSwitchPin = 5; // connected to the switch for turning the motor on and off
    const int potPin = A0; // connected to the potentiometer's output

    // create some variables to hold values from your inputs
    int onOffSwitchState = 0; // current state of the On/Off switch
    int previousOnOffSwitchState = 0; // previous position of the on/off switch
    int directionSwitchState = 0; // current state of the direction switch
    int previousDirectionSwitchState = 0; // previous state of the direction switch

    int motorEnabled = 0; // Turns the motor on/off
    int motorSpeed = 0; // speed of the motor
    int motorDirection = 1; // current direction of the motor

    void setup()
    {
     // intialize the inputs and outputs
     pinMode(directionSwitchPin, INPUT);
     pinMode(onOffSwitchStateSwitchPin, INPUT);
     pinMode(controlPin1, OUTPUT);
     pinMode(controlPin2, OUTPUT);
     pinMode(enablePin, OUTPUT);

     // pull the enable pin LOW to start
     digitalWrite(enablePin, LOW);
    }

    void loop()
    {
     // read the value of the on/off switch
     onOffSwitchState = digitalRead(onOffSwitchStateSwitchPin);
     delay(1);

     // read the value of the direction switch
     directionSwitchState = digitalRead(directionSwitchPin);

     // read the value of the pot and divide by 4 to get
     // a value that can be used for PWM
     motorSpeed = analogRead(potPin) / 4;

     // if the on/off button changed state since the last loop()
     if (onOffSwitchState != previousOnOffSwitchState)
     {
      // change the value of motorEnabled if pressed
      if (onOffSwitchState == HIGH)
      {
       motorEnabled = !motorEnabled;
      }
     }

     // if the direction button changed state since the last loop()
     if (directionSwitchState != previousDirectionSwitchState)
     {
      // change the value of motorDirection if pressed
      if (directionSwitchState == HIGH)
      {
       motorDirection = !motorDirection;
      }
     }

     // change the direction the motor spins by talking
     // to the control pins on the H-Bridge
     if (motorDirection == 1)
     {
      digitalWrite(controlPin1, HIGH);
      digitalWrite(controlPin2, LOW);
     }
     else
     {
      digitalWrite(controlPin1, LOW);
      digitalWrite(controlPin2, HIGH);
     }

     // if the motor is supposed to be on
     if (motorEnabled == 1)
     {
      // PWM the enable pin to vary the speed
      analogWrite(enablePin, motorSpeed);
     }
     else
     { // if the motor is not supposed to be on
      //turn the motor off
      analogWrite(enablePin, 0);
     }
     // save the current On/Offswitch state as the previous
     previousDirectionSwitchState = directionSwitchState;
     // save the current switch state as the previous
     previousOnOffSwitchState = onOffSwitchState;
    }

2: This one for the IR:

    #include "IRremote.h"  //-----( Import needed libraries )-----
    int receiver = 11; // ----- DAT pin of IR receiver to Arduino digital pin 11

    /*-----( Declare objects )-----*/
    IRrecv irrecv(receiver);           // create instance of 'irrecv'
    decode_results results;            // create instance of 'decode_results'

    void setup() /*----( SETUP: RUNS ONCE )----*/
    {
     Serial.begin(9600);  // Begin serial communication
     Serial.println("IR Receiver Raw Data + Button Decode Test");
     irrecv.enableIRIn(); // Start the receiver
    }    /*--(end setup )---*/

    void loop()  /*----( LOOP: RUNS CONSTANTLY )----*/
    {
     if (irrecv.decode(&results)) // have we received an IR signal?
     {
      //    Serial.println(results.value);  // Uncomment to print raw decimal values
      translateIR(); // run function "translateIR"
      irrecv.resume(); // receive the next value
     }
    }    /* --(end main loop )-- */

    /*-----( Declare User-written Functions )-----*/
    void translateIR()  // translate Makeblock remote raw values to keys
    {
     switch (results.value)
     {
      case 4219133059:      Serial.println(" A ");     break;
      case 667718909:       Serial.println(" B ");     break;
      case 3478241646:      Serial.println(" C ");     break;
      case 1322193145:      Serial.println(" D ");     break;
      case 3689098103:      Serial.println(" ^ ");     break;
      // case 3478241646:      Serial.println(" E ");     break;
      case 1776008254:      Serial.println(" < ");     break;
      case 1803700378:      Serial.println(" * ");     break;
      case 3495019267:      Serial.println(" > ");     break;
      case 1943112141:      Serial.println(" 0 ");     break;

      case 3444686410:      Serial.println(" v ");     break;
      case 2806989789:      Serial.println(" F ");     break;
      case 3689098101:      Serial.println(" 1 ");     break;
      // case 3689098103:      Serial.println(" 2 ");     break;
      case 1943112142:      Serial.println(" 3 ");     break;
      case 3689098102:      Serial.println(" 4 ");     break;
      // case 3689098102:      Serial.println(" 5 ");     break;
      case 2181502997:      Serial.println(" 6 ");     break;
      case 650941290:       Serial.println(" 7 ");     break;
      case 402038415:       Serial.println(" 8 ");     break;
      case 945450753:       Serial.println(" 9 ");     break;
      default:     Serial.println(" other button   ");
     }

     delay(250);
    } //END translateIR

body:
You should be able to search on Google and get a library to interface with the sensor.  Then you will need some motors, a motor controller, and a library to control that.  Then you will need to stick it all together using your code.

What you need to do is:

* Search for your IR library and a tutorial.
* Search for a Stepper motor tutorial and library.
* Then post a question when you are stuck with that.


body:
You need a good IR Library, or tons of low-level knowledge.

Ken Shirriff wrote the best IR library out there! [Here it is][1].

Adafruit writes awesome tutorials too. [Here's one][2].

  [1]: http://www.righto.com/2009/08/multi-protocol-infrared-remote-library.html
  [2]: https://learn.adafruit.com/using-an-infrared-library/hardware-needed


message:
Enternal Analog Reference mode not compiling in Arduino + Intel Galileo Gen 2

I am trying to use external voltage reference in Intel Galileo gen 2 operating in Arduino mode.

So I created a setup code like this:

    void setup() {
      // We'll send debugging information via the Serial monitor
      Serial.begin(9600);

      // If you want to set the aref to something other than 5v
      analogReference(EXTERNAL); // use AREF for reference voltage
    }

I selected the board as Intel Galileo Gen 2 in Tools option. When I compiled I am getting the following error:

    LM35_temp_sensor.ino:21:19: error: 'EXTERNAL' was not declared in this scope

But when I change the board to Arduino Uno in Tools option, the program in compiling fine.

This means that Intel Galileo Gen 2 does not support external analog voltage reference?

body:
There is no such thing as an external analog reference on the Galileo.  If you look at the block diagram that is on the Galiley Arduino.cc page you can clearly see that the Aref pin goes nowhere:

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

So no, it won't support the EXTERNAL analog reference function.

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


message:
Detect closed shutter

I want to controll some ambient lights in my living room.

Therefore, I got some 433mhz outlets which can be turned on or off with an remote, a 433mhz transmitter and receiver on the arduino.

The arduino receives the remotes signals and knows which lamp has which state and will turn any lamp off at specific times.

Now I want to turn on the lights automatically when I close the shutter, but I have no idea how I could do this.

A light sensor behind the window won't do the job. I don't want to turn on the lights when it get's dark, but when the shuhtter get's closed.

Edit:
What came to my mind first was an light sensor inside the window, facing outside, and a IR LED. I'd attach some tinfoil to the inside of the shutter to return the IR light, which the sensor will notice. But maybe the're are some simpler solutions? Also, the tinfoil would fall off quickly...

body:
I would go for a normally open read switch (should cost >$0.1) and a magnet on the shutter (again should cost >$0.1).  There are formulas to work out the distance that the reed switch will operate at, and it depends on the magnet, but the common ones are about 40mm.
(If you can wait 2 weeks for delivery you can get the parts off AliExpress.com)


message:
Any chance of repairing Mega 2560?

So I decided it would be a good idea to flash a firmware onto my mega 2560 for a project. I ended up flashing the wrong side of the ICSP header (one near the usb plug/ M16U2) and killed my arduino for the most part. I'm a newb for the most part when it comes to this. I plug it in and the 'L' light is on with the 'ON' light as well. Wont show up in device manager, can't load sketches and can't get into DFU mode.(REV3 has DFU right?)

I have both a usbasp and USBtinyisp programmer and have tried 5 - 10 firmwares on both sides of the headers in hopes I can get it to work again.Literally almost tried everything I could find to get it to flash back. One guide I did find that got me somewhere was this though:

http://forum.arduino.cc/index.php?topic=96706.0

It appears to flash correctly with whatever firmware I use, but cannot pull the firmware off it to check or do the rest of what it says.My guess is that 1 or 2 of the firmware's are gone. Have erased the firmware/relfashed and tried to flash in the IDE with no luck in it working.

I did use this command to read the firmware(or lack of) on both sides of the header to get a better idea of what might be going on:

[M16U2/M2560][1]

  [1]: http://pastebin.ca/3177996

I don't know if I'm supposed to flash one side first then the other or flashing one will be able to do both at the same time. Here is an example of how I would flash from avrdude:

    avrdude -C avrdude.conf -P usb -p m16u2 -b 1200 -c usbasp flash:w:Arduino-COMBINED-dfu-usbserial-atmega16u2-Mega2560-Rev3.hex -U lfuse:w:0xFF:m -U hfuse:w:0xD9:m -U efuse:w:0xF4:m -U lock:w:0x0F:m

With each side I would set the correct the fuses from what that file pulled up. So if anyone knows what I'm doing wrong for why it is not working I'd appreciate the help. Just don't know if I can save this or it's gonna end up in the garbage.Thanks

body:
http://altlab.org/d/m/jpralves/recover_atmega2560/

Change fuses/firmware depending on which side you are flashing (M2560/M16U2)

Firmwares: Arduino-COMBINED-dfu-usbserial-atmega16u2-Mega2560-Rev3.hex / stk500boot_v2_mega2560.hex

1st command:

    avrdude -C avrdude.conf -P usb -p m16U2 -b 57600 -c usbtiny -U lfuse:w:0xFF:m -U hfuse:w:0xD9:m -U efuse:w:0xF4:m -U lock:w:0x0F:m
2nd command:

    avrdude -c usbtiny -p m16U2 -P usb -b 115200 -V -U flash:w:Arduino-COMBINED-dfu-usbserial-atmega16u2-Mega2560-Rev3.hex
3rd command:

    avrdude -c usbtiny -p m16U2 -P usb -b 115200 -U lock:w:0x0F:m

http://pastebin.ca/3178420


message:
arduino project for c programming language

i am a student from 2nd semester BCA (Bachelor in Computer Application). My group need some project for presentation from c programming language so i thought of using #ARDUINO project for our presentation . i really don't have any idea in this project so any ideas, answer, guides will be helpful to us.

body:
I am not going to list example-projects as the possibilities with an arduino are endless. If you are looking for inspiration: take a look at websites like www.instructables.com and www.hackaday.io. Those are websites with mostly starter arduino projects that contain step-by-step guides on how they are created. I would suggest that you browse through those projects and look for something that peaks your interest and then think of your own similar project. You should however think of a project with a certain complexity as it is for your bachelor's. Most projects on instrucables lack the challenge. For getting parts: take a look at ebay. Ebay has some webshops that sell arduino's and arduino extension modules really cheap.
Good luck


body:
Good luck with this! Arduino is awesome. I really enjoy using it. You may find this at least a little insightful: http://www.electricrcaircraftguy.com/2014/01/the-power-of-arduino.html.

Arduino is a small computer. It can do essentially whatever you want it to do: drive robots, fly airplanes, control motors, turn on or off TVs, get on the internet, make a home alarm, buzz a speaker, make a touch lamp, fade LEDs, play music (even with *no* music chip; just using a skillfully-written library), control HollyWood action cameras, talk to your smartphone, read your heartbeat, make a bike speedometer or odometer, read a GPS receiver, etc. Cool stuff!


message:
how to change variable when a button connected to pin 2 is pressed

Hi i am writing a code where, i have to switch a variable called toggle from 0 to 1 to 0.... every time the button is pressed (the button is on a 2 pin). I am a little lost as I am new to arduino need some help. Thank you

body:
Go [here][1] --> Built-In Examples. Read the examples for Button, Debounce, and Digital Input Pullup. Digital Input Pullup is the best single one of those 3 I think, but read them all.

Those 3 are key.

Also, I wrote a buttonReader (debouncing) library [here][2].

Sounds like you're a beginner, so check out Adafruit's tutorials [here][3].

And lastly, I've compiled links to all my knowledge at the bottom of my article [here][4].

  [1]: https://www.arduino.cc/en/Tutorial/HomePage
  [2]: http://www.electricrcaircraftguy.com/2014/05/ercaguybuttonreader-library-for-arduino.html
  [3]: https://learn.adafruit.com/category/learn-arduino
  [4]: http://www.electricrcaircraftguy.com/2014/01/the-power-of-arduino.html


body:
What you need is to detect a *transition*. That is, either:

* It was closed and is now open.

Or:

* It was open and is now closed.

To do that you need to "remember" the previous state of the switch and detect a change, like this:

    const byte switchPin = 8;
    byte oldSwitchState = HIGH;  // assume switch open because of pull-up resistor
    bool toggle;

    void setup ()
      {
      pinMode (switchPin, INPUT_PULLUP);
      }  // end of setup

    void loop ()
      {
      // see if switch is open or closed
      byte switchState = digitalRead (switchPin);

      // has it changed since last time?
      if (switchState != oldSwitchState)
        {
        oldSwitchState =  switchState;  // remember for next time
        toggle = !toggle;   // toggle the variable
        delay (10);         // debounce
        }  // end of state change

      // other code here ...

      }  // end of loop

---

For more information see my post about [switches](http://www.gammon.com.au/switches).


message:
Arduino "piston" device

Is there any compact piston-like devices on the market that can apply pressure safely various parts of the head? I can further expound if needed.

The ideal size would be something within the 1-2 inch length range

body:
It sounds like this is nothing to do with an Arduino, just a general Electrical/Mechanical engineering question that you want to control from and Arduino.
I think you wan a device that when signalled by your Arduino can extend itself by up to 2 inches.

If that is right then I think what you are looking for is a Linear Actuator.  There are plenty out there and some do handle the small stroke you want, but most of them appear to be 9 to 12V.  This means you would require a Darlington transistor or relay to control them from an Arduino.

If you require an extremely precise stoke length then I would recommend a stepper motor with a screw axel.  This would allow you much finer control over how far you pushed, but it would impose limits on what you could do and how it could be mounted.

 - Can you provide more details on what you want to move?
 - List item
 - Is it heavy? Do you need lots of Torque?
 - Are you pushing straight or do you need to push in an arc (i.e. a door)?
 - What voltage supplies do you have available?
 - How fast do you want it to move?
 - Do you want it to move exactly the same distance every time?

The more info you can provide the better, but in answer to your original question Yes, it sounds like there might be so you plan is still on the rails.


message:
Deviation of power consumption between datasheet and real world?

According to the Atmega328P-PU Datasheet (side: 589) the current consumption of the microcontroller should be around 9.5mA (at 16MHz and 5V).
But I measured 15mA. (Nick Gammon who did some pretty good power saving research(gammon.com.au/power) got the same)
There is nothing connected to the outputs. The code I ran was this:

> void setup () {}
 void loop () {}

Now I'm wondering if this is just a normal deviation (datasheet to real world) or if Atmel measured their current consumption in a state that is different from mine?

**EDIT:**

I forgot to mention.. I didn't use it with the Arduino Uno board but as standalone device. There was only a 16Mhz oscillator with two capacitors connected. Power came directly form Power supply.

Now that I think about it..  Datasheet says this regarding the current measurement: "A sine wave generator with rail-to-rail output is used as clock source."

Is it possible that the oscillator needs that extra 5mA?

**EDIT2:**

Here is a screenshot of my schematic:
[![enter image description here][1]][1]

And a screenshot of the ATmega328P-PU Datasheet:
[![enter image description here][2]][2]

  [1]: https://i.stack.imgur.com/GZBCx.png
  [2]: https://i.stack.imgur.com/Ae11H.png

body:
Probably Atmel measured the chip consumption without any code. An empty sketch has some code in it (believe it or not).
Another possibility is the remaining components like voltage regulator, usb chip are also consuming some current.
Try to test in a bare minimum configuration.


body:
<!-- language-all: lang-C++ -->

According to the datasheet:

> All current consumption measurements are performed with all I/O pins configured as inputs and with internal pull-ups enabled.

---

That was the critical point. Trying this sketch:

    int main ()
      {
      for (int i = 0; i < 20; i++)
        pinMode (i, INPUT_PULLUP);
      }  // end of setup

Note that timers are not running (your sketch would have timer 0 running):

With that sketch, even using the crystal and capacitors (I actually had a resonator) the consumption at 5 V at around 20 °C was 9.2 mA which is within spec.

Fuses:

<!-- language-all: lang-none -->

    Signature = 0x1E 0x95 0x0F
    Processor = ATmega328P
    Flash memory size = 32768 bytes.
    LFuse = 0xFF
    HFuse = 0xDF
    EFuse = 0xFF
    Lock byte = 0xFF
    Clock calibration = 0x96

---

<!-- language-all: lang-C++ -->

If we turn pull-ups off:

    int main ()
      {
      }  // end of setup

Now it consumes 14.4 mA, closer to what you measured.

---

And with your actual test sketch:

    void setup () {}
    void loop () {}

It consumes 15.5 mA, which is more, because Timer 0 is running (started in the `init` function). It is also close to what I had on my [page about power](http://www.gammon.com.au/power) - 15.15 mA.

---

So, working as expected. Those pull-ups are important, to stop the input drivers consuming current.

I did mention further down in my page the importance of configuring the pins:

> Testing in SLEEP_MODE_PWR_DOWN:
>
> * **All pins as outputs**, and LOW: 0.35 µA (same as before).
>
> * **All pins as outputs**, and HIGH: 1.86 µA.
>
> * **All pins as inputs, and LOW** (in other words, internal pull-ups disabled): 0.35 µA (same as before).
>
> * **All pins as inputs, and HIGH** (in other words, internal pull-ups enabled): 1.25 µA.

Notice the difference there of 0.9 µA when asleep. It would appear that there is an ever greater difference if the processor is awake.


message:
How to capture good sound with Arduino?

Is it possible to capture good sound with Aduino? I need to record street / birds / nature sounds.

[As I found][1], maximal sample rate, achievable with built-in ADC is 9kHz, which is to low.

So, I require to use some external hardware. But wave shields I saw are to expensive (comparable by price with Arduino itself), probably, because of excess functions (including not only ADC but also DAC and so on).

Simultaneously, there are ICs, providing ADC functionality and even MP3 encoding functionality for relatively low price. But here a schematic design required.

So, how to find appropriate solution here?

  [1]: https://arduino.stackexchange.com/a/701/6841

body:
Yes but you want something much faster then the Arduino, normally it is in the 96k~48k bps range.  Try this link, they make a lot of great parts and the bulk of what you have to do is control software.  You can let the chip do the grunt work (analog) and transfer thee data to where ever you want.  Some of the chips will record for 300 seconds plus.

http://www.aplusinc.com.tw/exec/product.php?lg=E&mod=show&cid=43&pid=aPR33A3

I have used there parts they work great.

Have fun,
Gil


body:
> Is it possible to capture good sound with Aduino? I need to record street / birds / nature sounds.

The answer is "no" for AVR based Arduino boards. They have simply too low sampling rate, ADC resolution, limited buffering memory and processing speed.

The ADC sample rate is at most 9 K samples per second (112 us per sample) at highest resolution (10 bits). The resolution can be improved (e.g. 12 bits) by using [oversampling][1] but this is at the cost of sampling frequency.

The Arduino Uno has only 2K byte memory. Using all that for buffering would give at most 1 K samples. That is little over a second sound data. A SD file could be used but requires a lot of smart programming to not drop samples at max sampling rate.

Low quality, 8-bit samples, then "yes". See [here][2].

Now an Arduino Due is much more powerful, has much more memory, etc. See [here][3].

  [1]: http://www.atmel.com/images/doc8003.pdf
  [2]: http://apcmag.com/arduino-projects-digital-audio-recorder.htm/
  [3]: https://www.arduino.cc/en/Tutorial/SimpleAudioPlayer


message:
actual use of noTone() in arduino

What is the use of noTone() function as the duration for which the note must be played can be specified using the third argument of note() function.

body: So that you can terminate the output prematurely, e.g. during an interrupt.


message:
Split RGBW hex String into integers

I have a program where the Arduino receives hex Strings that represent a RGBW color (similar to css for example). My goal is to create that color by using pwm, so I need to convert that one hex string into four integer values between 0..255 to use for the pwm.
Whats the best/easiest way to do this?

Example:

    void incomingMessage(const MyMessage &message) {

        // h = hex value
        // message = e.g. (h) #112233AB
        redval = ?; // h11 => 17
        greenval = ?; // h22 => 34
        blueval = ?; // h33 = 51
        whiteval = ?; //AB = 171

        analogWrite(RED_PIN, redval);
        analogWrite(GREEN_PIN, greenval);
        analogWrite(BLUE_PIN, blueval);
        analogWrite(WHITE_PIN, whiteval);

    }

body:
So you basically want to convert a pair of hexadecimal digits into a numeric value.  You also want to extract those values from a string.

The latter can be done using the [String.charAt()](https://www.arduino.cc/en/Reference/StringCharAt) method.  That allows you to extract individual characters from your string.

Then you need to convert those into a number.  There's a number of ways that could be done.

# strtol()

The strtol() function takes three parameters - the first is a C string (NULL-terminated char array) which contains the number you want to convert, the second you can ignore, and the third is the *base* to convert from.  So you could use something like:

    char temp[3] = { char1, char2, NULL };
    int val = strtol(temp, NULL, 16);

# Discrete functions

It's simple enough to write a function that converts a single hex digit into a value 0-15:

    unsigned char h2d(unsigned char hex)
    {
        if(hex > 0x39) hex -= 7; // adjust for hex letters upper or lower case
        return(hex & 0xf);
    }

It's then simple enough to use that to make a function that takes two hex digits and converts them into a number:

    unsigned char h2d2(unsigned char h1, unsigned char h2)
    {
        return (h2d(h1)<<4) | h2d(h2);
    }

There's as many ways of doing it as there are of skinning a cat (as the saying goes).  Every way has benefits and drawbacks though.  Of the two I have shown, to compare them:

* The first is "safer" as it has more error checking and can cope with other things besides hex values
* The second results in much smaller code but results with values other than hex digits are undefined.


body:
I don't like using the String class because it can cause memory fragmentation. This would do it by just using C-style strings:

    byte fromhex (const char * str)
      {
      char c = str [0] - '0';
      if (c > 9)
        c -= 7;
      int result = c;
      c = str [1] - '0';
      if (c > 9)
        c -= 7;
      return (result << 4) | c;
      }

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

      const char * test = "#112233AB";

      byte redval   = fromhex (& test [1]);
      byte greenval = fromhex (& test [3]);
      byte blueval  = fromhex (& test [5]);
      byte whiteval = fromhex (& test [7]);

      Serial.println ((int) redval);
      Serial.println ((int) greenval);
      Serial.println ((int) blueval);
      Serial.println ((int) whiteval);

      }  // end of setup

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

Output:

    17
    34
    51
    171

That does not do any validation (that the string is indeed 9 characters long, and contain hex characters) but I'll leave that for you to do. :)


message:
When the Arduino is in reset mode are the digital pins high impedance?

I have an Arduino (Arduino A) hooked up to an external FRAM chip and I want to be able to pull the Arduino A's reset pin to ground to keep it in a constant reset state. Then I want to hook up another Arduino (Arduino B) up to the same lines going from Arduino A to the external FRAM chip and pull data off of the FRAM chip.

I am worried that when I hook Arduino B to the lines running between the FRAM and Arduino A that it will damage Arduino A. If the digital pins are in a high impedance state while I do this though, then it should be fine. I can't find the necessary documentation to figure this out though.

All Arduinos involved are Uno Rev 3s.

Any help would be appreciated, thanks!

body:
From the ATMEGAxx8 datasheet...

> 11.1 Resetting the AVR
>
> ... The I/O ports of the AVR are **immediately** reset to their initial state
> when a reset source goes active. This does not require any clock
> source to be running.

(bold added)

Looking over the register descriptions for the Data Direction Registers, all bits have an initial value of `0`, corresponding to high impedance input.

...so it is safe to assume that all IO pins will be in a high impedance state a very short time after the `RESET` pin goes low.

Caveats:

1. The clamping diodes are in-circuit even when pins are in high impedance state, so current will flow if the voltage on the pin is higher than Vcc or lower than Ground (at least until the diode blows up!).

2. Some Arduino pins are connected to other things besides just the pin on the MPU. For example, digital pin 13 is connected to ground though a resistor and diode, so current will flow into it if you connect a voltage higher than the threshold for the diode. On the Uno there are also resistors on the RX and TX pins connected to the serial communications link, so current can flow there too.

3. The MISO pin can inadvertently become an output while `RESET` is held low if the Programming Enable command ($AC $53 xx yy) is transmitted over the MOSI & SCK lines. This process is described in [App Note AVR910][1].

  [1]: http://www.atmel.com/images/doc0943.pdf


message:
Wireless Communication Between Raspberry Pi 2 and multiple Arduinos

I have about 10 Arduinos that have sensors attached, which report information back around my house. I would like to have a RPi 2, because they have nice screen and GUI options, to collect the information and display it accordingly.

I am looking for success stories on what wireless parts you used to get these two working. The the wireless must be able to penetrate a brick wall about 120ft away.

Thanks for replying, I edited the response above.

body:
There's many options you could use.

The simplest, though most expensive, would be to equip all your Arduinos with WiFi shields and connect a USB WiFi dongle to the Pi.  The Pi could run in AP mode (investigate [hostapd](http://google.com/?q=hostapd+raspberry+pi)) so you don't have to connect them all to your internet router.

A cheaper option, though harder to work with on the Pi, would be to use the incredibly cheap but popular [nRF24L01+](http://google.com/?q=nrf24l01+) modules.  There are libraries aplenty for the Arduino, but I am not aware of code for the Pi (though there probably is somewhere if you google for it).

And then there are options in between which vary in price and complexity.

Of course, you haven't mentioned range, only a brick wall.  The right choice could well be affected by the range of communication you need - do you go for the bare nRF28L01+ with a range of maybe 10m, or the one with the power amplifier and SMA antenna with a range of many hundreds of meters? Is WiFi going to be long enough range? Would a 433mHz module be a better choice?  All these questions and more need to be answered, and the best way is for you to describe your setup in detail, including what the longest range is you need to deal with, what amount of data you will be sending, do you need ultra low power to save batteries, etc.


body:
I use the ESP8266 to get the data from my arduino to my webserver using wlan. You could easy install a webserver on your pi and connect it to your wifi, or just use a server online.
So you can install on all places where you get WLAN. Also you could use a repeater if your wlan is not strong enough.

Thats how my projekt works (Water level messure)

 1. Get range from ultrasonic sensor (every minute)
 2. Send data to the ESP8266 using SoftwareSerial
 3. Send getRequest with WLAN to my php page on the Server
 4. Save Data to MySql Database
 5. Show the Data Online with php and a javascript graph lib

My example is one way Arduino to Server, but you could easy communicate back to each of your arduinos.

good luck :)


body:
You could use an xBee.

I have 2 of these and they are really easy to set up. Here is a link to the data sheet: https://www.sparkfun.com/datasheets/Wireless/Zigbee/XBee-Datasheet.pdf

Link to site:
https://www.digi.com/lp/xbee

These I believe can interface to the GPIO of the pi - as i seem to recall doing that myself. Either I did that or used an arduio to get the readings and had the arduino feed the readings to the pi GPIO pins - either way the modules make sending data wireless super easy.


message:
Help with Flappy Bird Sketch

I am compiling the sketch found [here][1]. I just downloaded the .ino and .h files and opened them, so I have not modded the code at all. I keep getting the following error.

    In file included from flappyDuino.ino:7:0:
    Sprite.h:3: error: variable 'flappybird_frame_1' must be const in order to be put into read-only section by means of '__attribute__((progmem))'
     static unsigned char PROGMEM flappybird_frame_1[] = { 0x03, 0xF0, 0x0C, 0x48, 0x10, 0x84, 0x78, 0x8A, 0x84, 0x8A, 0x82, 0x42, 0x82, 0x3E, 0x44, 0x41,0x38, 0xBE, 0x20, 0x41, 0x18, 0x3E, 0x07, 0xC0 };

                                                     ^
    In file included from flappyDuino.ino:7:0:
    Sprite.h:4: error: variable 'flappybird_frame_2' must be const in order to be put into read-only section by means of '__attribute__((progmem))'
     static unsigned char PROGMEM flappybird_frame_2[] = { 0x03, 0xF0, 0x0C, 0x48, 0x10, 0x84, 0x20, 0x8A, 0x40, 0x8A, 0x40, 0x42, 0x7C, 0x3E, 0x82, 0x41, 0x84, 0xBE, 0x88, 0x41, 0x78, 0x3E, 0x07, 0xC0 };

                                                     ^
    Sprite.h:5: error: variable 'bar_bottom' must be const in order to be put into read-only section by means of '__attribute__((progmem))'
     static unsigned char PROGMEM bar_bottom[] = { 0xFF, 0xFF, 0xFF, 0x42, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E };

                                             ^
    Sprite.h:6: error: variable 'bar_top' must be const in order to be put into read-only section by means of '__attribute__((progmem))'
     static unsigned char PROGMEM bar_top[] = { 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x42, 0xFF, 0xFF, 0xFF };

                                          ^
    variable 'flappybird_frame_1' must be const in order to be put into read-only section by means of '__attribute__((progmem))'

I'd appreciate any help.

  [1]: https://github.com/huytd/arduino-flappybird

body:
The arrays need to be tagged with the keyword `const`.  It is possible that the original sketch was written using an earlier version of the IDE that you are using (or a later version?) and your version requires the `const` keyword whereas the author's doesn't.

Basically any arrays that are `PROGMEM` need the word `const` adding to them.  For instance, lines that start:

    static unsigned char PROGMEM ...

need changing to:

    static const unsigned char PROGMEM ...


message:
Move robot through the waypoints

My arduino robot has two dc motors as two wheels and have mounted an IR led on it. I get current position of the robot as (x,y) coordinates in the arena using camera which is mounted at the top of the arena..

My robot communicates with PC through bluetooth. I can read current position of robot on pc with the help of camera. Robot uses arduino motor shield to drive DC motors.

Which is the best method to move robot through the waypoints for a robot with DC motors without encoders?

body:
With the arrangement you have described I would say it's very very hard to do what you want.

* You know where the robot is
* You know where the robot has to get to
* You can easily calculate the direction the robot has to go in (simple trigonometry from school)

**But:**

You don't know what direction the robot is facing, so you don't know how to turn the robot to get it to drive in the direction you need.

So either you need some kind of *calibration* procedure whereby the computer moves the robot in different directions and watches what the IR LED does to determine what direction the robot is facing so it can move it to face the right way (tricky to do, and rather messy), or some way for the computer to visually calculate the direction of the robot.

The latter is probably the easiest.  Instead of just one IR LED on the top of the robot you would need an array of IR LEDs on top of the robot forming a shape.  What that shape is can be up to you, but there is one big constraint: *It must have a clear direction to it* (i.e., it must have *no rotational symmetry*.  Triangles are good since they only need 3 LEDs.  An equilateral triangle though wouldn't work since in three different rotations it would look the same.  However, a single LED at the front of the robot, with two LEDs at the back of the robot, with the two back LEDs closer together than the distance from the front to the back, would not have any rotational symmetry.

You could then, (theoretically, assuming you have control over the camera software), get the three points from the play area and calculate the direction the robot is facing (tangent from mid-way between the two close points passing through the distant point) so you can then calculate the angle the robot would need to turn through so it is facing the direction you need it to.

Remember in math class, doing trigonometry (sin, cos, tan, pythagoras, etc) thinking "Why the hell do we need to know this stuff?!", well, now you know.


body:
This depends if you want the hypothetical best solution, or if good enough is good enough.

If good enough is good enough, I'd take the following approach:

Work out the distance from your robot to the first waypoint; move forward. Work out how fast you're moving towards (away from) the goal. Turn left a bit, go forwards again; did things improve (less away from/more towards)? If not, turn slightly right. Keep turning this way (left or right), and going forward a bit; whenever your speed towards to the goal gets worse, change your turning direction.

This should get you to where you are going.

Then, start making improvements.

If you are moving away from the goal (distance is increasing), your rotates can be quite sharp; as your approach speed to the goal increases, make the rotates smaller.

You could also try rotating while driving - if you are driving forward, and want to turn slightly left, run your left wheel at 90% of the speed of the right.

With a bit of trial and error, you should be able to end up with a table - work out your approach speed, look up in a table (or formula) how fast your slower wheel should go - from 0% (or even 100% reverse!) if moving away from your goal, to 100% if you are going at your driving speed towards your goal. Remember that if you are turning, you will approach it more slowly than if you are going straight. And if you start to turn and things get worse, then you are turning the wrong way.


message:
Are there any ePaper modules that are bigger than 2.7 inches for arduino

I am looking for a large ePaper Display for the Arduino. The issue is is that I cannot seem to find one any larger than 4.5 inches in size. That will be compatible with arduino. Even with a controller board.

Are there any companies that sell controller boards for these displays? Is there anyone who can manufacture these epd displays upon request?

I am looking to take this project to a pcb board after I prototype it so do I need to build my own controller? If what parts would you need? Is it easy for a designer with intermediate capability?

I can find all kinds of display like at [pervasivedisplays.com][1] and [Mouser.com][2]

The end goal is to create a Arduino based project that I can score skeet with to keep track of my average score.

  [1]: http://www.pervasivedisplays.com/
  [2]: http://mouser.com

body:
I would suggest you to start the other way: find a sw stack that is known to work and check if any of the controllers/displays it already supports fits your needs. This is how I would do it.

[Here][1] is a starting point.

  [1]: http://ugfx.org/platforms


message:
Powering arduino and 12V Fan from same supply

I have found a relatively small 12V switching power supply that I want to build into my device, using it to power both the Arduino Pro Mini and a couple of 12V cpu fans.

Am I correct in assuming that I can have the Arduino RAW pin and Fan+ on the same power supply lead? Or do I need to protect the Raw pin in any way? Also, I need to power 2x cpu fans, can this be done with one transistor or do I need one for each fan?

If I stay within the Current specs of my supply (6A) could I keep adding other 12V components on the same +lead as in the diagram below?
[![enter image description here][1]][1]

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

body:
The board will take 12V, but the regulator will have to dissipate (as in heat) the excess power.

However, how much do you trust your power supply to not exceed the 12V?

The same applies to the other loads.

About max current, you should do the math for both typical case and peak case. Ex: the fan will draw much more current if for any reason it is stopped.

If you use only 1 transistor, you will get both fans to behave in the same way, because you will be using only 1 control line. Is this what you want?


body:
Sounds fine.

You can connect the two fans in **parallel**, as long as they don't use more than 5A combined, as that is the maximum of the TIP120. Though you definitely need to attach a heatsink to the TIP120, if you are using a largish amount of current. Though in that case, I'd suggest using a MOSFET instead of a Darlington Transistor (TIP120), as MOSFETs don't heat up that much.

The diode is not needed if you use the TIP120, as there is already a diode inside the package.

Since you are using 12V as a power supply, the voltage regulator has to convert 7v into heat. Depending on the amount of current you use, this could result in the voltage regulator getting very hot. If you are only powering the ATMega328 and maybe some LEDs from the 5v line, you'll be fine. Just don't connect something like a 5v fan.


message:
How can BMP180 measure a temperature too?

I got the following device

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

(sorry for imperfect focus)

and found, that it can measure not only pressure, but also a temperature too. The code was taken from common sketches for Adafruit BMP085 and they were working. I checked, that temperature value rises if I touch sensor with finger.

Simultaneously, on [Bosch site for BMP180][2] I can't find any notes it can measure temperature, only pressure.

How can it be?

1) Bosch's BMP180 has undocumented feature to measure a temperature

2) The device on picture has additional component to measure temperature

3) The device on picture has completely different sensor, which has the name of "BMP180" just by coincidence.

4) Something else....

  [1]: https://i.stack.imgur.com/HNSIF.png
  [2]: https://www.bosch-sensortec.com/en/homepage/products_3/environmental_sensors_1/bmp180_1/bmp180

body:
The [BMP085 Barometric Pressure/Temperature/Altitude Sensor- 5V ready](https://www.adafruit.com/products/391) page at adafruit.com says the BMP180 is a drop-in replacement for the BMP085.

The  [BMP180 Barometric Pressure/Temperature/Altitude Sensor- 5V ready](http://www.adafruit.com/products/1603) page at adafruit.com says the BMP180  is completely identical to the BMP085 in terms of firmware/software/interfacing.

In addition, while [Bosch's web page for the BMP085](https://www.bosch-sensortec.com/en/homepage/products_3/environmental_sensors_1/bmp180_1/bmp180) doesn't mention temperature, the data sheet itself – the final reference, typically, for a device like this – says “Temperature measurement included” on page 2, and on page 14 refers to measuring temperature in steps of 0.1°C, and on other pages shows temperature register numbers, etc.  To get the data sheet, click the Documents & Drivers tab, then the BST-BMP180-DS000-12 Datasheet link.


body:
If you read the data sheet (on the site you point to) you see plenty of references to temperature:

> The BMP180 is designed to be connected directly to a microcontroller of a mobile device via the I 2 C
bus. The pressure and **temperature** data has to be compensated by the calibration data of the
E 2 PROM of the BMP180.

and

> The BMP180 consists of a piezo-resistive sensor, an analog to digital converter and a control unit with EEPROM and a serial I2C interface. The BMP180 delivers the uncompensated value of pressure and **temperature**. The E 2 PROM has stored 176 bit of individual calibration data. This is used to
compensate offset, temperature dependence and other parameters of the sensor.

And many many more.


body:
See, for example, [Adafruit BMP085 library][1] (it's work with BMP180 too), function

    void Adafruit_BMP085_Unified::getTemperature(float *temp)

in file Adafruit_BMP085_u.cpp line 330

  [1]: https://github.com/adafruit/Adafruit_BMP085_Unified