message:
Can I make the Arduino ignore serial print

I like having serial communication for debugging and testing purposes but after a while it takes away too much speed from the sketch.

Is it possible to have the Arduino ignore serial.print and serial.println throughout my code, without turning it into a comment or placing every serial printing inside for example "if(debug == true)" statements?

Thanks in advance.

body:
If you insist on top performance, the best thing would be to use a macro for that:

    #define Sprintln(a) (Serial.println(a))

Then instead of

    Serial.println(F("Hello world!"));

write

    Sprintln(F("Hello world!"));

etc. To deactivate the `Serial` printing, define the macro empty:

    #define Sprintln(a)

This will have the preprocessor remove all debugging code defined with `Sprintln` from your code.

(Of course, there's a huge number of variations on this theme.)


sender: user

sender: assistant

body:
You could, for example, use the preprocessor to change all `Serial` in your code.

    #ifndef ENABLE_PRINT
    // disable Serial output
    #define Serial SomeOtherwiseUnusedName
    static class {
    public:
        void begin(...) {}
        void print(...) {}
        void println(...) {}
    } Serial;
    #endif


body:
Yet another solution is to implement a dummy Serial device. That would be a class that as HardwareSerial inherits from Stream and implements the necessary virtual member functions with dummy functions.

    class NullSerial : public Stream {
    public:
      virtual size_t write(uint8_t) { return (1); }
      virtual int available() { return (0); }
      virtual int read() { return (0); }
      virtual int peek() { return (0); }
      virtual void flush() {}
      ...
      void begin(unsigned long, uint8_t) {}
      void end() {}
      ...
    };

    NullSerial Serial;

As Serial is not defined as a weak symbol the application would need to use a Steam variable for output. And bind this to the HardwareSerial or the NullSerial.

    #if defined(DEBUG)
    Stream& trace = Serial;
    #else
    NullSerial noSerial;
    Stream& trace = noSerial;
    #else

    #endif
    ...
    trace.print(42);

This is not complete as all the HardwareSerial member functions (that the sketch uses) are needed but gives the general idea how to use OOP to solve the problem.

Cheers!


message:
What is the fastest and easiest way to transmit arduino's sensor data to a PC wirelessly

I have a specific problem :

1. I'm working on a testing platform. It has to be absolutely isolated, so I cannot wire it back to my PC. I again reiterate it. There is no way to wire it to my PC. IT HAS TO BE ABSOLUTELY ISOLATED

2. It has about 10 different sensors on it and I need to read sensor's data simultaneously at 100Hz.  It is currently working fine with 16Hz, but I need to improve it further, so I think maybe in future sampling rates higher than 100 is beneficial. 7 Hz is the lowest possible value that doesn't botch the whole things up.

3. I have a laptop on the platform which reads the sensor data via RS232, then it processes them in a fraction of a second and produce a control signal and send it to the actuators. It has to happen at real-time. Control algorithm is not heavy, it is several PIDs.

4. It has 6 actuators with the fastest possible reaction time of 0.005 second.

5. The main sensor currently is [Microstrain 3DM-GX1][1]. It is a very good sensors.

6. I want to add a [GY-80][2] sensor in parallel to 3DM-GX1. I want to test various filtering algorithms on the GY-80's output and compare them to 3DM-GX1.

7. Platform has 6 degrees of freedom so I think laser transmission is not practical.

4. Distance between the computer and the platform is at most 3 meters.

For some reasons I am not able to use the laptop anymore. I want to read the sensor's data with an Arduino, preferably Arduino Mega 2560. My problem is that I don't want to load the control algorithm to the Arduino.

IMHO the perfect solution is going to be a Wireless link between the Sensors via Arduino to my PC. This way my PC logs data and also the Control Algorithm can promptly calculate the feedback signal and send it to Arduino which will send them to the actuators. This immensely makes things easier for me.

I think I need a RS232 shield for the 3DM-GX1 & Arduino, + some wireless solution for sending data from both sensors to my computer. Then I need to send back the control signal back to the actuators wirelessly.

Now what is the fast and easy way to transmit the data between PC and Arduino in real-time?

Thank you in advance!

  [1]: http://www.microstrain.com/inertial/3DM-GX1
  [2]: http://www.forkrobotics.com/2013/06/using-the-gy80-10dof-module-with-arduino/

body:
The fastest way would be to use a laser link!! Yeah lasers. You could go with wifi or some other custom wireless but lasers will guarantee the highest energy density and therefor best bandwidth.  This guy claims near 10 MB/s with his setup:

http://www.instructables.com/id/Laser-Transceiver/


message:
IR Receiver interrupt and arduino sleep mode

I need to put my arduino into the sleep mode in order to consume less power. My arduino receives IR data and do some work with it, but I need to make it sleep until there is no data. If the data has appeared it should wake up and do something with data and go back to sleep mode.
Is there any way to do this.
I would be grateful for any help.

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

This is what I have managed to achieve ...

---

## Library

[IRLib - GitHub](https://github.com/cyborg5/IRLib/)

> Version 1.51 March 2015
> Copyright 2013-2015 by Chris Young http://tech.cyborg5.com/irlib/
>
> This library is a major rewrite of IRemote by Ken Shirriff which was covered by GNU LESSER GENERAL PUBLIC LICENSE ...

---

## Code

Modified code (from the demo IRrecord example):

    /* Example program for from IRLib – an Arduino library for infrared encoding and decoding
     * Version 1.5  June 2014
     * Copyright 2014 by Chris Young http://cyborg5.com
     * Based on original example sketch for IRremote library
     * Version 0.11 September, 2009
     * Copyright 2009 Ken Shirriff
     * http://www.righto.com/
     */

    /*
     * IRrecord: records IR signals
     * An IR detector/demodulator must be connected to the input RECV_PIN.
     * Record a value by pointing your remote at the device
     */

    #include <IRLib.h>
    #include <avr/sleep.h>
    #include <avr/power.h>

    const byte LED_PIN = 8;
    const byte RECV_PIN = 11;
    const unsigned long BAUD_RATE = 115200;
    const unsigned long NO_ACTIVITY_TIMEOUT = 2000;  // milliseconds

    IRrecv My_Receiver(RECV_PIN);
    IRdecode My_Decoder;
    IRsend My_Sender;
    /*
     * Because this version of the library separated the receiver from the decoder,
     * technically you would not need to "store" the code outside the decoder object
     * for this overly simple example. All of the details would remain in the object.
     * However we are going to go ahead and store them just to show you how.
     */
    // Storage for the recorded code
    IRTYPES codeType;          // The type of code
    unsigned long codeValue;   // The data bits if type is not raw
    int codeBits;              // The length of the code in bits

    // These values are only stored if it's an unknown type and we are going to use
    // raw codes to resend the information.
    unsigned int rawCodes[RAWBUF]; // The durations if raw
    int rawCount;                   //The number of interval samples

    bool GotOne, GotNew;

    // added by Nick Gammon
    EMPTY_INTERRUPT (PCINT0_vect);

    void setup()
    {
      GotOne=false; GotNew=false;
      codeType=UNKNOWN;
      codeValue=0;
      Serial.begin(BAUD_RATE);
      while(!Serial);//delay for Leonardo
      Serial.println(F("Send a code from your remote and we will record it."));
      Serial.println(F("Type any character and press enter. We will send the recorded code."));
      My_Receiver.enableIRIn(); // Start the receiver
    }

    // Stores the code for later playback
    void storeCode(void) {

      // added by Nick Gammon
      pinMode (LED_PIN, OUTPUT);
      digitalWrite (LED_PIN, HIGH);

      GotNew=true;
      codeType = My_Decoder.decode_type;
      if (codeType == UNKNOWN) {
        Serial.println("Received unknown code, saving as raw");
        // To store raw codes:
        // Drop first value (gap)
        // As of v1.3 of IRLib global values are already in microseconds rather than ticks
        // They have also been adjusted for overreporting/underreporting of marks and spaces
        rawCount = My_Decoder.rawlen-1;
        for (int i = 1; i <=rawCount; i++) {
          rawCodes[i - 1] = My_Decoder.rawbuf[i];
        };
        My_Decoder.DumpResults();
        codeType=UNKNOWN;
      }
      else {
        Serial.print(F("Received "));
        Serial.print(Pnames(codeType));
        if (My_Decoder.value == REPEAT) {
          // Don't record a NEC repeat value as that's useless.
          Serial.println(F("repeat; ignoring."));
         }
         else {
           codeValue = My_Decoder.value;
           codeBits = My_Decoder.bits;
         }
         Serial.print(F(" Value:0x"));
         Serial.println(My_Decoder.value, HEX);
      }

      // added by Nick Gammon
      pinMode (LED_PIN, INPUT);
      digitalWrite (LED_PIN, LOW);

    }

    void loop() {

      // added by Nick Gammon
      static unsigned long lastActivity;  // when we last woke
      // sleep if no activity for a while
      if (millis () - lastActivity >= NO_ACTIVITY_TIMEOUT)
        {
        Serial.flush ();  // wait for Serial to finish outputting
        Serial.end ();    // shut down Serial
        noInterrupts ();  // timed sequence coming up

        // pin change interrupt for D11
        PCMSK0 |= bit (PCINT3);  // want pin 11
        PCIFR  |= bit (PCIF0);   // clear any outstanding interrupts
        PCICR  |= bit (PCIE0);   // enable pin change interrupts for D8 to D13

        set_sleep_mode (SLEEP_MODE_STANDBY);
        sleep_enable();

        byte old_ADCSRA = ADCSRA;
        // disable ADC to save power
        ADCSRA = 0;
        power_all_disable ();  // turn off various modules
        interrupts ();
        sleep_cpu ();
        sleep_disable();
        power_all_enable ();   // enable modules again
        ADCSRA = old_ADCSRA;   // re-enable ADC conversion
        Serial.begin(BAUD_RATE);
        lastActivity = millis ();
        }  // end of no activity for a couple of seconds

     if (My_Receiver.GetResults(&My_Decoder)) {
        My_Decoder.decode();
        GotOne=true;
        storeCode();
        delay(500);
        My_Receiver.resume();
      }
    }

---

## Explanation

Main changes are in `loop` (near the bottom) where it sleeps if there is no activity for two seconds. This "no activity" test gives it time to catch an incoming pulse stream.

Before sleeping it turns off Serial (to save power), and sets up to detect the pin-change interrupt. It also turns off the ADC, and calls `power_all_disable` to disable various internal modules.

Note that it uses pin-change interrupts on Arduino pin D11 (pin 17 on the chip). For a different processor than the Atmega328P, or a different input pin, you would have to change which pin-change interrupt is used.

I found that I had to use SLEEP_MODE_STANDBY rather than SLEEP_MODE_PWR_DOWN, otherwise it seemed to take too long to wake up and handle the incoming pulse.

For testing, I flashed D8 pin to make sure it was working when hooked up in low-power configuration.

---

## Power consumption

I tested with an AX-1838T IR-receiver that I had to hand (same pin-outs as in the Adafruit article).

Measured stand-alone (ie. not connected to the Arduino) it consumed 630 µA, so therefore we could not expect lower power consumption than that.

Connected up to a "bare-bones" board (ie. just the Atmega328P chip, decoupling capacitors, etc.) I measured 1.158 mA when idle.

[![Bare bones board][1]][1]

My tests on [my page about power](http://www.gammon.com.au/power) indicate that SLEEP_MODE_STANDBY uses 480 µA more power than SLEEP_MODE_PWR_DOWN, so this sounds about right.

    630 + 480 = 1110 µA

You might be able to save more power by operating at a lower voltage. This particular receiver can operate at a lower voltage. As an indication, I tried the setup at 3.3 V (which is out of spec for the processor, but whatever, I was just testing) and it consumed 978 µA when idle. This is a modest saving over the 5 V test.

---

## References

* [Power saving](http://www.gammon.com.au/power)
* [Interrupts](http://www.gammon.com.au/interrupts)
* [Adafruit IR library](https://learn.adafruit.com/using-an-infrared-library/hardware-needed)
* [IR library source](https://github.com/cyborg5/IRLib/)

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


message:
Convert uint8_t array to uint32_t array

I have this array of bytes, that I need to convert to an array of unsigned ints. Also the function (`btea`) that needs it, seems to need a pointer.

I'm currently using `reinterpret_cast` which seems to work, but I'd like to know how/why. I'm pretty new to `C`. It also seems kind of dirty. I could use a for loop, and bitshift everything into a separate int array variable, but that seems wasteful.

    uint8_t data[] = {1,2,3,4,5,6,7,8};//can be any multiple of 4 bytes

    btea(reinterpret_cast<uint32_t*>(data), sizeof(data)/4, encryption_key);

    radio.write(data, sizeof(data));

    ...

    void btea(uint32_t *v, int n)
    {
      ...
    }

Any pointers (pun intended) are much appreciated.

body:
I prefer to use unions. example:

    union fourbyte {
      uint32_t dword;
      uint16_t word[2];
      uint8_t  byte[4];
    };

    union fourbyte val;

    val.dword = 0x03020100;

    Serial.println(val.byte[0], HEX);
    Serial.println(val.byte[1], HEX);
    Serial.println(val.byte[2], HEX);
    Serial.println(val.byte[3], HEX);

    Serial.println(val.word[0], HEX);
    Serial.println(val.word[1], HEX);

    Serial.println(val.dword, HEX);


body:
@mpflaga's answer gives a great alternative, but I thought I'd explain why your code works (grossly simplified).

All the reinterpret cast does is let the compiler know how wide of a variable it assumes is in each element of the array.  When you access `data[1]`, it uses one byte at an offset of one byte from `data[0]`.  When you cast to uint32_t and access `data[1]`, it uses 4 bytes at an offset of 4 bytes.

If your memory looks like this (each square is one byte)...

![enter image description here][1]

...before the cast you are interpreting it as the top layout, after the cast you interpret it as the bottom layout.  It's still exactly the same in memory, you're just telling the compiler to use it differently. The reason that using a union is better is that it is safer.  Your code would read garbage after the end of the array if its length *wasn't* divisible by 4.

One other quick note, be careful with the sizeof() operator on arrays - it always gives the length in bytes regardless of the element size.

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


message:
Day-night powered Arduino

What should I do to have an Arduino Pro Mini 5V (clone) powered by a 5V solar panel during the day and by battery during night which will be charged during the day by the solar panels.

 - is there any guide out there?
 - is it possible with the 5V version of Arduino Pro Mini or will I have to buy the 3.3V
 - I prefer to make the circuits by myself rather than buying them (for example: the charging circuit.)

body:
This would be better answered on Stack Exchange Electrical Engineering.

Also [see this question and answers](https://arduino.stackexchange.com/questions/665/powering-arduino-with-solar-panels?rq=1). This is not quite the same and the answers there are OK but less than complete or correct, but it adds to the resource available.

You need a battery charging controller, a PV (solar) panel capable of producing somewhat more than maximum battery voltage and enough energy to operate your circuit and a battery with enough voltage to operate the device and enough capacity to store the energy.

Current drain will vary with total circuit. You can measure this will a milliammeter. I'll assume that 50 mA continuous will be enough. Less or much less may suffice. I have a pro mini clone operating at 20 mA on 5V at present and with due care you may be able to operate one with less or much less current depending on application and what your circuit needs are.

Looking at solar current needs at present, the average solar current needed is about Icircuit x 24/SSH mA where SSH = average sunshine hours per day. eg if you had 4 hours of sunshine per day but want to run the circuit for 24 hours a day the sun must provide (24 hours per day)/(4 hours of sun) = 6 x as much current as the circuit needs on average. So if your circuit needs 50 mA continuous the PV panel must provide 6 x 50 mA = 300 mA for 4 hours per day. You will see below that this is not a trivial amount.

Sunshine hours per day may be found for sites worldwide using the excellent www.gaisma.com The [**average sunshine hours per day for Iráklion**](http://www.gaisma.com/en/location/iraklion.html) may be found at that link and other locations in Greece can be found [**here**](http://www.gaisma.com/en/dir/gr-country.html) but will probably be similar.
For Iráklion the SSH may be found in the 1st line of the 4th chart.
Average hours/day of equivalent full sunshine = kWh/m^2/day = a peak of 8.53 hours in June and a low of 2.08 hours in December.
Wow!
I think that is about as sunny a place in Summer as anywhere on earth not in the polar regions.  In Winter it gets about the same SSH as in [my city](http://www.gaisma.com/en/location/manukau.html). You can calculate PV sizing for peak summer - but if you want year round operation you should use the worst case winter month and add a bit for bad days.
For Iraklion us say 2 SSH per day so the panels needs to provide 24/2 = 12 x winter average load. So per 10 mA of load yo need 120 mA of panel and if the mean load is 50 mA you need 12 x 50 = 300 mA panel output.

Battery voltage needs to be > 5V at all times.
An easy cheap available starting solution is to use a 6B lead acid battery.
These are easyish to charge and provide a relatively stable operating voltage.
Vmax_charge is **about** 7V so an 8V or 9V PV panel is "about right". 9V is a common voltage for hobby applications. An alternative is to use a 12V panel. this is probably more suitable as they are widely available and cost per energy out is often lower. This wastes MOST of the panel output but still MAY be the cheapest option in many cases. (A 12V x 600 mA panel is rated at about 18V x 0.6A ~= 10 Watts. Actual Arduino load = 50 mA x 5V x 12:1 = 3 Watts)

At 50 mA load you need 24/2 x 50 mA = 600 mA PV output in full sun.
PV panel sizing is not as may be expected. It is easiest to get a panel that makes at least enough voltage and enough current. This is because panel RATED voltages are usually higher than the voltages they are used at. eg 12V system PV panels are usually rated at 18V max power voltage- so an 18W panel provide 18V at 1 A BUT if attached directly to a 12V battery the input to the battery = 12V x 1A = 12 Watts. There are ways around this but at first, just concentrate on panel mA.

So, you "need" a 600 mA panel for a 50 mA load.
Or a 60 mA panel for a 5 mA load.
Or a 6 mA panel for a 0.5 mA load.
Obviously, reducing load current is going to help panel sizing.
So knowing what your application really needs is essential.

Batery is easier.
If you use 6V lead acid then for one day you need.
Hours x load = mAh.
Here load=24 hours. mA = 50 in this example.
mAh = 24 x 50 mA =  1200 mAh = 1.2 Ah. This is the capacity of about the smallest LA battery commonly available. In practice you want to discharge your battery by only a small % of its actual capacity so use a 2.4 Ah or 3.5 Ah or larger. 7Ah is not vastly dearer and will last far longer and will have several days of reserve capacity for bad weather.

Charging can now be discussed - but I'll stop here and see what is said about the above. We can add charging and other detail if it seems useful to do so.

![enter image description here][1]

An easy battery to use is 2 x LiIon or LiPo cells in series.

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


message:
Arduino is not recognized by any computer

I have an Arduino Uno R3 and when I plug it into any computer, the computer doesn't recognize the Arduino. I checked up and the LEDs are working fine and when I open the device manager it doesn't show any `Unkown Device`.

What it could be? Could the ATMega be dead? I tried on two Windows 7 and one Linux machines, none recognized the Arduino.

body:
The reason that it is not connecting can be anything from wrong driver installation to the dead Atmega 16u2 chip. But I must exclude the former option as you said you'd tried on different OS and different computers. So double check the driver installation. And if does not work try to find out whether Atmega16u2 is fried or not. One solution might be to reflash the original firmware through an external ICSP programmer. If don't have any programmer but another arduino uno you might try out the gamon's tutorial on flashing firmware on the little USB to serial interface chip.
Anyway if your arduino is new and official you can get the right support online on arduino.cc. but if it is a clone you may try to contact the reseller whom you bought from.


body: I had the same problem. When I connected the board to PC the ON Green LED turned on and the arduino run the last code was uploaded but the board wasn't recognized. Changing the cable fixed this problem for me.


body:
If your arduino runs the last uploaded sketch, the problem is with the ATMega16U2 chip in your Arduino. Try to update the firmware with this tutorial https://www.arduino.cc/en/Hacking/DFUProgramming8U2

If you can't update the 16U2 firmware don't throw away, you can program the Arduino with a ISP programmer like this https://www.pololu.com/product/1300


message:
Delay versus polling power consumption?

Does using the delay function use any less power than spinning in a polling loop on a timer?

body:
The answer is probably "they are equal" because what the CPU is doing is less than 1% of power draw. In order to save power while waiting you can put the chip to sleep. Assuming you have an Arduino uno, this post contains sample code about sleeping and current consumption. http://forum.arduino.cc/index.php?topic=78430.0

Maybe explain what you are doing (what size battery you have) and we can add some advice about ways to save power


body:
That depends very much on how delay() was written (and how it will be written in the future!). There are "sleep modes", which will reduce the power consumption of the arduino - these are one of the best way to reduce power consumption. Delay() may or may not activate these. If not, there could be a replacement Delay() function that could do this.

If you want to reduce power, check out http://www.gammon.com.au/power - this is an excellent step-by-step tutorial on how to reduce power consumption from 50mA down to 288 µA


message:
Set the timeout - Ethernet Shield library

Does anyone know if you can set the time for the timeout Ethernet Shield library? Let me explain:

I created a very simple function (below) that attempts to connect to an address if it is not accessible returns 0 if it is available returns 1. Problem is that when the site is not available, the microcontroller is waiting for an answer for a long time, wanted to reduce it.

    uint8_t ping(const char* address)
    {
        EthernetClient http;

        if(http.connect(address, 80)) {
            http.stop();
            return 1;
        }
        else
            return 0;
    }

body:
In the stream class there is a setTimeout(ms) function. e.g.

    String str;
    Serial.setTimeout(5000) ;
    str = Serial.readStringUntil('\r');

Where this does timeout the initial connection attempt in http.connect(). Whereas I found it also important to timeout each line, as a web page may not disconnect at the end or not send anything.

    int httpGetHeaders() {
      String request, response;
      int result = 0;
      long startOfHttpResponseTime;

      client.setTimeout(1000) ;
      response = "";
      inHeaders = true;
      startOfHttpResponseTime = millis();
      while((client.connected()) && inHeaders && ((long)(millis() - startOfHttpResponseTime) < HTTP_RESPONSE_TIMEOUT)) {
        String header = client.readStringUntil('\n');
        header.trim(); // trim off white spaces including CR and LF at end.
        Serial.print(F("head["));
        Serial.print(header.length());
        Serial.print(F("]:\""));
        Serial.print(header);
        Serial.println(F("\""));
        if (!header.length()) { // first blank line indicates end of headers
          inHeaders = false;
          Serial.println(F("No longer in Headers"));
        }
        else {
          if (header.startsWith("HTTP")) {
            Serial.println(F("HTTP Found"));
            int firstspace = header.indexOf(" ");
            result = header.substring(firstspace + 1, header.indexOf(" ", firstspace + 1)).toInt();
            Serial.print(F("result = "));
            Serial.println(result);
          }
        }
      }

      Serial.print(F("Result code = "));
      Serial.println(result);
      return result;
    }

You may want to review the whole code at https://github.com/lansing-makers-network/StatusBotArduino/blob/master/StatusBotArduino.ino I have reduced the connection to a sequence of commands that can be used consectutively in the desired order to meet different needs. The above is just to read a headers response.


message:
How to interrupt a code after delay

I have a functionality on my mega 2560 to connect with other devices. Sometimes, devices can't answer. I don't want to wait for a longwhile. So, how can I interrupt the chunk of program after the specific amount of time?

My code for receiving messages is:

    while (!(UCSR1A & (1<<RXC1)));

so, `millis` can't solve my problem because I haven't ability to check for conditional loops like that

    if(currentMillis - previousMillis > interval) {

body: OMG, I was stupid. I can just place millis in this `while` condition.


message:
Arduino Uno, Ethernet shield, MySQL

I'm trying to connect my Arduino Uno with MySQL.

This is my code:

    #include <SPI.h>
    #include <Ethernet.h>
    #include <sha1.h>
    #include <mysql.h>

    /* Setup for Ethernet Library */
    byte mac_addr[] = { 0xC8, 0x0A, 0xA9, 0xAF, 0x83, 0x58 };
    IPAddress server_addr(192,168,0,102);

    /* Setup for the Connector/Arduino */
    Connector my_conn; // The Connector/Arduino reference
    char user[] = "root";
    char password[] = "fifa2005";
    char INSERT_SQL[] = "INSERT INTO test_arduino.hello VALUES ('Hello from Arduino!', NULL)";

    void setup() {
    Ethernet.begin(mac_addr);
    Serial.begin(115200);
    delay(1000);
    Serial.println("Connecting...");
    if (my_conn.mysql_connect(server_addr, 3306, user, password))
    delay(500);
    else
    Serial.println("Connection failed.");
    }

    void loop() {
    }

I have the following database:

    mysql> CREATE DATABASE test_arduino;
    Query OK, 1 row affected (0.00 sec)
    mysql> USE test_arduino;
    Database changed
    mysql> CREATE TABLE hello (source char(20), event_date timestamp);
    Query OK, 0 rows affected (0.01 sec)

This is the output message:

    Connecting... Connection failed.

I am not sure this is the right IP address: `192,168,0,102`. I tried with the localhost IP address - `127.0.0.1`, but nothing happened.

body:
First you have to grant permission to the user!

Type the query in MySQL like:

<!--language: lang-mysql -->

    GRANT ALL ON test_arduino.* TO root@'192.168.0.102' IDENTIFIED BY 'fifa2005';


body:
Can't comment, so I put here. In your Arduino you shall use unique MAC address, that can't be same as in your laptop or any other node in network segment. And it can't be just any number because some bits have different meanings, so to be safe, use MAC from Ethernet shield samples (BTW in production units, MAC addresses have to be purchased, but unfortunately Ethernet shield comes without it).

127.0.0.1 is a "virtual" localhost address (alternative address used to access the services within same host), in your case you shall use MySQL server (your laptop?) host address, so

    > server_addr(192,168,0,102);

is right.


message:
Control Brushless ESC From Arduino

I am trying to build a quadcopter using an arduino. I Bought 4 30A ESC's from Ebay the link is http://www.ebay.co.uk/itm/4pcs-Brushless-speed-controller-ESC-MultiCopter-KK-Quad-rotor-X-copter-30A-S-/310950293677?pt=LH_DefaultDomain_3&hash=item486614f0ad and a A2212 2200KV motor, im also using a sparkfun arduino uno. I have connected the white (data) servo wire of the ESC to pin 9 of my arduino and the black (ground) servo wire of the ESC to gnd of the arduino. When i connect the battery to the esc i get the 3 beeps because of my 3 cell battery regardless of what code is on the arduino even if the arduino is not present. the code that is on the arduino is.

    #include <Servo.h>

    Servo motor;

    void setup()
    {
      Serial.begin(9600);
      motor.attach(0);
    }
    void loop()
    {
      motor.write(100);
    }
I'm not sure what is wrong. Can someone please help me.

body:
I had a similar problem. I solved it by using an oscilloscope to measure the arming sequence of an out-of-the-box RC remote controller and receiver.

The arming sequence through the controller-receiver was like this:

 1. Connect ESC to battery (arduino is connected to signal and ground prior to this)
 2. Wait for 3 beeps
 3. Set the throttle to the lowest possible
 4. Wait for another beep

I then adjusted my arduino code to output the same(similar) sequence.

Here is the code:

    #include <Servo.h>
    #define POT A0

    Servo m1;

    void setup() {
      m1.attach(6);
      Serial.begin(9600);
      delay(50);
      Serial.println("Serial ready:");
      arm(m1);
    }

    void loop() {
      int potValue = analogRead(POT);
      int s = map(potValue,60,930,1200,1700); //Map the pot values to motor values

      m1.write(s);
      Serial.println(s);
    }

    void arm(Servo m){
      Serial.print("Arming.");
      m.write(0);
      delay(100);
      m.write(1224); //A value at which the motor starts turning
      delay(2000);
      m.write(1024); //A value at which the motor stands still
      delay(3000);
      Serial.println(" Armed!");
    }

You can also see a video of the whole thing in action here: [A2212/13T brushless motor on a pivoting arm][1]

  [1]: https://www.youtube.com/watch?v=jJPW61Joacw

**EDIT:** Further testing shows, that it suffices to output a low non zero value to arm this ESC. Simply doing Servo.write(1024); until you hear the confirmation beep seems to work.


message:
Can I charge a 4.2 V battery with a 5 V adapter?

Can I charge a 4.2 V battery with a 5 V adapter without damaging the battery?

body: No. You must use a charger properly designed for the battery; attempting to connect a Li-ion battery directly to a USB charger will damage the battery, possibly catastrophically.


body:
This question would be a better match to the Stack Exchange Electrical Engineering group.

A 4.2V battery is very likely a LiIon or LiPo battery. I'll call it LiPO below as it's easier to type.

Most cellphones and many small electronic device use a single LiPo battery and use a 5V input to charge them. To do this they have internal control circuitry that ensures the battery's specifications are met. You can obtain suitable control electronics (in many cases as a single IC requiring maybe a few external resistors to configure it) and it makes great sense to use such a control circuit.

In an emergency you can use a 5V source to charge a 4.2V battery **IF** you know what you are doing and are able to ensure the battery specifications are adhered to. Failing to stay "in spec" may lead to the traditional LiPo "vent with flame" response, and even if there is no apparent damage the battery life can be greatly or very greatly reduced by out of spec treatment.

Key requirements are:

- NEVER exceed 4.2V at battery terminals.

- NEVER exceed Ichg_max = manufacturers max charging current.
This is usually the same value in mA as the battery capacity in mAh.
ie 1000 mA for a 1000 mAh battery
 3300 mA for a 3300 mAh battery etc

- When charging, EITHER stop charging when battery potential reaches 4.2V OR if you are able to hold the battery AT 4.2V, then stop charging when Ichg falls (under battery control) to say Ichgmax/4.

- If Vbattery is under 3.0 V (which it NEVER should be) charge at no more than C/10 (eg  for a 1000 mAh cell) until Vbattery rises to >= 3.0V. If the battery will not rise to 3.0V under C/10 charge it is dead.

IF you can satisfy ALL these requirements at all times you can charge a LiPo or LiIon battery from 5V without a special charger.


message:
Convert string plus hexadecimals to array of hex:

I have a string which I send to the arduino using serial monitor. Something like that:

    my specific string 0x0F 0x2C 0x98 0xBC

How can I parse this string in the arduino to get an array of hex values:

    0x0F 0x2C 0x98 0xBD

? There are two prerequisites:

1. All hexadecimal starts with `#`
2. The size of hexadecimal is 2. No `0x111` or '0xbbb'

body:
You can try reading each character and convert it to hexadecimal representation.
I suppose you wanna 1 byte each value in hexadecimal representation, so, let's start.

For example the string "0x25", ignore the 0x and read the '2' and save it into a char variable. Same for '5';

    char highBits = '2' - '0'; // convert to decimal representation
    char lowBits  = '5' - '0';

    byte = (highBits << 4 | lowBits);

Now, save it inside you array. Make sure you check if the value is one of the possible letters in hexadecimal and convert it properly (A=10 and so on).
Just include an if statement if it is a letter and convert it.


body:
> How can I parse this string in the arduino to get an array of hex values:

There are a few standard library ([stdlib][1]) functions that can help you with that. Below is a snippet:

    char buf[] = "0x0F 0x2C 0x98 0xBD";
    uint8_t val[4];

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

      char* bp = buf;
      int i = 0;
      do {
        char* ep;
        val[i] = strtol(bp, &ep, 16);
        Serial.println(val[i], HEX);
        bp = ep;
        i += 1;
      } while (*bp != 0);
    }

    void loop()
    {
    }

Cheers!

  [1]: http://www.nongnu.org/avr-libc/user-manual/group__avr__stdlib.html#gaf8ce3b8dae3d45c34c3b172de503f7b3


message:
Install Bluetooth inside a home theater, How?

I have a 5.1 home theater(old one), I would like to transform it into a audio streaming system. I have a Arduino UNO and HC-05 Bluetooth Module, and I don't know how to install it in my home theater(if it does). solution please...

body:
I don't think this will be feasible. There are two main issues:

**1.** I don't think there's a sensible way to get the HC-05 module to work with A2DP. It's great for a simple serial connection, but Bluetooth-enabled media devices generally won't connect to it if they're looking for audio streaming systems (as far as I know).

**2.** The Uno probably isn't powerful enough. Even if you could get the audio data into it, I don't think it will be able to decode the information to an analog audio signal in real-time.

Something like a Raspberry Pi with a suitable Bluetooth module might be a better choice for this.


message:
Overloading function loop

I want to introduce a boolean that is the first iteration of loop and then false
every subsequent iteration. I want it invisible, so I have to modify loop in some way. Is that possible?

body:
The way to do this isn't to overload the loop function, the way to do this is to abuse the linker and replace main().

The main.cpp file that gets used in the Arduino make prototypes main as `int main(void)`. On my system at least the linker prefers the longer prototype, so you can just do this:

    int main(int argc, char* argv[])
    {
     init();

    #if defined(USBCON)
     USBDevice.attach();
    #endif

     setup();

        //The one shot loop...
        loop();
        if (serialEventRun) serialEventRun();
        //Put whatever else you need to do between before the unending loop here.

     for (;;) {
      loop();
      if (serialEventRun) serialEventRun();
     }

     return 0;
    }

Both get compiled, but the `int main(int argc, char* argv[])` prototyped version gets linked as the entry point, so your "invisibile" code gets executed.


message:
Serial structure data transfer between an Arduino and a Linux PC

I use the Arduino compatible [chipKIT WF32][1] board. I want to transfer structure data between my board and a Linux PC. Can I do it like the following?

    struct data d;
    char *tx = (char*)d;
    Serial.print(tx);

Even if the above code works, the data type size in Arduino and on Linux will vary. Is there a way to serialize the data, like [Protocol Buffers][2] on Arduino?

  [1]: http://www.digilentinc.com/Products/Detail.cfm?NavPath=2,892,1193&Prod=CHIPKIT-WF32
  [2]: https://en.wikipedia.org/wiki/Protocol_Buffers

body:
The following solution isn't strictly portable, but it should work as long as both ends are [little-endian][1] (most platforms).

You can use the GCC attribute `packed` to tell the compiler not to pad the fields like this:

    struct __attribute__ ((packed)) my_struct {
      char c;
      int32_t n;
    };

Then you can send your struct like this:

    Serial.write((uint8_t*) a_my_struct_ptr, sizeof(my_struct));

On the receiving end you just copy the received data to a similarly packed struct. If you would rather use [Python][2] over C/C++ you can use the `struct` module to unserialize the data.

----------

I just googled your product and the [MIPS][3] processor is bi-endian, but I will assume that it is configured for little-endian by default. You can try and see if `int`s keep their value after transmit. Also remember to use explicit size types such as int16_t, uint64_t, etc.

  [1]: https://en.wikipedia.org/wiki/Endianness
  [2]: http://en.wikipedia.org/wiki/Python_(programming_language)
  [3]: https://en.wikipedia.org/wiki/MIPS_instruction_set


body:
I usually send structures from arduino via serial port to PC <del>and use the memcpy function to do it.</del>
Let's say you have the struct data d (_as pointed by the comments the memcpy as unnecessary. Use cast or union_):

     struct data state;
     len = sizeof(state);
     Serial.write((uint8_t *)&state,len);

It is useful to create a starting and ending character to delimit your important data and make sure you receive all data and good information.
Let me give you one of my recent work example:

    ...

    void send_state(){
  len = sizeof(state);
  Serial.write('S');
  Serial.write((uint8_t *)&state, len);
  Serial.write('E');
  return;
    }
    ...

In this example the struct state is preceded with "S" (start) and succeeded with "E".
Then in python, for example, you can get the data using the unpack function. In my case:

    ...

    # wait for data from arduino
    myByte = port.read(1)
    if myByte == 'S':
        data = port.read(39)
        myByte = port.read(1)
        if myByte == 'E':
            # is  a valid message struct
            new_values = unpack('<c6BH14B4f', data)

    ...

See if arduino sends data in little endian. The one I have used to send it.


message:
Connecting an AB phase encoder motor to arduino

i'm trying to understand how to connect this motor:

"Mitsumi 334P/R AB"

[Link to the motor i bought][1]

![enter image description here][2]

connections are:

GND - Obvious.

5v - Obvious.

rest of the connections are a bit confusing to me and i do not want to fry my arduino trying.

 - do i need a driver or this looks like a built in one?
 - do i need to add any electrical components like resistors and capacitors ect?

  [1]: http://www.ebay.com/itm/Mitsumi-334P-R-AB-phase-encoder-encodes-tacho-motor-speed-disk-DC3V-24V-5V-6V-/221702525894?pt=LH_DefaultDomain_0&hash=item339e8013c6
  [2]: https://i.stack.imgur.com/UST5F.jpg

body:
It's just a regular motor, with a (optical) rotary encoder inside. So the first two `motor` pins are to run the motor. So connect to VCC and GND, or GND and VCC, if you want to run it in reverse. (VCC doesn't have to be 5v; it can be 3v to 30v).

Connect A and B to a digital input pin. You can see what kind of signal you can expect in the screenshot of the oscilloscope, attached to the ebay-listing. So you can measure the speed, and relative position of the motor-shaft.


message:
How do I turn on or off an array of LEDs based on the value of a variable?

I've created a function whereby an int ('cleanCount') automatically goes up or down (0-1000) based on the situation. The value changes every few milliseconds.

Based on the value, I would like to turn on or off LEDs. Let's say for every increment of '100' another LED goes on. So if the value is 359 there are 3 leds on, if It would been 899 there would've been 8 LEDs on.

I could simply write

    if (cleanCount <= 100) { // turn on NO LEDs
        digitalWrite(led1, LOW);
        digitalWrite(led2, LOW);
        ...
    }

    ...

    else if (cleanCount <= 500) { // turn on 4 LEDs
        ...
        digitalwrite(led3, HIGH);
        digitalwrite(led4, HIGH);
        digitalwrite(led5, LOW);
        digitalwrite(led6, LOW);
        ...
    }

but that would be a big pile of code which could be way more efficient. Perhaps.. my code isn't even correct.

So how could this be more efficient or perhaps actually working?

----------

*The whole code, here below.*

    int cleanCount = 1000;
    int softpotPin = A0; //analog pin 0

    void setup () {
     Serial.begin(9600);
     digitalWrite(softpotPin, HIGH); //enable pullup resistor
    }

    void loop() {
     int softpotReading = analogRead(softpotPin);
     if (softpotReading < 980) { // IF AANGERAAKT
      digitalWrite(werktIeLED, HIGH);
      ++cleanCount;
      Serial.println(cleanCount);
      delay(16); // 5x zo snel als leeglopen
     }
     else if (softpotReading > 980) { // IF NIET AANGERAAKT
      digitalWrite(werktIeLED, LOW);
      --cleanCount;
      Serial.println(cleanCount);
      delay(64); // 1000 / 60 seconden
     }
     else {   // Als er een fout optreed..
      Serial.println("Fout!");
      digitalWrite(werktIeLED, HIGH);
      delay(250);
      digitalWrite(werktIeLED, LOW);
      delay(250);
     }

    }

body:
Instead of repeating several calls to `digitalwrite` you should consider changing the pins directly as described [here][1].

This now depends on which port your LEDs are connected to. Assuming port D you would use `DDRD` to define the pins as output (usually in `setup()`) and `PORTD` to set their values (in `loop`), e.g.

    DDRD = B11111110; // define pins 1..7 as outputs, pin 0 as input

and

    PORTD = B11110000; // switch on first 4 LEDs

Now all you need to do is to write a function to map your number range to suitable bit strings.

The function could look like this:

    int convert(int n) {

      int res = 0;   // start with all pins off (zero)
      while (n > 100) {
        res <<= 1;   // shift pattern 1 bit (i.e. pin) to the left
        res |= 1;    // "switch on" lowest pin
        n -= 100;    // defines step size (1 LED for every  100)
      }
      return res;

    }

It takes your value and returns an `int` that you can assign to the port. I.e. for 0..100 it returns `0`, for 101..200 it returns `1`, for 201..300 it returns `3` = `B11`, for 301..400 it returns `7` = `B111` and so on. (Note that it does not do any sanity checks on the input / output but that's certainly easy for you to add if needed.)

(In response to comment: Note that the bit pattern I use as example for `DDRD` above is an example: It sets bit / pin 0 as input. If you use `convert` you would, of course, set the lowest bit of `DDRD` to 1 to make it an output.)

  [1]: http://www.arduino.cc/en/Reference/PortManipulation


body:
Here is a suggestion with the led pins in an array that you loop over.

I suggest making the array global, so put it outside any functions (usually at the top):

    byte led_pins[] = {pin1, pin2, pin3, pin4, pin5, pin6, pin7, pin8};

Then put this in your loop (assumes that you have a `int` called cleanCount that is in scope:

    const int increment = 100;

    for (int i = 0; i < sizeof(led_pins) / sizeof(led_pins[0]); i++) {
      boolean onOrOff = cleanCount > (i+1) * increment;
      digitalWrite(led_pins[i], onOrOff);
    }


body:
You can use the barGraph example from the Arduino code examples. This gives a bar-type graph and not point. I will give rough explination why it will work and the need not to re-invent the wheel.

        int sensorReading = analogRead(analogPin);
      // map the result to a range from 0 to the number of LEDs:
      int ledLevel = map(sensorReading, 0, 1023, 0, ledCount);

      // loop over the LED array:
      for (int thisLed = 0; thisLed < ledCount; thisLed++) {
        // if the array element's index is less than ledLevel,
        // turn the pin for this element on:
        if (thisLed < ledLevel) {
          digitalWrite(ledPins[thisLed], HIGH);
        }
        // turn off all pins higher than the ledLevel:
        else {
          digitalWrite(ledPins[thisLed], LOW);
        }
      }

`int ledLevel = map(sensorReading, 0, 1023, 0, ledCount);`

This will give you the point in the array, 0-10, for 0-1000, if you replace `1023` with `1000`

Simplified `map()` function:

`int point = sensorReading*10/1000` this gives you a range of 0-10, the int keeps it from having decimal points.

As you can see from the for loop it turns on all the LEDs that are in the array to the end and then turns off those not needed.


message:
Why does the ADC overflow when using an external Aref?

I'm using an LM35 temperature sensor, and it outputs 190 mV (which agrees with 19°C). I'm using an external reference voltage which I measure as 417mV. (This is set by the pin "aRefCntrl"). So I should have a reading around 467, but I get 1023, i.e. the ADC overflows. When I use the internal 1.1V reference I get a correct reading. Any ideas?

This is my code (Arduino waits for a request from the PC to send the data):

    #define lm35 A0
    #define aRefCtrl 10

    void setup() {
      pinMode(aRefCtrl, OUTPUT);
      digitalWrite(aRefCtrl, 0);
      analogReference(EXTERNAL);
      analogRead(lm35); // dummy read
      Serial.begin(9600);
    }

    void loop() {
      if ( Serial.available() ) {
        Serial.read(); // PC's request is a single byte
        int temperature = analogRead(lm35);
        Serial.println(temperature);
      }
    }

**follow-up** on Ignacio's comment: would a decoupling capacitor do? (I can't test for the moment, I have to order some)

body:
The minimum reference voltage is 1.0 V according to the atmega328 [datasheet][1]. See table 29-15. ADC Characteristics.

  [1]: http://www.atmel.com/images/Atmel-8271-8-bit-AVR-Microcontroller-ATmega48A-48PA-88A-88PA-168A-168PA-328-328P_datasheet_Complete.pdf


message:
Has anyone modified a 16x2 LCD shield to work with Arduino DUE?

Since the DUE works on 3.3 volts has anyone successfully modified a 5V 16x2 LCD shield to work with Arduino DUE?  I'm thinking 3.3V will be seen as a logic "1"
by the 5V LCD shield and there are no 5V outputs that feed back to the 3.3V due if the R/~W line on the LCD is simply grounded.

Would love to hear anyone's opinion on this.

Thanks,
Charlie

body:
I understand this is an 8yo thread, however my answer might still help someone.
I connected an unmodified no-brand LCD Shield to an Arduino DUE and it works perfectly - the only thing I had to change was the analog thresholds to identify the buttons. Just upload the sketch and read out the real values on the display then enter the averages between adjacent buttons in read_LCD_buttons function.

    //Sample using LiquidCrystal library
    #include <LiquidCrystal.h>

    /*******************************************************

    This program will test the LCD panel and the buttons
    Mark Bramwell, July 2010

    ********************************************************/

    // select the pins used on the LCD panel
    LiquidCrystal lcd(8, 9, 4, 5, 6, 7);

    // define some values used by the panel and buttons
    int lcd_key = 0;
    int adc_key_in = 0;
    #define btnRIGHT 0
    #define btnUP 1
    #define btnDOWN 2
    #define btnLEFT 3
    #define btnSELECT 4
    #define btnNONE 5

    // read the buttons
    int read_LCD_buttons()
    {
    adc_key_in = analogRead(0); // read the value from the sensor

    if (adc_key_in < 90) return btnRIGHT;
    if (adc_key_in < 297) return btnUP;
    if (adc_key_in < 533) return btnDOWN;
    if (adc_key_in < 814) return btnLEFT;
    if (adc_key_in < 1000) return btnSELECT;

    return btnNONE; // when all others fail, return this...
    }

    int button_count=1;

    // Pin 13 has an LED connected on most Arduino boards.
    // give it a name:
    int led = 13;

    int i;

    void setup()
    {
    lcd.begin(16, 2); // start the library
    lcd.setCursor(0,0);
    lcd.print("Push the buttons"); // print a simple message

    // initialize the digital pin as an output.
    pinMode(led, OUTPUT);

    }

    void loop()
    {
      delay(100);
      lcd.setCursor(9,1); // move cursor to second line "1" and 9 spaces over
      lcd.print("        ");
      lcd.setCursor(9,1); // move cursor to second line "1" and 9 spaces over
      lcd.print(analogRead(0)); // display A0 analog input to calibrate values

      lcd.setCursor(0,1); // move to the begining of the second line
      lcd_key = read_LCD_buttons(); // read the buttons

      switch (lcd_key) // depending on which button was pushed, we perform an action
      {
        case btnRIGHT:
            lcd.print("RIGHT ");
            button_count = 2;
            break;

        case btnLEFT:
            lcd.print("LEFT ");
            button_count = 3;
            break;

        case btnUP:
            lcd.print("UP ");
            button_count = 4;
            break;

        case btnDOWN:
            lcd.print("DOWN ");
            button_count = 5;
            break;

        case btnSELECT:
            lcd.print("SELECT");
            button_count = 6;
            break;

        case btnNONE:
            lcd.print("NONE ");
            button_count = 1;
            break;
      }

    }


message:
Arduino turns LEDs off when set 'high', opposite direction as coded

I've got a function that decreases over time (1000 / 60 seconds) and by touching a softPotentiometer you can increase that value. By every increment of 200 a LED is lid. So for 0-200, 1 LED; 201-400, 2 LEDs; etc. And since it decreases over time while doing nothing, if it drops below a certain value, a LED is shut off.

However, I've got a (amateur) coded set up, but somehow it lids the LEDs in the opposite direction. In a way that, I've coded it that if it's above 800, lid 5 LED's. However, it will only lid one LED when it's dropped below the 800, in the area of 601-800.

That's exactly the opposite of what I want. So what am I doing wrong here?

----------

My code:
*And with amateur, I mean that I didn't use arrays and therefor write everything multiple times..*

    int cleanCount = 1000;
    int IsItWorkingLED = 13;
    int softpotPin = A0; //analog pin 0
    int LED1 = 1;
    int LED2 = 2;
    int LED3 = 4;
    int LED4 = 5;
    int LED5 = 7;

    void setup () {
     Serial.begin(9600);
     digitalWrite(softpotPin, HIGH); //enable pullup resistor
            pinMode(1, OUTPUT);
            pinMode(2, OUTPUT);
            pinMode(4, OUTPUT);
            pinMode(5, OUTPUT);
            pinMode(7, OUTPUT);

               digitalWrite(1, HIGH);   // turn the LED on (HIGH is the voltage level)
               digitalWrite(2, HIGH);   // turn the LED on (HIGH is the voltage level)
               digitalWrite(4, HIGH);   // turn the LED on (HIGH is the voltage level)
               digitalWrite(5, HIGH);   // turn the LED on (HIGH is the voltage level)
               digitalWrite(7, HIGH);   // turn the LED on (HIGH is the voltage level)

    }

    void loop() {
     int softpotReading = analogRead(softpotPin);
     if (softpotReading < 980) { // IF TOUCHED
      digitalWrite(IsItWorkingLED, HIGH);
      ++cleanCount;
      Serial.println(cleanCount);
      delay(16); // Drain 5 times as fast
     }
     else if (softpotReading > 980) { // IF NOT DTOUCHED
      digitalWrite(IsItWorkingLED, LOW);
      --cleanCount;
      Serial.println(cleanCount);
      delay(64); // 1000 / 60 seconds
     }
     else {   // Als er een fout optreed..
      Serial.println("Something wrong!");
      digitalWrite(IsItWorkingLED, HIGH);
      delay(250);
      digitalWrite(IsItWorkingLED, LOW);
      delay(250);
     }

            if (cleanCount >= 0 && cleanCount <= 200) {
               Serial.println("Knal 1 LED aan");
               digitalWrite(LED1, HIGH);   // turn the LED on (HIGH is the voltage level)
               digitalWrite(LED2, LOW);   // turn the LED on (HIGH is the voltage level)
               digitalWrite(LED3, LOW);   // turn the LED on (HIGH is the voltage level)
               digitalWrite(LED4, LOW);   // turn the LED on (HIGH is the voltage level)
               digitalWrite(LED5, LOW);   // turn the LED on (HIGH is the voltage level)
            }
            else if (cleanCount >= 201 && cleanCount <= 400) {
               Serial.println("Knal 2 LEDs aan");
               digitalWrite(LED1, HIGH);   // turn the LED on (HIGH is the voltage level)
               digitalWrite(LED2, HIGH);   // turn the LED on (HIGH is the voltage level)
               digitalWrite(LED3, LOW);   // turn the LED on (HIGH is the voltage level)
               digitalWrite(LED4, LOW);   // turn the LED on (HIGH is the voltage level)
               digitalWrite(LED5, LOW);   // turn the LED on (HIGH is the voltage level)
            }
            else if (cleanCount >= 401 && cleanCount <= 600) {
               Serial.println("Knal 3 LEDs aan");
               digitalWrite(LED1, HIGH);   // turn the LED on (HIGH is the voltage level)
               digitalWrite(LED2, HIGH);   // turn the LED on (HIGH is the voltage level)
               digitalWrite(LED3, HIGH);   // turn the LED on (HIGH is the voltage level)
               digitalWrite(LED4, LOW);   // turn the LED on (HIGH is the voltage level)
               digitalWrite(LED5, LOW);   // turn the LED on (HIGH is the voltage level)
            }
            else if (cleanCount >= 601 && cleanCount <= 800) {
               Serial.println("Knal 4 LEDs aan");
               digitalWrite(LED1, HIGH);   // turn the LED on (HIGH is the voltage level)
               digitalWrite(LED2, HIGH);   // turn the LED on (HIGH is the voltage level)
               digitalWrite(LED3, HIGH);   // turn the LED on (HIGH is the voltage level)
               digitalWrite(LED4, HIGH);   // turn the LED on (HIGH is the voltage level)
               digitalWrite(LED5, LOW);   // turn the LED on (HIGH is the voltage level)
            }
            else if (cleanCount >= 801 && cleanCount <= 1000) {
               Serial.println("Knal 5 LEDs aan");
               digitalWrite(1, HIGH);   // turn the LED on (HIGH is the voltage level)
               digitalWrite(2, HIGH);   // turn the LED on (HIGH is the voltage level)
               digitalWrite(4, HIGH);   // turn the LED on (HIGH is the voltage level)
               digitalWrite(5, HIGH);   // turn the LED on (HIGH is the voltage level)
               digitalWrite(7, HIGH);   // turn the LED on (HIGH is the voltage level)
            }
            else {
              Serial.println("Just..do nothing");
            }

    }

body: If your LEDs are connected anode to +5, cathode to i/o pin, they would behave this way. Cathode to ground, anode to i/o would behave as you expect.


body:
Try reversing the if statements.
You say:
> I've coded it that if it's above 800, lid 5 LED's.

And your code is:
`(softpotReading < 980) { // IF TOUCHED`

The code describes: `IF softpotReading IS SMALLER THAN 980, DO{ code.. }`

----------

In dutch (as OP is dutch, and to be honest his English somehow confuses me a bit, to be sure it's not the other way around also):

Ik denk dat je de IF statements verkeerd om hebt.
Je beschrijft dat bij een waarde hoger dan 800 de ledjes aan gaan...

Echter staat in je code `(softpotReading < 980) { // IF TOUCHED`
Wat dus zal betekenen dat de code wordt uitgevoerd als die < (kleiner dan) 980 is.

----------

        if (softpotReading > 980) { // IF TOUCHED
        digitalWrite(IsItWorkingLED, HIGH);
        ++cleanCount;
        Serial.println(cleanCount);
        delay(16); // Drain 5 times as fast
    }
    else if (softpotReading <= 980) { // IF NOT DTOUCHED
        digitalWrite(IsItWorkingLED, LOW);
        --cleanCount;
        Serial.println(cleanCount);
        delay(64); // 1000 / 60 seconds
    }


message:
Use same ground with 2 wires?

So I have 3 ground pins, but I need 4 motors on my Arduino. Can I connect multiple motors to the same ground pin?

body: You can do it as long as the current isn't excessive. I don't think there are any specs available, but the connector and the width / thickness of the copper tracks on the PCB will be the limiting factor.


body:
All ground is internal connected.<br>
But anyway, you CANNOT use the Arduino's power to power a motor, you will need an external power source.And again, you will connect the external power source's ground to the Arduino's ground.


body: You can connect multiple components to a single ground pin.  IF you are using a breadboard, be sure to put the wire going to the go


message:
trying to delay between sequences

I am trying to build a set of four stars using an Arduino, potentiometer and a four channel relay to control how fast it speeds across the stars. My question is how can I delay the process, say for 20 or 30 seconds before it starts again?

body:
[`delay()`][1]:

    delay(20000); // wait for 20 seconds

  [1]: http://arduino.cc/en/pmwiki.php?n=Reference/Delay


body:
Use Delay(  ).
Or this code<br>

    long previousMillis;

    void setup(){
      previousMillis = millis();//in void setup
      bool lS=LOW;//in void setup
    }

    void loop(){
      long currentMillis= millis();//in void loop

      if(currentMillis-previousMillis>=20000){
         if (lS==LOW){
           digitalWrite(pinNo,HIGH);
           lS=HIGH;
         }
         else
         {
           digitalWrite(pinNo,LOW);
           lS=LOW;
         }
         previousMillis= millis();
      }
      delay(1);
    }

While this does not serve your purpose, it shows you an how to switch on and off and LED after every 20 sec without keeping the Arduino idle for 20 sec.You could improve on it and make your own code.


body:
If you want to just provide a delay use this function

    delay(ms) -> where the argument is an integer value that represents the time in milliseconds.

For example, 1s = 1000ms

If you wanna stop everything and wait 1s, just use like that:

    delay(1000);

Note that the atmega controller will stop everything it is doing and wait the amount of time. If you need to count or wait for something while other things are occurring, use timer interrupts. So the counting process is done in background and your main loop continues to do its jobs.


message:
Serial Monitor breaks normal behaviour of Nano + NRF24l01

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

Couldn't find any other post that mentions Serial Monitor crippling the normal workflow of the NRF24l01, so here it goes.

I have two Arduino Nano, both with NRF24l01 attached, and an RF24 library working. Both NRF24l01 have 10uF caps soldered on them. One is only sending data, another is receiving only. Both of them flash LED on, successful transmission and successful receiving respectively.

When I run both devices, i see both LEDs flashing, so one succeeds in sending, and another one in receiving. But whenever I try to open Serial Monitor in my Arduino 1.6.1 software, the LEDs flash only every forth of fifth time of expected, and in my Serial Monitor I can see only 1 of 4 or 5 packets received (though received correctly).

Any ideas what I could have done wrong? Could Serial Monitor somehow interfere with Nano talking to NRF24l01?

The code follows, it's simple.

Sender

        /*
         Copyright (C) 2011 J. Coliz <maniacbug@ymail.com>

         This program is free software; you can redistribute it and/or
         modify it under the terms of the GNU General Public License
         version 2 as published by the Free Software Foundation.
         */

        #include <SPI.h>
        #include "nRF24L01.h"
        #include "RF24.h"
        #include "printf.h"

        // On Successfull Sending Blink PIN

        #define BLPIN 5

        //
        // Hardware configuration
        //

        // Set up nRF24L01 radio on SPI bus plus pins 9 & 10

        RF24 radio(9,10);

        //
        // Topology
        //

        // Radio pipe addresses for the 2 nodes to communicate.
        const uint64_t pipe = 0xF0F0F0F0E1LL;

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

          //
          // Print preamble
          //

          Serial.begin(57600);
          printf_begin();
          printf("\n\rRF24/examples/GettingStarted/\n\r");

          //
          // Setup and configure rf radio
          //

          radio.begin();

          // optionally, increase the delay between retries & # of retries
          radio.setRetries(15,15);

          // optionally, reduce the payload size.  seems to
          // improve reliability
          radio.setPayloadSize(8);

          //
          // Open pipes to other nodes for communication
          //

          radio.openWritingPipe(pipe);

          //
          // Dump the configuration of the rf unit for debugging
          //

          radio.printDetails();
        }

        // counter data to be sent
        unsigned long counter = 0;

        void loop(void)
        {

          // Increase the counter and send it
          counter++;
          printf("Sending counter = %lu...", counter);

          if (radio.write( &counter, sizeof(unsigned long) ))
          {
            printf("ok...\n\r");
            digitalWrite(BLPIN, HIGH);
            delay(10);
            digitalWrite(BLPIN, LOW);
          }
          else
            printf("failed.\n\r");

          // Try again 1s later
          delay(1000);
        }

Receiver

  /*
   Copyright (C) 2011 J. Coliz <maniacbug@ymail.com>

   This program is free software; you can redistribute it and/or
   modify it under the terms of the GNU General Public License
   version 2 as published by the Free Software Foundation.
   */

  #include <SPI.h>
  #include "nRF24L01.h"
  #include "RF24.h"
  #include "printf.h"

  // On Receiver Blink PIN

  #define BLPIN 5

  //
  // Hardware configuration
  //

  // Set up nRF24L01 radio on SPI bus plus pins 9 & 10

  RF24 radio(9,10);

  //
  // Topology
  //

  // Radio pipe addresses for the 2 nodes to communicate.
  const uint64_t pipe = 0xF0F0F0F0E1LL;

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

    //
    // Print preamble
    //

    Serial.begin(57600);
    printf_begin();
    printf("\n\rRF24/examples/GettingStarted/\n\r");

    //
    // Setup and configure rf radio
    //

    radio.begin();

    // optionally, increase the delay between retries & # of retries
    radio.setRetries(15,15);

    // optionally, reduce the payload size.  seems to
    // improve reliability
    radio.setPayloadSize(8);

    //
    // Open pipes to other nodes for communication
    //

    radio.openReadingPipe(1,pipe);

    //
    // Start listening
    //

    radio.startListening();

    //
    // Dump the configuration of the rf unit for debugging
    //

    radio.printDetails();
  }

  unsigned long counter;

  void loop(void)
  {
    // if there is data ready
    if (radio.available())
    {
      while( radio.available() ) {
        radio.read( &counter, sizeof(unsigned long) );
        // Dump the payloads until we've gotten everything
        printf("Got payload %lu...\n\r", counter);
      }
      digitalWrite(BLPIN, HIGH);
      delay(10);
      digitalWrite(BLPIN, LOW);
    }
  }

body:
The reason for the Monitor being unable to work properly seems to be the length of the usb cable or a faulty usb port on my computer. I had a usb-cable extender, to which another (this time short) usb cable of my Arduino Nano was attached. It seemed to work fine while I was uploading things to Nano, but a quick serial exchange was, perhaps, not possible.Another usb port, or bypassing the usb cable extender brings everything back to normal.

This is a solution, while I still had no reason, how debugging through serial could influence that much on the chip behaviour itself, until now. I just thought it may well be the same power problem, as FTDI chip both powers the radio (even with the capacitor I installed!) and talks to computer through my long usb cable. If it starts talking, there could be no power for RF24 for a longer period than could be saved by my capacitor.


message:
A LED should be lit when 'high'. Why does mine only burn with 'low'?

This is my followup question based on a serie of one project. Go my to profile to read 'm all.

So I'm building something which includes a function that has a count (1000) that decreases over time, but by pressing a soft pot meter the count increases. By every increment of 200 one LED is lit. So if the count is 837 4 LEDs are burning.

In my previous question I had issues lighting the LEDs, because they didn't burn even when the code was, as far as I could see correct. Instead it did the opposite of what I coded. Now I changed my code the opposite direction,

writing:

> digitalWrite(LED1, LOW);   // turn the LED on (LOW is the voltage level)

Which actually set the LED to bright. While is I'd write it 'HIGH' it would dim.

So my actual question is: How could my LED be lit if it's set to 'low', while you have to set it to 'high' to be actually popping off light?

----------

***My complete code:***

    int cleanCount = 1000;
    int IsItWorkingLED = 13;
    int softpotPin = A0; //analog pin 0
    int LED1 = 1;
    int LED2 = 2;
    int LED3 = 4;
    int LED4 = 5;
    int LED5 = 7;

    void setup () {
     Serial.begin(9600);
     digitalWrite(softpotPin, HIGH); //enable pullup resistor
     pinMode(LED1, OUTPUT);
     pinMode(LED2, OUTPUT);
     pinMode(LED3, OUTPUT);
     pinMode(LED4, OUTPUT);
     pinMode(LED5, OUTPUT);

     digitalWrite(LED1, HIGH);   // turn the LED on (HIGH is the voltage level)
     digitalWrite(LED2, HIGH);   // turn the LED on (HIGH is the voltage level)
     digitalWrite(LED3, HIGH);   // turn the LED on (HIGH is the voltage level)
     digitalWrite(LED4, HIGH);   // turn the LED on (HIGH is the voltage level)
     digitalWrite(LED5, HIGH);   // turn the LED on (HIGH is the voltage level)
    }

    void loop() {
     int softpotReading = analogRead(softpotPin);
     if (softpotReading < 980) { // IF TOUCHED
      digitalWrite(IsItWorkingLED, HIGH);
      ++cleanCount;
      Serial.println(cleanCount);
      delay(8); // Increase 5 times as fast
     }
     else if (softpotReading > 980) { // IF NOT TOUCHED
      digitalWrite(IsItWorkingLED, LOW);
      --cleanCount;
      Serial.println(cleanCount);
      delay(32); // Decrease slowly
     }
     else {   // If there is something wrong..
      Serial.println("Something wrong!");
      digitalWrite(IsItWorkingLED, HIGH);
      delay(250);
      digitalWrite(IsItWorkingLED, LOW);
      delay(250);
     }

      if (cleanCount <= 200) {
       Serial.println("Knal 1 LED aan");
       digitalWrite(LED1, LOW);   // turn the LED on (LOW is the voltage level)
       digitalWrite(LED2, HIGH);   // turn the LED on (LOW is the voltage level)
       digitalWrite(LED3, HIGH);   // turn the LED on (LOW is the voltage level)
       digitalWrite(LED4, HIGH);   // turn the LED on (LOW is the voltage level)
       digitalWrite(LED5, HIGH);   // turn the LED on (LOW is the voltage level)
      }
      else if (cleanCount >= 201 && cleanCount <= 400) {
       Serial.println("Knal 2 LEDs aan");
       digitalWrite(LED1, LOW);   // turn the LED on (LOW is the voltage level)
       digitalWrite(LED2, LOW);   // turn the LED on (LOW is the voltage level)
       digitalWrite(LED3, HIGH);   // turn the LED on (LOW is the voltage level)
       digitalWrite(LED4, HIGH);   // turn the LED on (LOW is the voltage level)
       digitalWrite(LED5, HIGH);   // turn the LED on (LOW is the voltage level)
      }
      else if (cleanCount >= 401 && cleanCount <= 600) {
       Serial.println("Knal 3 LEDs aan");
       digitalWrite(LED1, LOW);   // turn the LED on (LOW is the voltage level)
       digitalWrite(LED2, LOW);   // turn the LED on (LOW is the voltage level)
       digitalWrite(LED3, LOW);   // turn the LED on (LOW is the voltage level)
       digitalWrite(LED4, HIGH);   // turn the LED on (LOW is the voltage level)
       digitalWrite(LED5, HIGH);   // turn the LED on (LOW is the voltage level)
      }
      else if (cleanCount >= 601 && cleanCount <= 800) {
       Serial.println("Knal 4 LEDs aan");
       digitalWrite(LED1, LOW);   // turn the LED on (LOW is the voltage level)
       digitalWrite(LED2, LOW);   // turn the LED on (LOW is the voltage level)
       digitalWrite(LED3, LOW);   // turn the LED on (LOW is the voltage level)
       digitalWrite(LED4, LOW);   // turn the LED on (LOW is the voltage level)
       digitalWrite(LED5, HIGH);   // turn the LED on (LOW is the voltage level)
      }
      else if (cleanCount >= 801 && cleanCount <= 1000) {
       Serial.println("Knal 5 LEDs aan");
       digitalWrite(1, LOW);   // turn the LED on (LOW is the voltage level)
       digitalWrite(2, LOW);   // turn the LED on (LOW is the voltage level)
       digitalWrite(4, LOW);   // turn the LED on (LOW is the voltage level)
       digitalWrite(5, LOW);   // turn the LED on (LOW is the voltage level)
       digitalWrite(7, LOW);   // turn the LED on (LOW is the voltage level)
      }
      else {
       Serial.println("Just..do nothing");
      }

    }

body:
Your assumption that a high is required to light a LED is false. All you need is to meet certain minimum voltage and current thresholds. Since the anode of the LED is tied high, the way to meet these is to bring the cathode low.

![LED symbol][1]

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


body:
When you command digitalWrite LOW you are basically connecting that pin to GND.  If you command digitalWrite HIGH then you are connecting that pin to +5v.  So depending on how you have the LED wired up you can use either to turn on the LED.  Since LOW turns your LED on then you must have the long lead of the LED attached to +5v supply and the short lead to the pin on the arduino.  I don't know why the LED doesn't turn all the way off when you command digitalWrite HIGH, but it should.

If you wanted to dim the leds then you should try using the analogWrite command which will send a PWM signal and will allow you to make the LEDs any intensity you want to.


body:
An LED wants positive voltage to flow from the anode to the cathode (the + terminal to the - terminal)

You can wire it to a digital pin 2 different ways. (In both cases you'll also need a current limiting resistor to avoid burning out your LED and/or your digital pin, but ignore that for this discussion.)

You can wire the positive terminal of the LED to +5V, and the negative terminal to a digital pin. It sounds like this is what you've done. When you do that, if you set the digital output to HIGH, then both terminals of the LED are connected to +5V, so the LED will be off. Set the output to LOW, and it gets connected to ground. Now current flows out of the +5V rail, through the LED, into the grounded digital pin, and the LED lights up.

You can reverse that wiring instead. Connect the positive terminal of the LED to a digital pin and the negative side to ground. Now, when you set the pin to HIGH, +5V flows out of the pin, through the LED, and into the ground connection, so the LED lights. Set the pin to LOW and both sides of the LED are connected to ground, so it turns off.

# Edit:

Note that you talk about voltage levels and dimming LEDs. If you're using digital outputs and HIGH or LOW, you can only turn the LED on or off. There's no way to vary its brightness.

You can, however, hook an LED to a PWM (Pulse Width Modulation) pin and set up that pin for analog output. In PWM, the Arduino switches the LED on and off rapidly. Set it to the highest output value, 255, and the LED stops flashing and is on 100% o the time. Set the output to 128, and the LED is on half the time and off half the time. Set the output to 64, and the LED is on 1/4 of the time and off 3/4 of the time, and so on.

When you flash a light fast enough, our eyes average out the brightness, and a light that's on 1/4 of the time looks 1/4 as bright as a light that's on 100% of the time.

Most Arduinos have a limited number of analog outputs. The Arduino model you're using might not have 7 analog outputs.


message:
Uploading over Bluetooth Low Energy - bootloader not responding

I'm working on sketches uploading over BLE. I had to write my own uploader (looking at avrdude sources with one eye) so i can change uploading behaviour as needed and it's working over USB just perfect but it does not get response from bootloader if trying over Bluetooth LE.

My hardware:

 - Arduino Uno (and i'm having Arduino Mega2560)
 - HM-10 BLE module

As HM-10 does not support DTR/RTS i had to add my own software reboot:

In brief: it reads incoming bytes on interrupt event and compares to reset command passed in ble_setup. If it's equal then it uses watchdog timer to reboot the board. If it's not equal it stores byte in byffer, then sketch loop() just returns incoming byes back ("echo").

    #include <avr/wdt.h>

    const char *ble_reset_cmd;
    int ble_reset_index = 0;
    int ble_available = 0;       // chars available
    int ble_byte;                // income buffer as 1 char
    int *ble_bytes = &ble_byte;  // income buffer
    boolean delete_ble_bytes = false;

    //#define BLE_DEBUG

    // reboot Arduino board using Watchdog timer
    void reboot() {
    //    #ifdef BLE_DEBUG
        Serial.println("rebooting ...");
    //    #endif

    //    digitalWrite(13, HIGH);
    //    delay(2000);

        wdt_enable(WDTO_15MS);
        while(1) { };
    }

    void ble_setup(int baud, const char *reset_cmd) {
        Serial.begin(baud);
        ble_reset_cmd = reset_cmd;
    }

    int Serial_available() {
        return ble_available;
    }

    int Serial_read() {
        if (ble_available < 0)
            return -1;

        int inByte = ble_bytes[--ble_available];
        if (ble_available == 0 && delete_ble_bytes) {
            // restore buffer as 1 char buffer
            delete[] ble_bytes;
            ble_bytes = &ble_byte;
            delete_ble_bytes = false;
        }
        return inByte;
    }

    void serialEvent() {
        if (Serial.available() <= 0)
            return;

        int inByte = Serial.read();
        if (inByte == ble_reset_cmd[ble_reset_index]) {
            // entered char is cmd character

            if (ble_reset_cmd[++ble_reset_index] == 0)
                reboot();

            #ifdef BLE_DEBUG
            Serial.write("ble_index = ");
            Serial.print((byte)ble_reset_index);
            Serial.write('\n');
            #endif

        } else {
            // entered char is NOT cmd character

            if (ble_reset_index > 0) {
                // got character not from cmd, so we should to return characters
                // starting ble_reset_cmd until current index and then this character

                ble_available = ble_reset_index + 1;
                ble_reset_index = 0;

                #ifdef BLE_DEBUG
                Serial.print("Copy ");
                Serial.print((byte)(ble_available - 1));
                Serial.println(" bytes");
                #endif

                // recreate input buffer using cmd characters
                ble_bytes = new int[ble_available + 1];
                delete_ble_bytes = true;
                ble_bytes[0] = inByte;
                for (int i=0; i<(ble_available-1); i++) {
                  ble_bytes[i + 1] = ble_reset_cmd[ble_available - i - 2];
                }
                ble_bytes[ble_available] = 0; // null-terminated array

                #ifdef BLE_DEBUG
                Serial.print("input buffer now contains ");
                Serial.print(ble_available);
                Serial.println(" bytes");
                #endif

            } else {

                #ifdef BLE_DEBUG
                Serial.println("ble_index = 0");
                #endif

                // pass inByte next ...
                ble_available++;
                ble_byte = inByte;
            }

        }
    }

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

    int led = 13;
    int ledHIGH = 0;

    void setup() {
      ble_setup(9600, "AT+RESET");
      Serial.print("ready\n");
      pinMode(led, OUTPUT);
    }

    void loop() {
      while (Serial_available() > 0) {
        int inByte = Serial_read();

    //    Serial.write('>');
    //    Serial.write(inByte);
    //    Serial.write('\n');
        ledHIGH = 1- ledHIGH;
        digitalWrite(led, ledHIGH);
        Serial.write(inByte); // echo
      }
    }

As i said it's working good for USB uploading:
right after rebooting bootloader waits for upload commands and start to reply:

    015-04-07 21:22:10.860 Apploader[11226:303] Apploader v0.1
    2015-04-07 21:22:12.772 Apploader[11226:303] DTR/RTS supported by Serial, resetting
    2015-04-07 21:22:13.075 Apploader[11226:303] draining ...
    2015-04-07 21:22:13.327 Apploader[11226:303] drain done
    2015-04-07 21:22:13.328 Apploader[11226:303] Send: 0 [0x30]   [0x20]
    2015-04-07 21:22:13.328 Apploader[11226:303] draining ...
    2015-04-07 21:22:13.723 Apploader[11226:303] drain done
    2015-04-07 21:22:13.724 Apploader[11226:303] Send: 0 [0x30]   [0x20]
    2015-04-07 21:22:13.724 Apploader[11226:303] draining ...
    2015-04-07 21:22:13.977 Apploader[11226:303] drain done
    2015-04-07 21:22:13.978 Apploader[11226:303] Send: 0 [0x30]   [0x20]
    2015-04-07 21:22:13.979 Apploader[11226:303] Recv: . [0x14]
    2015-04-07 21:22:13.980 Apploader[11226:303] Recv: . [0x10]
    2015-04-07 21:22:13.980 Apploader[11226:303] Send: A [0x41]  . [0x81]   [0x20]
    2015-04-07 21:22:13.984 Apploader[11226:303] Recv: . [0x14]
    2015-04-07 21:22:13.984 Apploader[11226:303] Recv: . [0x04]
    2015-04-07 21:22:13.985 Apploader[11226:303] Recv: . [0x10]
    2015-04-07 21:22:13.985 Apploader[11226:303] Send: A [0x41]  . [0x82]   [0x20]
    2015-04-07 21:22:13.988 Apploader[11226:303] Recv: . [0x14]
    2015-04-07 21:22:13.988 Apploader[11226:303] Recv: . [0x04]
    2015-04-07 21:22:13.989 Apploader[11226:303] Recv: . [0x10]
    2015-04-07 21:22:13.989 Apploader[11226:303] Send: B [0x42]  . [0x86]  . [0x00]  . [0x01]  . [0x00]  . [0x01]  . [0x01]  . [0x01]  . [0x03]  . [0xff]  . [0xff]  . [0xff]  . [0xff]  . [0x00]  . [0x80]  . [0x04]  . [0x00]  . [0x00]  . [0x00]  . [0x80]  . [0x00]   [0x20]
    2015-04-07 21:22:13.996 Apploader[11226:303] Recv: . [0x14]
    2015-04-07 21:22:13.997 Apploader[11226:303] Recv: . [0x10]
    2015-04-07 21:22:13.997 Apploader[11226:303] Send: E [0x45]  . [0x05]  . [0x04]  . [0xd7]  . [0xc2]  . [0x00]   [0x20]
    2015-04-07 21:22:14.000 Apploader[11226:303] Recv: . [0x14]
    2015-04-07 21:22:14.001 Apploader[11226:303] Recv: . [0x10]
    2015-04-07 21:22:14.003 Apploader[11226:303] Send: P [0x50]   [0x20]
    2015-04-07 21:22:14.004 Apploader[11226:303] Recv: . [0x14]
    2015-04-07 21:22:14.008 Apploader[11226:303] Recv: . [0x10]

But when trying over BLE bootloader stops listening in 200ms and then launches sketch, i can see sketch setup() started as it prints "ready". Also i can see it actually reboots the board as it sends "rebooting".

    015-04-07 21:23:30.287 Apploader[11253:303] Apploader v0.1
    2015-04-07 21:23:30.296 Apploader[11253:1503] CBCentralManager state is 5
    2015-04-07 21:23:31.297 Apploader[11253:303] BleSerialDevice: open()
    2015-04-07 21:23:31.298 Apploader[11253:303] Waiting for peripheral to be discovered ...
    2015-04-07 21:23:31.591 Apploader[11253:1503] Found peripheral: <CBPeripheral: 0x100401940 identifier = D92ECAAB-51A5-44D5-8C6C-536CD797867E, Name = "Ardu", state = disconnected>
    2015-04-07 21:23:31.593 Apploader[11253:1503] Stop scanning
    2015-04-07 21:23:31.595 Apploader[11253:1503] Connecting to <CBPeripheral: 0x100401940 identifier = D92ECAAB-51A5-44D5-8C6C-536CD797867E, Name = "Ardu", state = disconnected>
    2015-04-07 21:23:32.025 Apploader[11253:1503] Connected to peripheral <CBPeripheral: 0x100401940 identifier = D92ECAAB-51A5-44D5-8C6C-536CD797867E, Name = "Ardu", state = connected>
    2015-04-07 21:23:32.041 Apploader[11253:1503] Discovered services for peripheral <CBPeripheral: 0x100401940 identifier = D92ECAAB-51A5-44D5-8C6C-536CD797867E, Name = "Ardu", state = connected>
    2015-04-07 21:23:32.042 Apploader[11253:1503] Discovered service <CBService: 0x103701450>
    2015-04-07 21:23:32.043 Apploader[11253:1503] Discovered service <CBService: 0x1037015f0>
    2015-04-07 21:23:32.043 Apploader[11253:1503] Discovered service <CBService: 0x103701630>
    2015-04-07 21:23:32.044 Apploader[11253:1503] Discovered characteristics for service <CBService: 0x103701630>
    2015-04-07 21:23:32.044 Apploader[11253:1503] Discovered characteristic <CBCharacteristic: 0x1037005c0>
    2015-04-07 21:23:32.045 Apploader[11253:1503] Subscribed to Rx value
    2015-04-07 21:23:32.046 Apploader[11253:303] Connected successfully
    2015-04-07 21:23:33.342 Apploader[11253:303] BleSerialDevice: open()
    2015-04-07 21:23:33.343 Apploader[11253:303] already connected, exiting
    2015-04-07 21:23:33.343 Apploader[11253:303] DTR/RTS supported by Serial, resetting
    2015-04-07 21:23:33.594 Apploader[11253:303] Within interval
    2015-04-07 21:23:33.595 Apploader[11253:303] Perform reset
    2015-04-07 21:23:33.596 Apploader[11253:303] Send: A [0x41] T [0x54] + [0x2b] R [0x52] E [0x45] S [0x53] E [0x45] T [0x54]
    2015-04-07 21:23:33.647 Apploader[11253:303] Skip draining after reset
    2015-04-07 21:23:33.648 Apploader[11253:303] Send: 0 [0x30]   [0x20]
    2015-04-07 21:23:33.648 Apploader[11253:303] Draining for 200 ms ...
    2015-04-07 21:23:33.649 Apploader[11253:303] Start reading
    2015-04-07 21:23:33.712 Apploader[11253:1503] Rx value received 15 bytes: r [0x72] e [0x65] b [0x62] o [0x6f] o [0x6f] t [0x74] i [0x69] n [0x6e] g [0x67]   [0x20] . [0x2e] . [0x2e] . [0x2e] . [0x0d] . [0x0a]
    2015-04-07 21:23:33.713 Apploader[11253:1503] _characterRead = true
    2015-04-07 21:23:33.780 Apploader[11253:1503] Rx value received 6 bytes: r [0x72] e [0x65] a [0x61] d [0x64] y [0x79] . [0x0a]
    2015-04-07 21:23:33.780 Apploader[11253:1503] _characterRead = true
    2015-04-07 21:23:33.850 Apploader[11253:303] Finish reading
    2015-04-07 21:23:33.851 Apploader[11253:303] Drained 21 bytes
    2015-04-07 21:23:33.852 Apploader[11253:303] Send: 0 [0x30]   [0x20]
    2015-04-07 21:23:33.853 Apploader[11253:303] Draining for 200 ms ...
    2015-04-07 21:23:33.853 Apploader[11253:303] Start reading
    2015-04-07 21:23:33.982 Apploader[11253:1503] Rx value received 2 bytes: 0 [0x30]   [0x20]
    2015-04-07 21:23:33.983 Apploader[11253:1503] _characterRead = true
    2015-04-07 21:23:34.054 Apploader[11253:303] Finish reading
    2015-04-07 21:23:34.055 Apploader[11253:303] Drained 2 bytes
    2015-04-07 21:23:34.056 Apploader[11253:303] Send: 0 [0x30]   [0x20]
    2015-04-07 21:23:34.056 Apploader[11253:303] Reading 1 bytes ...
    2015-04-07 21:23:34.057 Apploader[11253:303] Start reading
    2015-04-07 21:23:34.057 Apploader[11253:303] _characterRead = false
    2015-04-07 21:23:34.184 Apploader[11253:1503] Rx value received 1 bytes: . [0x00]
    2015-04-07 21:23:34.185 Apploader[11253:1503] _characterRead = true
    2015-04-07 21:23:34.186 Apploader[11253:303] Finish reading
    2015-04-07 21:23:34.186 Apploader[11253:1503] Rx value received 2 bytes: 0 [0x30]   [0x20]
    2015-04-07 21:23:34.186 Apploader[11253:1503] _characterRead = true
    2015-04-07 21:23:34.186 Apploader[11253:303] Recv: . [0x00]
    2015-04-07 21:23:34.187 Apploader[11253:303] stk500_getsync() attempt 1 of 5: not in sync: resp=0x00

Once again - bootloader stops listening in 200 ms instead of 1-1.5 secons as over USB:

    2015-04-07 21:23:33.596 Apploader[11253:303] Send: A [0x41] T [0x54] + [0x2b] R [0x52] E [0x45] S [0x53] E [0x45] T [0x54]
    ...
    2015-04-07 21:23:33.780 Apploader[11253:1503] Rx value received 6 bytes: r [0x72] e [0x65] a [0x61] d [0x64] y [0x79] . [0x0a]

I expect bootloader to reply with 0x14 0x10 as over USB:

    2015-04-07 21:22:13.978 Apploader[11226:303] Send: 0 [0x30]   [0x20]
    2015-04-07 21:22:13.979 Apploader[11226:303] Recv: . [0x14]
    2015-04-07 21:22:13.980 Apploader[11226:303] Recv: . [0x10]

As you can see later communication over Bluetooth is working good, as i receive exactly what was sent (0x30 0x20)

So when sketch is launched it's ok.

My ideas what's wrong:

  1. baud rate

Since serial.begin(N) is invoked after bootloader stops and launch sketch bootloader by default uses another baud rate? Is it correct? HM-10 default daud rate is 9600 and in sketch i also use 9600.

  2. wrong wire connection?

Bluetooth-arduino:
rx -> tx
tx -> rx
Since its working for sketch i believe it's ok. Do i need any capacitors or resistors?

Any thoughts are highly appreciated!

**UPDATE**:

It seems i've found [Uno bootloader source code][1] and bootloader baud rate is 19200 by default

    /* set the UART baud rate */
    /* 20060803: hacked by DojoCorp */
    //#define BAUD_RATE   115200
    #ifndef BAUD_RATE
    #define BAUD_RATE   19200
    #endif

**UPDATE2**:

I'm in stuck as in this tutorial 115200 is used:
http://makezine.com/projects/diy-arduino-bluetooth-programming-shield/

in step 8. "build the programmer circuit" R1 2.2K is set on arduino rx pin. Why? Another thing i can't understand is that SoftwareSerial baud rate is set to 38400 but BT module baud rate is set 115200 using "AT" command. why?

  [1]: https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/bootloaders/atmega/ATmegaBOOT_168.c

body:
It seems that's [the reason][1] why bootloader does not wait:

    // Check if the WDT was used to reset, in which case we dont bootload and skip straight to the code. woot.
     if (! (ch &  _BV(EXTRF))) // if its a not an external reset...
      app_start();  // skip bootloader

Now i have another question ;) How to reboot arduino board from the sketch to jump into bootloader waiting for upload command?

  [1]: https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/bootloaders/atmega/ATmegaBOOT_168.c#L286


body:
The bootloader used on the Uno is [optiboot][1]. But it contains the same "feature" of skipping straight to the application program if the reset source wasn't external.

You could remove this feature and reprogram the bootloader to the chip (using an external programmer).

Alternatively you can use a dirty trick, and jump into the bootloader right after this check of the reset source happens. It happens to be right in the beginning, so not much has happened. The problem is that optiboot makes the assumption that the system is in a freshly reset state. So either you can write a flag to EEPROM to indicate that you just made an intentional WDT reset, or you can jump and hope for the best(not really recomendable).

You could also write a routine to reset the system to the same state as after a reset. But it might not be trivial since there are a lot of reserved memory addresses that Atmel (the manufacturer of AVR's the microcontroller used on the uno, mega, and others) recommends you never write to. So basically you would have to more or less manually set a lot of registers to their reset default (usually zero), in the right order (eg. first tri-state / set pins to input).

You can jump to the bootloader using this inline assembler code:

    asm volatile ("jmp 0x7e00");

Optiboot fits in 512 bytes = 256 AVR words. The bootloader address can be found in the [datasheet][2] Table 27-13. Boot Size Configuration, ATmega328/328P. It is printed in the datasheet as the word address, but the avr-as assembler takes the byte address. Word address 0x3f00 * 2 = 0x7e00 byte address.

You can also see the address in [optiboot_atmega328.lst][3] where code starts at byte address 0x7e00.

In order to jump past the boot source check we find the first address in optiboot_atmega328.lst that comes after the check. It is 0x7e0a. We then modify our bootloader jump:

    asm volatile ("jmp 0x7e0a");

You will want to make this jump first thing after a reset. We want to skip the Arduino initialization code. As per suggestion by user [Comintern][4] in another question you can write a `main` routine with a longer prototype to make the linker prefer it over the one shipped with Arduino:

    int main(int argc, char** argv) {
      if (/* is your bootloader reset flag set in EEPROM */) {
        // first clear the flag
        // ...

        // Jump to bootloader, after reset source check (optiboot on atmega328)
        asm volatile ("jmp 0x7e0a");
      }

      // Else proceed same as Arduino main
      init();

      #if defined(USBCON)
          USBDevice.attach();
      #endif

      setup();

      //The one shot loop...
      loop();
      if (serialEventRun) serialEventRun();
      //Put whatever else you need to do between before the unending loop here.

      for (;;) {
          loop();
          if (serialEventRun) serialEventRun();
      }

      return 0;
    }

Note:

Using these jumps depends on your bootloader being exactly the one referenced. AFAIK that is the one the Uno ships with, but that could change in the future.

The code is untested.

The `main` overwrite trick depends on the linker exhibiting this behaviour which I think is also prone to change (it could be guaranteed by c/c++ standard, I don't know that).

  [1]: https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/bootloaders/optiboot/optiboot.c
  [2]: http://www.atmel.com/images/Atmel-8271-8-bit-AVR-Microcontroller-ATmega48A-48PA-88A-88PA-168A-168PA-328-328P_datasheet_Complete.pdf
  [3]: https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/bootloaders/optiboot/optiboot_atmega328.lst
  [4]: https://arduino.stackexchange.com/users/8216/comintern


message:
Arduino Mega 2560: Busted Atmega 16U2

I just bought an Arduino Mega2560 R3 and it doesn't connect to my Laptop. The connection is somewhat random, sometimes it connects and sometimes it doesn't.

Can someone help me identify whats the problem?

When it gets connected I can upload sketches.

I would like to remove the Atmega 16U2 and replace it with ftdi USB to Serial, would it be possible?

body:
You can use your USB/Serial adapter to program the 2560 as the Arduino uses the 16u2 as the same thing to program the mega. You shouldn't remove the 16u2, just wait till you get the programmers and reflash the 16u2 with its firmaware and it will work, I actually had the same problem where the DFU didn't work and the 16u2 stopped responding, after reflashing the firmware it worked. The firmaware can be found under(as of 1.6.0):

`...\Arduino\hardware\arduino\avr\firmwares\atmegaxxu2\MEGA-dfu_and_usbserial_combined.hex`

You need to connect the Serial pins on the FTDI and Mega in the below fashion:

     FTDI           MEGA
     GND<----------->GND
     CTS<----------->GND
     VCC<----------->VCC
     TXD<----------->RX0
     RXD<----------->TX0
     RTS/DTR<---||-->RST

The Capacitor between the `DTR` pin and `RST` pin are needed this should be 100nF.

![enter image description here][1]
> I have bought an I |SP programmer but it will take 3 weeks to reach and no I dont have another arduino, TBH I'm scared to buy another one... –  echo_salik

If you are buying clones, those will more than likely give issues as they will be cutting back on costs in places, i.e. QC checks.

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


message:
Execute Code on power off?

Arduino newbie here.

I'm thinking about building an Arduino-based light switch to control the Philips Hue light system in my living room. I have standard wall light switches that power ceiling lamps, and I basically want all Hue lamps that are scattered around the room to be on when the switch is on, and off when the switch is off, so that I don't necessarily need the app or the Hue remote to turn the room's lights on.

My idea is to install an Arduino on the ceiling instead of a normal lamp, so that its power supply is switchable through the light switch.

I would configure it as a Hue remote control, e.g. with [ArduinoHue](https://github.com/bsalinas/ArduinoHue); if all works well, this would control the Hue lamps directly via ZigBee or via WiFi through the bridge - in both cases without having to use additional wiring.

**Whenever it gets power, I would have it `turnOn()` all lamps, and whenever its power supply is turned off, I would have it `turnOff()` all lamps.**
The first part seems simple to me, the second part - not so much.

So here's my question:
**Can I execute code in the event of the Arduino losing power, i.e. turn off my Hue lights with its last energy before shutting down?** Is there maybe some hardware configuration that would allow me to detect the power off event and retain enough energy through a battery or capacitors to still run the code?

I have never worked with Arduino before, but I do have some colleagues that can help me out when there's trouble.

body:
You could do what you want as you describe it, but are making things harder for yourself that you need to. If you can access the circuit from the switch at or near the switch (which should be 'easy' in most cases) then your system does not have to be depowered when the lighting circuit is as you will have access to the mains AC voltage on either side of the switch.

If you do wish to depower the processor when the lights are turned off you can easily add either a backup battery or a capacitor that runs the processor for "long enough". You can also run a processor in "sleep" mode at extremely low power so that it is always running so have no 'wakeup time". And it is possible to power up a processor so that the delay is not noticeable for practical purposes.

However, as [**Hue Bulbs**](http://www.philips.co.nz/c-p/8718291547778/hue-personal-wireless-lighting) are Zigbee controlled, with provision ofr both iOS and Android control,  you should be able to control them via Zigbee directly without any connection to their wiring.

__________________

[Hue control](https://ifttt.com/hue)

[Hue specifications](http://www.philips.co.nz/c-p/8718291547778/hue-personal-wireless-lighting/specifications)


body:
For the capacitor part, two one Farad supercapacitors in series (each 2.7 volts max) cost about a dollar, and there is one 10 Farad cap for two dollars each.  I guess that one of these options would work.  And the supercaps should last a very long time.  I'm not an Electrical Engineer -- just a Joule Thief hobbyist, but I thought this would contribute to your design and wouldn't cost much.

As far as balancing the supercaps, since we're close to the 2.7 volt max, I personally would just put three of the supercaps in series with a voltage divider of three 10K resistors in series tied in, but they would probably not really be necessary.

Oh, and the supercaps I spoke about are actually relatively small (10mm dia x 32mm high for each 10F, and 8mm dia. x 13.5 mm high for the 1F supercaps).  Found the 1F at $1.03 as 1572-1270-ND on Digikey.  The 10F was $1.97 each for 1572-1287-ND also on Digikey.


message:
How do I use I2C from an Arduino Uno when I have a GSM shield mounted?

This may be an extremely obvious question but I don't seem able to find a definitive answer.

I have an Arduino Uno and a Sim900 GPRS/GSM shield fitted on top of it. I had I2C working on the Arduino to communicate with a Raspberry Pi, but now that I have put the shield on top I can't get the Pi to detect the Arduino. As far as I can tell the SDA and SCL pins on the Arduino aren't being used by the shield so does anyone have any idea how I go about this?

Thanks

body:
There seems to be a number of different Sim900 shields from different suppliers? I suggest you check/post the datasheet of the one you're using. If I2C works without the shield, and does not work with the shield connected , then it seems logical that there is a pin clash.

There is a good [Random Nerd Tutorial][1] on getting started with the shield on a Uno. Maybe test it out completely before connecting to the Raspberry Pi?

The [Raspberry Pi is 3.3v and the Uno is 5v][2]. You didn't mention level shifting in your question, but it may be worthwhile.

  [1]: https://randomnerdtutorials.com/sim900-gsm-gprs-shield-arduino/
  [2]: https://blog.oddbit.com/post/2013-03-12-i2c-on-the-raspberry/#:~:text=The Raspberry Pi is a,the Raspberry Pi via I2C.


message:
Servo broken? Explanation, Solution

I had a question, I tried to control a servo with the arduino, to the servo I attached a stick and at the end of the stick a little weight. After runing my code my servo tried to move the stick, but maybe it had not enough torque to move it so after that I paused the code. Then I tried to control the servo again without weight and this time it didn´t moved. Is it broken? why? Is there a posible solution? Thanks

body: You may have broken the gears if the servo was not rated for the load applied or if the servo was rotated too far (by software) 1ms and 2ms should be your (conservative) software limits, though most servos will work from 0.7ms to 2.3ms.


body:
Servo is probably broken, or fried.

Same thing happened to me, that too twice!

First time, I had fried the servo(overpowered it).

Second time, one of the gears had broken.(finally I managed to salvage one total servo by using gears from fried one in the one with broken gears)

First, try a different way to control the servo. If the servo fails to respond, then try opening up the servo.You might be able to salvage something.


body:
Without seeing the code you are using, it is difficult to know if you are attempting to drive the servo correctly.

Remember, with a servo, the PWM signal is a positioning signal, not a duty cycle signal as used with speed control on regular dc motors.