body:
As @Majenko has said it is defined in the FastLED library http://fastled.io/.  There is also EVERY_N_SECONDS.

It is not necessary to call any other FastLed function in the run loop (such as FastLED.delay()) in order to use these functions.

    include <FastLED.h>

    void loop() {
       ....
       EVERY_N_MILLISECONDS( <mseconds> ) {
         <your timed code here>;
       }

       EVERY_N_SECONDS( <seconds> ) {
         <your timed code here>;
       }
    }


sender: user

message:
"EVERY_N_MILLISECONDS"

One of the FastLED examples that I've seen was using code that looks like this:

>   EVERY_N_MILLISECONDS( 300 ) { transition_step(); }

I've copied it and successfully used it in the same context - but I have no idea what it is or how it works.

A Google search finds no reference anywhere at all.

I'm still a beginner with C but this looks like a Define to me - all being in uppercase - is it defined somewhere in the FastLED library?

sender: assistant

body:
Its a macro that wraps the code you put inside of it to only be run based on the time interval you pass to it. The purpose of it is to allow for timer based code to be ran without having to block the main `loop()`. When the code is compiled it gets wrapped by other code that governs how the code inside it should run.

Lets say you want to run a method every 100ms. A simple approach would be the following:

``` c
// loop() runs the code within it over and over at a rate based on the
// how fast the microprocessor runs - specifically how long it takes
// for the processor to get through the code inside of it.
void loop(){

doMethod();
delay(100);

checkForButtonInput();

}
```

The issue here is that during the `delay()`, the `delay()` function, by its design, hogs all the processor time for 100ms, and so the `checkForButtonInput()` is not able to check for input, as the program is currently stuck looping inside of `delay()` until 100ms has passed.

`EVERY_N_MILLISECONDS( <mseconds> ){}` is the answer here, and you can think of it working to add code to you code like this (although this isn't exactly accurate):
``` c
void loop() {
   EVERY_N_MILLISECONDS( 100 ){
  //pseudocode
  //if ( it has been 100ms since last time we did doMethod() ) {
      doMethod();
      // reset time since we did doMethod() to 0
  //}
  //else {
  //  continue...
  //}
  }
  checkForButtonInput();
}
```
so if it hasn't been 100ms since the last time we were in the `EVERY_N_MILLISECONDS` wrapped code then we just move on, and so the `checkForButtonInput()` is called as much as possible and inputs wont be missed.


message:
Shift Register Not Working

I am trying to learn how to use a shift register to control 8 LEDs but for some reason my shift register is misbehaving and none of the LEDs are lighting up. I imagine that it's a problem with my wiring? I have replicated the circuit on 123D Circuits.

[![circuit diagram][1]][1]

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

    //Pin connected to ST_CP of 74HC595
    int latchPin = 8;
    //Pin connected to SH_CP of 74HC595
    int clockPin = 12;
    ////Pin connected to DS of 74HC595
    int dataPin = 11;

    void setup() {
      //set pins to output so you can control the shift register
      pinMode(latchPin, OUTPUT);
      pinMode(clockPin, OUTPUT);
      pinMode(dataPin, OUTPUT);
    }

    void loop() {
      // count from 0 to 255 and display the number
      // on the LEDs
      for (int numberToDisplay = 0; numberToDisplay < 256; numberToDisplay++) {
        // take the latchPin low so
        // the LEDs don't change while you're sending in bits:
        digitalWrite(latchPin, LOW);
        // shift out the bits:
        shiftOut(dataPin, clockPin, MSBFIRST, numberToDisplay);

        //take the latch pin high so the LEDs will light up:
        digitalWrite(latchPin, HIGH);
        // pause before next value:
        delay(500);
      }
    }

body:
From the Arduino website:

> ## shiftOut() ##
>
> Description
>
> Shifts out a byte of data one bit at a time. [...]
>
> Note: if you're interfacing with a device that's clocked by rising
> edges, you'll need to make sure that the clock pin is low before the
> call to shiftOut(), e.g. with a call to digitalWrite(clockPin, LOW).

You need to pull `clockPin` low before each `shiftOut()` call, as the documentation says.

Also, you have misunderstood the behaviour of the `latchPin`. This can be high or low at any time; it's the *change from low to high* that latches the data into the output cells.


message:
How to make two wheels turn only for a particular amount of time?

I am trying to make a robot turn (dc motors are being used) back 180 degrees. So I used an l289n for it and made one wheel turn clockwise and vice-versa.

But as I wan't it to make only a 180 degrees turn, I wanted to set an amount of time for it to turn.  Is there any other way to do the same thing, if yes, please tell, if no, help me...

body:
Use the [delay()](https://www.arduino.cc/en/Reference/Delay) function.

Pseudo code as follows:

    1) Turn clockwise motor on;
    2) Turn counterclockwise motor on;
    3) delay(<time>);
    4) Turn CW motor off;
    5) Turn CCW motor off.


message:
Arduino to DAC to ADC back to Arduino?

My question is simple. Is the following possible?

I am using one Arduino Mega 2560 board and its SPI functionality to adjust voltages (0-4.096V) through a 12-bit DAC (MCP4822).

I would like to measure the output voltages from the DAC by feeding them through a 12-bit ADC and back to the Arduino. The DAC's output voltages that will be directly measured by the ADC will be displayed on an LCD and on LabVIEW.

Is this possible, given that both the DAC and the ADC have to be connected to the same SDI and SCK pins on the Arduino for SPI to work?

body: Yes, perfectly possible. Just provide two separate CS pins to select between the two devices.


message:
DCMotorTest from the Adafruit site – got fatal error exit status 1

New to Arduino, I plugged in DCMotorTest from the Adafruit site and got this error message: a fatal error exit status 1

    /*
    This is a test sketch for the Adafruit assembled Motor Shield for Arduino v2
    It won't work with v1.x motor shields! Only for the v2's with built in PWM
    control

    For use with the Adafruit Motor Shield v2
    ----> http://www.adafruit.com/products/1438
    */

    #include <Wire.h>
    #include <Adafruit_MotorShield.h>
    #include "utility/Adafruit_MS_PWMServoDriver.h"

    // Create the motor shield object with the default I2C address
    Adafruit_MotorShield AFMS = Adafruit_MotorShield();
    // Or, create it with a different I2C address (say for stacking)
    // Adafruit_MotorShield AFMS = Adafruit_MotorShield(0x61);

    // Select which 'port' M1, M2, M3 or M4. In this case, M1
    Adafruit_DCMotor *myMotor = AFMS.getMotor(1);
    // You can also make another motor on port M2
    //Adafruit_DCMotor *myOtherMotor = AFMS.getMotor(2);

    void setup() {
      Serial.begin(9600);           // set up Serial library at 9600 bps
      Serial.println("Adafruit Motorshield v2 - DC Motor test!");

      AFMS.begin();  // create with the default frequency 1.6KHz
      //AFMS.begin(1000);  // OR with a different frequency, say 1KHz

      // Set the speed to start, from 0 (off) to 255 (max speed)
      myMotor->setSpeed(150);
      myMotor->run(FORWARD);
      // turn on motor
      myMotor->run(RELEASE);
    }

    void loop() {
      uint8_t i;

      Serial.print("tick");

      myMotor->run(FORWARD);
      for (i=0; i<255; i++) {
        myMotor->setSpeed(i);
        delay(10);
      }
      for (i=255; i!=0; i--) {
        myMotor->setSpeed(i);
        delay(10);
      }

      Serial.print("tock");

      myMotor->run(BACKWARD);
      for (i=0; i<255; i++) {
        myMotor->setSpeed(i);
        delay(10);
      }
      for (i=255; i!=0; i--) {
        myMotor->setSpeed(i);
        delay(10);
      }

      Serial.print("tech");
      myMotor->run(RELEASE);
      delay(1000);
    }

_**My error message was:**_

    Arduino: 1.6.7 (Mac OS X), Board: "Arduino/Genuino Uno"

    /Users/student/Downloads/Adafruit_Motor_Shield_V2_Library-master/examples/DCMotorTest/DCMotorTest.ino:11:34:
     fatal error: Adafruit_MotorShield.h: No such file or directory
     #include <Adafruit_MotorShield.h>
                                      ^
    compilation terminated.
    exit status 1
    Error compiling.

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

body:
Based on the error report it seems that you have just opened the example program from the downloaded folder. In order to add library files (which includes the header files, c++ source code, etc.) you have to move the *Adafruit_Motor_Shield_V2_Library-master* folder to the libraries folder.

> Documents > arduino > libraries

If no such folder exist, then create a new folder and name it *libraries*.

To check weather the libraries have been installed, open arduino IDE goto

> file > example and check weather the example programs are added (you will see "adafruit" in the list)

Now, restart the arduino IDE and things should get going.

**Note:**
Do not use "-" and do not include space while naming a folder, as the compiler may throw up error. Instead you are free to use "_","$". Name of a folder should always start with a letter.

For more detail visit https://learn.adafruit.com/adafruit-all-about-arduino-libraries-install-use/how-to-install-a-library


message:
ESP8266 Analog read interferes with wifi?

Short version:
I have a program that connects my ESP8266 to WIFI so I can control a relay connected to it over the internet or a button. I also have a sensor for my door. This software works perfectly, if I add a light dependent resistor to it (which is connected correctly since I do get readings from it) and start reading data I lose my WIFI connection. Has anyone got any idea why this is happening?

Long version:

