message:
Arduino Nano (clone) not recognized

Asking here cause I ran out of options in searching. My Arduino Nano clone isn't recognized by my computer anymore. It was, until I plugged into a Windows machine, that did not recognize it... and now even my Linux Mint distro doesn't detect the Nano at all. Here's the thing, though: the green power LED still lights up and, if I connect my DC motor to it like I used to before, the LED turns off and the motor is powered only a little bit, with less speed than if it were powered by a 1.5V battery.

My voltimeter reads a 2.18V out of the 5V pin.

Here's all I did: uploaded a sketch to power a 5v motor, it worked, unplugged the Arduino, took it home to my Windows machine on the casing I got it from my school, plugged it there, then it didn't detect anything. Go back to the lab today, plug it in, doesn't detect it there either.

From there, I've replaced USB cables, tried different USB ports, checked with lsusb and dmesg, tried finding it using the FTDI tool (the chip underneath is FTDI), then tried powering it from a phone charger, but the voltage readings at the 5v pin still are around 2.18V with that. Nothing seems to give this little thing an output greater than 2.18V.
The only thing I haven't tested is powering it through the VIN pin.

I came across other questions of similar problems but nothing that seems quite like mine... since they all either are able to detect the device but it is displayed as an unknown device or can't recognize the device at all but their power LED does not turn on.

Any ideas on what is going on?

body:
Apart from 5V pin, the rest sounds like your FTDI clone chip might be bricked. Check your device VID (under Device Manager -> Device Properties -> Details tab -> under Property select Hardware Ids). If VID and/or PID is 0000 than it is.

It is possible restore the original VID/PID (thus recover the Arduino). Google for "Fix bricked FTDI", there are many instructions like this: http://internetofhomethings.com/homethings/?p=987

Most of these cheap Arduino Nano clones have also fake FTDI IC and at some point FTDI (the vendor) released new driver which bricks such clones by setting VID/PID of the chip to 0. This effectively makes the IC undetectable / incompatible with original FTDI drivers. That is why it is not recognized on a PC where it was working earlier.

http://hackaday.com/2016/02/01/ftdi-drivers-break-fake-chips-again/

After recovery, make sure to use older FTDI driver.


sender: user

sender: assistant

body: It sounds like a blown protection diode MBR0520 in between USB and +5V of the nano.


body:
What was your schema? did you try to control 5V motor from arduino directly.

Now assuming that
```
$ lsusb
```
doesn't show something like:
```
Bus 002 Device 005: ID 1a86:7523 QinHeng Electronics HL-340 USB-Serial adapter
```

 It is generaly a bad idea to control any mechanical (magnetic) device without using transistor and maybe a diode to protect against current in an opposite direction

standard DC motors can generate quite a nice voltage if turned mechanically (during transport) or even current increase if motor is blocked when powered.

TO me it sounds like you have burned your chip. USB on most computers has got an over-current protection resulting in lover voltage if something you connect has very low resistance.
2.8volt is more then enough to lit-up green LED on a damage MCU, but probably not to power the FTDI chip wired for 5V


message:
I just bought a TFT screen is it still possible to use the serial port 1 and 0?

so I have a question regarding the TFT touch screen... I would like to use the serial ports 1 and 0 (on my UNO) to transmit data to my mega... however it take up those ports. on the back of it, it shows what each prong should occupy. However, nothing is noted to be required for those ports. is it possible to clip those prongs off and still have the screen be usable or are they important to keep?

body:
Yes, you can use those pins. Just because there are physical pins on the shield doesn't mean they are actually used. If nothing is written next to them then yes you can use them.

Be warned though that those pins are used for communication with your PC - and that includes uploading sketches - so you may experience problems doing things like that while your Mega is connected to those pins.


message:
LED Pin 13 Input or Output?

It is not clear to me whether Pin 13, corresponding to the LED, should be driven by an external voltage or not.

From the [documentation][1],

> LED: 13. There is a built-in LED driven by digital pin 13. When the
> pin is HIGH value, the LED is on, when the pin is LOW, it's off.

However, in the "Blink" example code I am running, the Pin 13 appears to be driven by the ATmega328:

    void setup() {
      // initialize digital pin 13 as an output.
      pinMode(13, OUTPUT);
    }

    // the loop function runs over and over again forever
    void loop() {
      digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)
      delay(100);              // wait for a second
      digitalWrite(13, LOW);    // turn the LED off by making the voltage LOW
      delay(2000);              // wait for a second
    }

If I now attach a voltage source to Pin 13, will there be contention issues?

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

body:
Like any other I/O pin, there should be no problem driving this pin (and
thus the builtin LED) from an external source, as long as you make sure
it is in `INPUT` mode. If the pin is set to `OUTPUT` you will likely
damage the Arduino.

**Warning**: If you have the Blink example already loaded in the
Arduino, the pin is in output mode. Be sure to upload another program,
that does not set pin 13 to output, **before** connecting anything that
could drive pin 13.


message:
Which (Official) Arduino IDE to use?

I have bought an Arduino UNO that turned out to be the Italian version (Arduino SRL) not the American one (Arduino LLC).

Now when I go to arduino.org and arduino.cc, they both have different versions of the IDE!

So, which one should I use (if they are even different) ?

body:
You can use both IDEs no matter of the origin of the UNO even fake ones runs with the IDEs.
The arduino.org IDE is just a fork of the arduino.cc.
But arduino.org has many Board which are only run with the .org IDE.


message:
Arduino IDE/Visual Micro - Undefined reference to constructor

I am using Visual Studio Community 2015 with the newest version of the Visual Micro Arduino Plugin, however I also tried compiling my code in the Arduino IDE.
When compiling my code, there is the following error:

    Compiling debug version of 'Autonomous_Car' for 'Arduino/Genuino Uno'
    Autonomous_Car.cpp.o:In function `setup
    Autonomous_Car.ino:undefined reference to `List<UpdateAble>  List()
    Autonomous_Car.ino:undefined reference to `List<UpdateAble>  ~List()
    collect2.exe*:error: ld returned 1 exit status
    Error creating .elf

**Some info**

- Adding `#include "List.cpp"` fixes the error, however this does not seem like valid C++.
- The files do not lay in any sub-directory
- In my Project Explorer both `List.h` and `List.cpp` are added to the project.
- I also removed both files from the project, deleted them and added them again
- I deleted the ´%AppData%\Local\Arduino15´ directory
- I am fairly new to C++ and Arduino, there might be something obvious, what I just can't find

**Autonomous_Car.ino**

    #include "List.h"
    #include "UpdateAble.h"

    void setup()
    {
        List<UpdateAble>* myList = new List<UpdateAble>();
        myList->GetCount();

        delete myList;
    }

**List.h**

    #ifndef _LIST_h
    #define _LIST_h

    #if defined(ARDUINO) && ARDUINO >= 100
    #include "arduino.h"
    #else
    #include "WProgram.h"
    #endif

    template <class T>
    class List {
    public:
     void Add(T &item);
     bool Contains(T &item);
     bool Remove(T &item);
     void Clear();
     int IndexOf(T &item);
     T* GetItem(int index);

     inline int GetCount() { return count; };
     inline int GetCapacity() { return capacity; };

     List();
     ~List();
    private:
     void EnsureCapacity(int capacity);

     int count;
     int capacity;
     T** items;
    };

    #endif

**List.cpp**

    #include "List.h"

    // Constructor
    template <class T>
    List<T>::List() {
     List::capacity = 4;
     List::count = 0;

     List::items = new T*[List::capacity];
    }

    // Cleanup
    template <class T>
    List<T>::~List() {
     delete[] List::items;
    }

    template <class T>
    void List<T>::EnsureCapacity(int capacity) {
     if (List::capacity < capacity) {
      // Kapazität verdoppeln
      List::capacity = List::capacity * 2;

      // Speicher für neues array reservieren
      T** newArray = new T*[List::capacity];

      // Array kopieren
      for (unsigned int i = 0; i < List::count; i++) {
       newArray[i] = List::items[i];
      }

      // Speicher von alten array freigeben und neues array zuweisen
      delete[] List::items;
      List::items = newArray;
     }
    }

    // Adds a new item to the list
    template <class T>
    void List<T>::Add(T &item) {
     List::EnsureCapacity(count + 1);

     List::items[count] = item;
     List::count++;
    }

    // Gets whether the list contains an item or not
    template <class T>
    bool List<T>::Contains(T &item) {
     return List::IndexOf(item) != -1;
    }

    template <class T>
    bool List<T>::Remove(T &item) {
     int index = List::IndexOf(item);

     // If the item does not exist, we cannot remove it
     if (index == -1) return false;

     // Move every item behind our item one further
     for (int i = index + 1; i < List::count; i++) {
      List::items[i - 1] = List::items[i];
     }

     List::count--;
    }

    // Release the heap
    template <class T>
    void List<T>::Clear() {
     for (int i = 0; i < List::count; i++) {
      delete List::items[i];
     }

     delete[] List::items;
    }

    // Gets an index of an item, -1 if not found
    template <class T>
    int List<T>::IndexOf(T &item) {
     for (int i = 0; i < List::count; i++) {
      if (List::items[i] == item) {
       return i;
      }
     }

     return -1;
    }

    template <class T>
    T* List<T>::GetItem(int index) {
     if (index < List::count && index >= 0) {
      return List::items[index];
     }

     return 0;
    }

I'd be very glad, if we can find the solution.

body:
You're using a *template class*. A *template class* is a special corner case that breaks the "code in .cpp and definitions in .h files" rule.

Because it's a template it can't be pre-compiled - it needs to be specially compiled each time it is used, so that it can get the right values compiled in to the template place-holders, which are provided by the CU that has the template class included with it.

Because of that it is one of the rare cases where the code has to be in the header file.

