message:
Arduino Vending Machine problem

Currently I'm working on a vending machine project. The vending machine works using 3 button on LCD Keypad Shield DFRobot where 1 button of it assigned as 0.10 cent,the other two 0.20 cent and 0.50 cent respectively. My problem here is how can my system keep track on the balance/coin inserted so that whenever I pressed `button 1 = balance 0.10` then later I pressed `button 2 = balance 0.30` (because 0.20 cent added to the system). Or if you have a better idea for my code, that should be great. This is my code so far:
<!-- language-all: lang-cpp -->

        #include <LiquidCrystal.h>
        LiquidCrystal lcd(8, 9, 4, 5, 6, 7);
        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
        volatile float balance = 0.00;
        float number1 = 0.10;
        float number2 = 0.20;
        float number3 = 0.50;
        int read_LCD_buttons()
        {
        adc_key_in = analogRead(0);      // read the value from the sensor
        if (adc_key_in > 1000) return btnNONE;
        if (adc_key_in < 50)   return btnRIGHT;
        if (adc_key_in < 195)  return btnUP;
        if (adc_key_in < 380)  return btnDOWN;
        if (adc_key_in < 555)  return btnLEFT;
        if (adc_key_in < 790)  return btnSELECT;
        return btnNONE;
        }

        void setup()
        {
        lcd.begin(16, 2);
        lcd.setCursor(0,0);
        lcd.print("TouchNGo Machine");
        }

        void loop()
        {
        lcd.setCursor(0,1);
        lcd.print("Balance=");
        lcd.setCursor(10,1);
        lcd_key = read_LCD_buttons();
        balance = 0.00 ;

        switch(lcd_key)
        {
        case(btnLEFT):
        {
        balance = balance + number1  ;
        lcd.print("RM");
        lcd.println(balance);
        break;
        }
        case(btnRIGHT):
        {
        balance = balance + number2 ;

        lcd.print("RM");
        lcd.println(balance);
        break;
        }
        case(btnUP):
        {
        balance = balance + number3  ;
        lcd.print("RM");
        lcd.println(balance);
        break;
        }
        }
        }

I would love to hear any comment from you guys.Thanks for the help!

<!-- Arduino -->

body: Remove "balance = 0.0;" from you main loop.  It's always clearing your balance.


sender: user

message:
Regarding using I2C with Arduino for Silicon Micro-structure 5852 D 1.5 psi

I am trying to get output from a sensor (micro-structure 5852D), but I only get two outputs: 11 and 255 for even applying pressure.

The following is my code, please show me how to over come this problem.

    #include "Wire.h"
    #define addrs 0x5F // I2C bus address

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

    void loop()
    {

       byte lobyte;
       byte hibyte;
       int Press;

       Wire.beginTransmission(addrs);
       Wire.write(1);
       int x = Wire.endTransmission();

       Serial.print("endTransmission: ");
       Serial.println(x, DEC);

       Wire.requestFrom(addrs, 2); // contents of your first two registers
       while(Wire.available() < 2 );          // Check for data from slave
       {
          delay(1000);
          lobyte = Wire.read();       // Read press high byte
          Serial.println(lobyte, DEC);
          hibyte = Wire.read();      // Read press low byte
          Serial.println(hibyte, DEC);

          Press = toPressure(hibyte, lobyte);
          Serial.print("Pressure: ");
          Serial.println(Press);

          delay(1000);
       }

    }

    float toPressure(byte hi, byte lo)
    {
      int a = (hi * 256 + lo) & 0x3FFF;  // see pdf, mask 14 bit

      float rv = (a - 116)* 0.8606; // faster //(t - 1638.0) / 30.84 + 600.0
      return rv;

    }

sender: assistant

body:
The issues in your code:

 - When communicating with the sensor, the sensor expects a **register address** after the device address. Instead of providing it the register address, you sent the *number of bytes you would like to receive*. Good guess, but unfortunately the device was not designed that way.

 - You did not combine the least significant bits and most significant bits of the sensor output correctly. The LSB contains the 6 (**not 8**) least significant bits, while the MSB contains the 6 most significant bits. You first combined them like ` 00MMMMMM00LLLLLL` (where bits marked L come from the LSB and bits marked M come from the MSB), and then masked off the upper two bits as in ` MMMMMM00LLLLLL`. The proper way would have been to only left shift the MSB 6 bits, producing `0000MMMMMMLLLLLL`, and then masking away the upper 4 bits leaving `MMMMMMLLLLLL`.

 - You should avoid 32 bit floating point math on 8-bit microcontrollers at all costs unless you have a huge amount of processor cycles to spare.

In order to read data from the sensor you must first select the register you want to read. To select a register you must first send the device address (95 in decimal, 5F in hexadecimal) with the write request bit set, and then the register address of the byte you want to read.
You can then read the contents of the selected register by first sending the device address, this time with the write request bit clear, and then receiving one byte of data immediately followed by a not acknowledge (NACK) to end the transmission.

The internal registers are organized as in the following table:

![register table](https://i.stack.imgur.com/ZFjGh.png)

Here is my take on the code. It compiles fine, but obviously I cannot test if it actually works as I don't have the sensor. I removed the scaling routine, as it would be wise to first get it working to some level before implementing less essential features.

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

    #include "Wire.h"
    #include <stdint.h>

    #define SENSOR_I2C_ADDR 95
    #define SENSOR_REG_PRESSURE_LSB 128
    #define SENSOR_REG_PRESSURE_MSB 129

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

    void loop()
    {
        Wire.beginTransmission(SENSOR_I2C_ADDR);        //Send the address of the register where the least
        Wire.write(SENSOR_REG_PRESSURE_LSB);            //..significant bits of the pressure measurement are found
        Wire.endTransmission(false);                    //Send a repeated start
        Wire.requestFrom(SENSOR_I2C_ADDR, 1, false);    //Request 1 byte of data, followed by a repeated start

        Wire.beginTransmission(SENSOR_I2C_ADDR);        //Send the address of the register where the most
        Wire.write(SENSOR_REG_PRESSURE_MSB);            //..significant bits of the pressure measurement are found
        Wire.endTransmission(false);                    //Send a repeated start
        Wire.requestFrom(SENSOR_I2C_ADDR, 1, true);     //Request 1 byte of data, followed by a stop, ending the transaction.

        uint16_t pressureRaw;

        //There should now be two bytes of data in the receive buffer.
        if(Wire.available() == 2)
        {
            uint8_t lsb = Wire.read();                  //The first byte contains the 6 least significant bits
            uint16_t msb = Wire.read();                 //The second byte contains the 6 most significant bits
            pressureRaw = (msb << 6 | lsb) & 0x0FFF;    //The most significant bits are aligned and combined with the
                                                        //..least significant bits. As the resulting value only has
                                                        //..12 bits of precision the upper 4 bits are masked to zero.

            Serial.print("Raw pressure value: ");
            Serial.println(pressureRaw);
        }
        else                                            //If more or less than 2 bytes have been received something isn't right.
        {
            while(Wire.available())                     //Clear the buffer
                Wire.read();
            Serial.println("I2C transaction error");
        }
        delay(1000);
    }

For some unfathomable reason Silicon Microstructures decided to not include the I2C interface specification in the [datasheet](http://www.si-micro.com/upload/product/pdf/SM5852-003-004-015_Datasheet.pdf) itself. The information is instead found in a separate [application note](http://www.si-micro.com/ci2/userfiles/files/40an0110.02.pdf).

EDIT:
Apparently Wire.flush() does absolutely nothing. Implementation from Wire.cpp:

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

    void TwoWire::flush(void)
    {
        // XXX: to be implemented.
    }

And no, the implementation isn't in the base class either: `virtual void flush() = 0;`. To work around this, I replaced the flush call with a read() loop.


body:
Sorry if I'm late to the party. I solved this years ago. Here's my YT video demo with a google drive link to the code in the video description. It works with the entire SM58XX series of sensors. Just input the parameters for your particular model in the top lines of the code and you'll be off to the races.
https://www.youtube.com/watch?v=Xb2J1puSOwk


message:
Multiple non-blocking countdown timers?

I'm building a control system for three sump pumps using a single Arduino and a set of relays.  I have float sensors for each one, and need the Arduino to trigger the relays when the float sensors are triggered.  Sensor 1 triggers pump 1, sensor 2 triggers pump 2, etc.

Simple enough, but I also need each pump to remain on for 30 seconds after its float sensor returns to normal.  This throws me for a loop since I need the other pumps and sensors to function during this delay time.  I quickly found that the blocking `delay()` function is no longer feasible.

How can I trigger the relays, keep them on for 30 seconds after the sensors return to normal, but all the while still monitor and control the other sensors/relays?  Would a non-blocking timer solution work?  Would I have to delve into interrupts?

body:
>  Would a non-blocking timer solution work?

Yes.  Your "timer" doesn't have to be anything more than a start time from `millis()` and a flag.  Then your loop just compares the start time to the current `millis()` value, and if it's more than the interval you wanted, do the "thing".  In code:

    uint32_t startTime;
    bool waiting = false;
    const uint32_t PUMP_DURATION = 30000UL;

    void setup()
    {
      // start the "timer"
      startTime = millis();
      waiting = true;
    }

    void loop()
    {
      if (waiting && (millis() - startTime >= PUMP_DURATION)) {
        waiting = false;
        // do something now!
        foo();
      }

The flag keeps it from checking when the pump *isn't* running.

If you have multiple timed things, just make another set of variables (i.e., `startTime2` and `waiting2`).  Give 'em better names, eh?

There are also Arduino libraries that encapsulate this common design pattern.  [TimeMark](https://github.com/mikaelpatel/Arduino-Timemark) is one.

Here's some [sample code](http://forum.arduino.cc/index.php?topic=223286.0) on the Arduino forum.


body:
The ["blink-without-delay"-pattern][1] shows how this can be solved but with several time periods and logic this becomes complex. Some abstraction is needed. The [Timemark][2] library provides a solution. Belows is the logic for a single sensor-relay pair with a state trace to serial:

    #include <Timemark.h>

    const uint32_t TURN_OFF_TIMEOUT = 30000L;
    Timemark turnOff(TURN_OFF_TIMEOUT);
    const int sensorPin = 2;
    const int relayPin = 3;

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

      pinMode(sensorPin, INPUT_PULLUP);
      pinMode(relayPin, OUTPUT);
      digitalWrite(relayPin, LOW);

      trace.start();
    }

    void loop()
    {
      if (trace.expired()) {
        Serial.print(millis());
        Serial.print(F(":sensor="));
        Serial.print(digitalRead(sensorPin));
        Serial.print(F(", relay="));
        Serial.println(digitalRead(relayPin));
      }

      if (digitalRead(sensorPin) == LOW) {
        digitalWrite(relayPin, HIGH);
        turnOff.start();
      }
      else if (turnOff.expired()) {
        digitalWrite(relayPin, LOW);
      }
    }

Expanding to three sensor-relays becomes:

    #include <Timemark.h>

    const uint32_t TURN_OFF_TIMEOUT = 30000L;
    const int CONTROL_MAX = 3;
    Timemark turnOff[CONTROL_MAX];
    const int sensorPin[CONTROL_MAX] = { 2, 4, 6 };
    const int relayPin[CONTROL_MAX] = { 3, 5, 7 };

    void setup()
    {
      for (int i = 0; i < CONTROL_MAX; i++) {
        turnOff[i].limitMillis(TURN_OFF_TIMEOUT);
        pinMode(sensorPin[i], INPUT_PULLUP);
        pinMode(relayPin[i], OUTPUT);
        digitalWrite(relayPin[i], LOW);
      }
    }

    void loop()
    {
      for (int i = 0; i < CONTROL_MAX; i++) {
        if (digitalRead(sensorPin[i]) == LOW) {
          digitalWrite(relayPin[i], HIGH);
          turnOff[i].start();
        }
        else if (turnOff[i].expired()) {
          digitalWrite(relayPin[i], LOW);
        }
      }
    }

An alternative solution is to use the [Scheduler][3] library. Below is a rewrite using template functions and a controller task per sensor-relay pair.

    #include <Scheduler.h>

    const uint32_t TURN_OFF_TIMEOUT = 30000L;
    const uint32_t DEBOUNCE_TIMEOUT = 40L;

    template<const int sensorPin, const int relayPin> void setupController()
    {
      pinMode(sensorPin, INPUT_PULLUP);
      pinMode(relayPin, OUTPUT);
      digitalWrite(relayPin, LOW);
    }

    template<const int sensorPin, const int relayPin> void loopController()
    {
      if (digitalRead(sensorPin) == LOW) {
        digitalWrite(relayPin, HIGH);
        while (digitalRead(sensorPin) == LOW) delay(DEBOUNCE_TIMEOUT);
        delay(TURN_OFF_TIMEOUT);
        digitalWrite(relayPin, LOW);
      }
      yield();
    }

    void setup()
    {
      Scheduler.start(setupController<2,3>, loopController<2,3>);
      Scheduler.start(setupController<4,5>, loopController<4,5>);
      Scheduler.start(setupController<6,7>, loopController<6,7>);
    }

    void loop()
    {
      yield();
    }

Please note that the Scheduler requires yield() or delay() to switch between the tasks.

Cheers!

  [1]: https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay
  [2]: https://github.com/mikaelpatel/Arduino-Timemark
  [3]: https://github.com/mikaelpatel/Arduino-Scheduler


body:
You might use something like this:

    #define AMOUNT_OF_TIMERS 10
    unsigned int timer[AMOUNT_OF_TIMERS];
    unsigned int sensors[AMOUNT_OF_TIMERS];
    unsigned int pumps[AMOUNT_OF_TIMERS];
    void setup()
    {
      sensors[0] = 1;
      sensors[1] = 2;
      sensors[2...
      ......s[9] = 12;
      pumps[0] = 13;
      pumps[1....
      ....s[9] = 22;
      for(unsigned int i = 0; i< AMOUNT_OF_TIMERS; i++){
        PinMode(sensors[i],INPUT);
        PinMode(pumps[i],OUTPUT);
      }
    }

    void loop()
    {
      checkPins();
      decreaseTimers();
      delay(1000);
    }

    void checkPins(){
      for(unsigned int i = 0; i< AMOUNT_OF_TIMERS; i++){
        if(digitalRead(sensors[i])
        pump[i] = 30;
      }
    }

    void decreaseTimers(){
      for(unsigned int i = 0; i< AMOUNT_OF_TIMERS; i++){
        if(timer[i]>0)
        timer--;
      }
    }

Personally, I think, handling the timing events in an interrupt is way better. Which might also be for the sensor inputs.

It's not the neatest thing, but it will do.
Using interrupts should make it even more efficient.

- You should use interrupts.
- You might use unsigned chars to preserve extra RAM.
- You should adjust the timers/delay. (set timer to 300, and delay to 100ms) for better result.


body:
Using info from every suggestion, I've so far come up with the following.  I may not need to touch this code again for years and years (or a new house owner may need to look at it should I move out), so I tried to comment it as much as possible.

I don't like that I've repeated so much code in the readFloatSensor functions, but this is where I am so far.  How can I eliminate the code duplication?  I believe I could use arrays and `for` loops but now I've entered another grey area for my knowledge level.

    // PumpController.ino

    // ----CONSTANTS
    // ----Edit these if you need to change the pin layout or pump duration

    #define RELAY_ON 0                     // The pump relays are active-LOW; on when LOW (0)
    #define RELAY_OFF 1                    // and off when HIGH (1). These #defines just help keep track.

    const int pumpRelayPin1 =  12;         // Pin numbers for the pump relays
    const int pumpRelayPin2 =  11;
    const int pumpRelayPin3 =  10;

    const int floatSensorPin1 = 7;         // Pin numbers for the float sensors
    const int floatSensorPin2 = 8;
    const int floatSensorPin3 = 9;

    const int pumpDuration = 500;          // Number of millisecs that the pumps run
                                           // after the float sensors no longer detect water

    // ----VARIABLES

    byte pumpState1 = RELAY_OFF;           // Used to record whether the pumps are on or off
    byte pumpState2 = RELAY_OFF;           // (default to HIGH/OFF)
    byte pumpState3 = RELAY_OFF;

    unsigned long currentMillis = 0;       // Stores the value of millis() in each iteration of loop()

    unsigned long pumpTimerMillis1 = 0;    // Stores the times when the float sensors were last triggered
    unsigned long pumpTimerMillis2 = 0;
    unsigned long pumpTimerMillis3 = 0;

    // ----SETUP (Sets up the pins at startup/reset)

    void setup()
    {

     // Debug
     Serial.begin(9600);
     Serial.println("Starting PumpController.ino");

     // Pump relays are active-LOW. Initialize pump
     // pins HIGH so the relays are inactive at startup/reset
     digitalWrite(pumpRelayPin1, RELAY_OFF);
     digitalWrite(pumpRelayPin2, RELAY_OFF);
     digitalWrite(pumpRelayPin3, RELAY_OFF);

     // THEN set the pins as outputs
     pinMode(pumpRelayPin1, OUTPUT);
     pinMode(pumpRelayPin2, OUTPUT);
     pinMode(pumpRelayPin3, OUTPUT);

     // Set the float sensor pins as inputs and use the built-in pullup resistors
     pinMode(floatSensorPin1, INPUT_PULLUP);
     pinMode(floatSensorPin2, INPUT_PULLUP);
     pinMode(floatSensorPin3, INPUT_PULLUP);

    }

    // ----MAIN LOOP

    void loop()
    {
     // Get the current clock count

     currentMillis = millis() + pumpDuration;       // We add the countdown timer duration to
                                                    // the clock to prevent the pumps from
                                                    // running at boot time, while the clock
                                                    // counter is still below the timer value

     // Call the functions that do the work

     readFloatSensor1();             // check each float sensor and decide whether
     readFloatSensor2();             // to start the pump and countdown timer
     readFloatSensor3();
     triggerPumps();                 // Actually toggles the relay pins based on
    }                                   // the data from the above functions.

    // ----WORKER FUNCTIONS

    void readFloatSensor1()
    {
     if (digitalRead(floatSensorPin1) == LOW)   // If the float sensor is tripped (pulled low)
     {
      pumpState1 = RELAY_ON;                 // then trigger the pump relay pin
      pumpTimerMillis1 = currentMillis;      // and set the pump countdown timer to the current clock time
     }

     if (currentMillis - pumpTimerMillis1 >= pumpDuration)   // If the countdown timer has expired,
     {
      pumpState1 = RELAY_OFF;                             // then turn off the pump relay pin
      pumpTimerMillis1 = 0;                               // and reset the timer to 0 for the next trigger
     }
    }

    //========

    void readFloatSensor2()
    {
     if (digitalRead(floatSensorPin2) == LOW)   // If the float sensor is tripped (pulled low)
     {
      pumpState2 = RELAY_ON;                 // then trigger the pump relay pin
      pumpTimerMillis2 = currentMillis;      // and set the pump countdown timer to the current clock time
     }

     if (currentMillis - pumpTimerMillis2 >= pumpDuration)   // If the countdown timer has expired,
     {
      pumpState2 = RELAY_OFF;                             // then turn off the pump relay pin
      pumpTimerMillis2 = 0;                               // and reset the timer to 0 for the next trigger
     }
    }

    //========

    void readFloatSensor3()
    {
     if (digitalRead(floatSensorPin3) == LOW)   // If the float sensor is tripped (pulled low)
     {
      pumpState3 = RELAY_ON;                 // then trigger the pump relay pin
      pumpTimerMillis3 = currentMillis;      // and set the pump countdown timer to the current clock time
     }

     if (currentMillis - pumpTimerMillis3 >= pumpDuration)   // If the countdown timer has expired,
     {
      pumpState3 = RELAY_OFF;                             // then turn off the pump relay pin
      pumpTimerMillis3 = 0;                               // and reset the timer to 0 for the next trigger
     }
    }

    //========

    void triggerPumps()
    {
     // Toggle the pump relay pins on and off based on
     // pumpState from the readFloatSensor functions

     digitalWrite(pumpRelayPin1, pumpState1);
     digitalWrite(pumpRelayPin2, pumpState2);
     digitalWrite(pumpRelayPin3, pumpState3);
    }

    //=====END


message:
Sending data to a webserver with GPRS/GPS Shield (U-blox Sara G-350)

I am working on a project for tracking cars. I am using an Arduino UNO to receive the position from GPS/GPRS shield. I am OK on obtaining the coordinates position.
Now I need to send the position to a webserver and then show it on a webpage using the Google Maps API. Which accepts it in a POST or GET method.
Here is the shield model:
[U-blox Sara G-350][1]
and this is its manual [here][2]

Here is my approach:

    #include <SoftwareSerial.h>
    #include <String.h>

    SoftwareSerial gprsSerial(7 ,8);

    void setup() {
      // put your setup code here, to run once:
      gprsSerial.begin(19200);
      Serial.begin(19200);
      delay(2000);

     gprsSerial.println("AT+CGDCONT=3,\"IP\",\"weborange\"");
     toSerial();
     delay(2000);

     gprsSerial.println("AT+UHTTP=0");
     toSerial();
     delay(2000);
     gprsSerial.println("AT+UHTTP=2,1,\"www.navtec.16mb.com\"");
                       //AT+UHTTP=<profile_id>,<op_code>,<HTTP_server_name>
     toSerial();
     delay(2000);

     gprsSerial.println("AT+UHTTP=0,5,80");
     toSerial();
     delay(2000);

    }

    void loop() {

     //gprsSerial.println("AT+UHTTP=2,1,\"submit\"");
                        //AT+UHTTP=<profile_id>,<op_code>,<param_val>[,<param_val1>]
     //toSerial();
     //delay(2000);

     gprsSerial.println("AT+UHTTPC=2,1,\"/add.php\",\"filename\"");  //Problem here!!!!!!!!
                       //AT+UHTTPC=<profile_id>,<http_command>,<path>,<filename>[,<param1>[,<param2>[,<param3>]]]
     toSerial();
     delay(2000);
    }

    void toSerial()
    {
      while(gprsSerial.available()!=0)
      {
        Serial.write(gprsSerial.read());
      }

    }

This is what I get:

> +CGDCONT=3,"IP","weborange"
>
> OK
> +UHTTP=0
>
> OK
> +UHTTP=2,1,"www.navtec.16mb.com"
>
> OK
> +UHTTP=0,5,80
>
> OK
> +UHTTPC=2,1,/add.php,filename
>
> ERROR
> +UHTTPC=2,1,/add.php,filename
>
> ERROR
> +UHTTPC=2,1,/add.php,filename
>
> ERROR
> +UHTTPC=2,1,/add.php,filename
>
> ERROR ...

Thanks for your time, I am waiting for your support, any ideas could help. Sorry for my bad English

  [1]: https://i.stack.imgur.com/HfhAU.jpg
  [2]: https://www.u-blox.com/sites/default/files/u-blox-ATCommands_Manual_(UBX-13002752).pdf

body:
I worked on a project similar to yours. I think you forgot to **establish a connection first**.
Just add those lines of code at the top of `setup()` method:

     gprsSerial.println("AT+UPSDA=2,0"); //Reset connection
     toSerial();
     delay(2000);
      gprsSerial.println("AT+UPSD=2,1,\"weborange\""); //Establish a new one
     toSerial();
     delay(2000);
     gprsSerial.println("AT+UPSDA=2,3");
     toSerial();
     delay(2000);
     gprsSerial.println("AT+UPSND=2,0");
     toSerial();
     delay(2000);

I hope it works for you. Else, you can use `AT+UHTTPER=2` after all to check for error source.


message:
Did I fry my ESP8266 module or was it something wrong with it?

I was trying to connect my Arduino Nano to my home Wi-Fi. To do that, I connected my Arduino to ESP8266 module.

I connected pins

    Arduino  | ESP8266
    3.3V     | VCC
    3.3V     | CH_PD
    D10      | RXD
    D11      | TXD
    GND      | GND

to connect to Wi-Fi, I used code which I found on internet.

What I'm getting is `"FAILED - Timeout exceeded"` which indicates there is no response from the ESP module. Is it possible I did something wrong and I fried it, or I connected it wrong? Or maybe it does not have enough power (I'm powering my Arduino via computer USB port)? I also read reviews which indicates customers who bought similar product from different vendors they had issues with firmware. Is it possible I have same problem?

#Code

    #include <SoftwareSerial.h>
    SoftwareSerial softSerial(10, 11); // RX, TX
    String WSSID = "xxxxxxxxxxxx";
    String WPASS = "xxxxxxxxxxxx";
    bool r;

    void setup() {
      /* SETUP SERIAL COMMUNICATION */
      espSerialSetup();
      delay(2000); // Without this delay, sometimes, the program will not start until Serial Monitor is connected
      r = espSendCommand( "AT+CIFSR" , "OK" , 5000 );
      if( !r ) {
        r = espSendCommand( "AT+CWMODE=1" , "OK" , 5000 );
        r = espSendCommand( "AT+CWJAP=\""+WSSID+"\",\""+WPASS+"\"" , "OK" , 15000 );
      }
    }

    void loop(){
      r = espSendCommand( "AT+CIPSTART=\"TCP\",\"108.59.11.102\",80" , "OK" , 5000 );
      String getRequest = "GET /shiznic/ HTTP/1.1\r\nHost: www.rootpower.com\r\n";
      int getRequestLength = getRequest.length() + 2; // add 2 because \r\n will be appended by SoftwareSerial.println().
      r = espSendCommand( "AT+CIPSEND=" + String(getRequestLength) , "OK" , 5000 );
      r = espSendCommand( getRequest , "+IPD" , 15000 );
      //r = espSendCommand( getRequest , "world" , 15000 ); // page should respond with Hello, world.
      if( !r ) {
        Serial.println( "Something wrong...Attempting reset...");
        espSendCommand( "AT+RST" , "ready" , 20000);
        espSendCommand( "AT+CWMODE=1" , "OK" , 5000 );
        espSendCommand( "AT+CWJAP=\""+WSSID+"\",\""+WPASS+"\"" , "OK" , 15000 );
      }
      delay(3000);
    }

    void espSerialSetup() {

      // change baud rate so SoftwareSerial works better -- need a certain version of ESP for this to work and be retained after power cycle
      // make sure Serial Monitor port speed is set to 9600
      softSerial.begin(115200); // default baud rate for ESP8266
      delay(1000);
      softSerial.println("AT+CIOBAUD=9600");
      delay(1000);
      softSerial.begin(9600);
      Serial.begin(9600);
    }

    bool espSendCommand(String cmd, String goodResponse, unsigned long timeout) {
      Serial.println("espSendCommand( " + cmd + " , " + goodResponse + " , " + String(timeout) + " )" );
      softSerial.println(cmd);
      unsigned long tnow = millis();
      unsigned long tstart = millis();
      unsigned long execTime = 0;
      String response = "";
      char c;
      while( true ) {
        if( tnow > tstart + timeout ) {
          Serial.println("espSendCommand: FAILED - Timeout exceeded " + String(timeout) + " seconds" );
          if( response.length() > 0 ) {
            Serial.println("espSendCommand: RESPONSE:");
            Serial.println( response );
          } else {
            Serial.println("espSendCommand: NO RESPONSE");
          }
          return false;
        }
        c = softSerial.read();
        if( c >= 0 ) {
          response += String(c);
          if( response.indexOf(goodResponse) >= 0 ) {

            execTime = ( millis() - tstart );
            Serial.println("espSendCommand: SUCCESS - Response time: " + String(execTime) + "ms");
            Serial.println("espSendCommand: RESPONSE:");
            Serial.println(response);
            while(softSerial.available() > 0) {
              Serial.write(softSerial.read());
            }
            return true;
          }
        }
        tnow = millis();
      }
    }

**UPDATE**
I changed connections to
  D11      | RXD
  D10      | TXD

and i also simplified my code

    #include <SoftwareSerial.h>

    SoftwareSerial esp(10, 11);

    void setup() {
       Serial.begin(115200);
      while (!Serial);
      Serial.println("Started");
      esp.begin(115200);
      esp.write("AT\r\n");
    }

    void loop() {
      if (esp.available()) {
        Serial.write(esp.read());
      }

      if (Serial.available()) {
        esp.write(Serial.read());
      }
    }

now I'm sending basic AT command to test connection, and still not getting any response. LED on ESP module is on, so I'm assuming it is working.

body:
By the looks of the information you have provided, it looks as though you have not made the crossed serial connection: `rx-tx tx-rx`.

Your wiring:

    Arduino  | ESP8266
    3.3V     | VCC
    3.3V     | CH_PD
    D10      | RXD
    D11      | TXD
    GND      | GND

And when you intialize the software serial library:

    SoftwareSerial softSerial(10, 11); // RX, TX

You declare `D10` as `RX` and then connect it to the ESPs `RX` and ditto for the `TX` line.

What you need to do is the following:

    Arduino  | ESP8266
    3.3V     | VCC
    3.3V     | CH_PD
    D10      | TXD   //change to this
    D11      | RXD   //change to this
    GND      | GND

Also you need to ensure that the arduino TX line does not exceed 3.3V you can use a voltage divider, logic-level shifter board or a 74LVC245. This is important as the 5V arduino pins will damage a 3.3V device. This is a note as arduino nano is a 5V device from what I know(I may be corrected).


body:
As far as I know, the 3.3v on the Arduino board might not have enough current for the ESP module, as it is very 'power hungry'.

I've had some hard time making my modules work properly, and your problem could be a number of things.

I will stick to Ockam's razor principle and go by the simple side.

In your code you are using 9600 baud,but the ESP8266 'base' speed is 115200. Try that speed (and CR+LF) also on your Usb cable and it might work.


message:
ESP 8266 web server using arduino

I have built a system using arduino and Ethernet shield. It gets rgb values through URL and changes an rgb led's value. Today I bought an ESP 8266 12E. I want to change to wifi but I cannot find an arduino library that uses spi to connect the arduino to the ESP. I do not want to use only the ESP. Do you know any libraries to do the job or any tutorials.

body: The ESP communicates using the UART, not SPI. It uses modem-like AT commands. Unless you write your own ESP firmware, in which case how it communicates is up to you - and so is the accompanying Arduino library.


body:
The following link is a great resource for learning how to use the WiFi module.  It has all the commands you are likely to need.  The guide is written with the intent that the user will use the module as a standalone device without the Arduino, but at the end of the guide the commands given are all the same.  This is the reference I use for projects like this.  [ESP8622 Quick Start Guide][1]

  [1]: http://rancidbacon.com/files/kiwicon8/ESP8266_WiFi_Module_Quick_Start_Guide_v_1.0.4.pdf


message:
Use only one pin as serial output/input with arduino

I'm looking for a way to use Arduino UNO's as serial outputs or input "individually", I don want to have an RX pin for each TX pin. I know the library *SoftwareSerial*, but I'm not sure if it is posible to achieve my objective with it.

I have also read that in this library "If using multiple software serial ports, only one can receive data at a time". Is there any library or method I can use to achieve both of my objectives, using pins "individually" and receiving data from more than a pin at a time?

Thank you for your time.

body: AVR304, "Half Duplex Interrupt Driven Software UART on tinyAVR and megaAVR devices" describes how to implement a half-duplex software UART using 2 pins. Simply omit the half of the UART that you do not need in your own implementation.


body:
Serial ports do not require both directions to work. You can connect just one if you want. Of course you won't be able to reply or receive but you know that. Multiple TX from a microcontroller is easy. Just send the data at the speed required. RX is harder because you have to be able to read multiple high speed random inputs at the same time. It requires careful and complicated coding and will not be small or simple. You may not be able to do it and the rest of your project as well.

There are ICs or setups that can multiplex serial lines though. See https://electronics.stackexchange.com/questions/111491/multiplexing-ttl-serial-lines-with-transistors


body:
> I don't want to have an RX pin for each TX pin ...

I adapted the SoftwareSerial library a while ago to omit the receiving part. You can download that from:

http://www.gammon.com.au/Arduino/SendOnlySoftwareSerial.zip

You use that like SoftwareSerial but if you read you will always get -1 returned, and `available` always returns 0.

The constructor only has the transmit pin:

      SendOnlySoftwareSerial(uint8_t transmitPin, bool inverse_logic = false);

---

> Is there any library or method I can use to achieve both of my objectives, using pins "individually" and receiving data from more than a pin at a time?

You don't want an Rx pin, but you want to receive from more than one pin at a time? Now you've lost me.

Sounds like an [X-Y Problem](http://xyproblem.info/) - maybe describe this requirement in more detail.

Having said that, hardware serial can receive from one pin while the processor is doing something else. If you have a Mega you could receive from 4 ports at once (it has 4 x hardware serial ports).


message:
Serial not working with I2C

I have been working on a hydroponic garden that is controlled with Arduinos. I have everything working except for the user interface. What I would like to do is have an LCD screen paired with a rotary encoder for use on the garden, and an ESP8266 WiFi module set as a server working with a custom Android app that I am writing.

I have been working on writing the app and the code that will allow the Arduino and the app to talk to each other, but I have been running into a problem. Sometimes the serial data between the ESP266 and the Arduino is not being picked up by the Arduino. I have verified that the data coming out of the WiFi module is correct, but the Arduino seems to be missing characters. This seems to happen almost at random. Sometimes it will work, and other times it will simply get stuck. I used a SoftwareSerial library to add an extra serial port and printed what the Arduino was receiving from the WiFi module, and it just seems to be missing random characters.

Up until now I have had the WiFi module connected and the LCD screen. I was using the LCD screen to display debugging messages. I took the LCD screen off and deleted all the LCD code and now everything seems to work just fine.

The LCD screen uses I2C.

Why does disconnecting the LCD screen solve the issue? Is there a way to make both run at the same time? The LCD uses I2C. I am unaware of anything that would prevent this from working.

Thanks.

body:
**Explanation**

The SoftwareSerial library requires continually polling the serial ports over short periods of time therefore it presents a problem of having to parse received data into something usable, which is going to be nearly impossible as your program is going to be too busy trying to keep up with all the incoming NMEA characters to assemble it all into something meaningful.

So in your situation the data from the ESP8266 module is probably fine as you say, but parsing it and sending it to the lcd over I2C is a lot of work and sometimes it will "lose" data it simply doesn't have time to process. This explains why the data loss is hit and miss, and gets resolved when you reduce the processing workload of your program by removing the lcd component.

**Solution**

What you need here is to use an interrupt-driven SoftwareSerial library instead, which works by filling a buffer in the background with received data and allows a little breathing room to process the serial data. A great example is the [NewSoftwareSerial][1] library. This link will show you how to use the library , also expand into the details my answer to give you a deeper understanding.

  [1]: http://arduiniana.org/libraries/NewSoftSerial/


message:
compilation error in arduino

I'm new to arduino. I had found an interesting project to work on with, but unfortunately I'm held up at compilation error. I tried finding answers to this problem but not able to understand.

Here is my code:

        // Include Libraries
    #include <Wire.h>
    #include <Servo.h>
    #include <Adafruit_TCS34725.h>

    // Initialize Sensors
    Adafruit_TCS34725 tcs = Adafruit_TCS34725(TCS34725_INTEGRATIONTIME_50MS, TCS34725_GAIN_4X);
    Servo myservoRed;
    Servo myservoGreen;
    Servo myservoBlue;

    int posRed = 0;
    int posGreen = 0;
    int posBlue = 0;

    void setup() {
      Serial.begin(9600);
      Serial.println("Color View Test!");

      if (tcs.begin()) {
        Serial.println("Found sensor");
      } else {
        Serial.println("No TCS34725 found ... check your connections");
        while (1); // halt!
      }

      //Attach servos to ouput pins
      myservoRed.attach(9);
      myservoGreen.attach(6);
      myservoBlue.attach(3);

      // Initialize Fan pin
      pinMode(7, OUTPUT);

    }

    void loop() {
      uint16_t clear, red, green, blue;
      tcs.setInterrupt(false);
      delay(60);  // takes 50ms to read
      tcs.getRawData(&red, &green, &blue, &clear);
      tcs.setInterrupt(true);
      Serial.print("C:\t"); Serial.print(clear);
      Serial.print("\tR:\t"); Serial.print(red);
      Serial.print("\tG:\t"); Serial.print(green);
      Serial.print("\tB:\t"); Serial.print(blue);

      // Map color to motor position
      posRed = map(red,100,10000,10,80);
      Serial.print("\tRedPos:\t"); Serial.print(posRed);
      posGreen = map(green,100,10000,10,80);
      Serial.print("\tGreenPos:\t"); Serial.print(posGreen);
      posBlue = map(blue,100,10000,10,80);
      Serial.print("\tBluePos:\t"); Serial.print(posBlue);
      Serial.println();

      // Write position to motor
      myservoRed.write(posRed);
      delay(100);
      myservoGreen.write(posGreen);
      delay(100);
      myservoBlue.write(posBlue);
      delay(100);

    }

Here is the Wire.h:

    /*
     * TwoWire.h - TWI/I2C library for Linux Userspace
     * Copyright (c) 2013 Parav https://github.com/meanbot.
     * All rights reserved.
     *
     * This library is free software; you can redistribute it and/or
     * modify it under the terms of the GNU Lesser General Public
     * License as published by the Free Software Foundation; either
     * version 2.1 of the License, or (at your option) any later version.
     *
     * This library is distributed in the hope that it will be useful,
     * but WITHOUT ANY WARRANTY; without even the implied warranty of
     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
     * Lesser General Public License for more details.
     *
     * You should have received a copy of the GNU Lesser General Public
     * License along with this library; if not, write to the Free Software
     * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
     */

    #ifndef TwoWire_h
    #define TwoWire_h

    #include "Stream.h"
    #include "variant.h"

    #define BUFFER_LENGTH 32
    #define I2C2 0x4819c000
    #define I2C1 0x00000000
    #define WIRE_INTERFACES_COUNT 1

    class TwoWire : public Stream {
    public:
     TwoWire(void(*begin_cb)(void));
     void begin();
     void begin(uint8_t);
     void begin(int);
     void beginTransmission(uint8_t);
     void beginTransmission(int);
     uint8_t endTransmission(void);
        uint8_t endTransmission(uint8_t);
     uint8_t requestFrom(uint8_t, uint8_t);
        uint8_t requestFrom(uint8_t, uint8_t, uint8_t);
     uint8_t requestFrom(int, int);
        uint8_t requestFrom(int, int, int);
     virtual size_t write(uint8_t);
     virtual size_t write(const uint8_t *, size_t);
     virtual int available(void);
     virtual int read(void);
     virtual int peek(void);
     virtual void flush(void);
     void onReceive(void(*)(int));
     void onRequest(void(*)(void));

        inline size_t write(unsigned long n) { return write((uint8_t)n); }
        inline size_t write(long n) { return write((uint8_t)n); }
        inline size_t write(unsigned int n) { return write((uint8_t)n); }
        inline size_t write(int n) { return write((uint8_t)n); }
     using Print::write;

     void onService(void);

    private:
     // RX Buffer
     uint8_t rxBuffer[BUFFER_LENGTH];
     uint8_t rxBufferIndex;
     uint8_t rxBufferLength;

     // TX Buffer
     uint8_t txAddress;
     uint8_t txBuffer[BUFFER_LENGTH];
     uint8_t txBufferLength;

     // Service buffer
     uint8_t srvBuffer[BUFFER_LENGTH];
     uint8_t srvBufferIndex;
     uint8_t srvBufferLength;

     // Callback user functions
     void (*onRequestCallback)(void);
     void (*onReceiveCallback)(int);

     // Called before initialization
     void (*onBeginCallback)(void);

     // Timeouts (
     static const uint32_t RECV_TIMEOUT = 100000;
     static const uint32_t XMIT_TIMEOUT = 100000;

     uint8_t adapter_nr;
     int i2c_fd;
     int i2c_transfer;
    };

    #if WIRE_INTERFACES_COUNT > 0
    extern TwoWire Wire;
    #endif
    #if WIRE_INTERFACES_COUNT > 1
    extern TwoWire Wire1;
    #endif

    #endif

Here is Wire.cpp:

    /*
     * TwoWire.h - TWI/I2C library for Linux Userspace
     * Copyright (c) 2013 Parav https://github.com/meanbot.
     * All rights reserved.
     *
     * This library is free software; you can redistribute it and/or
     * modify it under the terms of the GNU Lesser General Public
     * License as published by the Free Software Foundation; either
     * version 2.1 of the License, or (at your option) any later version.
     *
     * This library is distributed in the hope that it will be useful,
     * but WITHOUT ANY WARRANTY; without even the implied warranty of
     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
     * Lesser General Public License for more details.
     *
     * You should have received a copy of the GNU Lesser General Public
     * License along with this library; if not, write to the Free Software
     * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
     */

    extern "C" {
    #include <string.h>
    #include <i2c.h>
    }

    #include "Wire.h"

    #include <Mux.h>
    #include <trace.h>
    #define MY_TRACE_PREFIX "Wire"

    TwoWire::TwoWire(void(*_beginCb)(void)) : rxBufferIndex(0), rxBufferLength(0),
           txAddress(0), txBufferLength(0),
           srvBufferIndex(0), srvBufferLength(0),
           onBeginCallback(_beginCb),
           adapter_nr(-1), i2c_fd(-1),
           i2c_transfer(0)
    {
     // Empty
    }

    void TwoWire::begin(void)
    {
     muxSelectI2c(0);
     if (onBeginCallback)
      onBeginCallback();
     if ((adapter_nr = i2c_getadapter(I2C2)) < 0) {
      return;
     }
     if ((i2c_fd = i2c_openadapter(adapter_nr)) < 0) {
      return;
     }

    }

    void TwoWire::begin(uint8_t address)
    {
     if (onBeginCallback)
      onBeginCallback();
    }

    void TwoWire::begin(int address)
    {
     begin((uint8_t) address);
    }

    uint8_t TwoWire::requestFrom(uint8_t address, uint8_t quantity, uint8_t sendStop)
    {
     if (quantity > BUFFER_LENGTH)
      quantity = BUFFER_LENGTH;

     /* Set slave address via ioctl  */
     i2c_setslave(i2c_fd, address);

     if(i2c_transfer) {
     /* Need to perform a combined read/write operation
      */
      i2c_transfer = 0;
      if (sendStop == false)
       return 0;
      i2c_add_to_buf(address, 1, rxBuffer, quantity);
      if (!i2c_readwrite(i2c_fd)) {
       rxBufferIndex = 0;
       rxBufferLength = quantity;
       i2c_transfer = 0;
       return quantity;
      } else
       return 0;
     }
     if (i2c_readbytes(i2c_fd, rxBuffer, quantity) < 0)
      return 0;
     // set rx buffer iterator vars
     rxBufferIndex = 0;
     rxBufferLength = quantity;

     return quantity;
    }

    uint8_t TwoWire::requestFrom(uint8_t address, uint8_t quantity)
    {
     return requestFrom((uint8_t) address, (uint8_t) quantity, (uint8_t) true);
    }

    uint8_t TwoWire::requestFrom(int address, int quantity)
    {
     return requestFrom((uint8_t) address, (uint8_t) quantity, (uint8_t) true);
    }

    uint8_t TwoWire::requestFrom(int address, int quantity, int sendStop)
    {
     return requestFrom((uint8_t) address, (uint8_t) quantity, (uint8_t) sendStop);
    }

    void TwoWire::beginTransmission(uint8_t address)
    {
     if (i2c_fd < 0 || adapter_nr < 0)
      return;
     /* set slave address via ioctl in case we need to perform terminating
      * write operation
      */
     i2c_setslave(i2c_fd, address);
     // save address of target and empty buffer
     txAddress = address;
     txBufferLength = 0;
    }

    void TwoWire::beginTransmission(int address)
    {
     beginTransmission((uint8_t) address);
    }

    //
    // Originally, 'endTransmission' was an f(void) function.
    // It has been modified to take one parameter indicating
    // whether or not a STOP should be performed on the bus.
    // Calling endTransmission(false) allows a sketch to
    // perform a repeated start.
    //
    // WARNING: Nothing in the library keeps track of whether
    // the bus tenure has been properly ended with a STOP. It
    // is very possible to leave the bus in a hung state if
    // no call to endTransmission(true) is made. Some I2C
    // devices will behave oddly if they do not see a STOP.
    //
    uint8_t TwoWire::endTransmission(uint8_t sendStop)
    {
     int err;
     if (sendStop == true) {

      // transmit buffer (blocking)
      if (txBufferLength > 1)
       err = i2c_writebytes(i2c_fd, txBuffer, txBufferLength);
      else if (txBufferLength == 1)
       err = i2c_writebyte(i2c_fd, *txBuffer);
      else
      /* FIXME: A zero byte transmit is typically used to check for an
       * ACK from the slave device. I'm not sure if this is the
       * correct way to do this.
       */
       err = i2c_readbyte(i2c_fd);
      // empty buffer
      txBufferLength = 0;
      if (err < 0)
       return 2;
      return 0;
     } else {
     /* sendStop = false
      * pretend we have held the bus while
      * actually waiting for the next operation
      */
      i2c_add_to_buf(txAddress, 0, txBuffer, txBufferLength);
      i2c_transfer = 1;
      return 0;
     }
    }

    // This provides backwards compatibility with the original
    // definition, and expected behaviour, of endTransmission
    //
    uint8_t TwoWire::endTransmission(void)
    {
     return endTransmission(true);
    }

    size_t TwoWire::write(uint8_t data)
    {
     if (txBufferLength >= BUFFER_LENGTH)
      return 0;
     txBuffer[txBufferLength++] = data;
     return 1;
    }

    size_t TwoWire::write(const uint8_t *data, size_t quantity)
    {
     for (size_t i = 0; i < quantity; ++i) {
      if (txBufferLength >= BUFFER_LENGTH)
       return i;
      txBuffer[txBufferLength++] = data[i];
     }
     return quantity;
    }

    int TwoWire::available(void)
    {
     return rxBufferLength - rxBufferIndex;
    }

    int TwoWire::read(void)
    {
     if (rxBufferIndex < rxBufferLength)
      return rxBuffer[rxBufferIndex++];
     return -1;
    }

    int TwoWire::peek(void)
    {
     if (rxBufferIndex < rxBufferLength)
      return rxBuffer[rxBufferIndex];
     return -1;
    }

    void TwoWire::flush(void)
    {
     // Do nothing, use endTransmission(..) to force
     // data transfer.
    }

    void TwoWire::onReceive(void(*function)(int))
    {
     onReceiveCallback = function;
    }

    void TwoWire::onRequest(void(*function)(void)) {
     onRequestCallback = function;
    }

    void TwoWire::onService(void)
    {
    }

    #if WIRE_INTERFACES_COUNT > 0
    static void Wire_Init(void)
    {
    }

    TwoWire Wire = TwoWire(Wire_Init);

    void WIRE_ISR_HANDLER(void) {
     Wire.onService();
    }
    #endif

    #if WIRE_INTERFACES_COUNT > 1
    static void Wire1_Init(void)
    {
     if ((adapter_nr = i2c_getadapter(I2C1)) < 0) {
      return;
     }
     if ((i2c_fd = i2c_openadapter) < 0) {
      return;
     }
    }

    TwoWire Wire1 = TwoWire(Wire1_Init);

    void WIRE1_ISR_HANDLER(void) {
     Wire1.onService();
    }
    #endif

Here is the error message i got:

    libraries\Servo\Wire.cpp.o: In function `WIRE_ISR_HANDLER()':

    C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Servo\src/Wire.cpp:186: multiple definition of `TwoWire::write(unsigned char)'

    libraries\Wire\Wire.cpp.o:C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Wire\src/Wire.cpp:186: first defined here

    libraries\Servo\Wire.cpp.o: In function `TwoWire::write(unsigned char const*, unsigned int)':

    C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Servo\src/Wire.cpp:194: multiple definition of `TwoWire::write(unsigned char const*, unsigned int)'

    libraries\Wire\Wire.cpp.o:C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Wire\src/Wire.cpp:194: first defined here

    libraries\Servo\Wire.cpp.o: In function `TwoWire::requestFrom(unsigned char, unsigned char, unsigned char)':

    C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Servo\src/Wire.cpp:204: multiple definition of `TwoWire::available()'

    libraries\Wire\Wire.cpp.o:C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Wire\src/Wire.cpp:204: first defined here

    libraries\Servo\Wire.cpp.o: In function `TwoWire::read()':

    C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Servo\src/Wire.cpp:209: multiple definition of `TwoWire::read()'

    libraries\Wire\Wire.cpp.o:C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Wire\src/Wire.cpp:209: first defined here

    libraries\Servo\Wire.cpp.o: In function `TwoWire::peek()':

    C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Servo\src/Wire.cpp:216: multiple definition of `TwoWire::peek()'

    libraries\Wire\Wire.cpp.o:C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Wire\src/Wire.cpp:216: first defined here

    libraries\Servo\Wire.cpp.o: In function `TwoWire::flush()':

    C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Servo\src/Wire.cpp:223: multiple definition of `TwoWire::flush()'

    libraries\Wire\Wire.cpp.o:C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Wire\src/Wire.cpp:223: first defined here

    libraries\Servo\Wire.cpp.o: In function `TwoWire::TwoWire(void (*)())':

    C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Servo\src/Wire.cpp:32: multiple definition of `TwoWire::TwoWire(void (*)())'

    libraries\Wire\Wire.cpp.o:C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Wire\src/Wire.cpp:32: first defined here

    libraries\Servo\Wire.cpp.o: In function `TwoWire::TwoWire(void (*)())':

    C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Servo\src/Wire.cpp:32: multiple definition of `TwoWire::TwoWire(void (*)())'

    libraries\Wire\Wire.cpp.o:C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Wire\src/Wire.cpp:32: first defined here

    libraries\Servo\Wire.cpp.o: In function `TwoWire::begin()':

    C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Servo\src/Wire.cpp:43: multiple definition of `TwoWire::begin()'

    libraries\Wire\Wire.cpp.o:C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Wire\src/Wire.cpp:43: first defined here

    libraries\Servo\Wire.cpp.o: In function `TwoWire::begin(unsigned char)':

    C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Servo\src/Wire.cpp:57: multiple definition of `TwoWire::begin(unsigned char)'

    libraries\Wire\Wire.cpp.o:C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Wire\src/Wire.cpp:57: first defined here

    libraries\Servo\Wire.cpp.o: In function `TwoWire::begin(int)':

    C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Servo\src/Wire.cpp:63: multiple definition of `TwoWire::begin(int)'

    libraries\Wire\Wire.cpp.o:C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Wire\src/Wire.cpp:63: first defined here

    libraries\Servo\Wire.cpp.o: In function `TwoWire::requestFrom(unsigned char, unsigned char, unsigned char)':

    C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Servo\src/Wire.cpp:68: multiple definition of `TwoWire::requestFrom(unsigned char, unsigned char, unsigned char)'

    libraries\Wire\Wire.cpp.o:C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Wire\src/Wire.cpp:68: first defined here

    libraries\Servo\Wire.cpp.o: In function `TwoWire::requestFrom(unsigned char, unsigned char)':

    C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Servo\src/Wire.cpp:100: multiple definition of `TwoWire::requestFrom(unsigned char, unsigned char)'

    libraries\Wire\Wire.cpp.o:C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Wire\src/Wire.cpp:100: first defined here

    libraries\Servo\Wire.cpp.o: In function `TwoWire::requestFrom(int, int)':

    C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Servo\src/Wire.cpp:105: multiple definition of `TwoWire::requestFrom(int, int)'

    libraries\Wire\Wire.cpp.o:C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Wire\src/Wire.cpp:105: first defined here

    libraries\Servo\Wire.cpp.o: In function `TwoWire::requestFrom(int, int, int)':

    C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Servo\src/Wire.cpp:110: multiple definition of `TwoWire::requestFrom(int, int, int)'

    libraries\Wire\Wire.cpp.o:C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Wire\src/Wire.cpp:110: first defined here

    libraries\Servo\Wire.cpp.o: In function `TwoWire::beginTransmission(unsigned char)':

    C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Servo\src/Wire.cpp:115: multiple definition of `TwoWire::beginTransmission(unsigned char)'

    libraries\Wire\Wire.cpp.o:C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Wire\src/Wire.cpp:115: first defined here

    libraries\Servo\Wire.cpp.o: In function `TwoWire::beginTransmission(int)':

    C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Servo\src/Wire.cpp:128: multiple definition of `TwoWire::beginTransmission(int)'

    libraries\Wire\Wire.cpp.o:C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Wire\src/Wire.cpp:128: first defined here

    libraries\Servo\Wire.cpp.o: In function `TwoWire::endTransmission(unsigned char)':

    C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Servo\src/Wire.cpp:146: multiple definition of `TwoWire::endTransmission(unsigned char)'

    libraries\Wire\Wire.cpp.o:C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Wire\src/Wire.cpp:146: first defined here

    libraries\Servo\Wire.cpp.o: In function `TwoWire::endTransmission()':

    C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Servo\src/Wire.cpp:181: multiple definition of `TwoWire::endTransmission()'

    libraries\Wire\Wire.cpp.o:C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Wire\src/Wire.cpp:181: first defined here

    libraries\Servo\Wire.cpp.o: In function `TwoWire::onReceive(void (*)(int))':

    C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Servo\src/Wire.cpp:229: multiple definition of `TwoWire::onReceive(void (*)(int))'

    libraries\Wire\Wire.cpp.o:C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Wire\src/Wire.cpp:229: first defined here

    libraries\Servo\Wire.cpp.o: In function `TwoWire::onRequest(void (*)())':

    C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Servo\src/Wire.cpp:233: multiple definition of `TwoWire::onRequest(void (*)())'

    libraries\Wire\Wire.cpp.o:C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Wire\src/Wire.cpp:233: first defined here

    libraries\Servo\Wire.cpp.o: In function `TwoWire::onService()':

    C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Servo\src/Wire.cpp:238: multiple definition of `TwoWire::onService()'

    libraries\Wire\Wire.cpp.o:C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Wire\src/Wire.cpp:238: first defined here

    libraries\Servo\Wire.cpp.o: In function `WIRE_ISR_HANDLER()':

    C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Servo\src/Wire.cpp:248: multiple definition of `WIRE_ISR_HANDLER()'

    libraries\Wire\Wire.cpp.o:C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Wire\src/Wire.cpp:248: first defined here

    libraries\Servo\Wire.cpp.o: In function `WIRE_ISR_HANDLER()':

    C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Servo\src/Wire.cpp:186: multiple definition of `Wire'

    libraries\Wire\Wire.cpp.o:C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Wire\src/Wire.cpp:186: first defined here

    collect2.exe: error: ld returned 1 exit status

    exit status 1
    Error compiling.

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

body:
Looks like the Servo library has Wire source files in it for some reason. I checked my Servo library, and it doesn't have those, so not sure what's going on there, but maybe try removing Wire.cpp from Servo/src/? (keep in the file so you can put it back if necessary)

**credits to uint128_t**(in the comments)

Based on his suggestion i removed the
*wire* library files present in servo library folder and things worked just fine.


message:
Need some explain before desigin my own custom Arduino Due board

I'd like to ask you some questions about ARM processor from Atmel like the SAM3X8E, the one used in the Arduino Due. I have found this [AVR programming guide] from abcminiuser on avrfreaks very helpful.

Q1. Why are there no ICSP pins in Arduino Due to use it to program the SAM3X8E from an external programmer instead of the USB port in the Due board?

Q2. If I want to program an Arduino Due from an external programmer which of the programmers in abcminiuser guide will do the job and give me the ability to program 8/16/32bit AVR and ARM chips from Atmel at the same time?

Q3. On the Arduino Due website I read this:

>"Uploading sketches to the SAM3X is different than the AVR Microcontrollers found in other Arduino boards because the flash memory needs to be erased before being re-programmed. Upload to the chip is managed by ROM on the SAM3X, which is run only when the chip's flash memory is empty. "

What is that mean?

body:
1. Because it is not needed. The chip comes with the bootloader pre programmed in  ROM, not in Flash. It cannot be replaced, upgraded, removed, etc like other more sensible chips. So there is no real need for ICSP since the main use for that is putting the bootloader on.
2. Unknown.
3. Unlike the AVR chips, whose bootloader always runs first for about 2 seconds, the SAM3X's boot loader only runs if the flash is empty. As a result there is a way to empty the flash built in to the Arduino code, so that it can be erased by software. That means that the software has to be working right though, which isn't always the case, since people write bad code which crashes the chip. As a result they added a erase button to the board so you can manually erase the chip and get the bootloader to run.

I have always maintained that the SAM3X is a really idiotically designed chip and I wouldn't ever use it in a design of my own.


message:
Store TinyGPS++ latitude value into a variable of type string or float

I want to get the GPS ordinates in degrees with 6 decimal accuracy. I can obtain this by creating a gps object with TinyGPS library. but In the TinyGPS example codes, its written

    Serial.println(gps.location.lat(), 6);

But I actually want to store this latitude degrees in a variable of type string or float. when i write this;

    double Tiny_latitude = (gps.location.lat());
    Serial.print("Tiny lat:");
    Serial.println(Tiny_latitude);

it returns me Tiny lat:33.55 on serial monitor. But i want 33.546600.
How do I do that ?

body:
> it returns me Tiny lat:33.55 on serial monitor. But i want 33.546600. How do I do that?

The issue is simply the number of decimal places. That can be added to the Serial.println().

    double Tiny_latitude = (gps.location.lat());
    Serial.print("Tiny lat:");
    Serial.println(Tiny_latitude, 6);

> Now if i want to make a String "your location is \nlat:33.546600 \nlong: 75.456912" , i.e. my String variable are stored in Tiny_latitude and Tiny_longitude and want to make a string my_Location. How do i do that?

I would use sprintf() for that but as that requires some additional build parameters the easiest way is to use String. Some special care is needed to increase the number of decimal places.

    void loop()
    {
      ...
      float latitude = 33.546600;
      float longitude = 75.456912;
      String buf;
      buf += F("your location is \nlat:");
      buf += String(latitude, 6);
      buf += F("\nlong:");
      buf += String(longitude, 6);
      Serial.println(buf);
      ...
    }

Cheers!


message:
Is there a practical way to broadcast and receive ascii payloads over ethernet or wifi?

How best might arduino nodes pass incoming serial ascii messages out as ascii network broadcasts for all others to receive and pass out through their serial ports?

ie: typing a msg from the IDE serial monitor of any ethernet node should cause that msg to be output to the serial monitors of all other nodes.

body:
The magical trick you are looking for is Ethernet UDP Broadcast. By chance there is an example sketch in the [Arduino Tutorial][1]. I cannot say if it is up to date but this will help you get started.

Cheers!

  [1]: https://www.arduino.cc/en/Tutorial/UDPSendReceiveString


message:
How to append float value of into a string ?

I have a float variable lng = 33.785469 and lat = 78.126548. Now can I convert them to String and append in a String variable "my_location" as "your location is \nlng = 33.785469 \nlat = 78.126548". I was trying to do this with

        char charVal[5];               //temporarily holds data from vals
        String stringVal = "";     //data on buff is copied to this string

        dtostrf(lng , 4, 2, charVal);  //4 is mininum width, 2 is precision; float value is copied onto buff
        //convert chararray to string
        for(int i=0;i<sizeof(charVal);i++)
        {
        stringVal+=charVal[i];
        }
        GPS_string = GPS_string + "Car location: \nlat:" + stringVal;
        stringVal = "";

and it given me an error :

    error: cannot convert 'String' to 'double' for argument '1' to 'char* dtostrf(double, signed char, unsigned char,

body:
This has been answered in the previous [question][1] but I can repeat it here:

    void loop()
    {
      ...
      float latitude = 33.546600;
      float longitude = 75.456912;
      String buf;
      buf += F("your location is \nlat:");
      buf += String(latitude, 6);
      buf += F("\nlong:");
      buf += String(longitude, 6);
      Serial.println(buf);
      ...
    }

An alternative is to use [dtostrf()][2] as in your snippet:

    void loop()
    {
      ...
      float latitude = 33.546600;
      float longitude = 75.456912;
      const int BUF_MAX = 64;
      char buf[BUF_MAX];
      const int VAL_MAX = 16;
      char val[VAL_MAX];
      strcpy_P(buf, (const char*) F("your location is \nlat:"));
      dtostrf(latitude, 8, 6, val);
      strcat(buf, val);
      strcat_P(buf, (const char*) F("\nlong:"));
      dtostrf(longitude, 8, 6, val);
      strcat(buf, val);
      ...
    }

Cheers!

  [1]: https://arduino.stackexchange.com/questions/20908/store-tinygps-latitude-value-into-a-variable-of-type-string-or-float
  [2]: http://www.nongnu.org/avr-libc/user-manual/group__avr__stdlib.html#ga060c998e77fb5fc0d3168b3ce8771d42


message:
I can't seem to receive data to the ArduinoStudio serial monitor on ubuntu 14.04

I'm using the Arduino Starter Kit so I have a Uno R3 and going through the examples I'm trying to read temperature data from my controller in Arduino Studio.

In essence my problem can be reduced down to

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

    void loop() {
        Serial.print("stuff");
    }

Which I'd expect to keep printing "stuff" on the serial monitor.

(In practice I'm running [this](https://codebender.cc/example/10.StarterKit/p03_LoveOMeter#p03_LoveOMeter.ino) exact code but all the temperature-reading going on feels irrelevant to my problem, I'm simply mentioning it because I can observe that mye LEDs light up when the temperature rises so I know the code is uploaded and running on the Duo).

I'm not seeing any errors in the studio console, and if I connect using `gtkterm` or `screen` I can see data being sent so the problem seems to be isolated to the AndroidStudio serial monitor itself.

I'm running Ubuntu 14.04 and I've connected via USB on `/dev/ttyACM3`.

I tried running
> stty -F /dev/ttyACM3 cs8 9600 ignbrk -brkint -icrnl -imaxbel -opost -onlcr -isig -icanon -iexten -echo -echoe -echok -echoctl -echoke noflsh -ixon -crtscts

as suggested [here](http://playground.arduino.cc/Interfacing/LinuxTTY) and I also tried with baud 115200, taking care to also change the value in my `setup` function.

I also ran
> chmod a+rw /dev/ttyACM3

But I'm still not seeing any errors or output. How do I proceed to debug this issue?

Running `ls -l /dev/ttyACM*` gives

> crw-rw---- 1 root dialout 166, 0 feb.  20 14:22 /dev/ttyACM0
>
> crw-rw---- 1 root dialout 166, 1 feb.  20 14:22 /dev/ttyACM1
>
> crw-rw---- 1 root dialout 166, 2 feb.  20 14:22 /dev/ttyACM2
>
> crw-rw-rw- 1 root dialout 166, 3 feb.  20 14:30 /dev/ttyACM3

body:
By default, on a linux system without specific
udev binding rules to rename the device into something non standard, the FTDI driver should map the usb to serial port on /dev/ttyUSB* and not to /dev/ttbACM*. I suspect that you were just looking in the wrong place.
I think it defaults to /dev/ttyUSB* for any usb to serial dongle:

    usb-serial.c:   usb_serial_tty_driver->name = "ttyUSB";


message:
Arduino Nano PWM output acting strange after running for a day or so

I have an Arduino Nano, and I have some issues with it. Basically it needs to control the brightness of a lamp via PWM (plus some circuitry of course). It's hooked up via serial to a little x86 embedded board which runs Linux, and that board is telling the Arduino the desired brightness level (0-255) every 5 seconds over serial. So the only thing the Arduino has to do is retrieve numbers from the other device over serial, and set the PWM output to those values. Here's the code that runs on the Arduino (I inserted some comments so it's easier to read):

***Edit: I removed the original code to clean things up as it's not relevant anymore, but you can still view it [here](http://pastebin.com/RpELDBx2).***

There's nothing fancy about the code really. It checks for incoming data about 10 times a second, and if there's any, it converts it into an `int` and sets the PWM output to that value. I know, that part where I manually extract the number characters probably could be replaced by Arduino library calls for cleaner code, but whatever. It works just fine.

The incoming data as I mentioned is the textual representation of an integer ranging from 0-255 followed by a new line character. This data is sent to the Arduino once every 5 seconds.

So whenever I turn this on, it works just fine for a day or so. But this is supposed to be a system that's constantly on 24/7. If I leave it running for a day or so, the output will start acting weird. I already checked, and the values that the other device sends are perfectly normal. It's the Arduino that messes up something. The brightness is NOT what it needs to be. The Arduino is outputting wrong PWM values. If I simply reset the Arduino (without restarting the other device), everything goes back to normal, and it works again for a day, so the problem is definitely in the Arduino somewhere. But I don't think it's in my code. This piece of code looks super simple and innocent, and I bet it is. I have no idea what causes this.

Could this be a hardware problem? I do have another Arduino, so I could try replacing it with that one. I haven't tried that yet since I already put all components in a case, fixed everything in place with screws, and soldered wires directly to the Arduino, so I would rather not replace it if it's not necessary.

So, any ideas on what could cause this?

----------

**Update:**

I updated the programs on both devices to use a more error-prone protocol for communicating (as suggested [here](https://arduino.stackexchange.com/a/20989/17324)), which is kind of similar to the [NMEA 0183](https://en.wikipedia.org/wiki/NMEA_0183) protocol (basically a simplified version of that). The sender sends the data in the following format now:

 - A single `$` character to indicate the beginning of the data
 - The data itself (which is the textual representation of a single integer)
 - A single `*` character to indicate the end of the data
 - An exactly two digit long hexadecimal checksum value. This is the bitwise XOR of the ASCII codes of all the characters between `$` and `*` (not including those). Letters (if any) are always uppercase.
 - The packet is finished up with either `\n` or `\r\n`

An example would be `$178*3E\n`, where \n of course means a newline character.

The code running on the Arduino now is the following:

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

    #include <Time.h>

    #define _analogWrite(a, b) analogWrite(a, 255-(b))
    #define clamp(X, minVal, maxVal) min(max(X, minVal), maxVal)

    const PROGMEM int pwmPin = 3;
    time_t lastUpdate = 0;
    String incoming = "";
    int pwmValue = 0;

    inline void flushSerialBuffer() {
        while (Serial.available()) Serial.read();
    }

    void setup() {
        Serial.begin(9600);
        Serial.setTimeout(500);
        pinMode(pwmPin, OUTPUT);
        _analogWrite(pwmPin, 0);
    }

    void loop() {
        time_t currentTime = now();

        if (Serial.available()) {
            delay(250); // Just to make sure that all data has arrived in the buffer
            incoming = "";
            incoming = Serial.readStringUntil('\n');
            flushSerialBuffer();
            int b = incoming.indexOf('$') + 1;
            if (b == 0) return; // -1 was returned
            int e = incoming.indexOf('*', b);
            if (e == -1) return;
            int checksum = 0x0;
            for (int i=b; i<e; i++) checksum ^= incoming[i];
            String hexString = String(checksum, HEX);
            hexString.toUpperCase();
            if (hexString.length() < 2) hexString = String("0") + hexString;
            if (!hexString.equals(incoming.substring(e+1, e+3))) return;

            pwmValue = incoming.substring(b, e).toInt();

            if (pwmValue < 0 || pwmValue > 255) pwmValue = 0;
            lastUpdate = currentTime;
        }

        if (currentTime - lastUpdate > 30) pwmValue = 0;

        _analogWrite(pwmPin, pwmValue);

        delay(250);
    }

It seems like it's working so far, although I'm still testing if this is reliable over a longer period of time. I will edit the question once again to let you know.

----------

**Update 2:**

Still no success. After a while it just gets stuck on one PWM value and keeps outputting that, regardless of what it receives over serial. It's kind of like it ignores the incoming data after a day or so. I can verify that the other device still sends data correctly, since if I only restart the Arduino, everything goes back to normal.

body:
You have a
[race condition](https://en.wikipedia.org/wiki/Race_condition) in your
code: if you try to read a message while it's being sent, you may catch
only a partial message, and end up reading the wrong numbers. My bet is
that this is exactly what is biting you. Once this happens once, it is
bound to happen again for some time, since 5 seconds is a multiple
of your 100 ms delay.

The right thing to do would be to wait until you get the new-line
character (then you know you have a complete message) before trying to
parse the message. A quick and dirty hack is to just `delay(10)` after
`Serial.available()` but before `Serial.readString()`.


body:
Your problem may be related to the dynamic memory allocation of your String objects. Each time the Arduino receives data, you are creating two new String objects. Perhaps the memory is not being released properly, causing eventual exhaustion of your RAM.

You could make your Strings global and empty them out each time, but a far better solution would be to replace all your string manipulation with a call to Serial.ParseInt() so your big if block becomes

   `if (Serial.available()) {
        pwmValue = Serial.ParseInt();
        while(Serial.available() > 0 {
          Serial.read();    // flush anything after the integer
        // Save the current time
        lastUpdate = currentTime;
    }`

Serial.ParseInt also makes use of the timeout so you don't have to worry about partial values being read.


body:
After trying the original code using Arduino IDE 1.6.7, I do not see a problem with using up memory.

Depending on the nature of the errors you are seeing, another possible explanation is that you are getting spurious data between real events. If electrical noise or whatever produces one or more characters on the serial line in the long interval between real data points, the current code will treat it as a new data point. If the bogus characters are numeric, they will be sent to the pwm. In the more likely case of non-numeric data, this code converts them to a value of 0 and sends that to the port. This situation is likely if the Arduino is more than a few feet from the PC. A slew rate limited differential driver and receiver like the MAX488 should greatly reduce the chance of this happening. Also make sure there is a good ground between the ends.

You could also reduce the chance of undetected data errors by delimiting your data with something like a '$' to start, then the data, then '*' then a checksum then a newline. The checksum could be simply the sum of all the characters up to the *, truncated to 8 bits and sent as 2 hex characters. This is what the NMEA protocol used by GPS receivers does. At the receiving end you only accept data packets with the proper format and checksum.


message:
Shaft Encoder Accuracy

So, first of all I just want to point out this code is from: [Reading Rotary Encoders][1] and is not mine.

I have a magnetic shaft encoder mounted on a regular DC motor, my problem is that I cannot receive the exact angle of the motor. The encoder outputs `+1` each 90 degrees (I then multiply by 90). And is there any relationship between `valx`, `valy`, `valz` and the angle?

<!-- language: c -->

    #define encoder0PinA 2
    #define encoder0PinB 3
    int rounds= 0;
    volatile unsigned int encoder0Pos = 0;
    unsigned int tmp_Pos = 1;
    unsigned int valx;
    unsigned int valy;
    unsigned int valz;

    boolean A_set;
    boolean B_set;

    int enA = 9;
    int in1 = 10;
    int in2 = 11;

    void setup() {

      pinMode(encoder0PinA, INPUT);
      pinMode(encoder0PinB, INPUT);
      // encoder pin on interrupt 0 (pin 2)
      attachInterrupt(0, doEncoderA, CHANGE);

      // encoder pin on interrupt 1 (pin 3)
      attachInterrupt(1, doEncoderB, CHANGE);
      Serial.begin( 9600 );

      pinMode(enA, OUTPUT);

      pinMode(in1, OUTPUT);
      pinMode(in2, OUTPUT);
      digitalWrite(in1, HIGH);
      digitalWrite(in2, LOW);
      analogWrite(enA, 225);
      Serial.begin (9600);
    }

    void loop(){
    //Check each second for change in position

      if (tmp_Pos != encoder0Pos) {
        Serial.print("Index:"); Serial.print(encoder0Pos * 90,DEC);
        Serial.println();
        Serial.print("valx:");Serial.print(valx,DEC);
        Serial.println();
        Serial.print("valy:");Serial.print(valy,DEC);
        Serial.println();
        Serial.print("valz:");Serial.print(valz,DEC);
        Serial.println();
        tmp_Pos = encoder0Pos;
      }
    }

    // Interrupt on A changing state
    void doEncoderA(){

      // Low to High transition?
      if (digitalRead(encoder0PinA) == HIGH) {
        A_set = true;
        if (!B_set) {
          encoder0Pos = encoder0Pos + 1;
          valx=analogRead(0);
          valy=analogRead(1);
          valz=analogRead(2);
        }
      }

      // High-to-low transition?
      if (digitalRead(encoder0PinA) == LOW) {
        A_set = false;
      }
    }

    // Interrupt on B changing state
    void doEncoderB(){

      // Low-to-high transition?
      if (digitalRead(encoder0PinB) == HIGH) {
        B_set = true;
        if (!A_set) {
          encoder0Pos = encoder0Pos - 1;
        }
      }

      // High-to-low transition?
      if (digitalRead(encoder0PinB) == LOW) {
        B_set = false;
      }
    }

  [1]: http://playground.arduino.cc/Main/RotaryEncoders

body:
If the encoder only gives +1 pulse per 90 degrees, you aren't going to get better than 90 degree accuracy out of it.

In the example code at the link, the val{x,y,z} are measured analog variables of some other thing that are sampled at each encoder lcoation:

> My project is a data loger where three analogue inputs are sampled
> each time a rotary encoder pulse steps clockwise. On an Arduino, time
> is of the essence to get this data sampled and saved somewhere (I have
> not included the 'saving somewhere' part of this project yet.) In
> order to save some processor cycles, I have slightly redesigned the
> interrupt system to maintain a pair of boolean states outside of the
> interrupt loop.

These are not directly related to the positioning of the encoder, and there is no reason to think they provide angle information.


message:
FCC Certification

I noticed that both the Uno and Wifi101 are FCC certified.  Does this mean that these components can actually be used in commercial applications?  This never really occured to me before I noticed the markings.

I'm sure there is more to a commercial product than just FCC certification but I know that the certification process isn't cheap!

body:
These products are not certified, they merely have been verified and issued a Declaration of Conformity. The WiFi module on the WiFi shield itself has been certified, as indicated by the FCC ID on its label.

To explain what that means, I am going to give a simplified explanation. If you are looking to make a commercial product and you are not sure what you need to do to be compliant, hire out a professional to help you through the process.

In the eyes of the FCC, devices fall into one of two categories, devices that are intentional transmitters, and devices that are not. Devices that are intentional transmitters need to be certified. Certification is a process of making sure that it is only transmitting on the frequency band it specified, that it is maintaining certain power limits, and that it will not cause interference with other devices. This is a very expensive testing procedure.

Devices that are not intentional transmitters, only need to get a verification. What this means is that the devices is not designed to transmit anything and is test to makes sure that it indeed does not. If you pass the verification you are issued a Declaration of Conformity basically stating that the device is not unintentionally transmitting any frequencies. This is usually a lot less expensive than than certification (but still in the few thousand USD range).

[![WiFi Shield Module][1]][1]

So taking the WiFi shield as an example, the module shown above circled in red is an intentional transmitter, i.e. it is designed to transmit on a particular frequency band (in this case 2.4 GHz ISM band). The device is certified to make sure that its emissions are within FCC specifications and it is issued an FCC ID.

Now at this point only the module is certified and is good to be used in a product, however, now that it is on a shield with extra circuitry added to it, the extra circuitry could be unintentionally transmitting. So now the whole shield is tested to make sure that the added circuitry does not have any emissions exceeding the FCC specifications and is issued a Declaration of Conformity.

So now fast forward to making your own thing, the module is certified, the WiFi shield and the Uno are verified, you add your own additional circuity around those components that may emit electromagnetic fields. You now may have to get your product verified to ensure that the added components to the system have not caused it to unintentionally emit radio frequencies.

The whole process, conditions, and requirements are a lot more nuanced than my description above. So this should in no way be used as the basis for product development or legal advice.

(Image borrowed from https://www.arduino.cc/en/Main/ArduinoWiFiShield101)

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


message:
Connecting Winbond W49F002U-12B to Arduino Mega

I am trying to connect a CMOS flash memory Winbond W49F002U-12B to an Arduino Mega, but failing.

[![Winbond W49F002U-12B][1]][1]

What I did:

1. Read the Winbond W49F002U-12B datasheet. The key points are: CE - chip enabled; OE - output enabled; WE - write enabled and this table:

> [![Winbond W49F002U-12B Operating Modes][2]][2]

2. Wrote this code and uploaded to Mega2560:

        int A_pins[18] = {22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39};
        int DQ_pins[8] = {40, 41, 42, 43, 44, 45, 46, 47};
        int CE = 50;
        int OE = 49;
        int WE = 48;

        char ch;
        char addrs[5];
        unsigned long address;
        unsigned int result;
        void setup() {
          Serial.begin(9600);
          for(int i=0; i<18; ++i)
              pinMode(A_pins[i], INPUT);
          for(int i=0; i<8; ++i)
              pinMode(DQ_pins[i], OUTPUT);
          pinMode(CE, OUTPUT);
          pinMode(OE, OUTPUT);
          pinMode(WE, OUTPUT);
          digitalWrite(WE, HIGH);
          digitalWrite(OE, HIGH);
          digitalWrite(CE, LOW);

        }

        void func(unsigned long adr)
        {
          for(int i=0; i<18; ++i){
            if(adr & (1ul << i)){
              digitalWrite(A_pins[i], HIGH);
              Serial.print("A_pins[");
              Serial.print(i);
              Serial.println("] = HIGH");}
            else{
              digitalWrite(A_pins[i], LOW);}}
          digitalWrite(OE, LOW);
          delay(100);
          for(int i=0; i<8; ++i){
            if(digitalRead(DQ_pins[i]) == HIGH){
              result|=1<<i;
              Serial.print("DQ_pins[");
              Serial.print(i);
              Serial.println("] = HIGH");}
          }
          Serial.println(result);
          digitalWrite(OE, HIGH);
        }

        void loop() {
          if (Serial.available() > 0)
          {
           address = (unsigned long)Serial.parseInt();
           Serial.print("address = ");
           Serial.println(address);
           func(address);
           }
        }

What this code is doing is basically after reading serial:

 -> takes the value as address

 -> changes pins A0-A17 to select particular address cell

 -> changes OE to LOW

 -> reads DQ0-DQ7

 -> coverts those readings into int

 -> prints result out.

Example of Arduino IDE Serial Monitor inputs/ouputs stuff:

    address = 0
    0
    address = 1232
    A_pins[4] = HIGH
    A_pins[6] = HIGH
    A_pins[7] = HIGH
    A_pins[10] = HIGH
    0
    address = 131072
    A_pins[17] = HIGH
    0
    address = 245760
    A_pins[14] = HIGH
    A_pins[15] = HIGH
    A_pins[16] = HIGH
    A_pins[17] = HIGH
    0

> Arduino Mega board is 100% functioning. I don't think Winbond w49f002u-12b is not working. Where am I wrong?

**UPDATE:** Here is fixed code:

    int A_pins[18] = {22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39};
    int DQ_pins[8] = {40, 41, 42, 43, 44, 45, 46, 47};
    int CE = 50;
    int OE = 49;
    int WE = 48;

    unsigned long address;
    unsigned int result;
    void setup() {
      Serial.begin(9600);
      for(int i=0; i<18; ++i)
          pinMode(A_pins[i], OUTPUT);
      for(int i=0; i<8; ++i)
          pinMode(DQ_pins[i], INPUT);
      pinMode(CE, OUTPUT);
      pinMode(OE, OUTPUT);
      pinMode(WE, OUTPUT);
      digitalWrite(WE, HIGH);
      digitalWrite(OE, HIGH);
      digitalWrite(CE, LOW);

    }

    void func(unsigned long adr)
    {
      result = 0;
      for(int i=0; i<18; ++i){
        if(adr & (1ul << i)){
          digitalWrite(A_pins[i], HIGH);
        }
        else{
          digitalWrite(A_pins[i], LOW);}}
      digitalWrite(OE, LOW);
      //delay(100);
      for(int i=0; i<8; ++i){
        if(digitalRead(DQ_pins[i]) == HIGH){
          result|=1<<i;
        }}
      Serial.println(result);
      digitalWrite(OE, HIGH);
    }

    void loop() {
      if (Serial.available() > 0)
      {
       address = (unsigned long)Serial.parseInt();
       Serial.print(address);
       Serial.print(": ");
       func(address);
       }
    }

**UPDATE:** Changed code using PORTs, Thanks to @MikaelPatel for reminding about PORTs:

    unsigned long address;

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

      DDRL = B00000000; // DQ7-DQ0 42-49
      DDRA = B11111111; // A7-A0 29-22
      DDRC = B11111111; // A15-A8 30-37
      DDRG |= B00000011; // A17-A16 40-41
      DDRB |= B00000111; // WE, OE, CE

      PORTB = B00000110; // WE - HIGH, OE - HIGH, CE - LOW
    }

    void func(unsigned long adr)
    {
      PORTA = adr;
      PORTC = (adr>>8L);
      PORTG = (adr>>16L);
      PORTB = B00000100; //OE - LOW
      Serial.println(PINL);
      PORTB = B00000110; //OE - HIGH
    }

    void loop() {
      if (Serial.available() > 0)
      {
       address = (unsigned long)Serial.parseInt();
       Serial.print(address);
       Serial.print(": ");
       func(address);
       }
    }

  [1]: https://i.stack.imgur.com/4rh9M.png
  [2]: https://i.stack.imgur.com/3YZyj.png

body:
> What this code is doing is basically after reading serial: ... -> reads DQ0-DQ7

But all the DQn pins are in OUTPUT mode and the A pins in INPUT mode. Seems to be a mix up. BW: it is the same with all of the pins. The pin mode is from the Arduinos point of view and not the memory chip.

Cheers!


message:
Is it OK to Serial.print(message), when the USB cable is not connected to a host PC?

Often I put a bunch of `Serial.print( F("debugging messages") )` in my Arduino sketch.

Normally those messages go up a USB cable to a host PC so those messages can be seen on the serial monitor.

I want to install this Arduino as part of a stand-alone system far from any PC and plug the "host" end of the USB cable into a wall-wart USB charger.

Without anything to accept those messages, the buffer on the Arduino eventually fills up, right?
Do I need to do anything to keep the Arduino from overflowing and crashing when it's not connected to a host PC?

Does it make any difference if I'm using a (1) "single-chip" Arduino-compatible where the processor includes on-chip USB, vs. (2) an Arduino-compatible with separate "USB interface chip" and "processor chip"?
(By "single-chip Arduino-compatible", I mean things like the Arduino Leonardo, Arduino Yún, LilyPad Arduino USB, Arduino Micro, the Teensy-LC, etc.)

body:
It is OK to write out serial data with nothing connected.

In case (2) "Arduino + USB interface chip", the arduino has no idea if anything is connected or listening to the serial port. The code will transmit the bytes and act exactly the same whether plugged in to anything or not.

In case (1) "arduino with built in USB" it has some idea, but just drops bytes that are going to be transmitted when the USB port is not connected.

Hardware serial (case 2) has an output buffer, but that just makes the program a little faster. When the buffer is empty, a call to `serial.{print, write}` will place bytes in the buffer and move on. When it's full, `Serial.{print,write}` will wait until there is enough room to put the rest of the message in the buffer and move on. The hardware UART and interrupts it generates will keep taking bytes out of the buffer and transmitting them at a constant rate whether something is plugged in or not. In any case, the buffer is a fixed size and will never overflow.

As far as I can tell USB-Serial (case 1) only buffers incoming data. Since the calls to `Serial.{print, write}` do nothing when not connected, they may take less time than they would otherwise. If your code is really unsafe about timing, that could cause a problem, but I doubt it will.

Many examples that come with the Arduino IDE have the following bit of code that pauses native USB Arduino-compatibles until the USB connection is initialized:

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

This code stops the Arduino from doing anything until the USB cable is connected.
Comment out or delete those 3 lines if you want the Arduino to run "stand-alone" without a USB cable connection ([Arduino Cookbook][1] p. 117) --
after you delete those lines, if you later plug in a USB cable, the USB will initialize correctly, and *then* you will see on your serial monitor everything printed by any *later* Serial.print() commands that run. (Tested on a Teensy LC).

  [1]: https://books.google.com/books?id=3b3dDwAAQBAJ


message:
Code to control servo with shield

I recently bought an Arduino MEGA2560 and a [SainSmart InstaBots Robot Controller Shield for Arduino MEGA2560 R3 Robot Arm Control][1].

I understand how to control a servo in the method described in [Sweep][2]. However, I want to control six servos using the shield area circled in red below. Could anyone provide the code to setup and control servos from the area circled in red?

Please help me I am a beginner in robotics and I need this for a project.

[![enter image description here][3]][3]

  [1]: http://www.sainsmart.com/sainsmart-instabots-robot-controller-shield-for-arduino-mega2560-r3-robot-arm-control.html
  [2]: https://www.arduino.cc/en/Tutorial/Sweep
  [3]: https://i.stack.imgur.com/iVWnv.jpg

body:
> However, I want to control six servos using the shield area circled in red below. Could anyone provide the code to setup and control servos from the area circled in red?

With the limited amount of info you have provided about the shield this will have to be a wild guess. I am assuming that the pins are S(ignal), V(cc) and G(nd) for pins 8-13. On an Arduino Mega these can be used for PWM and therefore Servo control.

Include the Servo library, attach the pin and set the angle.

    #include <Servo.h>

    Servo servo[6];

    void setup()
    {
      ...
      for (int i = 0; i < 6; i++)
        servo[i].attach(8 + i);
      ...
    }

    void loop()
    {
       ...
       servo[i].write(pos);
       ...
    }

Cheers!

NB: Do not forget to provide the correct power supply. If USB Port is left, then the upper pin is positive and the lower pin negative.


body:
The SVG connectors on your board appear to be lacking header pins:

[![Three pin header][1]][1]

These should have been supplied with the board. If not you will need to source some. Either way, you will need to solder them on. I don't understand why they are not already attached.

If you look at the other images of the board on the SainSmart web page, the header pins are clearly visible:

[![SainSmart shield with header pins][2]][2]

The S pin of each SVG is the same as the output pins, near the green light, but for ease of use, they are replicated in the SVG pins, so that a servo plug can be easily, and conveniently plugged in, with out the user having to wire up power and ground separately.  If you look at the plug attached to the end of the cable coming from your servo, you will see the servo connector, like so:

[![Servo connector][3]][3]

As the board has arranged the pins in the SVG order, that means that it will support the Futaba J type connectors (but not the Airtronics, as the power and ground pins are reversed):

[![Futaba and Airtronics connectors][4]][4]

Also, Hitec and JR Radio connectors are supported by your board, as they have the same pin out:

[![JR Radio and HiTec connectors][5]][5].

For more information, take a look at [Choosing RC Servos][6].

In addition, as Mikael says, you will also need to attach an external power supply to the green terminals

[![SainSmart shield showing green external power connector][7]][7]

as the on board power regulator of the Arduino can not supply enough power to the servos, via the shield, by itself, neither with the USB, nor an external wall wart PSU, supplying power to the Arduino. So, use a bench power supply, battery pack, or otherwise and supply that power directly to the board via the Green power terminals at the end of the board.

Once you have done all of that, and got the hardware out of the way, then the software provided in [Mikael's answer][8] will work perfectly.

  [1]: https://i.stack.imgur.com/Ofsli.jpg
  [2]: https://i.stack.imgur.com/o9yaD.jpg
  [3]: https://i.stack.imgur.com/mylsp.jpg
  [4]: https://i.stack.imgur.com/Sy2RH.gif
  [5]: https://i.stack.imgur.com/Kjs4s.gif
  [6]: http://www.hooked-on-rc-airplanes.com/rc-servos.html
  [7]: https://i.stack.imgur.com/XI6lw.jpg
  [8]: https://arduino.stackexchange.com/questions/20931/code-to-control-servo-with-shield#answer-20937


body: Sainsmart STILL refuses to supply documentation for this board.Supposedly, it can control 6 servos and two motors, up to 4 Amps, with digital encoder inputs. There is NO documentation on the hardware or the software for the mega to drive this.


message:
Loop behaves oddly in I2C receiveEvent

I am messing around with an ATmega328P hooked on a Raspberry Pi, communicating over I2C. The ATmega is the slave (details at the end). While testing the basics of the concept, I faced an interesting problem.

This is the code on the ATmega:

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

    #include <Wire.h>

    #define SLAVE_ADRESS 0x1A
    #define LED 6

    int count = 10;
    void setup()
    {
        pinMode(LED, OUTPUT);
        /*for(int i=1; i<=3; i++)
        {
          digitalWrite(LED, HIGH);
          delay(100);
          digitalWrite(LED, LOW);
          delay(100);
        }*/
        Wire.begin(SLAVE_ADRESS);
        Wire.onReceive(receiveEvent);
        Wire.onRequest(requestEvent);
    }

    void loop()
    {
      delay(10);
    }

    void receiveEvent(int received_bytes)
    {
      while(Wire.available())
      {
        unsigned char i = Wire.read();
        if(1)
        {
          int j = 5;
          while(j>0)
          {
            digitalWrite(LED, HIGH);
            delay(300);
            digitalWrite(LED, LOW);
            delay(300);
            j-=1;
          }
        }
        delay(1);
      }
    }

    void requestEvent()
    {
      Wire.write(count);
    }

What you would expect it to do is blink the LED connected to pin 6 five times when the Pi sends a byte to the ATmega slave. (Things like `if(1)` are there because the code was much more specific originally.) The strange thing is that this is not the case:

*The LED only blinks 1 time.*

I honestly have no idea why. This "stdio-fitted" version of the problematic loop ran on the RPi as expected, prints 5*2 times:

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

    #include <stdio.h>

    int main()
    {
      int j = 5;
      while(j>0)
      {
        printf("LED, HIGH\n");
        printf("LED, LOW\n");
        j-=1;
      }
      return 0;
    }

**Circumstances:**

 - I compile the code in the Arduino IDE on the Pi, then upload it
   using AVRDUDE to the ATmega with the Pi's GPIOs. No error messages
   over the process.
 - The ATmega gets 3.3 V supply voltage from the Pi, and operates on
   16.000 MHz. Only the LED and the Pi is connected to it.
 - The (Python) code I use on the Pi to write and read a byte is the following. Reading works well, and I know by tests that the ATmega actually receives the correct byte:

<!-- language: lang-python -->

    import pigpio
    import time

    pi = pigpio.pi()
    atmega = pi.i2c_open(1, 0x1A)

    for i in range(6):
        a = pi.i2c_read_byte(atmega)
        print a

    pi.i2c_write_byte(atmega, 0x05)
    time.sleep(1)

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

    void receiveEvent(int received_bytes)
    {
      while(Wire.available())
      {
        unsigned char i = Wire.read();
        if(1)
        {
          int j = 5;
          while(j>0)
          {
            digitalWrite(LED, HIGH);
            delay(300);
            digitalWrite(LED, LOW);
            delay(300);
            j-=1;
          }
        }
        delay(1);
      }
    }

`receiveEvent` is an ISR (interrupt service routine). Don't do `delay` in an ISR. That will hang indefinitely. Thus the LED only blinks once. You could do `delayMicroseconds` for *testing*. In general an ISR should be **short**.

---

* [Interrupts](http://www.gammon.com.au/interrupts)
* [I2C](http://www.gammon.com.au/i2c)