So I have this program running on my Esp8266
<!-- language-all: lang-cpp -->

    #include <ESP8266WiFi.h>

    IPAddress ip(192, 168, 0, 150);
    IPAddress gateway(192, 168, 0, 1);
    IPAddress subnet(255, 255, 255, 0);

    const char* ssid = "mySSID";
    const char* password = "myPSW";
    const char* host = "192.168.0.228";

    const int buttonPin = 0;
    const int relayPin =  4;
    const int doorPin = 5;
    const int ldrPin = A0;

    //int ldrState;
    //int serialCount = 0;
    //int ldrMin = 0;
    //int ldrMax = 1024;
    int buttonState = 0;
    int doorState = 0;
    byte Main_Light_State_Begin;
    bool Main_Light_State;
    bool doorNotified = false;
    bool button_action_taken = false;
    bool Main_Light_DBR = true;
    String HTTP_Get_Response;

    WiFiServer server(80);

    //Functions
    String HTTP_Get(char* Adress, String URL, bool Last_Line_Bool) {
      WiFiClient client;
      const int httpPort = 80;
      if (!client.connect(Adress, httpPort)) {
        Serial.println("connection failed");
        return "Failed";
      }

      Serial.print("Requesting URL: ");
      Serial.println(URL);
      Serial.println("at adress");
      Serial.println(Adress);
      client.print(String("GET ") + URL + " HTTP/1.1\r\n" +
                   "Host: " + Adress + "\r\n" +
                   "Connection: close\r\n\r\n");
      delay(10);

      String Response;
      String Last_Line;

      while (client.available()) {
        String line = client.readStringUntil('\r');
        Serial.print(line);
        Response = Response + line;
      }
      return Response;

      Serial.println();
      Serial.println("closing connection");

    }

    void setup() {
      Serial.begin(115200);
      delay(1000);

      Serial.println();
      Serial.println();
      Serial.print("Connecting to ");
      Serial.println(ssid);

      WiFi.begin(ssid, password);
      WiFi.config(ip, gateway, subnet);

      while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
      }
      Serial.println("");
      Serial.println("WiFi connected");

      server.begin(); -
      Serial.println("Server started");

      Serial.println(WiFi.localIP());
      pinMode(relayPin, OUTPUT);
      pinMode(buttonPin, INPUT);
      pinMode(doorPin, INPUT);
    //  pinMode(ldrPin, INPUT);
    }

    void loop() {
      if (WiFi.status() != WL_CONNECTED) {
        Serial.println("Wifi NOT Connected");
      }
      //Sensors
      buttonState = digitalRead(buttonPin);
      doorState = digitalRead(doorPin);
      //ldrState = map(analogRead(ldrPin), ldrMin, ldrMax, 0, 100);
      //Serial.println(analogRead(ldrPin));
    //  if (serialCount == 1000) {
    //    Serial.println(ldrState);
    //    serialCount = 0;
    //  } else {
    //    serialCount ++;
    //  }

      //Doorsensor
      if (doorState == HIGH) {
        if (doorNotified == false) {
          Serial.println("DOOR");
          HTTP_Get_Response = HTTP_Get("192.168.0.228", "/index.php/?door_opened=true", false);
          doorNotified = true;
        }
      } else if (doorState == LOW) {
        if (doorNotified == true) {
          doorNotified = false;
          delay(500);
        }
        else {
          doorNotified = false;
        }
      }

      //Button
      if (buttonState == LOW) {
        if (button_action_taken == false) {
          if (Main_Light_State == true) {
            Serial.println("SWITCH");
            Main_Light_State = false;
            digitalWrite(relayPin, HIGH);
            delay(500);
            Main_Light_DBR = false;
          }
          else if (Main_Light_State == false) {
            Serial.println("SWITCH");
            Main_Light_State = true;
            digitalWrite(relayPin, LOW);
            delay(500);
            Main_Light_DBR = false;
          }
          button_action_taken = true;
        }
      } else if (buttonState == HIGH) {
        if (button_action_taken == true) {
          button_action_taken = false;
          delay(500);
        }
        else {
          button_action_taken = false;
        }

      }
      //Main_Light_State
      if (Main_Light_State == true) {
        digitalWrite(relayPin, LOW);
        if (Main_Light_DBR == false) {
          HTTP_Get_Response = HTTP_Get("192.168.0.228", "/index.php/?main_light_on_dbr=true", false);
          Main_Light_DBR = true;
        }

      } else if (Main_Light_State == false) {
        digitalWrite(relayPin, HIGH);
        if (Main_Light_DBR == false) {
          HTTP_Get_Response = HTTP_Get("192.168.0.228", "/index.php/?main_light_off_dbr=true", false);
          Main_Light_DBR = true;
        }
      }

      WiFiClient client = server.available();
      if (!client) {
        return;
      }

      Serial.println("new client");
      while (!client.available()) {
        delay(1);
      }

      String req = client.readStringUntil('\r');
      Serial.println(req);
      client.flush();

      if (req.indexOf("/main_light/on") != -1) {
        Main_Light_State = true;
        Main_Light_DBR = false;
      } else if (req.indexOf("/main_light/off") != -1) {
        Main_Light_State = false;
        Main_Light_DBR = false;
      } else if (req.indexOf("/main_light/switch") != -1) {
        Serial.println("SWITCH");
        if (Main_Light_State == true) {
          Main_Light_State = false;
        }
        else if (Main_Light_State == false) {
          Main_Light_State = true;
        }
        Main_Light_DBR = false;
      } else if (req.indexOf("/main_light/state") != -1) {

      } else {
        Serial.println("invalid request");
        client.stop();
        return;
      }

      client.flush();

      String s = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n";
      s += (Main_Light_State) ? "1" : "0";

      client.print(s);
      delay(1);
      Serial.println("Client disonnected");
    }

With the lines I commented like above everything works fine. I have a light dependant resistor connected (correctly, I get correct measurements from it) to A0. From the moment on I uncomment the lines involving this LDR and thus start reading data from it I lose my wifi connection. Has anyone got any idea why this is? Thank you!

body:
I have found that this was caused by reading the analog pin to many times in a short period of time. I replaced

      ldrState = map(analogRead(ldrPin), ldrMin, ldrMax, 0, 100);
      Serial.println(analogRead(ldrPin));
      if (serialCount == 1000) {
        Serial.println(ldrState);
        serialCount = 0;
      } else {
        serialCount ++;
      }
with this:

    if (serialCount == 10000) {
      ldrState = map(analogRead(ldrPin), ldrMin, ldrMax, 0, 100);
      Serial.println(ldrState);
      serialCount = 0;
    } else {
      serialCount ++;
    }

Although I thought of this approach before, my mistake was that I was still reading the sensor every time the code loops, I just wasn't printing it to the serial monitor until each 100th loop.

This still gives me a reading several times per second, which is way more then I need. Anyway, now I know that I can't read my ESP8266 Analog pin to many times per second or the wifi will disconnect (at least when using it with the Arduino IDE)


body:
This is an old question that has been answered, but I would like to offer a slightly more elegant solution (IMO!):

In my method which reads the analog data, I check and only read every 50 milliseconds:

    void readAnalogSensor() {
       if( millis() % 50 != 0 )
           return;
       .
       .  // Do your sensor read and processing here
       .
    }

This avoids having to keep a loop count and seems more deterministic - the loop count value will not necessarily increase in a consistent fashion depending on what else is going on in the loop.  Having the millis values available is also useful if you need to implement some button debounce code.


body:
Here is what I usually do to give repetition at fixed intervals:

    void readAnalogSensor(){
      if (millis()<taskTime) return; // time is not expired yet
      taskTime += 50; // set time for the following execution
      // .... more code for the task that is done every 50 ms
    }
This requires an `unsigned long variable taskTime`. You may also use a constant instead of the 50.
`taskTime` should be set to some value close to `millis()` at the end of `setup()`, otherwise there will be a rapid sequence of executions while `taskTime` catches up with `millis()`.


message:
Arduino and PHP communication only work if I open the Arduino IDE

I have a problem. I try to open a channel to arduino and PHP talk, the PHP would send a command and the Arduino should answer that. It works, but only if I execute some steps before:

 1.  sudo chmod 777 /dev/ttyACM0
 2.  sudo arduino
 3.  Open the serial monitor in arduino IDE
 4.  Close the serial monitor
 5.  Now everything is ok, they can talk

The first step is ok, I really need to do this, the 2-4 seems irrelevant, but the communication do not start without it. I put one LCD in arduino to print what he receive, when I send "HEYARD" with PHP to him, the RX led blinks and the TX led also, but nothing is printed on LCD. If I do the 2-4 steps, when PHP send "HEYARD", LCD show HEYARD and arduino answer with "HEYPHP"

Anyone could help? There is some way to open it via Terminal, or, at least, open the Serial Monitor from arduino and close to see if this start

body:
Here the setup block:

    <?php
     require("php_serial.class.php");
     $serial = new phpSerial();
        $serial->deviceSet("/dev/ttyACM0");
     $serial->confBaudRate(9600);
     $serial->confParity("none");
     $serial->confCharacterLength(8);
     $serial->confStopBits(1);
     $serial->confFlowControl("none");
     $conect = mysql_connect("localhost", "root", "") or print (mysql_error());
     mysql_select_db("ANM", $conect) or print(mysql_error());
    ?>

And here the connection block:

    <?php
        $serial->deviceOpen();
        exec("echo 'HEYARD' > /dev/ttyACM0");
        sleep(1);
        $read = $serial->readPort();
    ?>


body:
stty -F /dev/ttyACM0 ignpar
stty -F /dev/ttyUSB0 ignpar

> IGNPAR Ignore framing errors and parity errors.

That is what you need to fix minor framing issues.

Screen switches this by default; but NONE of the serial drivers do.
Especially when connecting PIs or BBB to Arduinos


message:
Changing how a longpress is executed

I have an RGB LED common Anode attached to my Uno and this code detects a long press to turn the LED on and off.  Short presses cycle through colors, then off.

The problem is that a longpress is 2+sec, but it doesn't register until I release the button.  How would I set this up to execute the code at 2sec regardless of whether the button is released?

It's probably not worth my time if it requres too much modification.  I have a working item, it's just not... ideal.

<!-- language: c -->

    Xhunsigned long keyPrevMillis = 0;
    const unsigned long keySampleIntervalMs = 25;

    int redPin = 11;
    int greenPin = 10;
    int bluePin = 9;
    int LEDcolor=0; // 0=White, 1=Red, 2=Green, 3-Blue, 4=Yellow, 5=Purple, 6=Pink, 7=Orange, 8=Off
    int LEDstatus =0; //0=Off, 1=On
    int changed =0; //has the LEDstatus just changed?
    byte longKeyPressCountMax = 80;    // 80 * 25 = 2000 ms
    byte longKeyPressCount = 0;

    byte prevKeyState = HIGH;         // button is active low
    const byte keyPin = 2;            // button is connected to pin 2 and GND

    // called when button is kept pressed for less than 2 seconds
    void shortKeyPress()
    {
       Serial.println("short");
       if (LEDstatus==1)
       {
          LEDcolor = LEDcolor +1;
          if (LEDcolor==0) {analogWrite(redPin, 0);analogWrite(greenPin, 0);analogWrite(bluePin, 0);Serial.println("White");}
          if (LEDcolor==1) {analogWrite(redPin, 0);analogWrite(greenPin, 255);analogWrite(bluePin, 255);Serial.println("Red");}
          if (LEDcolor==2) {analogWrite(redPin, 255);analogWrite(greenPin, 0);analogWrite(bluePin, 255);Serial.println("Green");}
          if (LEDcolor==3) {analogWrite(redPin, 255);analogWrite(greenPin, 255);analogWrite(bluePin, 0);Serial.println("Blue");}
          if (LEDcolor==4) {analogWrite(redPin, 0);analogWrite(greenPin, 0);analogWrite(bluePin, 255);Serial.println("Yellow");}
          if (LEDcolor==5) {analogWrite(redPin, 175);analogWrite(greenPin, 255);analogWrite(bluePin, 175);Serial.println("Purple");}
          if (LEDcolor==6) {analogWrite(redPin, 0);analogWrite(greenPin, 255);analogWrite(bluePin, 155);Serial.println("Pink");}
          if (LEDcolor==7) {analogWrite(redPin, 5);analogWrite(greenPin, 215);analogWrite(bluePin, 255);Serial.println("Orange");}
          if (LEDcolor==8) {analogWrite(redPin, 255);analogWrite(greenPin, 255);analogWrite(bluePin, 255);Serial.println("Off");LEDstatus=0;}
       }
    }

    // called when button is kept pressed for more than 2 seconds
    void longKeyPress()
    {
       Serial.println("long");
       if (LEDstatus==0 && changed==0)
       {
          analogWrite(redPin, 0);
          analogWrite(greenPin, 0);
          analogWrite(bluePin, 0);
          LEDcolor=0;
          changed=1;
          LEDstatus=1;Serial.println("On");
       }
       if (LEDstatus==1 && changed==0)
       {
          analogWrite(redPin, 255);
          analogWrite(greenPin, 255);
          analogWrite(bluePin, 255);
          LEDcolor=0;
          changed=1;
          LEDstatus=0;Serial.println("Off");
       }
       changed=0;
    }

    // called when key goes from not pressed to pressed
    void keyPress() {
       Serial.println("key press");
       longKeyPressCount = 0;
    }

    // called when key goes from pressed to not pressed
    void keyRelease() {
       Serial.println("key release");

       if (longKeyPressCount >= longKeyPressCountMax) {
          longKeyPress();
       }
       else {
          shortKeyPress();
       }
    }

    void setup()
    {
       Serial.begin(9600);
       pinMode(keyPin, INPUT);
       digitalWrite(keyPin, HIGH);
       pinMode(redPin, OUTPUT);
       pinMode(greenPin, OUTPUT);
       pinMode(bluePin, OUTPUT);
       analogWrite(redPin, 255);
       analogWrite(greenPin, 255);
       analogWrite(bluePin, 255);
    }

    void loop() {
    // key management section
       if (millis() - keyPrevMillis >= keySampleIntervalMs) {
          keyPrevMillis = millis();

          byte currKeyState = digitalRead(keyPin);

          if ((prevKeyState == HIGH) && (currKeyState == LOW)) {
             keyPress();
          }
          else if ((prevKeyState == LOW) && (currKeyState == HIGH)) {
             keyRelease();
          }
          else if (currKeyState == LOW) {
             longKeyPressCount++;
          }

          prevKeyState = currKeyState;
       }
    }