For a full example you can take a look at [my Average library](https://github.com/MajenkoLibraries/Average/blob/master/Average.h) which is a fully templated class.


message:
Two-wire communication (I2C) between Arduino Micros

I am attempting to communicate data via I2C between two Arduino Micros, but can't seem to get the "slave" device to detect a Wire.onRecieve() event.

Per the specification on this site [http://www.takktile.com/tutorial:arduino] (and verified against Arduino's own site) I am using pins 2 and 3 as SDA and SCL for I2C. I have pin2 of Arduino 1 (ARD1) connected to pin2 of Arduino 2 (ARD2), and pin3 of ARD1 connected to pin3 of ARD2.

ARD2 acts as slave, ARD1 acts as master.

I am reading in a text file from SD on ARD1. On ARD1, you then press a button to initiate transfer. ARD1 lights a red LED to indicate the transfer is underway. When I initiate the transfer, it remains solid (indicating it never gets past endTransmission to where the LED is supposed to be turned off).

Here is the code for ARD1:

    // include the SD library:
    #include <Wire.h>
    #include <SPI.h>
    #include <SD.h>
    // personal debugging routines
    #include "debug.h"
    /*
     *
     *  THIS IS THE SLAVE RECEIVING MODULE
     *  IT WILL WRITE DATA TO AN SD CARD
     */

    // GLOBAL VARIABLES
    const int chipSelect = 10; // 10 because this is an Adafruit SD module.
    File data;
    int buttonA; // the button
    char c;

    void sd_readstart() {
      unsigned char i = 0;
      // Open serial communications and wait for port to open:
      Serial.print("\nInitializing SD card...");
      if (!SD.begin(10)) {
        Serial.println("Card initialization failed.");
        errorblink();
        return;
      }
      Serial.println("Initialization successful.");

    }

    void setup() {
      pinMode(11, OUTPUT); // setup for blink
      pinMode(12, OUTPUT); // setup for blink
      pinMode(10, INPUT); // button
      Wire.begin(8); // intitalize this device as a slave on addr .
      Wire.onReceive(receiveEvent); // when data is recieved, run recieveEvent(int).
      Serial.begin(9600);
      sd_readstart();
    }

    void loop(void) {
      // short blink to confirm this is going down correctly
      buttonA = digitalRead(10);
      if (buttonA == HIGH) {
        // button open
        blink(100,1000);
      } else {
        // button pressed

      }

    }

    void receiveEvent(int howMany) {
      data = SD.open("testoutput.txt");
      digitalWrite(12,HIGH);
      while (Wire.available() > 0) { // loop through all but the last
        c = Wire.read(); // receive byte as a character
        Serial.print(c);         // print the character
        data.print(c);
      }
      data.close();
      digitalWrite(12,LOW);
    }

Here is the code for ARD2:

    // include the SD library:
    #include <Wire.h>
    #include <SPI.h>
    #include <SD.h>
    // Software Serial library:
    #include <SoftwareSerial.h>
    // personal debugging routines
    #include "debug.h"
    /*
     *
     *  THIS IS THE SLAVE RECEIVING MODULE
     *  IT WILL WRITE DATA TO AN SD CARD
     */

    // GLOBAL VARIABLES
    const int chipSelect = 10; // 10 because this is an Adafruit SD module.
    File data;
    int buttonA; // the button
    char c;

    void sd_readstart() {
      unsigned char i = 0;
      // Open serial communications and wait for port to open:
      Serial.print("\nInitializing SD card...");
      if (!SD.begin(10)) {
        Serial.println("Card initialization failed.");
        errorblink();
        return;
      }
      Serial.println("Initialization successful.");

    }

    void setup() {
      pinMode(11, OUTPUT); // setup for blink
      pinMode(12, OUTPUT); // setup for blink
      pinMode(10, INPUT); // button
      Wire.begin(8); // intitalize this device as a slave on addr 8.
      Wire.onReceive(receiveEvent); // when data is recieved, run recieveEvent(int).
      Serial.begin(9600);
      sd_readstart();
    }

    void loop(void) {
      // short blink to confirm this is going down correctly
      buttonA = digitalRead(10);
      if (buttonA == HIGH) {
        // button open
        blink(100,1000);
      } else {
        // button pressed

      }

    }

    void receiveEvent(int howMany) {
      data = SD.open("testoutput.txt");
      digitalWrite(12,HIGH);
      while (Wire.available() > 0) { // loop through all but the last
        c = Wire.read(); // receive byte as a character
        Serial.print(c);         // print the character
        data.print(c);
      }
      data.close();
      digitalWrite(12,LOW);
    }

For completeness, here is my debug.h:

    void blink(int h, int l) {
     digitalWrite(11, HIGH);
     delay(h);
     digitalWrite(11, LOW);
     delay(l);
    }

    void errorblink() {
      unsigned char counter = 0;
      while (counter < 4 ) {
        digitalWrite(12, HIGH);
        delay(50);
        digitalWrite(12, LOW);
        delay(50);
        digitalWrite(12, HIGH);
        delay(50);
        digitalWrite(12, LOW);
        delay(50);
        digitalWrite(12, HIGH);
        delay(50);
        digitalWrite(12, LOW);
        delay(1000);
        counter++;
      }
    }

    void goodblink() {
      unsigned char counter = 0;
      while (counter < 4 ) {
        digitalWrite(11, HIGH);
        delay(50);
        digitalWrite(11, LOW);
        delay(50);
        digitalWrite(11, HIGH);
        delay(50);
        digitalWrite(11, LOW);
        delay(50);
        digitalWrite(11, HIGH);
        delay(50);
        digitalWrite(11, LOW);
        delay(1000);
        counter++;
      }
    }

I did attempt to do the minimum working example of Wire from the examples in the Arduino IDE. That didn't work either, which is to say that I didn't see any text in the serial monitor on ARD2 when I uploaded the slave reciever sketch that comes with the IDE (with send master running on ARD1) which makes me wonder if I'm doing something horribly, fundamentally wrong in hardware rather than just in software.

I hope it's not inappropriate to post up the more advanced example in order to get feedback on the larger picture of what I'm trying to accomplish -- moving a text file from the SD card on one arduino to the SD card attached to another.

body:
I2c is an open collector setup. The pins go low, or open/input/hi-z, and let the line/bus free. Without a pull up on each line to VCC, the line never goes high. Pull up resistors are required. 4.7k typical.

Op's crudely drawn diagram is the correct way for a 5V I2C bus:

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

Keep in mind both arduinos/power supplies must have their grounds connected, as a reference ground voltage.

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


body:
The I2C protocol and hardware don't care how much data is transferred.

The time you have for the transfer, or the transfer rate is much more important; you might get bored waiting, but it won't.

You might get over 100k bits/second transfer (allowing time to write to the SD card) if that's enough then it's fine.

The significantly faster option, using Arduino's, is SPI to SPI, and you are likely using SPI for the SD card, so I2C is a reasonable alternative, and makes your hardware and software simpler.

The only faster interface on the Arduino, excluding SPI, is the UART. That might be a bit tricky to use while you are developing, testing and debugging your software.


message:
Using the Logging library, sometimes doesn't exit setup()

This has been a hard problem to diagnose, so I hope I'm giving enough info here.  I'm trying to write a program for the Arduino (a lighting controller) using a bit of OO.  There are several classes in my library, and some extend others.  I'm a long-time programmer (mostly Java) but this is my first big Arduino project.

I'm using [the Logging library][1] at various points in the main program, as well as the objects, and that's where it get complicated.  Depending on where I put calls to the logging library, or even Serial.print(), it either all works, or what gets sent to the serial port is a bit garbled, and the board never enters loop() (I'm not sure if that means that it's crashing in setup() or not).  This library hasn't been touched in 4 years and there are pending merge requests, so I don't think I'll get answers from the developer.

I have a sneaking suspicion that the root of the problem is that Logging.h ends with instantiating the logger ("Logging Log = Logging();") so multiple instances of the logger may be created and the serial port is being reset several times, possibly at different port speeds.  I thought it was bad form to initialize object, or even have any running code, in a .h file.  Is this a possibility, and do I have any options to fix this?

Are there any good alternatives for printing outputs at different debug levels?

I would hate to have to pass the logger instance in as a parameter to my classes, or have to write setLogger() methods for all my classes.

Thanks.

  [1]: http://playground.arduino.cc/Code/Logging

body:
> Logging.h ends with instantiating the logger ("Logging Log = Logging();") so multiple instances of the logger may be created and the serial port is being reset several times, possibly at different port speeds.

I think you are mistaken, or have done something wrong with the library files.  `Logging.cpp` ends with the instantiation, not `Logging.h`.  `Logging.h` only has an `extern` reference to the instantiated object.

So some guesswork:

If you try and do anything with logging or serial access (or indeed anything more than just setting a few variables) within the constructors of your objects, and you instantiate those in the global scope, you won't have full access to the serial port - if any access at all.  You can only use the serial port once `Serial.begin(...)` has been executed in setup, and global constructors are executed *before* `setup()` is run.

It is for this precise reason that 99% of Arduino libraries have a `.begin()` method which does all the work a constructor would normally do. The constructor is only used (if at all) for storing some default settings (pin numbers, etc) that are used later on. That way you have full control over what gets executed and when.


body:
The constructor (called in a rather weird way) doesn't do anything, so I don't think that is the issue.

**Logging.h**:

        /*!
      * default Constructor
      */
        Logging(){} ;

**Logging.cpp**:

     Logging Log = Logging();

---

You should be calling `Log.init(whatever)` **once** in your code (as in the example). Are you doing that?

Please post a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve).

Without any posted code, we can only guess at what you are doing.

---

>  I thought it was bad form to initialize object, or even have any running code, in a .h file. Is this a possibility, and do I have any options to fix this?

That is not done in the library you linked to.


message:
80 Apple Homebuttons and a steppermotor

I am graduating in a month and I want to make an installation with 80 apple homebuttons which are connected to a stepper motor. The idea is that each button that is pressed, turns the stepper motor the same amount of degrees each time. Also, each button is connected to an LED which must stay on, even if the button is pressed again and the motor too must not react. Once all 80 buttons have been pressed, the installation should switch off after a minute or so.

I am not sure how to connect 80 inputs to the arduino. Does anyone have any idea?

body: I have no idea what an apple homebutton is, but the easiest way to add more GPIO pins is to use something like an MCP23017; it connects over I2C and gives you 16 GPIO pins. Use five of them and you have your solution.


body:
If you follow JayEye's approach (ie, use five MCP23017 units to connect 80 switches, and five more to connect 80 LEDs) the wiring and the software should be fairly simple.  But dealing with all the wires will be a problem unless you use a custom printed circuit board to mount all the switches, LEDs, wiring traces, and connectors.  If you have experience with and hands-on access to printed circuit manufacturing equipment, and fast access to the parts you need, that approach should be ok.

A worthwhile alternative is to scale the project back slightly – say to 64 switches and LEDs instead of 80 – and use two Arduino Mega2650's, one to connect to switches, and another to connect to LEDs.  Or you could use one Mega to handle the first 32 switch-and-LED pairs, and another, identically-wired, to handle the other 32.  The two Mega's could communicate by I²C or via RxD-TxD connections (Arduino Mega's have four hardware serials ports, IIRC).  If you plan to wire stuff up with jumpers and breadboards, this probably would be among the simpler, faster, and cheaper approaches.  The modularity of building two identical units (except that only one of them will have the stepper driver attached) improves reliability and ease of debugging.  You could also use four or five identically-wired Uno or Nano boards.

Note, however, that you are likely to have serious reliability problems if you connect up 80 switches and 80 LEDs via breadboards and jumper wires.   As Chris Stratton suggested, start small.  For example, wire up a dozen or two dozen switches and LEDs on a single Mega.  This will let you see how much of a mess the wiring will be, and whether the original scale is practical.  It will also allow tracking down software bugs on a hardware system that is small enough to allow some confidence that the hardware is working.  If you build an 80-unit system before debugging the software, you are likely to run into problems where hours or days go by while you try to sort out whether the problem is due to a software error, a wiring error, or some combination of both.

Note that use of [Charlieplexed](https://en.wikipedia.org/wiki/Charlieplexing) connections or matrix connections would let you get by with about 10-20% as many IO lines as the direct-connect methods listed above.  However, unless you have used Charlieplexed or multiplexed LED displays and matrix-connected switches successfully in previous projects, and have experience with building and driving circuit boards, the likelihood of getting the project done on time is rather lower than for the other methods mentioned above.


body:
**Why Apple home buttons?**

Finding out how to get input/output from these things and wiring them in a reliable way may cost you some time (and quite some money).
I don't see how they would have other features than regular buttons.

(You won't get the fingerprint-scanning thing working, I'm afraid.)

**Start small**

It'll be quite a project to do in one month (especially when you're new to Arduino).

If you start out with 80 buttons and stuff, it will probably end up in a mess, and you'll be unable to show your prof anything.

You should however, order the 80 push-buttons (I shouldn't order the Apple ones, if you don't already know how they work) and LED's. Since they might take some shipping time.

Get yourself a [solder-less breadboard][1], maybe [3 buttons][2], some [LED's][3] and a stepper (if you don't have one already).
Depending on your type of stepper, you may need something to drive it.

*Start project*

Use two buttons or so, if you press one, it would go clockwise, if you press the other, it would go counter clockwise.

Make sure you pull up or down the button inputs, to be sure that they are not floating when the button is not pressed.

Find a way to drive the steppers, you'll most likely use Arduino libraries for this.

Code will be something like:

    if(digitalRead(button1))
      stepper.step(steps++);
    if(digitalRead(button2))
      stepper.step(steps--);

**Scaling up - alternative**

You could use the 80 buttons for each angle of the stepper.
But you could also use a keypad and LCD (or 3x 7segment display) to display a value typed in, and then send it to the motor.

**Scaling up**

In the case of the 80 buttons.
You could use 10 outputs in combination with 8 inputs.

With each output, you can energize a row of buttons, and with each input you read the columns. This way you only need 18 pins to read all keys.

I'm not sure if you want to control all LED's at the same time, or individually.

Or use shift registers or I/O expanders (JayEye).

  [1]: https://www.sparkfun.com/products/112
  [2]: http://www.amazon.com/6x6x7mm-Through-Hole-Tactile-Button-Switch/dp/B01481LNPW
  [3]: http://www.martoparts.nl/100-leds-3mm


message:
IF, ELSE IF functions not working with analogRead

not sure what is going wrong in the code below, but it's a simplified code of a larger piece I'm trying to debug. I notice that the code seems to skip to the else statement even though the if statement is valid.
Potential is set to analogRead(A0)

    while (potential < 1023) {
    Serial.println(analogRead(A0));
    if (potential < 1023) {
      if (potential > 200) {
        Serial.println("cool");
      } else {
        Serial.println("low");
        lcd.print("hello");
        delay(1000);
      }
    }

Results in serial monitor show

    235
    low
    324
    low

I've also tried if (potential < 1023 && potential > 200) and if ((potential < 1023) && (potential >200)) to no avail.

Can anyone help, let me know what's going wrong or suggest a fix to this?

body:
I'm not sure what you're trying to achieve with that `while`.
But this will result in none of your other code being executed until potential is above 1022, which sound rather weird. (Unless it's for some kind of safety mechanism).

The problem is that you do send the new value over serial.
But you do not assign that new value to the variable 'potential'.

Basically, you see something completely different as what is actually happening.
You should do `Serial.println(potential);` to be sure that you print the value of 'potential'.

And you should assign the `analogRead(A0);` to your variable `potential`.

I've also taken away the `while` since I think it would be misplaced. And I worked around it, so it doesn't block your complete sketch.

    void loop() {
      potential = analogRead(A0));
      Serial.println(potential);

      if (potential < 1023) {
        if (potential > 200) {
          Serial.println("cool");
        } else {
          Serial.println("low");
          lcd.print("hello");
          delay(1000);
        }
      }else{
        //Code that won't run if potential < 1023
      }

      //Other code that can run "simultaniously".
    }


body:
If in while loop, analogRead needs to be reassigned so it is constantly read.

    int potential = analogRead(A0);

    void setup() {
      while (potential < 1023) {
        potential = analogRead(A0);
        ...
        }
    }

Thanks guys for the help!


message:
MIDI controlled analog RGB LED strip (code problem)

I have a an Arduino Uno doing PWM on an RGB analog LED strip ala the Adafruit guide: https://learn.adafruit.com/rgb-led-strips?view=all. I've written a sketch that accepts MIDI data over USB and uses it to control the LEDs.

    #include <MIDI.h>
    #include <midi_Defs.h>
    #include <midi_Message.h>
    #include <midi_Namespace.h>
    #include <midi_Settings.h>

    #include <MIDI.h>

    MIDI_CREATE_DEFAULT_INSTANCE();

    #define REDPIN 5
    #define GREENPIN 6
    #define BLUEPIN 3

    byte commandByte;
    byte noteByte;
    byte velocityByte;

    byte noteOn = 144;
    byte noteOff = 128;

    int colorGroup;
    int pColor;
    int sColor;

    void setup()
    {
        pinMode(REDPIN, OUTPUT);
        pinMode(GREENPIN, OUTPUT);
        pinMode(BLUEPIN, OUTPUT);
        MIDI.begin(1);
        Serial.begin(115200);
    }

    void checkMIDI(){
      do{
        if (Serial.available()){
          commandByte = Serial.read();//read first byte
          noteByte = Serial.read();//read next byte
          velocityByte = Serial.read();//read final byte
          }
        }
      while (Serial.available() > 2);//when at least three bytes available
    }

    void updateLights(){
      colorGroup = noteByte/42;
      pColor = noteByteA*127/41;
      sColor = 127 - pColor;
      pColor = pColor*velocityByte/127;
      sColor = sColor*velocityByte/127;
      if (commandByte == noteOn && velocityByte > 0){
        if (colorGroup == 1){
          analogWrite(REDPIN, pColor);
          analogWrite(GREENPIN, sColor);
          analogWrite(BLUEPIN, 0);
        }
        else if(colorGroup == 1){
          analogWrite(GREENPIN, pColor);
          analogWrite(BLUEPIN, sColor);
          analogWrite(REDPIN, 0);
        }
        else{
          analogWrite(BLUEPIN, pColor);
          analogWrite(REDPIN, sColor);
          analogWrite(GREENPIN, 0);
        }
      }
      else if(commandByte == noteOff || velocityByte == 0){
        analogWrite(REDPIN, 0);
        analogWrite(GREENPIN, 0);
        analogWrite(BLUEPIN, 0);
      }
    }

    void loop()
    {
        checkMIDI();
        updateLights();
    }

Currently this code will turn the lights on and off in accordance with noteOn and noteOff messages. However, the color doesn't seem responsive to the note value and the brightness doesn't seem responsive to the velocity value. I suspect that the problem has to do with my arithmetic combined with the data type (maybe a problem with the order of operations), but I haven't been successful in debugging this.

The idea behind the RGB control is that I take the possible note values (0–127) and map it onto three different combinations of colors: R+G, G+B, and B+R. That's three groups of 42 values: 0-41, 42-84, and 85-127. Then I rescale the 42 values onto 0-127 for the intensity values of the LEDs. Finally I scale the intensity of all the colors by the velocity value over its possible max value.

body:
I suggest that you write separate test programs for MIDI input and LED control, before trying to combine them together.  That is, write a sketch to report back on Serial what MIDI data was read, and a sketch to cycle the LEDs through obvious patterns.

For example, if you read 10,20,30 as the three MIDI bytes, output "Got 10,20,30" (or similar).  If that appears to be working, then add your arithmetic and output the results of `colorGroup, pColor`, and `sColor` calculations.

Note, the comment after `do{ ...} while (Serial.available() > 2);` says `//when at least three bytes available`, which does not correctly represent what that `do` loop does.  When one or more bytes are available, that loop immediately reads three bytes (getting a value of -1 for any not-available byte).  To do the read only if three bytes are available, get rid of the `do{ ...} while` construct, and instead say `if (Serial.available() > 2) { <read 3 bytes> }`.

Note, use parentheses in expressions like `pColor*velocityByte/127`.  IIRC the C spec allows evaluation of that as either `(pColor*velocityByte)/127` or as `pColor*(velocityByte/127)`.  Since `velocityByte/127` can only evaluate to 0 or 1, the result of the latter form is either `pColor` or 0.

Note, your code shows `if (colorGroup == 1){` twice.  Change 1 to some other number in the second instance.

To cycle the LEDs through obvious patterns, you could have three different sketches, one that gradually raises and lowers the PWM level on Red, one that does the same for Green, and another for Blue.


message:
How do I read from /dev/ttyACM0 in Linux without a terminal emulator?

I just bought an Arduino Due and I'm having trouble reading from a simple serial IO program.

I have a SparkFun RedBoard which is like an Uno. With that, I just ran a "`stty`" command to configure the baud rate and other terminal settings, and then I could do "`cat /dev/ttyUSB0`". Actually I have a C++ program which opens "`/dev/ttyUSB01`" and reads from it like a normal file.

Now, with the Due, the device is "`/dev/ttyACM0`" and there have been a few snags. One of them is that after programming the Due, and running `stty`, I have to open `/dev/ttyACM0` using the `screen` program:

    screen /dev/ttyACM0 115200

and then kill screen, before `cat /dev/ttyACM0` will work. Otherwise, `cat` prints out one byte and exits; rarely it prints out 10 bytes or a line, or sometimes it prints nothing.

This is a bit annoying and I can't figure out what `screen` is doing to the device which I can't seem to accomplish using `stty`. My `stty` command is:

    sudo stty -F /dev/ttyACM* 115200 -parenb -parodd -cmspar cs8 -hupcl -cstopb cread clocal -crtscts \
    -ignbrk brkint ignpar -parmrk -inpck -istrip -inlcr -igncr -icrnl ixon -ixoff -iuclc \
    -ixany -imaxbel -iutf8 \
    -opost -olcuc -ocrnl -onlcr -onocr -onlret -ofill -ofdel nl0 cr0 tab0 bs0 vt0 ff0 \
    -isig -icanon iexten -echo echoe echok -echonl -noflsh -xcase -tostop -echoprt echoctl \
    echoke -flusho -extproc

I got this by running `stty -a < /dev/ttyACM0` after using `screen` to initialize as above.

I thought it might have something to do with serial auto-reset, so I tried using a resistor between `3.3V` and `RESET`, but this did not fix the problem.

I should note that `cu` from the `uucp` package is able to read continuously from `/dev/ttyACM0`, but unlike `screen` it does not leave the terminal set up in such a way that a subsequent `cat` command will work.

    $ cu -l /dev/ttyACM0 -s 115200
    <continuous stream of data>
    $ killall cu             # (from another shell)
    $ cat /dev/ttyACM0 | hexdump -c
    <e.g. 7 bytes>
    $

With `screen`, `cat` would have printed an infinite stream. Any ideas how to accomplish this setup without using `screen`?

body:
I have had very similar problems with my yun(shields) and I found the stty command to be very crucial for a good working.
I use following command and it works with mega and due on the yun

    stty -F ${PortName}  ${SerialSpeed}  raw -clocal -echo icrnl

Since I call these I can redirect from and to /dev/ttyxxx without problems.
As far as I can see you mis the raw.


message:
Is it possible to receive a 9 bit protocol on the Arduino Uno with Arduino?

I want send and receive a 9 bit async-serial protocol with 4800 baud on my Arduino Uno, i have read on the specification from the ATmega328P that the uart can do that.
My aim is that when my Uart receive the 9th bit as a 1 he must throw a interrupt. On this interrupt i can recognize that this byte was an adress byte.
When he receive a zero he sould do nothing spezial, only transmit it as hex-byte over usb to the pc.

My Problem now, i can´t initialize the Uart right because the command Serial.begin(4800, config) is not enough, i must throw the interrupt and translate the data to hex-bytes.
My Question can i modify the Serial.begin() source code respectively where can i find the source code for the Serial.begin function?

When there is no possibility to change the code has someone a other option for me to send and receive the 9 bit protocol with an Arduino Uno?

body:
If you want to set the UART to 9-bit mode, you will have to set the
UCSZ02 bit of the `_ucsrb` register to 1 in
[`HardwareSerial::begin()`](https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/HardwareSerial.cpp#L103).
For example:

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

    void HardwareSerial::begin(unsigned long baud, byte config)
    {
      // Mostly unchanged... but by the end:
      sbi(*_ucsrb, RXCIE0);
      cbi(*_ucsrb, UDRIE0);
      sbi(*_ucsrb, UCSZ02);  // set 9-bit data mode
    }

Notice that you do not need to modify the Arduino core library for this:
you could set that bit in your `setup()`, right after calling
`Serial.begin()`.

Then, in the [`HardwareSerial::_rx_complete_irq()` interrupt
handler](https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/HardwareSerial_private.h#L101),
you will have to read the 9th bit as the RXB80 bit in UCSR0B, **before**
reading the low byte from `_udr` (emphasis in the datasheet). For
example, you could replace the line `unsigned char c = *_udr;` by:

    bool is_address = UCSR0B & _BV(RXB80);  // read 9th bit first
    unsigned char c = *_udr;                // then the other bits
    if (is_address) {
      do_something_with_address(c);
      return;
    }

where `do_something_with_address()` is the stuff you wanted to do in
another interrupt (no need for that, you are already in interrupt
context).

It is worth noting that, with an Arduino Uno, you will not be able to do
all this while sending data to the PC. This is because the communication
with the PC uses the only UART of the ATmega328P.


body:
It sounds like you want some device with a 9-bit protocol to send data to an Arduino, and then the Arduino to forward that data (perhaps in a slightly different format) to a PC.

People who want to connect their Arduino to two serial devices at the same time (and the PC counts as one) generally either:

Change the hardware to accept multiple serial devices
-------------------

While the Arduino Uno has only one hardware serial port, the following (and probably many others) have 2 or more hardware serial ports:

* [Arduino Mega 2560][1] (USB and 3 other hardware serial ports)
* [Arduino Leonardo][2] (USB and 1 other hardware serial port)
* [Teensy LC][3] (USB and 3 other hardware serial ports) (["serial 9-bit on the t3"][4])

(["Sending and Receiving 9-bit Frames with Arduino"][5] uses the hardware approach).

Change the software to accept multiple serial devices
-------------------

In principle, it's possible to tweak SoftwareSerial to handle 9-bit data.
Several people have talked about it

* ["9bit SoftwareSerial library modification"][6]
* ["Altering New Soft Serial NSS for 9 bit- cans of open source worms"][7]

  [1]: https://www.arduino.cc/en/Main/ArduinoBoardMega2560
  [2]: https://www.arduino.cc/en/Main/ArduinoBoardLeonardo
  [3]: https://www.pjrc.com/teensy/teensyLC.html
  [4]: https://forum.pjrc.com/threads/23873-serial-9-bit-on-the-t3
  [5]: http://blog.bouni.de/blog/2014/10/07/sending-and-receiving-9-bit-frames-with-arduino/
  [6]: http://forum.arduino.cc/index.php?topic=345147.0
  [7]: http://citizengadget.com/post/22556427458/altering-new-soft-serial-nss-for-9-bit-cans-of


body:
The Max3140 is a very capable USART with built-in full/half-duplex RS-485 drivers that interfaces to a uController via SPI. They are a bit pricey and you would have to make a board, solder, etc..

Another solution would be to dedicate a simple and inexpensive minimal Arduino-compliant board (like a Pro-Mini) to interface with the "main" Arduino via I2C or SPI, and program the Pro-Mini for 9-bit addressing mode and add the RS-485 driver. Pro-Mini or Nano clones are dirt cheap, but it is not even that expensive to use an authentic Arduino product and support their great contributions ;-).


message:
How to rewrite code in millis?

I am currently working on a project that makes a plateua move back and forth using a stepper motor. On this plateau I have attached LEDs that create patterns.
However, the plateau should be moving whilst the pattern is changing. With my current code this is not happening. I know that I have to work with millis, but when I am completely lost on how to do it. Could someone help me?

Here is my code:

    #include <AccelStepper.h>

    AccelStepper stepper(1, 42, 38);

    int i;
    int microStep = 46;

    int currentAnimation = 0;
    int count = 0;
    int button = 13;

    int state = LOW;
    int lastState = LOW;

    //bytes for patterns
    byte a = B11110000;
    byte b = B00010000;
    byte c = B01000000;
    byte e = B10100000;

    //--------------------------------------------------------------------------------------------------------------------------------

    void setup()
    {
      DDRH = B1111000; // set PORT 6-9 of arduino mega high
      DDRB = B11110000; // set PORT 10-13 high

      stepper.setMaxSpeed(900.0);
      stepper.setAcceleration(400.0);

      pinMode(button, INPUT);
      state = digitalRead(button);

      pinMode(microStep, OUTPUT);
      digitalWrite(microStep, HIGH);
    }

    //--------------------------------------------------------------------------------------------------------------------------------

    void loop()
    {
      //This should happen constantly
      stepper.runToNewPosition(2000);
      delay(500);
      stepper.runToNewPosition(0);

      // These are the patterns, that should be played whilst the stepper is running. The patterns chaneg when you push the button
      if ( state == HIGH & lastState == LOW )
      {
        currentAnimation++;
      }

      if (currentAnimation % 3 == 0)
      {
        same();

      }
      if (currentAnimation % 3 == 1)
      {
        left();
      }
      if (currentAnimation % 3 == 2) {
        faster();
      }

      lastState = state;
      state = digitalRead(button);
    }

    //--------------------------------------------------------------------------------------------------------------------------------
    //PATTERNS
    void same() {
      for (int k = 0; k < 10; k++) //plays 10 times
      {
        PORTH = a;
        PORTB = a;
        delay(100);
        PORTH = 0;
        PORTB = 0;
        delay(100);
      }
    }

    void left() {
      for (int z = 0; z < 10; z++)
      {
        PORTH = e;
        PORTB = e;
        delay(100);
        PORTH = ~e;
        PORTB = ~e;
        delay(100);
      }

    }

    void faster() {
      for (int z = 0; z < 256; z++)
      {
        PORTH = z;
        PORTB = z;
        delay(100);
      }
      PORTH = 0;
      PORTB = 0;
    }

body:
### The basic pattern goes like this:
when you start the timer, you essentially store the current millisecond.
After this, in your loop code, among other things you should check if the time has passed by comparing current millisecond with the stored one. If their difference is equal or bigger of the desired delay interval, then the time has passed.

Make sure you use `unsigned long` variables to store times and check if time has passed with the condition used below (`if(millis() - mark >= interval ){...}`) so you will not have problem even after `millis()` rolls over.

If you need more help, do not hesitate to ask.

    unsigned long interval=2000; //2000ms
    unsigned long mark;
    boolean enabled=true;

    void setup() {
        Serial.begin(9600);
        Serial.println("starting timer");
        startTimer();

    }

    void loop() {
        check();
    }

    void startTimer(){
        mark=millis();
    }

    void check(){
        if(enabled){
            if(millis() - mark >= interval ){

                enabled=false;
                Serial.println("time elapsed");
            }

        }
    }


body:
You could try something along these lines, I haven't put all of the code in, but just how this could be done for the sweep timer using millis().

    unsigned long sweepTime;
    unsigned long animationTime;
    int stepperPosition;

    void setup()
    {
     //... other setup code
     sweepTime = millis();  // initialise the variables for the sweep timer, and the animation timer
     animationTime = millis();
     stepperPosition = 2000;  // initialise the next stepper position
    }

    void loop()
    {
     if (millis() - sweepTime > 500) // check if more than 500 milliseconds have elapsed since last time we ran this.
     {
      stepper.runToNewPosition(stepperPosition); // change stepper position
      sweepTime = millis();   // reset timer variable
      switch (stepperPosition) {  // need to change the value of the next position to set the stepper to
       case 0 :
        stepperPosition = 2000;
        break;
       case 2000 :
        stepperPosition = 0;
        break;
      }
     }
     //... continuation of loop code
    }

Additionally, I don't have my arduino with me, so can't verify the correctness of the code.


body:
Since microcontrollers typically only have one "core" or "thread" they can only do "one thing at a time".

A microcontroller will step through your code and do everything in order (if you don't call interrupts).

Basically, when you put in a `for-loop` (or any other type of loop) or a `delay`, it will only continue with the rest of your code when that is done.

To solve this, and "do two things at a time" (or actually rapidly switch between things) you'll need either interrupts or non-blocking code (or both).

**Interrupts**

I see you're doing some direct port manipulation, which is really nice. You're writing bytes directly to the control registers of the microcontroller.

You can leverage on that, to set up a timer (check the ATMega328P datasheet). You may make this timer give an interrupt each 100ms, and execute a "frame" of your animation at that point. And the next frame at the next interrupt. So that the time between each frames can be used for other code.

**Non-blocking code**

Arduino has built-in `millis();` which is basically an interrupt that fires every millisecond to keep track of the passed milliseconds. So you can use this instead of fiddling around with the timers (which may very well cause some of the Arduino's functions to fail (like millis() or the servo library).

To write non-blocking code, you'll not use delays, since they effectively throw away "processor time" by doing "nothing-instructions" all the time.

But if we take out the delays, the for-loops will run too fast. And a for-loop also doesn't really work without the delay. Because even if you use millis and wait for half a second, you can't do anything in between.

So we'll have to break up your code (specifically the animations) in chunks of code that can be executed withouth a delay. With only the need to delay in between these chunks.

**Frames**

Let's split up your animations in "frames". One of your animations `same()` works by PORTH&PORTB = A for 100msec and low for 100 msec.

    void sameAnimation(unsigned char frame){//plays 20 times (1x on, 1x off) instead of 10x on-off.
      if(frame%2==0){//If even
        PORTH = a;
        PORTB = a;
      }else{//if not even.
        PORTH = 0;
        PORTB = 0;
      }
    }

So based on the frame of the animation, the port will go high or low.

Now we look at the complete code, we have to change the motor every 500ms and have to change the animation frame every 100ms. And check a button.

We could put these in an interrupt that fires every 100ms, which would get reliable timing and minimum software overhead.
Or use the millis(); (checked against the previous milis) to check if the last update was 100ms ago.

My go at the code is below, but you should be able to figure it out yourself.

    void loop()
    {
      unsigned char currentFrame = 0;

      //Could be done every round.

      lastState = state;
      state = digitalRead(button);
      if ( state == HIGH & lastState == LOW )
      {
        currentAnimation++;
        PORTH = 0;
        PORTB = 0;
      }

      // These are the patterns, that should be played whilst the stepper is running.

      if(millis() - previousMillis > 500){// Should change every 100ms
        previousMillis = millis();

        if (currentAnimation % 3 == 0)
        {
          sameAnimation(currentFrame++);
        }
        if (currentAnimation % 3 == 1)
        {
          leftAnimation(currentFrame++);
        }
        if (currentAnimation % 3 == 2) {
          fasterAnimation(currentFrame++);
        }

        if(currentFrame % 5){//Should change every 500ms, so every 5 frames.
          if(forward){
            stepper.runToNewPosition(0);
            forward = false;
          }else{
            stepper.runToNewPosition(2000);
            forward = true;
          }
        }
      }
    }

    //--------------------------------------------------------------------------------------------------------------------------------
    //PATTERNS
    void sameAnimation(unsigned char frame){//plays 20 times (1x on, 1x off) instead of 10x on-off.
      if(frame%2==0){//If even
        PORTH = a;
        PORTB = a;
      }else{//if not even.
        PORTH = 0;
        PORTB = 0;
      }
    }

    void leftAnimation(unsigned char frame) {
      if(frame%2==0){//If even
        PORTH = e;
        PORTB = e;
      }else{//if not even.
        PORTH = ~e;
        PORTB = ~e;
      }
    }

    void fasterAnimation(unsigned char frame){
      PORTH = frame;
      PORTB = frame;
    }

**The button**

Checking the button every round isn't really needed. You can use an interrupt on that pin, so that the code to check it's state and go to the next frame only happens when the button is actually pressed. (interrupt triggered on rising edge?).


message:
Read int from Serial

with the following sketch I should be able to read and store what is entered in the Serial monitor

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

    void loop() {

      Serial.println("Enter Zone Number: ");
      while(!Serial.available()){
      }
       int zone = Serial.parseInt();
       Serial.println(zone);

    }

if I enter "1" I would except this:

    Enter Zone Number:
    1
but unfortunately I have this:

    Enter Zone Number:
    1
    Enter Zone Number:
    0

What am I missing?

body:
`.parseInt()` reads incoming text up until either it times out or *until it reads something that isn't a number*.

You are sending a number, and most likely a line-ending. If that line-ending is a simple `\n` then that will trigger the "end of number" and will be discarded and the number returned.  However, if you are sending `\r\n` (i.e., *CRLF*) then you effectively have two line endings there:

    1\r\n

Parsed as:

    1\r => return 1
    \n => return 0

Relying on the (poorly written) Arduino stream parsing routines is not good. Not only are they blocking, but often they just don't work right.

Instead you should be reading the serial properly, taking account of line endings, and then converting the string you have read into a number using the likes of `atoi()`.

Tutorial on reading serial:

* https://hackingmajenkoblog.wordpress.com/2016/02/01/reading-serial-on-the-arduino/


message:
TMC26XMotorTester:44: error: 'TMC26XStepper' does not name a type

I am working with a TOS-100 Stepper Driver Shield and am attempting to use the pre-written TMC26XMotorTester/Motor/Serial set of files to make it work.

I unzipped the files, copied the TMC26XStepper folder into the library directory in my Arduino folder, and restarted the Arduino IDE (as well as the Arduino and Driver Shield boards).  I also switched the DIR and STEP pins (6 and 7 swapped to match the wiring on my board).

In the TMC26XMotorTester file, I wrote

        #include <TMC26XStepper.h>

so I'm assuming (given everything I've done), that the functions should be available given this file inclusion.

However, I get the error

        TMC26XMotorTester:44: error: 'TMC26XStepper' does not name a type

along with the complete list of functions from the TMC26XStepper.h/.cpp file that were not identified.

Any thoughts?  I'm using Arduino-Uno version 1.6.9.

body:
Arduino libraries are normally written as a C++ Class.  When you start a sketch you normally tell the compiler where to find that Class and to Instantiate that class.  If the compiler does not find the Class and you attempt to Instantiate it, the compiler will telly you it does not know what to do.  That is, it will tell you the thing you are using (TMC26XStepper) does not describe anything or is not a Type.

Study the [structure of Arduino libraries][1] to make sure what you have installed agrees with the common Arduino library.

Also, newer version of the [Arduino IDE can download and unpack libraries automatically][2] given both the IDE and the library are setup to do this.

  [1]: https://learn.adafruit.com/arduino-tips-tricks-and-techniques/arduino-libraries
  [2]: https://www.arduino.cc/en/Guide/Libraries#toc3


message:
GikFun Arduino Nano locking up on serial I/O

I'm running into a problem with a GikFun Arduino Nano. The symptom appears when I'm reading the receive buffer to clear it after an operation completes. The unit just appears to stop somewhere in the loop function and never continues.

I know that this unit has a CH340 UART on it which seems to have issues.

Any suggestions on what I can do?

**OP Edits**

This code is more or less based on the code from this [Make: article][1]. I originally had this assembled through an Arduino Uno R3 with an HC-06 (Kootek BT2S) module. Everything connected via solderless bread-board.

This entire circuit works properly with the UNO, which I had it running on SoftwareSerial using pins 2, 3. After putting this on a perf-board in a project box using the GikFun Nano, it was not behaving. I had a number of wiring issues, which I resolved, but still had issues communicating on the HC-06/SoftwareSerial. I re-did the wiring using pins 0, 1 for the Serial and removed the SoftwareSerial references. The circuit worked as I expected with the HC-06 working as it had before. But if I issued more than 1-2 commands via Bluetooth the unit would just get stuck. I also tried this without the HC-06 connected and just used the Serial Monitor through the IDE same behavior. It would randomly lock up after clearing the receive buffer.

Code - as requested:

<!-- language: lang-cpp -->

 const int statusLED = 13; //the pin you connect your status LED to
 const int desiredBaud = 4;//index of your desired baud rate 4 is 9600
 char* myPin = "1234";//change to the pin of your choice

 const int memRed=0;
 const int memGreen=1;
 const int memBlue=2;

 const int redPin= 9;
 const int greenPin= 10;
 const int bluePin= 11;
 const int cmdLed= 12;

 // Max Red - 255
 const int max_red = 255;
 // Max Green - 90
 const int max_green = 255;
 // Max Green - 100
 const int max_blue = 255;

 int red= 255;
 int green= 255;
 int blue= 255;

 unsigned int baudLookup[] =
 {
   1200,  //code 1
   2400,  //code 2
   4800,  //code 3
   9600,  //code 4
   19200, //code 5
   38400, //code 6
   57600  //code 7
 };

 void setup()
 {
   Serial.begin(9600);
   pinMode(redPin, OUTPUT);
   pinMode(greenPin, OUTPUT);
   pinMode(bluePin, OUTPUT);
   pinMode(cmdLed, OUTPUT);
   pinMode(statusLED, OUTPUT);
   digitalWrite(statusLED, HIGH);

   Serial.begin(9600);
   delay(1500);//wait for reset to complete

   Serial.print("AT");
   delay(1500);//wait for reset to complete
   while(Serial.available()) {
  Serial.read();
   }
   delay(1500);//wait for reset to complete

   digitalWrite(statusLED, HIGH); //SUCCESS!

   digitalWrite(redPin, map( red, 0, 255, 0, max_red) );
   digitalWrite(greenPin, map( green, 0, 255, 0, max_green) );
   digitalWrite(bluePin, map( blue, 0, 255, 0, max_blue) );
 }

 void loop()
 {
   digitalWrite(statusLED, LOW); //fast blink means success
   delay(200);
   digitalWrite(statusLED, HIGH);
   delay(200);

   String stat;
   char buffer[13];
   buffer[12]= 0;
   if( Serial.available() >= 3 ) {
  String stat = String("OK");

  Serial.readBytes(buffer, 3);
  buffer[3]= 0;
  String command= String(buffer);

  Serial.println(command);
  if( command == "GET" ) {
    char outBuffer[7];
    sprintf(outBuffer, " xxx", red, green, blue);
    stat += outBuffer;
  }
  else if( command == "SET" ) {
    if( Serial.available() >= 6 ) {
   Serial.readBytes(buffer, 6);

   int redVal= (getVal(buffer[0])<<4) | (getVal(buffer[1]));
   int greenVal= (getVal(buffer[2])<<4) | (getVal(buffer[3]));
   int blueVal= (getVal(buffer[4])<<4) | (getVal(buffer[5]));

   digitalWrite(redPin, map( redVal, 0, 255, 0, max_red) );
   digitalWrite(greenPin, map( greenVal, 0, 255, 0, max_green) );
   digitalWrite(bluePin, map( blueVal, 0, 255, 0, max_blue) );

   red= redVal;
   green= greenVal;
   blue= blueVal;

   char outBuffer[7];
   sprintf(outBuffer, " xxx", redVal, greenVal, blueVal);
   stat += outBuffer;
    } else {
   stat = "ERR";
    }
  }
  else {
    Serial.println("No Command");
  }
  Serial.println(stat);
  Serial.println("Clearing receive buffer");
  delay(1500);
  while(Serial.available()) {
    Serial.read();
    delay(100);
  }
  delay(1500);
   }
 }

 byte getVal(char c)
 {
   if(c >= '0' && c <= '9') {
  return (byte)(c - '0');
   } else {
  return (byte)(c-'A'+10);
   }
 }

  [1]: http://makezine.com/projects/make-36-boards/android-arduino-led-strip-lights/

body:
The mix of delays and flushing in your code has a high chance of leading to unreliable operation.  Consider for example:

    Serial.println("Clearing receive buffer");
    delay(1500);
    while(Serial.available()) {
      Serial.read();
      delay(100);
    }
    delay(1500);

As the loop there can only consume about 10 characters per second, it would be quite easy for something on the far end to produce inputs faster than they are consumed, essentially making the loop infinite.

Time-based delineation of serial messages tends to be quite risky; better reliability is usually had by using a defined delimiting condition - for example, ending each message with a newline character and reading until that is seen.

USB-serial conversion also introduces added challenges for time-based schemes, as it introduces a sense of grouping into packets into a stream which in its native form does not have any.


message:
I feel like an idiot, why can't I make a servo move with the boilerplate code?

So I was working on a far more grand project, until I discovered that I couldn't get any of my servos to move.

I've gone back to basics, and am trying to just get the [boilerplate code found here, working][1].

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

    #include <Servo.h>

    Servo myservo;  // create servo object to control a servo
    // twelve servo objects can be created on most boards

    int pos = 0;    // variable to store the servo position

    void setup() {
      myservo.attach(9);  // attaches the servo on pin 9 to the servo object
    }

    void loop() {
      for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees
        // in steps of 1 degree
        myservo.write(pos);              // tell servo to go to position in variable 'pos'
        delay(15);                       // waits 15ms for the servo to reach the position
      }
      for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
        myservo.write(pos);              // tell servo to go to position in variable 'pos'
        delay(15);                       // waits 15ms for the servo to reach the position
      }
    }

[Here are pictures of my setup.][2]

  [1]: https://www.arduino.cc/en/Tutorial/Sweep
  [2]: https://i.stack.imgur.com/bK6ij.jpg

body:
The only thing I see that could be the problem is with your servo wiring. It seems that most servos use this kind of wiring ![Servo Wires](https://i.stack.imgur.com/Y1Rim.gif)

 Which is the way that you seem to wire it, but depending on how Radioshack servos are made the signal wire could correspond with a different wire. I imagine this could possibly be on the packaging so I would start by looking there to confirm your wiring.


message:
Circumventing overflow error by pushing data into computer?

It seems in certain applications, for example signal processing, Arduino and other micro-controllers in general run into the overflow error when they're trying to store even moderate amounts of data. It would seem the obvious answer would be to simply take this data, push it onto the computer, and deal with it there instead, where you have much more available computing power. Is this possible with Arduino, or am I missing something that makes it not feasible?

body:
One of the "features" of most microcontrollers/microprocessors is that they don't have a whole heap of RAM - this keeps costs down, and lets the manufacturers keep everything on one chip (unlike your PC).

However to "push" data to somewhere that can process it, you need to have a fast communications channel. SPI is quite fast, but you don't generally talk to PCs using SPI. Serial communication is slower, but if it gets converted into a USB interface (such as on a Uno) you can get respectable speeds talking to a PC. Something like 115200 baud is usually reliable, which lets you transmit 11520 bytes per second.

However it depends on what you want to send (ie. how many bytes), how you are going to indicate where one piece of data ends and the next one starts, maybe allow for error detection or correction, and so on.

Say, for example, it takes 5 bytes to send one piece of data (eg. 4 digits plus a delimiter). Now you are down to 11520/5 = 2304 pieces of data per second.

This may or may not be adequate for whatever-it-is you are trying to do.


message:
Why doesn't my LEDs turn on?

i have just started learning Arduino, so please be patient to me :)

Why doesnt my circuit below doesn't work?

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

Here's the code:

    #define led_green 2
    #define led_yellow 8
    #define led_red 13

    void setup() {
      pinMode(led_green, OUTPUT);
      pinMode(led_yellow, OUTPUT);
      pinMode(led_red, OUTPUT);

      // Strarting all turned off
      digitalWrite(led_green, LOW);
      digitalWrite(led_yellow, LOW);
      digitalWrite(led_red, LOW);
    }

    void loop() {
    digitalWrite(led_red, HIGH);

    delay(1000);

    digitalWrite(led_red, LOW);
    digitalWrite(led_green, HIGH);

    delay(1000);

    digitalWrite(led_green, LOW);
    digitalWrite(led_yellow, HIGH);

    delay(1000);

    digitalWrite(led_yellow, LOW);

    }

I'm trying to reproduce this circuit that I saw in a tutorial:

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

  [1]: https://i.stack.imgur.com/lmIQg.jpg
  [2]: https://i.stack.imgur.com/xwl6c.jpg

Thank you.

body:
If you are doing what is in the first picture then you're doing it wrong.

You have to make sure the led is horizontal, not vertical. The signal is going through the led and not making it into ground. And your ground is in the same lane as your signal.

I think you should learn how breadboards work and then move on from there. Its pretty simple and I think you'll learn it quickly.

For your code part, instead of defining the variables, you could just use `int`.

 Refer to this as a starter tutorial, https://www.arduino.cc/en/Tutorial/.

[![This how the breadboard is connected underneath. ][1]][1]

This is how your wiring should look like if you followed the tutorial, [![enter image description here][2]][2]

  [1]: https://i.stack.imgur.com/NGQFq.png
  [2]: https://i.stack.imgur.com/fVlVt.png


message:
message received from GSM contains parenthesis instead of curly braces

the GSM code i have been working out is up and running, I use JSON format in sending the data obtained by my sensors, but the JSON message I have been receiving contains parenthesis instead of curly braces.

body: One or both of your GSM endpoints is incapable of handling ESC prefixes according to GSM 03.38. The only difference between "{" and "}" and "(" and ")" is that the former are signified by a preceding ESC which either is not being generated by the sender or is not being interpreted by the receiver.


message:
Is it safe to power the Uno with 18v?

So I'm aware the Arduino Uno can take 6-20 volts, with a recommended voltage of 7-12. But I have an unregulated 12v power adapter, which puts out about 18v with no load.

Most of the time the Arduino won't be doing much of anything but powering a 16x2 LCD, which should take only a couple mA.\* I have a 10k ohm resistor on the back light, so it should only take 0.5mA.
<sup>\*I don't have a datasheet, but from what I've read 1-2mA is reasonable</sup>

The Arduino won't be doing anything else that would draw any meaningful amount of current (except looping to check for input, etc). Online sources generally indicate the power draw when not doing anything is a little under 50mA, so I'm guessing that's about what the current draw will be. Using the formula in [this answer](https://arduino.stackexchange.com/a/100/19256), I calculate the power dissipation by the voltage regulator to be (18v-5v)*0.05A=0.65 Watts.

* Is this correct?
* Is the voltage regulator likely to overheat?

I'm not really concerned about power usage, because it will be plugged into the wall all the time. Also, the Arduino will be out of sight, but will have plenty of air around it to disipate heat (though not access to a breeze).

body:
It won't do any harm to try it at 18V for a while. Most voltage regulators have thermal protection and just cut out if they get a little too hot. If it works reliably, stay with it.

EDIT: Their [Uno page][1] warns against overheating the board, so I would test it for a short while and make sure there is no overheating or strong "plastic" smell coming from the board. If there's enough heat to worry, then it's best not to run like that for extended periods.

If 18V is too high, you could get a power resistor (I'd guess say a 10 watt resistor around 24 ohms) to waste approximately half an amp from the power supply. Connect this to the supply, in parallel with the Arduino.  It's wasteful (unless your room needs heating anyway) but will lower the voltage (that reaches the Arduino) a little.

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


message:
How do I lock a servo motor?

I am working on a robot which uses Ackermann's steering principle. Now the steering principal itself is in the development stage and the first prototype is pretty much good except for the fact that it can get turned very easily.

So I was hoping to find a way to lock the servo operating the steering mechanism so that it only rotates when the servo does. Any way to do that??

I'm using a UNO.

Thanks!

body:
A normale servo will stay in position when:

 1. It's powered up (with enough current)
 2. You are feeding the control signal into it.

And

 3. It's rated for the amount of force applied.

Based on your comments, it seems that it's not a regular servo or could be faulty.
I couldn't find the datasheet for your servo, so I can't tell if it's normal behavior, though it seems unlikely. (Servo's aren't made to bounce around)

Edit:
It doesn't really make sense that it could be easily rotated by touching it, that would also mean that it can't lift anything? I would suggest trying another servo.


message:
Avoid the 10 attempts of Avrdude when programmer is not responding

Sometime I update my sketch in the Arduino environment, and when I click on the transfer arrow but forget to plug my arduino (I'm using the UART in my project so every time I need to plug/unplug some wires) it's a drama, avrdude throw this for at least 2 minutes :

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

It's a real pain because I can't stop avrdude when this happens.
Is there a way to configure the Arduino environment to disable it?

body:
Unfortunately, `MAX_SYNC_ATTEMPTS` is a constant in the source code, and one which appears several times.

avrdude is an open source project, so customizing and building it should be relatively straightforward.  Since it is a numeric rather than string value, and is checked in several places, simply modifying the binary is likely to be tricky.

One can of course manually kill the process, though it is annoying to have to.

Another approach could be to write a wrapper which might potentially do some sanity checking first (does any other process have the port open?) and then would launch avrdude as its child, passing through all the arguments.  By monitoring the output before passing it on, it should be possible to detect this message and terminate the avrdude instance automatically.


body:
I had the same question and found following solution in linux: write a script,

    #!/bin/bash
    avrdude=`ps -C avrdude | tail -n 1 | head -c 7`
    kill $avrdude

store it and connect it with a shortcut


message:
Peristaltic Pump Project

I am designing a peristaltic pump and need some advice for parts. I am using an Arduino Leonardo and also have an UNO and am planning on adding a temperature and pH sensor as well. I have two questions:

**1) I am planning to use a Stepper Motor but am unsure if I should use the *NEMA 17 or 23* or some other motor. I need a relatively "high" amount of torque maybe around 1 to 3 N-m.**

**2) Should I go with a Motor Shield or Motor Driver. I am currently looking at the *Big Easy Driver* or *A4988 Bipolar Driver* or the simple *Arduino Motor Shield*.**

Does anyone know which of these would be best or have any suggestions? Thank you very much!

body:
The specifications for each stepper motor varies, with the larger models having the greater torque. With great torque comes the requirement of great power. A quick search for nema 17 stepper motors finds the torque figures on the low side of your request, while the nema 23 motors display a greater range, including your figures.

The additional power requirements may exceed the capabilities of the Arduino Motor Shield (2a per channel, 4a max), while the A4988 board specifies up to 2a per coil. Also note that to achieve the use of the higher power levels, these boards will require heat sinks.

If you expect to require the higher figure for torque, consider to research for a driver board that has a greater power limit, "just in case".


message:
Is the C++ STL fully supported on Arduino?

I don't yet own an Arduino board to run code on, and as the title says, I'm curious if the [C++ STL][1] is fully supported on Arduino **and already part of** the Arduino IDE. The STL is probably the most efficient, fully tested, and resource-minimal (which is a slightly redundant phrase, as I already mentioned efficiency) publicly available C++ code out there, and would make life much easier to code for Arduino.

*If* the STL is not a part of Arduino IDE, then how to include specific libraries such as `<algorithm>` and `<utility>`? (I'm very tempted to ask "why isn't it included?" but that seems too broad.)

  [1]: http://www.cplusplus.com/reference/

body:
The STL is not a part of Arduino IDE.

Although efficient by desktop standards, the consensus is it doesn't fit comfortably in an Arduino's limited space.  That said, here's someone who seems to have done it:

https://github.com/maniacbug/StandardCplusplus

Check out the forks, they seem more up to date


body:
The STL is not part of Arduino and no support for [libstc++ from AVR][1].

My "answer" differences from Malachi at one point though, as explained in the comments.

I don't think you shouldn't, just because "most people say" that you shouldn't. There are a lot of people that even think you shouldn't use C++ at all.
The problem is that C++ (and C++ standard library) are very powerful and may be ported in a non-efficient way.

----------

**Why use libstdc++?**

I think, however, that if you use it with care, it can be very usefull.

Let's say we've got two buffers, a send buffer and a receive buffer.
With C, you would store them in a fixed char array. In C++ you can use dynamic containers.

So in C, you'll use 2x 256 bytes of memory to save your messages. Any longer message won't fit.

In C++ you'll use only whatever bytes are needed at one point (plus some extra probably). And if you get a longer message, it will simply scale up.

If the C++ thing works for you, and just test it very very well, why not use it? On average, it will use less memory, since you don't assign all of it when it's not used. You will have a problem when your messages get too big, since your memory will overflow, often causing the microcontroller to reset. But if more buffers in your program are dynamic, one may leave some space for the other, etc. Effectively using the memory more efficient!

But, without dynamic allocation, it might be a little safer, since you've already claimed those pieces of memory, there is no way you can't use those pieces. Any message that is bigger, simply won't fit, but you can easily check on that. Another thing is that the C++ stl's you find, might not be as well optimalised for your architecture/microcontroller.

Also, creating your very own dynamic storage in C may cause even more problems than the C++ stl ;). And it's not like you have to use dynamic storage for everything, simply being able to do so is nice.

----------

Current microcontrollers are also getting much more serious as the 8-bit Arduino's (328P). 20$ can get you a Teensy 3.2 which has `256K Flash Memory, 64K RAM` so, in this case, dynamic memory can be very useful (if you are certain you always have enough memory left).
Also: `All STM32F41xxx products embed: Up to 192 Kbytes of system SRAM including 64 Kbytes of CCM (core coupled memory) data RAM`

By that, it can also be a very nice way to learn C++ and program in the same language as you do on the PC.
But keep in mind that on an 8-bit micro, you should check if your stl-functions don't give too much overhead.

----------

How use C++ standard template library for AVR?

I've followed the blog from [Andy Brown][2] and now have iterators/string/vectors working in AtmelStudio.

Though I did get some errors, the first batch of errors included:

    Error        '_M_deallocate' was not declared in this scope, and no declarations were found by argument-dependent lookup at the point of instantiation [-fpermissive]      D:\avr-stl\include\string    173
    Message        declarations in dependent base 'std::_String_alloc_base<char, std::allocator<char>, true>' are not found by unqualified lookup        D:\avr-stl\include\string    173
    Message        use 'this->_M_deallocate' instead     D:\avr-stl\include\string    173

This error actually explains itself; you should use `this->_M_deallocate`.

After that I got `undefined reference to "operator new(unsigned int, void*)`. But I fixed it by including "pnew.cpp" right under `#include <new>`  in `stl_construct.h` which is weird, but it works.

(Piece of stl_construct.h)

    #ifndef __SGI_STL_INTERNAL_CONSTRUCT_H
    #define __SGI_STL_INTERNAL_CONSTRUCT_H

    #include <new>
    #include <pnew.cpp>

    __STL_BEGIN_NAMESPACE

  [1]: http://www.atmel.com/webdoc/AVRLibcReferenceManual/FAQ_1faq_cplusplus.html
  [2]: http://andybrown.me.uk/2011/01/15/the-standard-template-library-stl-for-avr-with-c-streams/


body:
STL is efficient on the platform it was designed for, which is personal computers and similar-scale devices, where allocating a single byte in the heap consumes a 4k memory page (that's several times as much as ALL Arduino RAM), and where array indexes can be efficiently replaced by pointers (8-bit microcontrollers need at least two commands to deal with a pointer). So no, it's not efficient with Arduino.

Think of quicksort algorithm - it performs very well on large lists, but is easily beaten by a simple sort if you need to sort an array of 5 elements. Being asymptotically efficient doesn't mean being efficient in every case.


body:
The STL is not a part of Arduino IDE.

Another answer is mentioning https://github.com/maniacbug/StandardCplusplus although this library doesn't seem to be maintained anymore.

Maybe a better idea could be to try https://github.com/mike-matera/ArduinoSTL

It's a port of uClibc++ packaged as an Arduino library.


message:
How do I stop the Arduino TX/RX LEDs from flashing? How do I turn off the "ON" LED?

I actually have a SparkFun RedBoard, but I think this question applies to Arduino Uno and other boards as well.

I'm wondering how much control the programmer has over the various LEDs on the board. First there's the "ON" LED which is very bright. Can this be turned off or dimmed, or do I need to resort to electrical tape?

More annoying is the "TX" and "RX" LEDs. These blink rapidly when data is being communicated over the USB-serial connection. I'm guessing these are not configurable, but I couldn't find the answer anywhere online.

I know that the "Pin 13 LED" can be controlled (via Pin 13!).

body:
> I'm wondering how much control the programmer has over the various LEDs on the board. First there's the "ON" LED which is very bright. Can this be turned off or dimmed, or do I need to resort to electrical tape?

Remove it, remove the resistor inline with it, or cut the track powering it. Either that or resort to electrical tape (or blu-tack). You have absolutely no control over it.

> More annoying is the "TX" and "RX" LEDs. These blink rapidly when data is being communicated over the USB-serial connection. I'm guessing these are not configurable, but I couldn't find the answer anywhere online.

**If your board uses an ATMega16U2**

As above, or compile a custom version of the ATMega16U2 firmware and flash it on to the ATMega16U2 chip.

**If your board uses an FT232 chip**

Download the FT232 EEPROM editing program from FTDI and use that to reconfigure the IO pins the LEDs are attached to so they do nothing. If you are on Linux you can use libftdi's `ftdi_eeprom` program.


message:
Problems running several Arduinos off of one HC-05 Tx pin

TL;DR: Multiple Arduinos listening to a single serial rail are burning out my HC-05's TX pin. Arduinos are leaking voltage onto the signal rail. How do I stop, or isolate that to keep from burning out Bluetooth TX pin?

I'm trying to build an LED-based track light that uses an HC-05 to communicate with up to 8 Arduinos to control up to 16 LEDs total. Each Arduino can only control 2 LEDs because of the shape and form factor of the project.

The track has 3 rails, 12V, Ground and Signal and all Arduinos share the same rails. Hopefully the schematic below does a good job explaining it.

[![Arduinos all share common ground, 12v and data line][1]][1]

On to my issue. Initially, I was getting almost 5V from my pin 7 (SoftwareSerial pin) on the Arduinos, which was quietly ruining the TX pin on my HC-05. I lowered that to about 1v after using `pinMode(bluetoothTx, INPUT);`, which is good but not good enough. That voltage starts to add up as I add more and more Arduinos to the overall setup.

My solution in theory is to add diodes to pin 7 on the Arduinos, so they can't put voltage on the signal rail. This drops the voltage by 0.7v from what I've read, which most likely is why the Arduinos aren't reading a signal now, because that drops it below the logic level required, since the HC-05 is only putting out 3v3. So I think to add a level shifter on the HC-05 to pump up the signal to 5v, then the diode's voltage drop shouldn't matter right? See schematic below.

[![Diode's keep pins from leaking voltage onto line, level shifter compensates for voltage drop over diode][2]][2]

My solution seems unnecessarily convoluted and I don't even know if it would work. The more I read without bouncing the information off of others, the more confused I am becoming. Now after reformatting this post for an hour, I am thinking about a decoupling capacitor between the pin and ground... Will that have the effect I am looking for?

I also looked into using a pulldown resistor, but from everything I've seen (and from the first electronics course I've taken), it seems like an inappropriate solution. The examples I've seen usually use a switch, which makes sense, but for my application I am protecting the TX pin on my HC-05, so I think it would not give the effect I am looking for (tapping the line in between resistor and pin would not isolate the voltage, tapping in after the resistor would short the signal to ground).

I'm including my code for completeness, but the schematic is where I think I need help. Could someone point me in the right direction, I don't mind working for my answers but I've been going solo at this for over a month now, and I'm not even at the point in my education where we've covered much logic yet. I'm reaching a little here.

 #include <EEPROM.h>
 #include <SoftwareSerial.h>

 byte address = 1; //change this to change light address
 byte lightno = (address + 1); // variable to print light number
 int addressShifter= ((address)*500); //This number will be subtracted from input
 int bluetoothTx = 7; //btTX to pin 7 //input from HC-05
 int bluetoothRx = 8; //btRX to pin 8 //not used
 int led1 = 3; // the PWM pin LED1 is attached to
 int led2 = 5; // the PWM pin LED2 is attached to
 int brightness1 = EEPROM.read(0); //Recalling previous setting
 int brightness2 = EEPROM.read(1); //Recalling previous setting
 int thismodMin = (0 + addressShifter); //min two-byte looked for
 int thismodMax = (499 + addressShifter); //max two-byte looked for

 SoftwareSerial bluetooth(bluetoothTx, bluetoothRx); //naming it bluetooth and assigning it to the variables shown

 void setup() {
  pinMode(led1, OUTPUT); // sets the pin as output
  pinMode(led2, OUTPUT); // sets the pin as output
  pinMode(bluetoothTx, INPUT); // sets the pin as input
  //Setup usb serial connection to computer
  Serial.begin(9600);
  //Setup Bluetooth serial connection to android
  bluetooth.begin(9600);
  analogWrite(led1, brightness1); //Set Led brightness from stored values
  analogWrite(led2, brightness2); //Set Led brightness from stored values
  Serial.println("SETUP COMPLETE, I am Light #"); //Identify self
  Serial.println(lightno);
  Serial.println("expecting Min "); //Min value listened for
  Serial.println(thismodMin);
  Serial.println("expecting Max "); //Max value listened for
  Serial.println(thismodMax);
 }

 void loop() {
  //---------Serial Communication---------
  if(bluetooth.available()>= 2) {
   unsigned int blu1 = bluetooth.read();
   unsigned int blu2 = bluetooth.read();
   unsigned int blueinput = (blu2 *256) + blu1;
   //I don't know why any of the above is neccesary but it will not read correctly without this conversion
   //Serial.println("blueinput = "); Not used
   //Serial.println(blueinput);  Not used
   if (((blueinput) >= (thismodMin)) && ((blueinput) < (thismodMax))){
    //If this blueinput is within this modules adress range, convert signal to PWM
    int thisMod = ((blueinput) - (addressShifter));
    //Convert blueinput to a value this module will work with (0-500)
    //-----------Lights---------
    if (((thisMod) >= 0) && ((thisMod) < 100)){ //0=off 1-100=on-Bright
     brightness1 = ((thisMod)*2.55); //converts percentage brightness to PWM value
     analogWrite(led1, brightness1); //apply brightness
     //      Serial.println("brightness1: "); //diagnostics
     //      Serial.println(brightness1); //diagnostics
     delay(10);
    } else if (((thisMod) >= 101) && ((thisMod) < 201)){ //101=off 102-201=on-Bright
     brightness2 = (((thisMod)-101)*2.55); //subtract starting value and then convert percentage brightness to PWM value
     analogWrite(led2, brightness2); //apply brightness
     //      Serial.println("brightness2: "); //diagnostics
     //      Serial.println(brightness2); //diagnostics
     delay(10);
    } else if ((thisMod) == (399)){ //if specific code recieved
     EEPROM.write(0, brightness1); //store brightness setting for light 1
     Serial.println("Epprom1 written");
    } else if ((thisMod) == (424)){
     EEPROM.write(1, brightness2); //store brightness setting for light 2
     Serial.println("Epprom2 written");
    } else{}
   }
  }
 }

  [1]: https://i.stack.imgur.com/ka3b8.png
  [2]: https://i.stack.imgur.com/krmGx.png

body:
**first of all just to clarify some things.**

softwareSerial library sets PinMode for rx,tx declared pins internally so it should not have any impact on voltages you measure if you include `pinMode(bluetoothTx, INPUT);` and if this happens, as you describe, it indicates a problem.

a pin declared as INPUT is on a high impedance state which means that it will not (in general) affect signals connected to it.

an RX pin, by default is _pulled up_ which means that when you do not have anything connected to it, you should measure 5V and when you connect it to GND you should read 0V.

--------------

i tried to reproduce your problem by implementing your first schematic utilizing 3 arduinos as receivers with the difference of having another arduino as transmitter instead of HC-05 and using a simplified version of your program (see it below).
I could not reproduce it. Also, I suspect that parallel pull up resistors from ~8 arduinos may be the problem, so I would suggest:

 * make sure communication between HC-05 and only one arduino works.
 * try connecting HC-05 with two arduinos and see if both arduinos are able to read incoming data.
 * keep adding arduinos and checking if every arduino can read incoming data.

also try with another arduino as transmitter instead of HC-05 in case you still have a problem and post the results so we can further investigate .

 #include <SoftwareSerial.h>

 int bluetoothTx = 7;    //btTX to pin 7 //input from HC-05
 int bluetoothRx = 8;    //btRX to pin 8 //not used

 SoftwareSerial bluetooth(bluetoothTx, bluetoothRx);  //naming it bluetooth and assigning it to the variables shown

 void setup()
 {
   //Setup usb serial connection to computer
   Serial.begin(9600);

   //Setup Bluetooth serial connection to android
   bluetooth.begin(9600);

   Serial.println("SETUP COMPLETE, I am Light #");  //Identify self
 }

 void loop()
 {
   //---------Serial Communication------
   if(bluetooth.available() )
   {
     Serial.print(bluetooth.read(),HEX );
   }

 }


message:
Why can't the OCR1A register be set to 1 to get a 8MHz PWM?

The max PWM frequency that can be achieved with an Arduino is by using the PWM fast mode with the pre-scaler set at 1 and the TOP counter value at 3, getting 4MHz

f_OC = 16000000/(1(1 + 3)) = 4000000

Why can't be the TOP value set at 1?

body: Because then you only have 1-bit PWM. And there aren't an awful lot of applications for 1-bit PWM.


message:
Get value from a website using Yún and a RPi

I have a project that requires opening a door remotely. I'm using an arduino Yún and a raspberry pi.
 I have a switch connected to the RPI and i'm sending it's value to a web server. How can I get the value from the website to the arduino, so that it can process it and see if an order to open the door is issued?

Thanks for any help :)

body:
You need to use the [Process](https://www.arduino.cc/en/Tutorial/Process) library that comes with the IDE.

That allows you to execute commands on the Linux portion of the Yun from within your Arduino code, and get data back from it.

You use that class to execute the `curl` command in Linux to fetch the content of a web page and return that content to the AVR code where you can deal with it.

If the content of the web page is complex it may be worth passing the output of `curl` through some other Linux based commands first (such as `grep` and `cut` or `awk`) to clean it up and reduce the amount of text you have to deal with at the AVR end.


message:
ESP8266 not able to communicate over serial connection with arduino UNO

This is the code I uploaded in Arduino UNO:
--------------------------------------------------------------------------------------
    #include<SoftwareSerial.h>
    SoftwareSerial ESP(2,3); // RX, TX
    //ESP RX-->3(UNO) TX-->2(UNO)

    void setup() {
    // Open serial communications and wait for port to open:

        Serial.begin(9600);
        while (!Serial) {
            ; // wait for serial port to connect. Needed for native USB port only
        }

        Serial.println("Goodnight moon!");

        // set the data rate for the SoftwareSerial port
        ESP.begin(9600);

    }

    void loop() {
        if (ESP.available()) {
            char inData = ESP.read();
            Serial.println("Got reponse from ESP8266: ");
            Serial.write(inData);
        }

        ESP.write("AT\r\n"); //Normally ESP responds to AT command with "OK"
    }

-------------------------------------------------------------------------------
But ESP is not able to receive the AT command properly...sometimes it recieves A, sometime T. It then responds with garbage value. Though we are able to give command to ESP through Serial Monitor and it responds pretty well. But when trying to communicate through code, the communication is not OK.

body:
The problem is in your `loop()` function. On each iteration, you will receive **at most one** character from the SoftwareSerial, while writing the same AT command again and again. As a result, your slave device (ie. ESP8266) will overflow its UART buffers, resulting in garbage being sent and received.

You should keep receiving data from the slave for as long as it has data:

    while (ESP.available()) {
        char inData = ESP.read();
        Serial.println("Got response from ESP8266: ");
        Serial.write(inData);
    }


message:
Any way to not explicitly include dependent libraries?

When I am including the `Adafruit_BMP280` library, Arduino IDE 1.7.10 complains that it wants all dependent libraries included:

    Adafruit_Sensors.h
    Wire.h
    SPI.h

Isn't it possible to circumvent that? [This question][1] says to include the first library like

    #include "Adafruit_BMP280"

but also with the full path, this doesn't work and just returns the same error.

  [1]: https://stackoverflow.com/questions/6504211/is-it-possible-to-include-a-library-from-another-library-using-the-arduino-ide

body:
No, it is not possible. The IDE needs to know which libraries you are using so that it can compile the source code for them.

Other IDEs have got around the problem by recursively scanning the libraries themselves and building up a list of dependencies (such as [UECIDE](http://uecide.org)) but this is not something that the Arduino IDE has been programmed to do.

The only other possible option might be to create a single massive library that contains everything that the "main" library relies on, however this may cause problems with other libraries also wanting the same things and you ending up with massive conflicts.


message:
ESP2866 and java ServerSocket

So I have an application that runs on the Arduino that passes info over serial.
I'm using a ESP2866 to make it wireless.

    Arduino->Serial->Esp2866->SocketConn->JavaSocket->Console

I have a working java socket server, that I can connect to with other applications. (Java, c++, ext.) And even across the network.

I just cant seem to get my ESP2866 to connect.

Iv tried several ESP2866 units, no success. Iv tried updating the firmware on each, nope.

    AT         -> OK
    AT+RST     -> ready
    AT+CWMODE=1    ->  OK
    AT+CWJAP="name","pass" ->  CONNECTED,GOTIP,OK
    AT+CIPMUX=0    -> OK
    AT+CIFSR    -> 192.168.0.30
    AT+CIPSTART="TCP","192.168.0.9","4160" -> ERROR

The lack of debug info is... Aggravating.
Iv Seen other examples of this that worked. So whats the problem?

Additional info:

    netstat -tulpn | grep 4160
    tcp6       0      0 :::4160          :::*      LISTEN      23058/java

(Edit 1:)Just tried restricting to IPV4 and rebinding the port. Nope.

    InetAddress localAddress = Inet4Address.getByAddress(new byte[]{(byte) 192,(byte) 168,0,9});
 System.setProperty("java.net.preferIPv4Stack", "true");
 ServerSocket listener = new ServerSocket(port,20,localAddress);
    //...Code to make socket work.

body: The ESP trys to connect to port 4160, but the server is listing on port 20.


message:
Does Serial.read() ever return a character?

I'm trying to program my Arduino Mega to work with a TSL1401 line scan module and while looking over someone else code I came across this:

    void loop()
    {
     int b = Serial.read();   //Reads incoming serial data. Returns the first byte of
            //incoming serial data available (or -1 if no data is available)

     if (b == 's')
     {
      getCamera();
      delay(2000);
     }
    }
For the most part I understand what it's doing but I got confused when I saw that he was setting the return value of `Serial.read()` equal to a variable and then checking to see if that variable was a character. To my understanding `Serial.read()` returns an integer so why would you compare it to a character?

body:
On an 8 bit arduino a character is a byte.  A byte can represent values between -128 and 127, or between 0 and 255, depending on how you "look" at them (signed or unsigned).

The whole concept of a character is a purely human thing. The Arduino only knows numbers.

For instance the character 'A' is actually the number 65. We, as humans, choose to represent it as an 'A' and call it "ASCII".

Again, the character 'a' is actually the number 97. You can also subtract characters from each other.  `'a' - 'A' = 32`


body:
Part of the answer is in the comment in your given example:

    int b = Serial.read();      //Reads incoming serial data. Returns the first
                                //byte of incoming serial data available
                                //(or -1 if no data is available)

If you're reading raw 8-bit data from the serial port (basically, could be any value from 0-255), how do you represent errors?   Per the comment: if nothing is available, it returns -1.  But... as @Majenko pointed out, -1 is a valid CHAR too, it all depends on how you look at the data (signed, or unsigned).

But an INT can hold a value from 0-255 easily, and also a -1 to represent 'nothing'.  The Serial.read function is non-blocking (it doesn't WAIT for a data byte), so it needs to be able to return a status that indicates 'empty bucket', meaning there's actually 257 (256+1) different possible values... thus you need more than 8 bits.

It's a painful lesson with usage of **fgetc(3)**, **getc(3)** and similar functions.  You need to be able to represent EOF, while also returning valid 8 bit data.  Hence the use of INT's as return value size.  Often someone (ok, me... but it was a _long_ time ago!) will figure that since they're reading CHAR's, you can use a CHAR sized variable... but then EOF never seems to be found... oops!

Hope this helps.


message:
How to modulate my IR sensor?

I'm looking to use a simple IR sensor out in bright sunlight, which means hell lot of distortion. Is there any way I can modulate it using my Arduino UNO so that it isn't affected by sunlight and other ambient light sources?

The IR sensor is just like [this][1] one.

[1]: http://www.amazon.in/Proximity-follower-Obstacle-sensing-Robots-Interface/dp/B01535L94C?tag=googinhydr18418-21&tag=googinkenshoo-21&ascsubtag=fb9dc0d3-db5f-411e-80bb-34bbe41b3335

body:
There is little information on the Amazon page about these devices.  Only that the output is digital (only on and off) and that the sensitivity is controlled manually by an on board pot.  It would appear impractical to enhance this type of device with out detailed specifications and / or a schematic.

If you would prefer using software to solve some of the problems you listed, I would suggest you use an IR parallax (not the company, the technique) distance sensor with an analog output.  That way the Arduino Uno's analog input can be used to read the sensor and software (sketch) can process (filter) the data before it is put to use.

Added later...

[Here][1] is an article describing how to use an IR parallax distance sensor.  [Here][2] is an Arduino library design to work specifically with the Sharp IR parallax distance sensor.

  [1]: http://www.robotshop.com/blog/en/arduino-5-minute-tutorials-lesson-4-ir-distance-sensor-push-button-2-3637
  [2]: http://playground.arduino.cc/Main/SharpIR