body:
I've rewritten the code entirely. Not that yours was terrible, it was just easier for me to start from scratch. You are left with a very empty `loop()`, which I always prefer.

The code contains three 'colours' and an OFF state. You can add as many other colours as you wish: add an enumeration to `_LED_STATE` and then add a corresponding `case(<NEW_COLOUR>)` statement in `LEDcontrol()`. I haven't included any `analogWrite()` functions - or in fact any declarations for the LED pins at all - because I'm a little too lazy but it should be obvious where to put them within the case statement.

Note that in the final `case()` statement, the LED state is changed from green to off. This means that a short press will turn the LED off after it has cycled through all the other colours, but will stay off until a long press. If you only want long pressed to switch off/on, change line 103 to `eLED_STATE = _LED_STATE_RED;`, or whichever the first colour is.

<!-- language: c -->

    #define btn 3 // button pin

    #define SHORT_PRESS 100  // useful for debouncing, can be changed
    #define LONG_PRESS 2000 // defines how long a 'long press' is
    #define CYCLE  false
    #define SHOW  true

    //--// You can add new colours in this enum block
    enum _LED_STATE
    {
     _LED_STATE_OFF,
     _LED_STATE_RED,
     _LED_STATE_BLUE,
     _LED_STATE_GREEN
    };

    _LED_STATE eLED_STATE = _LED_STATE_OFF;

    void setup()
    {
     pinMode(btn, OUTPUT);
     LEDcontrol(SHOW);
    }

    void loop()
    {

     if (digitalRead(btn))
      btnPressed();
    }

    void btnPressed()
    {
     unsigned long tStart = millis();

     //--// Loop continuously while button is pressed
     while (digitalRead(btn))
     {
      //--// If LONG_PRESS is exceeded...
      if (millis() > tStart + LONG_PRESS)
      {
       //--// If LED is off, turn it on
       if (eLED_STATE == _LED_STATE_OFF)
        eLED_STATE = _LED_STATE_RED;  // Choose 'starting' colour
       //--// If LED is on, turn if off
       else
        eLED_STATE = _LED_STATE_OFF;
       //--// Update LED to display new eLED_STATE
       LEDcontrol(SHOW);
       //--// Now loop here until button is released
       while (digitalRead(btn));
      }
     }

     //--// If button is released in between the two press times
     if ((millis() > tStart + SHORT_PRESS) && (millis() < tStart + LONG_PRESS))
     {
      //--// Ignore if LED is off   ////// REMOVE ////////////////////
      if (eLED_STATE == _LED_STATE_OFF) ////////// IF ////////////////////
       return;       ///////////// NECESSARY //////////

      //--// Change the LED colour
      LEDcontrol(CYCLE);
      //--// Update LED to display new eLED_STATE
      LEDcontrol(SHOW);
     }

     //--// This helps to debounce; experiment with it
     delay(10);
    }

    void LEDcontrol(bool SHOW_OR_CYCLE)
    {
     switch (eLED_STATE)
     {
      case(_LED_STATE_RED) :
      {
       if (SHOW_OR_CYCLE)
       {
        // paint it red
        return;
       }
       eLED_STATE = _LED_STATE_GREEN;
       return;
      }
      case(_LED_STATE_GREEN) :
      {
       if (SHOW_OR_CYCLE)
       {
        // paint it green
        return;
       }
       eLED_STATE = _LED_STATE_BLUE;
       return;
      }
      case(_LED_STATE_BLUE) :
      {
       if (SHOW_OR_CYCLE)
       {
        // paint it blue
        return;
       }
       //--// What happens after last colour? Next colour or OFF?
       eLED_STATE = _LED_STATE_OFF;
       return;
      }
      case(_LED_STATE_OFF) :
      {
       if (SHOW_OR_CYCLE)
       {
        // paint it black
        return;
       }
       eLED_STATE = _LED_STATE_RED;
       return;
      }
     }
    }


message:
Could I use metal buttons as a capacitive button for my arduino project?

Could I use something like this as a capacitive button for my arduino project?

http://www.banggood.com/10pcs-25mm-Vintage-Round-Metal-Buttons-Craft-Scrapbooking-Sewing-Suit-Shirt-Button-p-1011485.html

If I connect it into something like this... http://www.banggood.com/MPR121-Capacitive-Touch-Sensor-Module-For-Raspberry-Pi-Arduino-p-969002.html

Would that make that button a capacitive button? Or am I totally barking up the wrong tree here?

Thanks :)

body:
Yes, that would work.

The only thing to watch out for is that the buttons might be plastic with a thin layer of metal on top (Chemical vapor deposition).


message:
How to read bitmap image on Arduino

I want to convert a bitmap into binary array. My bitmap image is 272*208 pixel monochromatic 1bpp image. I'm confused when the width I get from my image is 16 instead of 272, the height is corrected. And when I skip the bitmap header to get bitmap infomation, I got string of meaningless number in my text file.

<!-- language: c -->

    #include <SPI.h>
    #include <SD.h>
    #include <TFT.h>

    File bmpImage;
    File textFile;

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

    Serial.print("Initializing SD card...");
    if (!SD.begin(53)) {
      Serial.println("initialization failed!");
      return;
    }
    Serial.println("initialization done.");
    int height = 0;
    int width = 0;

    // Open
    bmpImage = SD.open("Circle.bmp", FILE_READ);
    textFile = SD.open("test.txt", FILE_WRITE);

    bmpImage.seek(0x12);// width in pixel = 16
    width = bmpImage.read();
    bmpImage.seek(0x16);// height in pixel = 208
    height = bmpImage.read();
    Serial.println(width);
    Serial.println(height);

    int imageSize = height*width;

    bmpImage.seek(0x36);//skip bitmap header

    for(int i = 0; i < height; i ++) {
      for (int j = 0; j < width; j ++) {
        textFile.write(bmpImage.read());
        textFile.write(" ");
      }
      textFile.write("\n");
    }

    bmpImage.close();
    textFile.close();

    Serial.println("done write");
    }

    void loop()
    {
      // nothing happens after setup
    }

body:
That was a very raw way of trying to read a [BMP][1] file. There are a lot of assumptions that might give errors.

1. The file is a BMP file. The header signature is not checked.
2. The image offset is assumed to be directly after the file header. It is not read.
3. The image width is less than 256. Only the lowest byte of the 32-bit image width is read. As 272>256 the low byte is 16.
4. The image height is less than 256. Only the lowest byte of the 32-bit image height is read.

It is a small bitmap but it will take a very long time to read when reading a single byte at a time. There are methods to improve performance but that is an answer to another question.

A more robust method to read the BMP header and image information is to define them as a struct and read.

    struct bmp_file_header_t {
      uint16_t signature;
      uint32_t file_size;
      uint16_t reserved[2];
      uint32_t image_offset;
    };

    struct bmp_image_header_t {
      uint32_t header_size;
      uint32_t image_width;
      uint32_t image_height;
      uint16_t color_planes;
      uint16_t bits_per_pixel;
      uint32_t compression_method;
      uint32_t image_size;
      uint32_t horizontal_resolution;
      uint32_t vertical_resolution;
      uint32_t colors_in_palette;
      uint32_t important_colors;
    };

    bmpImage = SD.open("Circle.bmp", FILE_READ);
    ...
    // Read the file header
    bmp_file_header_t fileHeader;
    bmpImage.read(&fileHeader, sizeof(fileHeader));
    ...
    // Check signature
    ...
    // Read the image header
    bmp_image_header_t imageHeader;
    bmpImage.read(&imageHeader, sizeof(imageHeader));
    ...
    // Check image size and format
    ...
    // Locate the pixels
    bmpImage.seek(fileHeader.image_offset);

The file and image information are stored in little-endian so that works just fine on an AVR.

  [1]: https://en.wikipedia.org/wiki/BMP_file_format


body:
First of all I suggest you to read the full specification of the bmp file header (for instance on [wikipedia][1]).

Particularly see that

 1. You can have a color table (palette): consequently the starting address of the bitmap data CAN not be 0x36
 2. The pixels are not stored one per byte, but can be packed (see [Pixel storage][2])
 3. There are different type of headers
 4. Width and Height are 4 byte integers, so your width is fine (272 = 256 + 16)

This said, *if* your bitmap has a standard `BITMAPINFOHEADER` header, and *if* your bitmap has a 24 bit standard coding (16 millions of colors) you can do something like this:

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

    int32_t readNbytesInt(File *p_file, int position, byte nBytes)
    {
     if (nBytes > 4)
      return 0;

     p_file->seek(position);

     int32_t weight = 1;
     int32_t result = 0;
     for (; nBytes; nBytes--)
     {
      result += weight * p_file->read();
      weight <<= 8;
     }
     return result;
    }

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

     Serial.print("Initializing SD card...");
     if (!SD.begin(53)) {
      Serial.println("initialization failed!");
      while (1); // <- this is how you should block execution, not with returns
     }
     Serial.println("initialization done.");

     // Open
     File bmpImage = SD.open("Circle.bmp", FILE_READ);
     File textFile = SD.open("test.txt", FILE_WRITE);

     int32_t dataStartingOffset = readNbytesInt(&bmpImage, 0x0A, 4);

     // Change their types to int32_t (4byte)
     int32_t width = readNbytesInt(&bmpImage, 0x12, 4);
     int32_t height = readNbytesInt(&bmpImage, 0x16, 4);
     Serial.println(width);
     Serial.println(height);

     int16_t pixelsize = readNbytesInt(&bmpImage, 0x1C, 2);

     if (pixelsize != 24)
     {
      Serial.println("Image is not 24 bpp");
      while (1);
     }

     bmpImage.seek(dataStartingOffset);//skip bitmap header

     // 24bpp means you have three bytes per pixel, usually B G R

     byte R, G, B;

     for(int32_t i = 0; i < height; i ++) {
      for (int32_t j = 0; j < width; j ++) {
       B = bmpImage.read();
       G = bmpImage.read();
       R = bmpImage.read();
       textFile.print("R");
       textFile.print(R);
       textFile.print("G");
       textFile.print(G);
       textFile.print("B");
       textFile.print(B);
       textFile.print(" ");
      }
      textFile.print("\n");
     }

     bmpImage.close();
     textFile.close();

     Serial.println("done write");
    }

The text output of this should be a file with an array of strings like `R10G100B25`, where R is the red component of the pixel, G is the green component and B the blue one.

Now, this is only compatible with the 24bpp format. If you want to support more formats you will need to read the specs and code them.

Let me know if this works for you

  [1]: https://en.wikipedia.org/wiki/BMP_file_format
  [2]: https://en.wikipedia.org/wiki/BMP_file_format#Pixel_storage


body:
Or you could keep your old code with some adjustments, if you just want to read your image without bothering with too many checks.

Change the type of imageSize to `unsigned long`.

The height and width are 4-byte fields, so a single read() wont cut it. You have to declare the height and width as *long* or *int32_t* variables and then read 4 bytes at each offset, while using bit shifting to assemble the bytes into one number and remembering that it's little endian.
Something like this:

    long width |= bmpImage.read();
    width |= (long)(bmpImage.read()) << 8;
    width |= (long)(bmpImage.read()) << 16;
    width |= (long)(bmpImage.read()) << 24;

Repeat this to get the height but use *abs()* to get the absolute value since its usually negative.
You can also check for a colour table; usually the ColorDepth field is a good indicator (offset 28); if its less than 16, then you should expect a colour table. But if you know this already, you can skip it and get to the start offset, usually 0x36.
Your current code doesnt take the padding into account (even though your image doesn't have any padding) and it also isnt using the actual image width in bytes. To get this width, assuming the BMP uses RGB888 24 bits per pixel:

    width = ((width * 24) + 31) / 32;
    width *= 4;

With this, you can now read each row, though its usually arranged bottom-up. However, you arent writing properly to the file. You should use `textfile.print()` and not `write()`; the former will write the decimal value of each byte to your file while the latter will write the exact un-encoded byte to the text file, which would result in a lot of gibberish when you try to display the file's contents, say on Notepad, since the range of printable characters (under default ASCII encoding) is between 32 - 127 and your image probably has lots of bytes outside that range.


message:
Is Arduino uno SPI comunication can be also master and slave in the same time?

OR master 2 slaves in the same time?
------------------------------------------------------------

I want to recevice data from a sensor and display on OLED (all data transfer with SPI bus)

Can I master those two device (sensor & OLED) in the same time? (with SS pin to select slave )

OR Can I be both slave(recevices the data from sensor) and master (sent data to OLED) in the same time ?

What should I do ? and How can I do?

(I read the SPI example code on the Official website , but I still have no ideal about it)

body:
You can have several devices on an SPI bus. Each must have a chip select. The Arduino SS pin (Uno pin 10) is often used for chip select. Chip select pins should then be in output mode.

Connect the sensor and display to the SPI bus (MOSI, MISO, SCK) and use a chip select pin for each.

A driver (library) for a device connect to the SPI bus will typically assert the chip select pin and transfer commands and data. The SPI transfer is both read and write at the same time.


body:
SPI is bi-directional, so sending data or receiving data doesn't indicate if it's a master or a slave.

The master is the one that initiates the communications, that's all. So the arduino is a master in both cases. The master send data to the OLED. The master requests data from the sensor.


message:
How to dim background LEDs on TFT display with ILI9341

I have bought a 2.5" TFT shield online, which is equipped with the ILI9341 controller. I need to dim the intensity of the background LEDs to match ambient light.

This particular shield does not provide a pin to control the intensity of the LEDs with PWM via a separate input, so I need to dim the background LEDs of this display via software.

The zip file with the libraries can be downloaded [here][1].

Does one of you know how can issue a command to the TFT display to dim the background LEDs?

Thanks in advance!

# UPDATE 1:

I wrote a new function to set the display's brightness by controlling the background LEDs, but something is missing as I can seem to be writing correctly to the display. So I'm trying to get the display to answer to a known command first, like 0x28 (Display Off).

The new function is defined in Adafruit_TFTLCD.cpp:

    // Set display brightness (background LED's)
    void Adafruit_TFTLCD::setDisplayBrightness(uint8_t x) {
      // Try with 0x28 (Display Off) to see if display reacts
      writeRegister8(0x28, 0);
      return;
    }

The function prototype is defined in Adafruit_TFTLCD.h

    // New functions
    void setDisplayBrightness(uint8_t x);

Then I call the function in my main loop. To make sure, I first write some rectangles on screen, wait 5 seconds, then fill the screen with blue, call the new function and enter an endless loop so no other commands can interfere:

      tft.fillScreen(BLUE);
      tft.setDisplayBrightness(10); // Which really is command 0x28 to test

Any clues what I might be missing?

Thanks!

UPDATE 2:

I got so far as to have the ILI9341 react to some commands, but not all the time, and not to all commands. I suspect there is something in the way you issue the commands that I'm missing( timing?, sequence?, other?)

Here is what I have found out so far:

I can get the display to react to the Display Off command (0x28), but only when I issue it in the begin(..) function. So, the original code in Adafruit_TFTLCD.cpp is like this:

    void Adafruit_TFTLCD::begin(uint16_t id) {
    ...
    writeRegister8(ILI9341_DISPLAYON, 0);
    delay(500);

If I change it to the following the display reacts by remaining white:

    void Adafruit_TFTLCD::begin(uint16_t id) {
    ...
    writeRegister8(ILI9341_DISPLAYON, 0);
    writeRegister8(ILI9341_DISPLAYOFF, 0); // Display off is declared as 0x28
    delay(500);

So, I have a reaction to command 28h.

Then I tried function 0x51 like this in the begin(...) function:

    void Adafruit_TFTLCD::begin(uint16_t id) {
    ...
    writeRegister8(ILI9341_DISPLAYON, 0);
    delay(500);
    writeRegister8(0x51, 0x80); // Test command 0x51 - background intensity
    delay(500);

To no effect :-(

I even added command 0xBE (background PWM frequency) to see if it had any effect, but nothing :-(

    void Adafruit_TFTLCD::begin(uint16_t id) {
      ...
      writeRegister8(ILI9341_DISPLAYON, 0);
      writeRegister8(0xbe, 0x80);
      delay(500);
      writeRegister8(0x51, 0x0);
      delay(500);

Also if I issue the 0x28 command:

    writeRegister8(ILI9341_DISPLAYOFF, 0)

elsewhere in Adafruit_TFTLCD (e.g. in FillScreen, Fill Rect etc, it doesn't work either).

Any ideas? They would be highly appreciated!

  [1]: http://forum.arduino.cc/index.php?action=dlattach;topic=314613.0;attach=121865

body:
It looks like it should be controllable with command 0x51.

I would modify the library and add a new method to the `Adafruit_ILI9341_8bit_AS` class - something like:

    void Adafruit_ILI9341_8bit_AS::setBacklight(uint8_t brightness) {
        writeRegister8(0x51, brightness);
    }

Then you can change the brightness by calling that method on your TFT object in your sketch.  (Don't forget to add the prototype to the class definition in the header file of course).


body:
I got in contact with the manufacturer of the shield, they informed that the background LEDs are hardwired and not controllable via the ILI9341. So, it is not possible to dim the background light in this shield

:-(

I will look for another TFT shield and make sure it's dimmable before buying.


body: After looking at the schematic (mine is different) but on pin 16 is labeled as BL. If that is indeed the power for the LED backlights then a voltage applied to it should vary the brightness.  Caution:You need to know how much current the LEDs are pulling. If over the limit for a PWM pin you will have to run it through a transistor to boost the current.


body:
Most of thees cheap Chinese LCD modules have the LED backlight hardwired to Vcc and GND and cannot be controlled.

However, after inspecting the module I have and some similar ones online I found that most have the Back-light LEDs pins available through the LCD panel flex cable. If yours is similar to the one in the picture then you will notice that the main flex cable is for the LCD itself, and there are usually two other flex cables connected to it. The one on the left is for touch panel (if equipped), and the one of the right is for the back light LEDs (sometimes it is connected on the backside of the flex).

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

In this panel and on mine (a little different from this) they are labeled as K1, K2, K3 and K4 which are mostly the Cathode side of the LED (negative side) and they are exposed as separate pins in the main flex cable, while the Anode is soldered to the main flex cable Vcc plane and cannot be easily accessed without desoldering the LED flex cable.

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

So in ordered to control the backlight you have to cut the trace on the PCB (not the flex cable) and connect it to a transistor which you control through the Arduino.

* Double check the polarity in your LCD panel, it could be different from mine.

  [1]: https://i.stack.imgur.com/A8F27.png
  [2]: https://i.stack.imgur.com/geDK8.png


body:
I have successfully dimmed the backlight on a ili9341 by simply modulating the pin the LED pin is connected to.

Note, I am using a teensy 3.2 your mileage may vary.

    ledPin=32;

    void loop() {
    analogWrite(ledPin, 60);


message:
Error uploading Arduino Micro Sketch using Kubuntu

I have an arduino micro which I want to program from my Kubuntu 15.10 system. I installed the arduino software using apt-get, but when I try to upload the program (for test purpose I use the Basics\BareMinimum sketch) I get the following error:

    Found programmer: Id = "0.00 V1"; type =
        Software Version = 0..; Hardware Version = 0.0
    avrdude: error: buffered memory access not supported. Maybe it isn't
    a butterfly/AVR109 but a AVR910 device?

The proper device "Arduino Micro" is selected and also the proper port "/tty/ACM0". I found people on the internet which have the same error and could solve it by using another USB port or cable. But I tried it with two different cables and different ports and didn't manage to get it working. I even tried it on my Laptop running an older version of Kubuntu which produced the same error.

Therefore I tried the newest version of the Arduino software from the arduino homepage. With this I get a different error:

    avrdude: ser_open(): can't open device "/dev/ttyACM0": Device or resource busy
    avrdude: ser_send(): write error: Bad file descriptor

My user is added to the dialout group, so I should have access to the port. It is also the right port as the port disappears from the arduino menu when I unplug the board.

The arduino itself shouldn't be the problem, as I can upload the sketch from another windows laptop without problems.

EDIT: when I plug in the arduino, the following is added to the `dmesg` output:

    [ 8390.293960] usb 1-2: new full-speed USB device number 6 using xhci_hcd
    [ 8390.424861] usb 1-2: New USB device found, idVendor=2341, idProduct=8037
    [ 8390.424863] usb 1-2: New USB device strings: Mfr=1, Product=2, SerialNumber=0
    [ 8390.424864] usb 1-2: Product: Arduino Micro
    [ 8390.424865] usb 1-2: Manufacturer: Arduino LLC
    [ 8390.425283] cdc_acm 1-2:1.0: ttyACM0: USB ACM device
    [ 8390.426815] input: Arduino LLC Arduino Micro as /devices/pci0000:00/0000:00:14.0/usb1/1-2/1-2:1.2/0003:2341:8037.0007/input/input21
    [ 8390.482163] hid-generic 0003:2341:8037.0007: input,hidraw4: USB HID v1.01 Mouse [Arduino LLC Arduino Micro] on usb-0000:00:14.0-2/input2

body:
I have been meaning to try the Arduino IDE on Ubuntu. (I'm on Ubuntu 14.10 LTS and using an original Arduino UNO).

From the top, I installed using:

    sudo apt-get update && sudo apt-get install arduino arduino-core

(from: http://playground.arduino.cc/Linux/Ubuntu)

It's the older version 1.0.5 and loaded up the basic sketch. It worked straight off the bat.

Just some quick thoughts:

#Keyboard and mouse emulation

I noticed the `hid-generic` and was reminded of the caution on:
[https://www.arduino.cc/ re codig practices for keyboard and mouse emulation][1]

regarding coding practices for keyboard and mouse emulation. Does your old sketch utilise the keyboard/mouse libraries at all? It might come down to REALLY timing the reset perfectly.

#The `reset` problem

Given that you're getting a communication error based on the virtual USB device in the Leonardo/Micro (single chip as opposed to the previous versions), and you're seeing it in the IDE but not via the `avrdude` software, have you followed the `reset` instructions from [the above link][2]? So back to timing the reset (emphasis mine):

>In general, you upload code to the Leonardo or Micro as you would with the Uno or other Arduino boards. Click the upload button in the Arduino IDE and your sketch will be automatically uploaded onto the board and then started. This works more or less the same way as with the Uno: the Arduino software initiates a reset of the board, launching the bootloader - which is responsible for receiving, storing, and starting the new sketch.

>However, because the serial port is virtual, it disappears when the board resets, the Arduino software uses a different strategy for timing the upload than with the Uno and other boards. In particular, after initiating the auto-reset of the Leonardo or Micro (using the serial port selected in the Tools > Serial Port menu), the Arduino software waits for a new virtual (CDC) serial / COM port to appear - one that it assumes represents the bootloader. It then performs the upload on this newly-appeared port.

>These differences affect the way you use the physical reset button to perform an upload if the auto-reset isn't working. **Press and hold the reset button on the Leonardo or Micro, then hit the upload button in the Arduino software. Only release the reset button *AFTER* you see the message "Uploading..." appear in the software's status bar.** When you do so, the bootloader will start, creating a new virtual (CDC) serial port on the computer. The software will see that port appear and perform the upload using it. Again, this is only necessary if the normal upload process (i.e. just pressing the uploading button) doesn't work. (Note that the auto-reset is initiated when the computer opens the serial port at 1200 baud and then closes it; this won't work if something interferes with the board's USB communication - e.g. disabling interrupts.)

#`avrdude` command line
Next, share your `avrdude` command line and we can see if something is odd there. As an example with my UNO I see this:

    /usr/share/arduino/hardware/tools/avrdude -C/usr/share/arduino/hardware/tools/avrdude.conf -v -v -v -v -patmega328p -carduino -P/dev/ttyACM0 -b115200 -D -Uflash:w:/tmp/build1362089533882735765.tmp/Blink.cpp.hex:i

    avrdude: Version 6.0.1, compiled on Oct 21 2013 at 15:55:32
             Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
             Copyright (c) 2007-2009 Joerg Wunsch

             System wide configuration file is "/usr/share/arduino/hardware/tools/avrdude.conf"
             User configuration file is "/home/madivad/.avrduderc"
             User configuration file does not exist or is not a regular file, skipping

             Using Port                    : /dev/ttyACM0
             Using Programmer              : arduino
             Overriding Baud Rate          : 115200
    avrdude: Send: 0 [30]   [20]
    .... and so on ....

#USB 3 vs USB 2
I probably could have put this closer to the top, but are you using a USB 2 or USB 3 port? If USB 3 are the correct drivers loaded? Have you tried a USB 2 port (if available)

#Good luck

  [1]: https://www.arduino.cc/en/Guide/ArduinoLeonardoMicro#toc13
  [2]: https://www.arduino.cc/en/Guide/ArduinoLeonardoMicro#toc12


body:
You may find that there is a process on Ubuntu that is grabbing the newly created CDC/ACM port as soon as it enters programming mode.

With the Leonardo and Micro you have a CDC/ACM port while it's running, and when the board resets to enter programming mode that CDC/ACM port is destroyed and an entirely new one (hopefully under the same name) is created.  The process `modem-manager` can grab that newly created CDC/ACM device thinking it's a modem and try to configure it as such, thus locking you out of the port.  A similar process in Debian is `brltty` which tries to configure the CDC/ACM port as a braille TTY interface.

You can check to see what process has the CDC/ACM device node open if any with the `lsof` command:

    sudo lsof /dev/ttyACM0

If you find that you do have `modem-manager` running on your system (I'm not sure if it's still default or not, it's been a while since I used Ubuntu, preferring the purity of Debian) it's best to completely remove it:

    sudo apt-get remove modemmanager


body:
> Therefore I tried the newest version of the Arduino software from the arduino homepage.

> The package version I am using is 1:1.0.5+dfsg2-2, the other I tried was 2:1.0.5+dfsg2-4.

That is not the newest version.

I think the more recent versions of the IDE are more robust - after all they have fixed reported bugs. Try 1.6.5 or 1.6.7. The version 1.0.5 is pretty old.

---

I too have had "upload completed" on my Leonardo (virtually the same as the Micro) when it did no such thing.

I am using Ubuntu 14.04 and don't have any problems programming my Micro with IDE 1.6.7.

---

When programming you should see the Tx/Rx and yellow LEDs flicker. If not, press Reset when it starts to upload and try again.

---

Have you followed the instructions here? [Arduino Troubleshooting](https://www.arduino.cc/en/Guide/Troubleshooting).

---

> I installed the arduino software using apt-get ...

Personally I download the IDE from this page: <https://www.arduino.cc/en/Main/Software>

---

## Update

I just compiled and uploaded "Blink" with IDE 1.6.7 to my Micro on Ubuntu 14.04. This is what I saw:

    Forcing reset using 1200bps open/close on port /dev/ttyACM1
    PORTS {/dev/ttyACM0, /dev/ttyACM1, } / {/dev/ttyACM0, } => {}
    PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, /dev/ttyACM1, } => {/dev/ttyACM1, }
    Found upload port: /dev/ttyACM1
    /home/nick/Development/arduino-1.6.7/hardware/tools/avr/bin/avrdude -C/home/nick/Development/arduino-1.6.7/hardware/tools/avr/etc/avrdude.conf -v -patmega32u4 -cavr109 -P/dev/ttyACM1 -b57600 -D -Uflash:w:/tmp/build8f287ac41038dd4edf2d64ea95be7b6f.tmp/Blink.ino.hex:i

    avrdude: Version 6.0.1, compiled on Apr 14 2015 at 19:04:16
             Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
             Copyright (c) 2007-2009 Joerg Wunsch

             System wide configuration file is "/home/nick/Development/arduino-1.6.7/hardware/tools/avr/etc/avrdude.conf"
             User configuration file is "/home/nick/.avrduderc"
             User configuration file does not exist or is not a regular file, skipping

             Using Port                    : /dev/ttyACM1
             Using Programmer              : avr109
             Overriding Baud Rate          : 57600
             AVR Part                      : ATmega32U4
             Chip Erase delay              : 9000 us
             PAGEL                         : PD7
             BS2                           : PA0
             RESET disposition             : dedicated
             RETRY pulse                   : SCK
             serial program mode           : yes
             parallel program mode         : yes
             Timeout                       : 200
             StabDelay                     : 100
             CmdexeDelay                   : 25
             SyncLoops                     : 32
             ByteDelay                     : 0
             PollIndex                     : 3
             PollValue                     : 0x53
             Memory Detail                 :

                                      Block Poll               Page                       Polled
               Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
               ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
               eeprom        65    20     4    0 no       1024    4      0  9000  9000 0x00 0x00
               flash         65     6   128    0 yes     32768  128    256  4500  4500 0x00 0x00
               lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
               hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
               efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
               lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
               calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
               signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

             Programmer Type : butterfly
             Description     : Atmel AppNote AVR109 Boot Loader

    Connecting to programmer: .
    Found programmer: Id = "CATERIN"; type = S
        Software Version = 1.0; No Hardware Version given.
    Programmer supports auto addr increment.
    Programmer supports buffered memory access with buffersize=128 bytes.

    Programmer supports the following devices:
        Device code: 0x44

    avrdude: devcode selected: 0x44
    avrdude: AVR device initialized and ready to accept instructions

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

    avrdude: Device signature = 0x1e9587
    avrdude: reading input file "/tmp/build8f287ac41038dd4edf2d64ea95be7b6f.tmp/Blink.ino.hex"
    avrdude: writing flash (4456 bytes):

    Writing | ################################################## | 100% 0.33s

    avrdude: 4456 bytes of flash written
    avrdude: verifying flash memory against /tmp/build8f287ac41038dd4edf2d64ea95be7b6f.tmp/Blink.ino.hex:
    avrdude: load data flash data from input file /tmp/build8f287ac41038dd4edf2d64ea95be7b6f.tmp/Blink.ino.hex:
    avrdude: input file /tmp/build8f287ac41038dd4edf2d64ea95be7b6f.tmp/Blink.ino.hex contains 4456 bytes
    avrdude: reading on-chip flash data:

    Reading | ################################################## | 100% 0.03s

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

    avrdude done.  Thank you.

Can you please compare to what you get? Or post exactly what you see?

---

What do you see in your Port menu? This is what I see:

[![Port menu][1]][1]

---

# Installing Arduino on a fresh Ubuntu system

I did the following steps to get Arduino up on Ubuntu 14.04, on a PC where it was not previously installed.

## Download and install

* Downloaded Linux IDE 1.6.7 (64 bit) from <https://www.arduino.cc/en/Main/Software>

* Un-archive downloaded file into `~/development` folder

* Executed from terminal:  `./arduino`

## Compile "blink"

* Selected Uno device type
* Loaded "Blink" from examples
* Uploaded (checked Uno showed in menu as shown above)
* Got error:

        Sketch uses 1,030 bytes (3%) of program storage space. Maximum is 32,256 bytes.
        Global variables use 9 bytes (0%) of dynamic memory, leaving 2,039 bytes for local variables. Maximum is 2,048 bytes.
        avrdude: ser_open(): can't open device "/dev/ttyACM0": Permission denied
        ioctl("TIOCMGET"): Inappropriate ioctl for device

## Check permissions, join dialout and tty groups

See owner of `/dev/ttyACM*`

    $ ls -l /dev/ttyACM*
    crw-rw---- 1 root dialout 166, 0 Feb  1 07:32 /dev/ttyACM0

Am I in that group? (No)

    getent group dialout
    dialout:x:20:

Add to group `dialout`:

    $ sudo usermod -a -G dialout nick

Am I in that group? (Yes)

    $ getent group dialout
    dialout:x:20:nick

Try again:

    avrdude: ser_open(): can't open device "/dev/ttyACM0": Permission denied
    ioctl("TIOCMGET"): Inappropriate ioctl for device
    Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

Add to group `tty`:

    $ sudo usermod -a -G tty nick

Check groups I am in:

    $ groups nick
    nick : nick adm tty dialout cdrom sudo dip plugdev lpadmin sambashare

Try again (same error).

## Log out and log back in

After logging out and back in, it uploaded OK! Changed to Micro board (very similar to Leonardo) - still uploaded OK (after changing board type in IDE).

## Check USB for Micro

After reset:

    $ lsusb | grep Arduino
    Bus 002 Device 014: ID 2341:0036 Arduino SA

After about 3 seconds:

    $ lsusb | grep Arduino
    Bus 002 Device 015: ID 2341:8037 Arduino SA

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


body:
This is all the symptoms of not having the correct board selected in the IDE.
The fact that the LEDs are flashing during uploading means it's probably not a comms issue.

I understand you wrote that you have selected the correct board already, but please double/triple-check.

I work with both UNOs and Nanos, this is a classic mistake I make all the time.


message:
Send analog value over IR?

for my rc robot I want to use ir to send/receive the value from a jostick.

Is it possible ? I can't use any other radio chip like nrf24l01.

body:
Yes, it is possible. That is already supported by the IR library. Please see this [tutorial][1] for further details. The outline of the sender is:

     uint16_t sample = analogRead(A0);
     irsend.sendSony(sample, 16);

And the receiver:

     if (irrecv.decode(&decodedSignal)) {
        uint16_t sample = decodedSignal.value;
        ...
     }

Cheers!

  [1]: http://garagelab.com/profiles/blogs/tutorial-arduino-ir-sender-and-receiver


message:
Error compiling Arduino

I've just installed the last version of Arduino 1.6.7 plug my Arduino SmartEverything (http://www.smarteverything.it/) to OS X 10.11.2, try to compile this project: https://github.com/nicolsc/sigfox-weather-station/blob/master/sigfox_smart_weather.ino But i got this error

    /Applications/Arduino.app/Contents/Java/arduino-builder -dump-prefs -logger=machine -hardware "/Applications/Arduino.app/Contents/Java/hardware" -hardware "/Users/nunito/Library/Arduino15/packages" -tools "/Applications/Arduino.app/Contents/Java/tools-builder" -tools "/Applications/Arduino.app/Contents/Java/hardware/tools/avr" -tools "/Users/nunito/Library/Arduino15/packages" -built-in-libraries "/Applications/Arduino.app/Contents/Java/libraries" -libraries "/Users/nunito/Documents/Arduino/libraries" -fqbn=AMEL:samd:AMEL_SmartEverything_native -vid-pid=0X2341_0XE002 -ide-version=10607 -build-path "/var/folders/52/_nghc_ms7p52tqr5zdbwvj240000gn/T/build50d3a89dbbfb2b67c903ba23d4913431.tmp" -warnings=none -prefs=build.warn_data_percentage=75 -verbose "/var/folders/52/_nghc_ms7p52tqr5zdbwvj240000gn/T/arduino_50d3a89dbbfb2b67c903ba23d4913431/sketch_jan21c.ino"
    /Applications/Arduino.app/Contents/Java/arduino-builder -compile -logger=machine -hardware "/Applications/Arduino.app/Contents/Java/hardware" -hardware "/Users/nunito/Library/Arduino15/packages" -tools "/Applications/Arduino.app/Contents/Java/tools-builder" -tools "/Applications/Arduino.app/Contents/Java/hardware/tools/avr" -tools "/Users/nunito/Library/Arduino15/packages" -built-in-libraries "/Applications/Arduino.app/Contents/Java/libraries" -libraries "/Users/nunito/Documents/Arduino/libraries" -fqbn=AMEL:samd:AMEL_SmartEverything_native -vid-pid=0X2341_0XE002 -ide-version=10607 -build-path "/var/folders/52/_nghc_ms7p52tqr5zdbwvj240000gn/T/build50d3a89dbbfb2b67c903ba23d4913431.tmp" -warnings=none -prefs=build.warn_data_percentage=75 -verbose "/var/folders/52/_nghc_ms7p52tqr5zdbwvj240000gn/T/arduino_50d3a89dbbfb2b67c903ba23d4913431/sketch_jan21c.ino"
    Build options changed, rebuilding all
    ""   -w -x c++ -E -CC -DF_CPU=48000000L -DARDUINO=10607 -DARDUINO_SAMD_SMARTEVERYTHING -DARDUINO_ARCH_SAMD  -D__SAMD21J18A__        "-I/Users/nunito/Library/Arduino15/packages/AMEL/hardware/samd/1.1.0/cores/arduino" "-I/Users/nunito/Library/Arduino15/packages/AMEL/hardware/samd/1.1.0/variants/AMEL_SmartEverything" "/var/folders/52/_nghc_ms7p52tqr5zdbwvj240000gn/T/build50d3a89dbbfb2b67c903ba23d4913431.tmp/sketch/sketch_jan21c.ino.cpp" -o "/dev/null"
    ""   -w -x c++ -E -CC -DF_CPU=48000000L -DARDUINO=10607 -DARDUINO_SAMD_SMARTEVERYTHING -DARDUINO_ARCH_SAMD  -D__SAMD21J18A__        "-I/Users/nunito/Library/Arduino15/packages/AMEL/hardware/samd/1.1.0/cores/arduino" "-I/Users/nunito/Library/Arduino15/packages/AMEL/hardware/samd/1.1.0/variants/AMEL_SmartEverything" "/var/folders/52/_nghc_ms7p52tqr5zdbwvj240000gn/T/build50d3a89dbbfb2b67c903ba23d4913431.tmp/sketch/sketch_jan21c.ino.cpp" -o "/dev/null"
    ""   -w -x c++ -E -CC -DF_CPU=48000000L -DARDUINO=10607 -DARDUINO_SAMD_SMARTEVERYTHING -DARDUINO_ARCH_SAMD  -D__SAMD21J18A__        "-I/Users/nunito/Library/Arduino15/packages/AMEL/hardware/samd/1.1.0/cores/arduino" "-I/Users/nunito/Library/Arduino15/packages/AMEL/hardware/samd/1.1.0/variants/AMEL_SmartEverything" "/var/folders/52/_nghc_ms7p52tqr5zdbwvj240000gn/T/build50d3a89dbbfb2b67c903ba23d4913431.tmp/sketch/sketch_jan21c.ino.cpp" -o "/var/folders/52/_nghc_ms7p52tqr5zdbwvj240000gn/T/build50d3a89dbbfb2b67c903ba23d4913431.tmp/preproc/ctags_target_for_gcc_minus_e.cpp"
    exec: "-w": executable file not found in $PATH
    Error compiling.

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

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

body:
Install Arduino SAMD Boards (32-bits ARM Cortex-M0+) board (using "Tools" -> "Board" -> "Boards Manager" menu).

Just search for "SAMD" in the search bar, choose the latest version and install.


message:
Processing Serial data

I have a PM10 sensor that I'd like to get the values from.

Here's the official documentation from the sensor:
[![ Sensor documentation ][1]][1]

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

I've looked as serial communication, but how do i process byte by byte of information if it's coming in byte at a time?

I'm looking at this example:

    void setup() {
      Serial.begin(9600);
      Serial.println("<Arduino is ready>");
    }

    void loop() {
      recvOneChar();
      showNewData();
    }

    void recvOneChar() {
      if (Serial.available() > 0) {
        receivedChar = Serial.read();
        newData = true;
      }
    }

    void showNewData() {
      if (newData == true) {
        Serial.print("This just in ... ");
        Serial.println(receivedChar);
        newData = false;
      }
    }

Ideally, i'd like to get the PM2 and PM10 values and print them out.

body:
The proper method of receiving this kind of data is to use a *sliding window*. That is you visualise the stream of bytes as just that - a stream of bytes (think letters on paper tape).  You then have a conceptual "window" on that data which is the width of the packet (10 bytes in this case).  As the data passes behind the window you see just 10 bytes of it. When that 10 bytes is in the "right" format (that is, it starts with 0xAA, ends with 0xAB and the checksum is valid) then you have a valid packet and can read the values from it.

The simplest method of implementing that is with a 10-byte array. As a byte arrives on the serial port you shuffle all the bytes down the array to make room for the new byte at the top of the array.  Once 10 bytes have arrived that first byte should now have made its way to the bottom of the array.

For instance:

    uint8_t window[10];

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

    void loop() {
        if (Serial.available()) {
            // Slide the window
            for (uint8_t i = 0; i < 9; i++) {
                window[i] = window[i + 1];
            }
            // Add the new character
            window[9] = Serial.read();

            // Output the current window data for debugging
            dumpWin();

            // Check the framing characters
            if ((window[0] == 0xAA) && (window[9] == 0xAC)) {
                // Calculate the checksum
                uint8_t cs = 0;
                for (uint8_t i = 2; i < 8; i++) {
                    cs += window[i];
                }
                // If the checksum matches...
                if (cs == window[8]) {
                    // ...we have a valid packet!
                }
            }
        }
    }

    void dumpWin() {
        for (int i = 0; i < 10; i++) {
            Serial.print(window[i], HEX);
            Serial.print(" ");
        }
        Serial.println();
    }
Getting the data out of the valid packet is now a case of combining bytes into 16-bit integers then dividing them into floats.  For instance the PM2.5 would be:

    uint16_t pm25i = (window[3] << 8) | window[2];
    float pm25 = (float)pm25i / 10.0;

The PM10 would be the same but with window[5] and window[4] of course.

----

Since you can't really use the hardware UART for both communication with your sensor and communication with the PC you may want to investigate the use of [SoftwareSerial](https://www.arduino.cc/en/Reference/SoftwareSerial) instead of the hardware UART pins for communicating with the sensor.


message:
Windows driver installer not detecting arduino

I'm trying to program my Arduino Uno with my Windows PC. I followed all the instructions on the site. I mistakenly downloaded the .zip file and didn't unzip it, before plugging in my Arduino Uno. So naturally, no message came up. I then followed the correct procedure, but Windows driver installer does not detect the Arduino Uno. What can I do to fix this?

body:
Per my comment above, the drivers are not installed when using the Arduino editor from an extracted zip file. If you are feeling adventurous, they are located in the /drivers folder and you can install them manually, there are plenty of instructions elsewhere on the internet on how to do that.

My recommendation would be to just download and run the installer version of Arduino, as that will take care of registering the drivers for you. The installer can be found on the [download page][1] indicated with the text "Windows Installer".

  [1]: https://www.arduino.cc/en/Main/Software


message:
What is the best serial protocol for bidirectional communication with NodeMCU?

Except hardware UART. Main requirements are reliability and simplicity of use. Speed isn't as important.

Details:

I have an Arduino Pro Mini (ATmega328P 5V) controlled via UART.

I wish to connect an ESP8266 with stripped-down NodeMCU to offer a web interface for the same functionalities, sending <=122 character strings to Arduino and possibly getting a short response.

I do not want to use Arduino for processing the interface (too little memory) or use the ESP only (need a stable clock and multiple analog inputs).

My research shows that:

 - ESP8266 has obvious timing issues, having been designed for a different purpose.
 - [Controlling the ESP8266 from Arduino via hardware serial][1] works fine, but I need it the other way around, too. Also, NodeMCU is rather chatty and I don't know how to suppress it, and I'd rather keep the hardware serial ports for programming.
 - The same via [SoftwareSerial][2] is [unreliable][3]
 - Personal experience shows OneWire works poorly on ESP8266 (though it may have been fixed)

I have no experience with I2C and SPI beyond polling a slave, and don't know about reliability on ESP8266.

The Arduino already works as an I2C master.

I'm assuming I2C is the way to go, but wanted to ask for opinions first.

**[EDIT]**
Seems I have once again neglected to set up the proper context. The reason I'm asking is that ESP8266 *can't do very precise timing*, leading to communication problems. Hardware UART to hardware UART is shown to be reliable. For most other protocols, at least one side does bit-banging. I have not done or found extensive reliability tests for those options, and hope instead that the community can offer some insights. Can you?

  [1]: https://github.com/IRNAS/SimpleArduinoESP-Lua
  [2]: https://arduino.stackexchange.com/q/17184
  [3]: https://primalcortex.wordpress.com/2014/12/30/esp8266-nodemcu-and-lua-language-and-some-arduino-issues/

body:
While possibly not "the best", I have found I2C to be sufficient for [my needs][1].

Simple to use, if a bit different conceptually (master-slave).

My tests have shown it to be reliable thus far, zero errors over 20 minutes (sending & receiving 20 bytes each time), as long as there were sufficient pauses between calls.

I am going to make the Arduino switch its i2c master/slave role based on the state of other pins. Master most of the time (to use a DS1307 RTC, etc), switching to slave whenever NodeMCU (which can only work as master) has something to say. Thanks to Zeph for the idea.

  [1]: https://github.com/mamert/iot-a


body:
So you are asking how to use an Arduino Pro Mini as a smart peripheral connected to a NodeMCU master, without making use of the hardware serial port on the latter.

In general, this is either going to operate slowly enough that you can guarantee reception, or you will need to use some kind of flow control or acknowledgement.

One question is whether the APM can always receive at any time, or whether it has to do things which would cause it to not respond for some while and possibly lose data.

Hardware I2c or SPI, with a software flow control protocol using additional pins, are probably your best bets if you cannot use async serial.  For example the APM sets OK2SEND high when it's ready to receive (this is an APM output pin connected to a NodeMCU input pin).  When NodeMCU detects this high, it writes to I2C and then sets HAVESENT high.  When the APM detects & processes incoming data as I2C slave, it sets OK2SEND low.  NodeMCU sees OK2SEND low (ack'ing the byte) and sets HAVESENT low.  APM detects HAVESENT low which completes the handshake.  When APM is ready for another byte, it sets OK2SEND high again.  etc.  Variants could send more than one byte per handshake, if performance needs that; APM asserting OK2SEND would be contracting to handle that number of bytes.

If you can guarantee that the APM will respond quickly enough to interrupts, you could use an interrupt driven I2C slave system on it, and simplify the above.  The APM could be like a dedicated I2C peripheral, albeit a slow one.


message:
Morse code translator Loop the same sentence

I'm a newbie so forgive my ignorance.

I'am using the Morse code translator to light up the LED which is fine but after it has processed the sentence it turns off. How can I get it to loop the sentence continuously.

Thanks

body:
I guess this is the [sketch][1] you are using. It reads characters from Serial and translates them to Morse code.

What you need to do to make it loop a sentence is, 1) read a sentence into a buffer, 2) loop though the buffer and translate to Morse code.

  [1]: http://www.instructables.com/id/Morse-Code-Translator/step5/Program/


message:
Share battery pack with Arduino and DC motors

I used 6 rechargable AA batteries (total 7.2V) to power my Arduino (UNO R3) Car's two DC Motors (using L293D IC as motor driver). I used separate 9V battery to power arduino itself. But I want to share same 6 battery pack to power my arduino via barrel jack. Please suggest me how can I do this? What precautions Should I take? Like decoupling capacitors or any other?

body:
You may have read that the UNO can accept 7-12 volts as input power. Your AA battery pack (7.2 volts) is very near the low limit of 7 volts. After just a little discharge of the battery (and also voltage drop from motors running), your batteries are likely to deliver less than 7 volts.

As your AA battery goes below 7 volts, then the 5 volts (regulated) will also begin to go lower.  A reasonable scenario would be if AA battery was 6.5 volts (1/2 volt low), then the 5 volts regulated would be about 4.5 volts. The UNO is likely to operate ok at this voltage, but as voltage goes lower operation could become a problem depending upon your program used.

Since you are experimenting with a toy car, I would say to go ahead and run both the motors and UNO from the same battery pack.  Not a lot to lose on trying.

The UNO already has decoupling capacitors in it's 5 volt regulator circuit.

Just for fun,  you could use an Analog input to measure your 5 volts and if the voltage drops to 4.5 volts, you could dis-allow motor operation and flash an LED (or other action). Just a low battery indicator.

If you decide to measure the 5 volts with an analog input,  read up on using resistor dividers and the Analog reference (A-ref). Because 5 volts dropping to 4.5 volts could effect your analog reading, depending upon what you use for Analog reference.


message:
ArduinoMEGA: 64 digital inputs cause random digitalRead values

I have 64 hall effect sensors (magnetic field sensors) ([DRV5023AJQLPG][1]) connected to an Arduino MEGA 2560. For that, I use 48 digital pins and 16 analog pins as digital input pins. The program in the Arduino continuously reads out those 64 digital input pins (in a for-loop) and sends out a serial byte, to a laptop via a usb cable, whenever one of those input pins changes between LOW and HIGH. I also use the ATmega2560’s internal pullup resistors to prevent irregular readouts of the input pins when the sensor is not giving a 0v output (i.e. when it isn’t measuring a strong enough magnetic field).

Everything is working fine when I only physically connect up to 16 of the sensors. The laptop then only receives bytes that correctly tell when a sensor measures a state-change.

However, when I start connecting more of those 64 sensors, then the laptop starts receiving irregular streams of bytes, erroneously suggesting that all the connected sensors measure changing magnetic fields (HIGH and LOW readouts).

I can think of two reasons why these irregular readouts occur:
1. Either, the ATmeag2560’s internal pullup resistors arent working as I think they should.
2. Or, the arduino board and >16 hall effect sensors combined are pulling to much current.

1. **Pullup resistors not working?**
When testing with only 16 sensors connected, it is a stable, properly working setup. When I explicitly *don’t* use the pullup resistors in the program then the setup *does* start behaving irregular, also with just 16 sensors. So the internal pullup resistors seem to be properly activated by the program.

2. **Arduino + 64 sensors draw to much current?**
Besides powering the Arduino board and sensors via the usb cable (providing 500mA), I’ve also tried external power sources that provide 1 or 2A. I’ve also powered the Arduino board via an external 5v, +1A voltage regulator, bypassing the Arduino’s onboard voltage regulator. This all doesn’t seem to make a difference in the system’s irregular behaviour. When measuring those setup’s current usage (with amperage meter) it didn’t go above **250mA**.

Calculating the combined current usage (using datasheet info), I came to this:

 - sensor operating current:    2,7 mA
 - sensor output current when in ‘active’ state:  0,25 mA
 - TOTAL current of 64 sensors (3mA*64=)  192 mA
 - Arduino MEGA current (approx)    150 mA
 - TOTAL current of 64 sensors + Arduino MEGA:  **342 mA**

So, both the calculated and measured current usage seem within the range of what can be handled by mentioned power sources.

I’m kinda stuck now. Can anyone suggest anything that might cause this problem? Or point to incorrect thinking of me? Thanks for any responses.

----------

'Schematic' (only showing first 8 sensors connected. The ArduinoMEGA is connected to a computer via a usb cable with disabled power line):

[!['schematic' (only showing first 8 sensors connected. The ArduinoMEGA is connected to a computer via a usb cable with disabled power line)][2]][2]

Top-side: the hall effect sensors and Vcc an GND rails:
[![Top: the hall effect sensors and Vcc an GND rails][3]][3]

Bottom-side: ArduinoMEGA + the 64 red sensor output lines to the input pins:
[![Bottom: ArduinoMEGA + the 64 red sensor output lines to the input pins][4]][4]

Below is the Arduino code:

<!-- language: c -->

    /*
    Arduino to Pd protocol

     Placing or removing a chess piece sends only one byte.
     There’s no other serial data being communicated.

     event:      byte value:
     placing a chess piece on a square:  0-63
     removing a chess piece from a square:         64-127

     ArduinoMEGA pin to byte value mapping:
      byte  pin
      0  6
      1  7
      2  8
      3  9
      …
      46  52
      47  53

      48  A0 (analog 0)
      49  A1
      50  A2
      …
      62  A14
      63  A15

    */

    byte prevSquares[64];  // array that holds previous readouts
    byte i;                // variable used in for-loops
    byte sensorValue;      // variable temp storing of digitalread

    void setup() {
      Serial.begin(9600);
      for (i = 0; i < 64 ; i++) {
        pinMode(i+6, INPUT_PULLUP);  // activate pullup resistor
      }
      for (i = 0; i < 64 ; i++) {
        prevSquares[i] = digitalRead(i+6);
      }
    }

    void loop() {
      for (i = 0; i < 64 ; i++) {
        sensorValue = digitalRead(i+6);
        if (sensorValue != prevSquares[i]) {
          // chess piece was placed or removed from square
          if (sensorValue == 0) {
            // chess piece was placed
            // send serial byte (0-63):
            Serial.write(i);
          }
          else {
            // chess piece was removed
            // send serial byte (64-127):
            Serial.write(i + 64);
          }
          //update prevSquares array:
          prevSquares[i] = sensorValue;
        }
      }
    }

  [1]: http://nl.farnell.com/webapp/wcs/stores/servlet/ProductDisplay?partNumber=2455494
  [2]: https://i.stack.imgur.com/E57Se.jpg
  [3]: https://i.stack.imgur.com/cuwYF.jpg
  [4]: https://i.stack.imgur.com/0eqiP.jpg

body:
After seeing your schematic, I think the general problem here is that you need to more closely read and follow the datasheet for this part. A lot of times, when you are hobbling a project together at a small scale there are a lot of things you can ignore and get away with, but as you scale up, all the rounded corners start to add up. In this case, you can get away with 16, but once you start adding too more, it becomes too much. Let's go over a few:

**Pull up resistors**

Like I mentioned in the comments, relying on the internal pull ups is probably not a good idea. In my personal experience, they are only really good for adding a quick button input for debugging purposes. I'm not sure specifically what would cause issues only after 16 sensors. It could be that collectively internal pullups are subject to a different and lower current limit, but I'm not familiar enough with the internal architecture of the ATMega2560 to do more than just speculate.

Whatever the case, the best practice here would be to use separate external pull up resistors, within the specifications of the datasheet. (See equation 1 on page 13 of the datasheet.)

**Decoupling Capacitor**

Per the datasheet, page 17:

> A 0.01-µF (minimum) ceramic capacitor rated for VCC must be placed as close to the DRV5023 device as possible.

This capacitor is referred to as C1 in the datasheet figures and is required. This type of capacitor is called a decoupling capacitor, and one of the things it does is provide a local energy storage, so that when the sensor starts pulling a little extra current, it doesn't have to wait for the regulator to respond, it has some local energy already.

Your schematic indicates a single 1uF capacitor on the output of the voltage regulator, however, there are no capacitors for the sensors. The one capacitor is only for output filtering for the regulator, and will not satisfy any decoupling needs of the sensor.

**Filtering Capacitor**

Referred to as C2 in the datasheet, this an optional capacitor to filter out high frequency noise. This isn't needed in most cases, in fact, per the datasheet, page 13:

> Most applications do no require this C2 filtering capacitor.

However, your project might not fall into "most applications" and there are a few things specifically that worry me.

 1. You have long wires that are basically acting as antennas that will capture any nearby noise.
 2. You have long power lines running parallel to your signal lines which can cause stray inductance which leads to other interesting things. (With the thickness of the plywood separating them, this might not be an issue, but it is something to be aware of).

I would definitely try the first two ideas above to begin with, and only pursue this as a last resort. The  only way to know for sure if this is something you need is to stick an oscilloscope on the line and see how noisy it is, but that is not something you probably have handy.

**Other Concerns**

I'm just a little bit worried about voltage drop. Depending on the gauge of wire used, with all the sensors connected, at the end of a strand you might have a non-negligible voltage drop.

With that many wires running together into the Mega, there might be cross talk problems.

Another common problem with scaling up is that there is a higher probability of having faulty components. This is especially with this part which per the datasheet indicates that is particularly sensitive to ESD. It could be that there is a dead sensor that has failed in such a way that it is causing problems for the other sensors. Maybe go through and test all 64 sensors, 8~16 at a time to make sure that separately they all work, and that the issue only occurs when all of them are connected.

**Other Ideas**

Many other comments on the question have suggested a multiplexer and/or multiplexing and I will just briefly echo that here. Multiplexers are typically used in situations where you don't have enough pins and you want to split a single pin to multiple other pins. While that isn't an issue here with the Mega (it appears you have enough pins to do what you are wanting to do), there are other benefits that can be derived from multiplexing this.

For example, one thing you could do is split up the board into 8 - 2 x 4 chunks and then have a multiplexer (such as a 4051 or a 74151) local to each chunk. Then you would have just 8 short wires going into the multiplexer, as opposed to having long antenna-like wires heading to the Mega. This could improve overall signal integrity.


message:
How can I dim a 10w LED?

I'm trying to dim a 10w LED via Arduino PWM.

This is the LED that I have: http://www.banggood.com/10W-Warm-Pure-White-High-Brightest-Save-Power-LED-Light-Lamp-p-88169.html

Without knowing much about this stuff, I bought this (namely because it had LED, DIM, and PWM in its name): http://www.ebay.com.au/itm/121437119430?_trksid=p2057872.m2749.l2649&ssPageName=STRK:MEBIDX:IT

I can't get the eBay dimmer to work for love or money.  When I connect it to ground directly on the battery terminal, it goes off, which means the dimmer circuit is working.  I don't even know where to start with MOSFET dimming solution, but I think that the IRFZ44N MOSFETs are the wrong ones because they won't turn on with 5v power (they need 10v or something, but those are the ones I have on hand).

I can't seem to find any good guides on how to do this after stacks of googling, and to be honest, I don't even know if those LED's can be dimmed in the first place.

What do I need to make this happen?

body:
I would suggest the CAT4101 PWM controllable constant current sink LED driver.  You might want 2 in parallel for the higher current.

They can deal with up to 1A each (theoretically) though they may get a bit hot at that current level - so it would be better to parallel them so they deal with roughly 500mA each.


body:
Well, it appears that your driver should do that for you. Since you already have the MBI6651 driver, read [its datasheet][1] and so you can get a guess on how it should work:

 1. attach a 9-35V supply to the Vin-GND terminals. I suggest to use at least 12V
 2. attach the LED to the terminals LED+ and LED- (remember the polarity!)
 3. attach a transistor to pull down the pin DIM
 4. send a PWM signal (frequency between 100Hz and 1000Hz) to the transistor and you should see the LED light up and then dim

If it works then you can try to send to DIM directly th PWM signal, but personally I don't recommend so (unless the board already have the transistor)

EDIT:

How to attach an nMOS to the DIM pin. Since the pin is internally pulled up, you don't need any pullup. So you just need an nMOS. I suggest you to use a SOT-23 logic level nMOS connected this way:

[![nMOS connection][2]][2]

no external components (as long as the nMOS supports 5V on the gate, but every discrete mosfet should). As for the nMOS, I prefer the SMD case because it is easy to solder also on perfboards (just use three pads forming an L shape and you'll see that you can easily solder it). Just choose any n-channel mosfet with a maximum threshold voltage of 2V or less and you are done

  [1]: http://www.ledlabs.ru/pdf/macroblock/mbi6651.pdf
  [2]: https://i.stack.imgur.com/Myxdh.png


message:
Pelco D Library for Arduino

Does anyone know of any Pelco D libraries available for Arduino?

I already have a PTZ joystick controlling 3 PTZ cameras, but I would like to add an Arduino 'intelligent' controller capable of sending automated sequences of Pelco D commands according to various PIR triggers etc.

body:
It looks like someone wrote a Pelco library. Check out:

https://github.com/Pixelbo/Pelco_And_Arduino


message:
RS485 bus voltage?

Does anyone know the voltage situation regarding multi-drop nodes on an RS485 bus please?

Nick Gammons RS485 article shows 2 different hardware configurations, one using 5v devices, and another using 3.3v devices, and I am fairly sure my Pelco PTZ CCTV system uses 12v.

But I have never seen anything mentioned anywhere about needing to voltage-match nodes on an RS485 bus.

So I am unsure whether the MAX driver chips isolate the RS485 bus voltage from the mcu logic levels.

Or do any lower voltage devices (3.3v or 5v) need logic-level matching to their MAX driver chips, which all need powering from the higher bus level (perhaps 12v)?

Basically, I wish to add an 'intelligent' arduino controller to an existing ptz cctv system.

body: RS-485 is a differential bus. As long as the *difference* in voltage between the two lines reaches certain thresholds the signal can be interpreted unambiguously regardless of the system supply voltages. Isolation (from ground loops) is not provided by default by the driver, but can be implemented easily enough.


body:
According to my datasheet for the LTC1480:

* –7V to 12V Common Mode Range Permits ±7V Ground Difference Between Devices on the Data Line

**Absolute maximum ratings**

* Supply Voltage (V CC ) : 7V
* Driver Input Voltage  : – 0.3V to V CC + 0.3V
* Driver Output Voltage : ±14V
* Receiver Input Voltage : ±14V
* Receiver Output Voltage : – 0.3V to V CC + 0.3V

---

> I am fairly sure my Pelco PTZ CCTV system uses 12v.

Judging by the above you would need to drop Vcc on the part involving your 12V gadget and use level shifters for the logic levels (if you used this particular chip).


body:
I suspect that the line-driver Vcc may be using a commercial standard of 5v which we are not aware off.

The RS485 Vcc VMax is only 7v anyway, so presumably the thousands of different 12v RS485 CCTV devices on the market must use line-drivers chips with a Vcc of 5v because they were historically assumed to be interfacing to TTL logic levels, and therefore still will be for compatibility.

So for integration, I think any 3.3v logic nodes will require level-matching up to a line-driver chip which has its Vcc connected to 5v for RS485 bus compatibility.

Line-driver Vcc would not normally be a problem for any home-brew systems, but could offer a potentially serious gotcha if mixing 3.3v home-brew with existing commercial 5v equipment.

I had been expecting it to be an already known problem, but apparently not, so it would seem to be something worth being aware of.


message:
arduino flexbot drone connected in a wrong way

I have an arduino [flexbot](http://www.flexbot.cc/), I was making some test and accidentally I connected the battery in the opposite way. The drone turned on the six motors when I connected the battery, but any led turned on to see if the processor was working. I disconnected the battery and connected it in the wrong way again same thing happened the six motors turned on again. Then I realize that the battery was connected in a wrong way and connected it in the right way. The LED's turned on as always, and also the blue-tooth module was working I could detect the device using the control-application. I tried to fly the drone but the motors didn't turn on, I could hear little click and I saw a little movement of a motor.

I connected my drone to my PC using the micro USB connection, also I connected the battery. I tried to turn on the drone and in this way it looks to work fine.

But when I disconnect the USB port and I tried to fly it the same thing happens, the click and the little movement. Any idea of what can I do to fix this drone?

body:
The motors turning on is expected because or the reverse diode in the mosfets driving the motor.

Looking at the schematic, it seems like the problem is on the 5v rail. If 5v isn't supplied by the USB port, it is provided by the LTC3200 (DC/DC converter)(U3 on the pcb). I think that's where the problem is, as that would explain why it only work when USB is connected.

To confirm this you'd have to measure the output voltage (pin1 (pin nearest to the ATMega) of U3, and see if it's 5 volt.

To fix it you should ideally replace this part. But it might also work without, if you simply connect the battery voltage directly to the 5v (i.e. jumper pins 1 and 5).


message:
Use command line to upload program through hex file to Teensy-LC

I want to make a standalone programmer for Teensy-LC in **windows 8.1**.

So basically I have provided the board to a client of mine and now I want to change the program loaded into the Teensy-LC board.

But the solution available right now is to send the [Teensy Loader](https://www.pjrc.com/teensy/loader.html) and send the hex file. But the teensy LC board is packed inside a device. So reset button cannot be pressed.

Also it would be better if this code can be burned in an installer format instead of the [Teensy Loader](https://www.pjrc.com/teensy/loader.html).

Is there any way to make this work?

**EDIT**

My Teensy.exe does not have the option for program or reboot
The icons are not accessible

[![Teensy.exe][1]][1]

Does that mean my interrupts are disabled or there might be something else I am doing wrong?
My program loads on pressing the reset button but I cannot press the program button inside Teensy.exe

If I turn off the Auto Mode, all icons go grey.

[![AutoMode turned off][2]][2]

  [1]: https://i.stack.imgur.com/ZYGzx.png
  [2]: https://i.stack.imgur.com/d6vri.png

body:
Paul Stoffregen (Teensy creator) has released a command line version of the Teensy Loader which can be found on [his website][1]. However, this program appears to be Linux only, so unless your client has Linux, that may be a non-starter. The [source code][2] for the program is available, so you might be able to work out the logic and port it over to whatever platform you are wanting this to work on (just make sure you comply with the source code license).

All that being said, pressing the reset button is not necessary for programming. The Teensy loader should be able to trigger a reset over USB all on its own. So unless the current program on the device disables interrupts that are necessary for the USB port to function, or it was programmed with the USB port disabled (by selecting "No USB" in the USB Type menu), physically pressing the reset button isn't necessary for programming. For more details you can see this [forum post][3].

**Loading Firmware Without Pressing the Button**

When programming via Arduino, it does a lot of things for you automatically. To replicate that manually, follow these steps:

 1. Connect the Teensy to the computer via USB.
 2. Run `teensy.exe` (found in `C:\Program Files (x86)\Arduino\hardware\tools`)
 3. Click the button on the left to select the hex file to load.
 4. Go ahead and leave Auto enabled (this actually doesn't matter).
 5. Run `teensy_reboot.exe` (also found in `C:\Program Files (x86)\Arduino\hardware\tools`, this will restart the Teensy, as if you had pressed the button, and automatically start the programming process.)

  [1]: http://www.pjrc.com/teensy/loader_cli.html
  [2]: https://github.com/PaulStoffregen/teensy_loader_cli
  [3]: https://forum.pjrc.com/threads/30503-When-do-you-need-the-teensy-reset-button


body:
Sadly the accepted answer is incomplete and requires manual steps.

The reason why your "Auto" button is greyed out is that you did not execute the second executable that is required for that: "Teensy_Reboot.exe".
You find it on your disk if you have installed TeensyDuino.

First kill Teensy.exe if it is running (Important)

Then you write path and file of your Hex file into the registry:

    HKEY_CURRENT_USER\Software\PJRC\teensy\dir
    HKEY_CURRENT_USER\Software\PJRC\teensy\file

Then you start Teensy.exe

Then you start Teensy_Reboot.exe as a hidden process.

That is the solution of your problem!

It is a shame that Paul does not document his stuff.

NOTE: If you have previously loaded a sketch into the Teensy that was compiled with "USB Type: No USB" the reboot will not work and the button on the board must be pressed manually, but Teensy_Reboot.exe is still usefull because it enables the green "Auto" button in Teensy.exe.

NOTE: Teensy_Reboot.exe has a severe bug: If the Teensy.exe is not successfull because another program still had the Teensy CDC COM port open while you started Teensy.exe, the Teensy_Reboot.exe may run eternally consuming 100% CPU under some circumstances. I reported that bug in the forum of Paul but he never answered to my posting.

______________________________

**PLAN B:**

The disadvantage of using teensy_reboot.exe is that you don't know if the programming was successful or not because sadly teensy_reboot does not return any usefull exit code.

So the better option (which requires more code) is to instruct Teensy.exe directly from your program. Therefore you need a TCP connection to localhost.

You find more details in this thread:
https://forum.pjrc.com/threads/38684-How-does-Teensy-Reboot-exe-communicate?p=120443
where Paul (once again) did not answer my question.

___________________________

**PLAN C:**

You can even replace Teensy.exe with your own code.
Have a look at this project: https://github.com/Koromix/ty
Sadly this code depends on the huge QT library. Apart from that it may not work with future versions of Teensies.