message:
MPU 6050 stuck on same values

I'm having a problem with my MPU6050. I'm using PID to speed up a motor with the MPU values. What could the problem be?

Here is a link to a previous question that I asked concerning a problem with pid: https://arduino.stackexchange.com/questions/20700/pid-not-working-correctly/20703?noredirect=1#comment39146_20703

These are the values that I'm getting, which repeat forever. The values are:

 - motor speed;
 - the value that changes the motor speed;
 - the MPU value;
 - the change that PID made.

----
    0.00
    0
 10900
 4800

    0.00
 0
 10900
 4800

----

Here is the code itself.

<!-- language: c -->

    int16_t ax, ay, az;

    double Setpoint, Input, Output;
    //Specify the links and initial tuning parameters
    double Kp=2, Ki=5, Kd=1;
    PID myPID(&Input, &Output, &Setpoint, Kp,Ki,Kd, DIRECT);

    void setup() {
     Input = analogRead(ax);
      Setpoint = 100;
      //turn the PID on
       myPID.SetMode(AUTOMATIC);
    }

    void loop() {
     accelgyro.getAcceleration(&ax, &ay, &az);
      int a=ax+10900;
    //Here I set the used variable to around 0. ax is actually around -10900
    //This is always true, this won't be in the final code. This is just making        it work.

    if(1) {
     int val;
      val = map(a, -1300, 1300, 0, 1023);
       Input = val;
        myPID.Compute();
         Serial.println(Output);

    digitalWrite(motorPin2, HIGH);
    Serial.print("\t");
    Serial.println(ax);
    Serial.print("\t");
    Serial.println(a);
    Serial.print("\t");
    Serial.println(val);
         }
    }

body:
Let's deconstruct this down to a simple example which we can test without the MPU6050:

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

    #include <PID_v1.h>

    double Setpoint, Input, Output;
    //Specify the links and initial tuning parameters
    double Kp = 2, Ki = 5, Kd = 1;
    PID myPID(&Input, &Output, &Setpoint, Kp, Ki, Kd, DIRECT);

    void setup() {
      Setpoint = 100;
      //turn the PID on
      myPID.SetMode(AUTOMATIC);
      Serial.begin (115200);
      Serial.println (F("\n\nStarting\n\n"));
    }

    void loop() {
      int a = 0;
      int val = map(a, -1300, 1300, 0, 1023);
      Input = val;
      myPID.Compute();
      Serial.print (F("Input = "));
      Serial.println(Input);
      Serial.print (F("Setpoint = "));
      Serial.println(Setpoint);
      Serial.print (F("Output = "));
      Serial.println(Output);
      Serial.println();
      delay (300);
    }

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

Output:

    Starting

    Input = 511.00
    Setpoint = 100.00
    Output = 0.00

    Input = 511.00
    Setpoint = 100.00
    Output = 0.00

    Input = 511.00
    Setpoint = 100.00
    Output = 0.00

    Input = 511.00
    Setpoint = 100.00
    Output = 0.00

Indeed it isn't changing. Let's analyze why:

* The input is 511
* The setpoint is 100
* Therefore the error is 100 - 511 = -411
* Disregarding (for the moment) the integral and differential terms, you have a proportional term of 2 (Kp) so the algorithm tries to output 2 * Error
* Output would be 2 * -411 = -822
* However the maximum and minimum limits default to 0 to 255, and thus the output is clamped to 0.
* The algorithm outputs 0.
* And the next time it does the same thing.

There is a function `SetOutputLimits` which can be used to change the default minimum and maximum output values.

The Ki and Kd values might eventually have an impact, but you won't notice anything with the output clamped to zero.

For example, adding this line in `setup` gives different results:

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

      myPID.SetOutputLimits (-5000, 5000);

Result:

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

    Starting

    Input = 511.00
    Setpoint = 100.00
    Output = -5000.00

    Input = 511.00
    Setpoint = 100.00
    Output = -1233.00

    Input = 511.00
    Setpoint = 100.00
    Output = -1438.50

    Input = 511.00
    Setpoint = 100.00
    Output = -1644.00

    Input = 511.00
    Setpoint = 100.00
    Output = -1849.50

    Input = 511.00
    Setpoint = 100.00
    Output = -2055.00

    Input = 511.00
    Setpoint = 100.00
    Output = -2260.50

    Input = 511.00
    Setpoint = 100.00
    Output = -2466.00

Whether they are valid limits depend on what you are attempting to do exactly.


sender: user

sender: assistant

body:
The problem was that I had the SCL and SDA pins connected to the wrong Arduino pins.

Sorry for bothering your time. Thanks for the tips.


message:
SD card initialization fails randomly

I have a SD card reader that is working fine exept that sometimes SD.begin fails for no apparent reason.
To work around this issue I have put the SD.begin in a while loop and then I display the error on my LCD. When the error happens I then remove and reinsert the card witch works usualy on the first or second try. I have never seen any problem ones the card is initilized.
Does anyone has any idea what might be the problem?

body:
I have seen SD cards that do not like this section of code:

      // command to go idle in SPI mode
      while (cardCommand(CMD0, 0) != R1_IDLE_STATE) {
        if (((uint16_t)millis() - t0) > SD_INIT_TIMEOUT) {
          error(SD_CARD_ERROR_CMD0);
          goto fail;
        }
      }

Some SD cards (mine, of course) seem to need a little quiet time to finish their INIT process.  Adding a delay of <something> made the INIT process complete successfully, first time through the loop.

I'm *guessing* that the SD card spends so much time handling the repeated CMD0 commands (continuously sent by above loop) that they don't get to spend time on the INIT process.  IIRC, the standard says the card is allowed to take up to 2 seconds to INIT (!).  I can't recall, but I think I tried 150ms or so:

      // command to go idle in SPI mode
      while (cardCommand(CMD0, 0) != R1_IDLE_STATE) {
        delay( 150 ); // let SD get some time to work
        if (((uint16_t)millis() - t0) > SD_INIT_TIMEOUT) {
          error(SD_CARD_ERROR_CMD0);
          goto fail;
        }
      }

I do recall that reinserting the card would sometimes make it work.  I have suggested this to at least one SD card library maintainer, but I think we're all reluctant to impose a delay on *all* cards.  OTOH, it is just during `::begin`.

It might work for you, though.  The above snippet is from SdSpiCard.cpp, but you may have to go looking for it in other places, depending on which library and version you're using.


message:
Help with a rather specific implementation of FFT Library?

So, I guess what I'm trying to do here is properly understand the FFT library posted [here][1] by Open Music Labs, done in C++. I believe I understand the Fourier transform, but the FFT has some nuance that I'm not quite familiar with. From what I understand, the FFT takes a amplitude vs. time signal and transforms it into its constituent frequencies like a normal Fourier transform, but it only does so at given points that break down the signal into the Arduino's clock speed divided by the number of bins decided on, for the sake of efficiency. Thus each bin actually accounts for a number of frequencies that is also equal to the clock speed divided by bin number. I'm correct so far, right?

So here's my question. I have a very specific application of the FFT that requires reading only frequencies at roughly 0-100 Hz. Everything else I don't need, and I want to know how to achieve such high resolution. I imagine that because the number of bins seems to be capped at around 512, that there must be some sort of way to decrease the clock speed to an exorbitantly low number in order to read these frequencies. How might I go about doing that? Or maybe there is a better way to apply the transform to the data at such low frequencies through some other method outside of FFT?

Second, I'm wondering how performing multiple FFTs simultaneously will affect performance, and if there is some way I can export this data to another program in order to do the heavy lifting regarding data storage, seeing as I imagine performing many FFTs all at once will decimate the available memory on the Arduino itself if all of those values aren't being kept on my computer.

Thanks in advance for any insight you guys might be able to provide

  [1]: http://wiki.openmusiclabs.com/wiki/ArduinoFFT

body:
As Edgar has mentioned you are confusing things slightly.

First there is your sampling frequency. According to the Shannon-Nyquist theorem that is at a minimum of 2x the maximum frequency in your signal. So that is 2x100 = 200Hz. That's the number of samples per second in your sample set.

Secondly is your sample size, which is directly related to the FFT bucket size. For every two samples you can get one bucket. The more samples you have the more buckets you have, and the higher the resolution each bucket is. But for FFT to work you need a power-of-two sized sample set. That means 2, 4, 8, 16 etc samples.  So 256 samples would give you 128 buckets. That would be a little under 1Hz per bucket.

To make things cleaner though you can back-apply the last calculation to the first and get them to match. 256 samples at 256 samples per second will give you 128 buckets covering 0-128Hz so 1Hz per bucket.  Double that to 512 samples and you get 256 buckets at 0.5Hz per bucket. Double it again and you get double the resolution again.

The main speed issue that you will come across is not the time taken to do the FFT, but the time taken to capture your sample set. 256 samples at 256 samples per secod will, of course, take 1 second to capture. 512 samples will be 2 seconds, etc. Far longer than a decent FFT takes to calculate.


message:
Breadboard for kids

I am interested in teaching young kids how to build arduino projects. I was thinking that using a breadboard may be difficult for them, as the holes are all very close together. It is easy to put the pins in the wrong hole.

Are there any breadboards with larger hole spacings that could make it easier to use for kids?

body:
Breadboards are made to work with components of a standard size - a breadboard with larger hole spacing would not be able to fit standard through-hole chips. I have never seen such an item.

Having said that, I have had a lot of success using alligator clips. You can clip them directly on to wires for LEDs, resistors, capacitors, so long as you make sure they legs/clips don't touch.

Then there are made-for-children systems, snap-together, like http://www.vk3bq.com/2013/08/17/snap-circuits-electronics-kits/ or http://mashable.com/2013/05/21/lightup-magnetic-building-blocks/#t5Kq_yIDpaqr


body:
Build your own breadboard!

Literally, a wooden board with a grid of small woodscrews screwed into it, each screw holding down a cup washer.

Connections are made by trapping component leads and wires under the edge of the cup washer before screwing it down.

You need components with reasonably long leads, and it might still be necessary to solder longer wires to the leads in some cases.

I am told that in the olde days, this is how hobbyists used to do it...

Here's a link to an example (I read a copy of this book as a kid):
http://www.mds975.co.uk/Content/george_dobbs_trf_radio.html


body:
The problem (probably) isn't only because it's too small, wiring can be hard to understand.

I think this might be a solution:
[![enter image description here][1]][1]

It'll cost you some work. But it will get difficult for them to wire it wrongly.
Also, I believe coloring them, will make the kids understand it much better. This way they would also be less likely to short out pins etc. Saving you some rangers/arduinos.

Be sure that the power-connectors are not reversible. And you should use a separated supply (with overcurrent protection and what not) and tie the GND to the arduino GND. This way you could even use the supply power for heavier devices.

I'm not a 100% sure on the resistors though, they might interfere with some things you want to make/show.

Maybe even add blue color for inputs and yellow for outputs (or whatever the standard is). Or you might even make generic connectors, like on the Lego NXT robots, that's some really easy wiring! http://www.philohome.com/nxtldraw/NXTkitLDview.jpg

Or check out projects like: "LittleBits Arduino".
https://s3.amazonaws.com/lb-spree/spree/products/2003/large/ArduinoDetail4.png?1423167488

And, check http://www.rugged-circuits.com/ruggeduino/ on 10-ways to destroy your arduino. If you take these things into mind, you can make a pretty solid Arduino, so that wrong wiring won't lead to any damaged Arduino's etc.

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


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

or

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

or

Maybe use something like [Littlebits](http://littlebits.cc/), which uses magnets, but is kind of expensive.

  [1]: https://i.stack.imgur.com/Fqs65.jpg
  [2]: https://i.stack.imgur.com/1H0Os.jpg


message:
Bluetooth HC-05 Library for Proteus

I m working on a project in which I am using HC04 module so can anyone give me any Arduino Library for Proteus which have HC05 in it. Or tell me how to use HC05 in Proteus.

Thanks.

body:
I don't know Proteus, but I think HC05 a bluetooth module? If so, the module interface from HC05 <==> arduino is done through Serial (UART) communication.
Arduino has built in support for this - you don't need any special libraries besides SoftwareSerial.
wire up the module as such:
[![enter image description here][1]][1]

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

Then run the following code:

    #include <SoftwareSerial.h>

    #define rxPin 10 // connected to TX pin of HC05
    #define txPin 11 // connected to RX pin of HC05

    SoftwareSerial mySerial(rxPin, txPin); // RX, TX
    char bt;

    void setup() {
      Serial.begin(9600);
      Serial.println("Hello");

      mySerial.begin(9600);
      mySerial.println("World");
    }

    void loop(){
      while(mySerial.available()){
        bt = mySerial.read();
        Serial.print(bt);
      }

      while(Serial.available()){
       bt= Serial.read();
       mySerial.print(bt);
      }
    }


body:
There is no Proteus Library for HC05. (Not one I know of.)

Now, your HC05 is a serial device i.e. it acts as a **Serial monitor**. and fortunately there is **Serial Monitor** in Proteus. You can use that.

[Here, Have a look.][1]

P.S. if you are using ISIS 7.x. there is a thing to be noted. You have placed a **serial monitor** and connected to arduino and you started execution and its working fine. Now, what happens sometimes is that when you stop execution and start again, serial monitor might not work. No need to worry about. Stop execution, delete that serial monitor and place a new.That will work.

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


body:
I have found this [Bluetooth Library for Proteus][1]. Thanks for helping me out guys. I am posting it here so that others can also get benefit out of it.

Thanks.

  [1]: http://www.theengineeringprojects.com/2016/03/bluetooth-library-for-proteus.html


message:
"'Serial' does not name a type" error

I'm getting a `"'Serial' does not name a type"` error when this program is compiled. I need for the 8 channels of voltage to be displayed. I'm sure it's a simple fix, however I'm still learning Arduino programming. I thank you for your help.

    int pin_Out_S0 = 8;
    int pin_Out_S1 = 9;
    int pin_Out_S2 = 10;
    int pin_In_Mux1 = A0;
    int Mux1_State[8] = {0};
    //float Mux1_State[i] =0;
    int RawValue=0;
    float Voltage = 0;
    void setup() {
      pinMode(pin_Out_S0, OUTPUT);
      pinMode(pin_Out_S1, OUTPUT);
      pinMode(pin_Out_S2, OUTPUT);
      pinMode(pin_In_Mux1, INPUT);
      Serial.begin(9600);
    }

    void loop() {
     RawValue = analogRead(pin_In_Mux1);
     Voltage = (RawValue * 5.0) / 1024; //scale the ADC
      updateMux1();
      //Serial.println(Mux1_State);
      for(int i = 0; i < 8; i ++) {
        if(i == 7) {
          Serial.println(Mux1_State[i]);
        } else {
          Serial.print(Mux1_State[i]);
          Serial.print(",");
          //vout = (value * 5.0) / 1024.0;
        }
      }
    }

    void updateMux1 () {
      for (int i = 0; i < 8; i++){
        digitalWrite(pin_Out_S0, HIGH && (i & B00000001));
        digitalWrite(pin_Out_S1, HIGH && (i & B00000010));
        digitalWrite(pin_Out_S2, HIGH && (i & B00000100));
        Mux1_State[i] = analogRead(pin_In_Mux1);
      }
    }
    Serial.print("Raw  Value = " );
    Serial.print(RawValue);

body:
Your last two lines are not in any function. This confuses the compiler. You need to move those two statements inside a function.

Because those statements refer to `RawValue`, I'm guessing you want to put them in `loop()`, where RawValue is being updated.

Also, remember that the IDE will tell you on which line the error is, which is helpful when debugging compilation errors.


body:
Please put these lines inside the loop() function block:

    Serial.print("Raw  Value = " );
    Serial.print(RawValue);

Should look something like:

    void loop() {
     RawValue = analogRead(pin_In_Mux1);
     Voltage = (RawValue * 5.0) / 1024; //scale the ADC
      updateMux1();
      //Serial.println(Mux1_State);
      for(int i = 0; i < 8; i ++) {
        if(i == 7) {
          Serial.println(Mux1_State[i]);
        } else {
          Serial.print(Mux1_State[i]);
          Serial.print(",");
          //vout = (value * 5.0) / 1024.0;
        }
      }
      Serial.print("Raw  Value = " );
      Serial.print(RawValue);
    }

That should at least remove the first issue with your code.

Cheers!


body: In addition to the good answers by Mikael and Uint, everything needs to be inside {curly braces} otherwise the IDE does not know where it belongs. If you didn't want the last 2 lines in your loop segment you could put them in a separate `void xxxx ()` section to be called when the time is right (by using an ISR with an `enableinterrupt` function for example).


message:
How to know if my Bluetooth HC-05 is connected through serial monitor

I want to connect a Bluetooth module to arduino and check if my module is connected or not.. Through serial monitor. Is there and particular code to connect with that?

body:
If your board is actually a HC-05, you can

 1. Pull the KEY pin to Vcc (see note)
 2. Write the serial command `AT` on the serial interface
 3. Look at the output: if you receive `AT` or `OK` then the module is connected, otherwise it is not

Note: The key pin is the number 34 on the SMT module (with the antenna pointing upwards, its the pin in the top-right corner). If you have a THT module (so the one with about 6 pins) MAYBE this pin is connected to one of the pins you don't usually use (they are named EN, STATE, ...). Check with a multimeter if it is connected to one of these. If it is not, then you'll have to solder a wire from it to an arduino pin.

If, on the other hand, your board is a HC-06 (almost identical to HC-05, but with a different firmware - it is a slave-only bt device), then keep it disconnected from the master and perform steps 2 and 3: when not connected, in fact, the HC-06 is already in AT mode.

More information on [this webpage][1]

  [1]: http://www.instructables.com/id/AT-command-mode-of-HC-05-Bluetooth-module/?ALLSTEPS


message:
How to use strtok() and strstr() with arduino?

Can anyone explain how things like strtok() and strstr() can be used to provide a numeric value for a substring location position within the mainstring array.

I've tried to understand from the C++ examples, but their 'position' locations of the substring within the mainstring (which I need) are returned in C++ as %d variables, whereas all I can get returned by the arduino 'char * pointer=' is the actual substring chars if they exist, rather than a number for their start position locations within the mainstring.

The C++ examples show that it is possible to discover the position values from %d,  but how can I get that equivalent position value in arduino?

I want to be able to parse a char header[30] array for occurances of things like "s=123" and "d=789" in order to extract and assign the specified values to any appropriate variables (source or destination etc).

body:
You have to define a format for the header you will be parsing and stick to that format. Say this is a sample `header` terminated by null:

    s=123 d=789 e=463

A common property of each assignment in the string is the '=' symbol. You can use that to locate each variable and the value assigned to it. `strchr` is the function to use to locate a single character. Once you locate the = character, you move back and then forward along the array to obtain the variable and its value.

I will make some assumptions here: that your variable names will be single character, that numbers assigned will be no bigger than ints, and a space character is used to separate assignments.

    char header[] = "s=123 d=789 e=463";

    int d, s, e;   //your variables to be assigned to
    char * ptr = header;
    char * eq = NULL; //locate assmts
    int * num = NULL; //just for starters
    while (1){
      eq = strchr(ptr, '=');
      ptr = eq; // update the pointer
      if (ptr == NULL) // found no = chars
        break;
      switch (*(ptr - 1)){
        case 'd':    //all the possible variables
          num = &d; break;
        case 's':
          num = &s; break;
        case 'e':
          num = &e; break;
        default:   //unknown variable
          num = NULL;
      }
      ptr++;
      if (num == NULL) //unrecognized var
        continue;   // locate next = char
      *num = 0;
      while (*ptr && (*ptr != ' ')){  // while space or end of string not yet reached
        *num *= 10;  // extract each int
        *num += *ptr - '0';
        ptr++;
      }
    }

    Serial.println(d);  //now contains the numbers in the header
    Serial.println(s);
    Serial.println(e);

Untested but it should work for the header sample I gave.


message:
Trying to pass a char to software serial with a button press

Good day everyone,
I'm returning to the Arduino world after my a 3 year hiatus following the birth of my son.

I'm trying to push a button connected to pin 2 and have that send a 'd' to SoftwareSerial on pins 10,11. This should trigger an output back from the device connected to the SoftwareSerial.

I'm encountering an issue:

When I press the button it sends about 15 d's. I would like to limit this to just one char per button press, I attempted to build an if statement but it seems to ignore the conditions.

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

    #include <SoftwareSerial.h>
    // software serial #1: TX = digital pin 10, RX = digital pin 11
    SoftwareSerial portOne(10, 11);
    const int buttonPin = 2;     // the number of the pushbutton pin
    const int ledPin =  13;      // the number of the LED pin

    // variables will change:
    int buttonState = 0;         // variable for reading the pushbutton status
    int button1State = 0;

    // the setup function runs once when you press reset or power the board
    void setup() {
    // initialize digital pin 13 as an output.
      pinMode(ledPin, OUTPUT);
      pinMode(buttonPin, INPUT);
      Serial.begin(9600);
      while (!Serial) {
        ; // wait for serial port to connect. Needed for native USB port only
      }

      // Start each software serial port
      portOne.begin(4800);
      while (!portOne) {
        ; // wait for serial port to connect. Needed for native USB port only
      }
    }

    // the loop function runs over and over again forever
    void loop() {
      int Once = 0;
      buttonState = digitalRead(buttonPin);

      // check if the pushbutton is pressed.
      // if it is, the buttonState is HIGH:
      if (buttonState == HIGH ) {
        if (Once == 0) {
          Once = 1;
          // turn LED on:
          digitalWrite(ledPin, HIGH);
          // send D to Radio
          portOne.write("d");
          Serial.write("d");
          Serial.print(Once);
          Serial.println();
          delay(1);
        }
      }
      else (buttonState == LOW) {
        // turn LED off:
        Once = 0;

        digitalWrite(ledPin, LOW);

      }
      portOne.listen();
      // while there is data coming in, read it
      // and send to the hardware serial port:
      while (portOne.available() > 0) {
        char inByte = portOne.read();
        Serial.print(inByte);
      }
    }

body:
As pointed out by Edgar you should debounce the button. Perhaps increasing the delay() should do the trick.

Try with 100-200 milliseconds.

With this edit you can delete Once unless you are planning on using it somewhere else.


body:
As Edgar stated my issue was I didn't make the Once variable static

"1) You should debounce your button. 2) You should qualify Once as static, otherwise it's reset to zero (actually, recreated) every time you enter loop()."


message:
Arduino serial hex decimal values code

I'm trying to send heximal values from arduino to PZEM-04 power module (it shows voltage, current and ect.) over serial communication in heximal format and get values in decimal format for further actions with them. Any help with the code please?
One of the commands:
Send command: B4 C0 A8 01 01 00 1E
Reply data: A4 00 00 00 00 00 A4

Edit: I am connecting wires from PZEM module TTL to arduino "serial port": TX-RX, RX-TX, VCC-VCC, GND-GND, so it's serial communication..
    PZEM module: http://www.aliexpress.com/store/product/PEACEFAIR-AC-100A-Electric-power-monitoring-and-communication-module-power-meter-power-energy-Volt-Ammeter/1773456_32373508101.html

body:
A possible implementation of the protocol using serial read/write of binary data (command and response).

    void send(Stream& ios, uint8_t cmd[6])
    {
      uint8_t sum = 0;
      for (int i = 0; i < 6; i++) {
        uint8_t c = cmd[i];
        sum += c;
        ios.print((char) c);
      }
      ios.print((char) sum);
    }

    bool recv(Stream& ios, uint8_t res[6])
    {
      uint8_t sum = 0;
      uint8_t c;
      for (int i = 0; i < 6; i++) {
        while (!ios.available());
        c = ios.read();
        sum += c;
        res[i] = c;
      }
      while (!ios.available());
      c = ios.read();
      return (sum == c);
    }

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

      uint8_t cmd[] = { 0xB4, 0xC0, 0xA8, 0x01, 0x01, 0x00 };
      uint8_t res[6];
      send(Serial, cmd);
      recv(Serial, res);
    }

    void loop()
    {
    }

Cheers!


message:
Power Arduino Nano with OTG cable

I have a project that I am putting an Arduino Nano in an enclosed box that will light LEDs in a pattern. I am planning to power it with a 5 V power brick but I would like to build a way a update the code to the Arduino without needing to disassemble the box.

Could I use an OTG cable with power (OTG Y cable)  to accomplish this? or is there a better way to do this?

body:
It is possible to use a OTG Y cable just plug it into your phone, power cable into the power source and use the third connector to connect  to your PC. (Assuming the PC only gets GND, D+ and D- and battery bank GND, 5V)

It is also possible to reprogram an Arduino with an Android device that has OTG support.
Would save you a bit of hassle.

My Android phone (LG D605) with [ArduinoDroid][1] can easily upload code to my Nano and Uno.

  [1]: https://play.google.com/store/apps/details?id=name.antonsmirnov.android.arduinodroid2


message:
See compiled assembly output (Visual Micro)

I'm curious about what some of my code is being compiled into, is there a way to have the compiler save the intermediate assembly files, ideally somewhere in the project folder?  I read some forum posts about holding down shift when compiling from the Arduino IDE, but even that seems pretty hackish.

body:
Turn on Verbose Compiling in the Arduino IDE and you will see all the intermediate file names (they are done in a temporary folder).

For example:

    /home/nick/Development/arduino-1.6.7/arduino-builder -dump-prefs -logger=machine -hardware "/home/nick/Development/arduino-1.6.7/hardware" -hardware "/home/nick/.arduino15/packages" -hardware "/home/nick/Arduino/hardware" -tools "/home/nick/Development/arduino-1.6.7/tools-builder" -tools "/home/nick/Development/arduino-1.6.7/hardware/tools/avr" -tools "/home/nick/.arduino15/packages" -built-in-libraries "/home/nick/Development/arduino-1.6.7/libraries" -libraries "/home/nick/Arduino/libraries" -fqbn=arduino:avr:uno -ide-version=10607 -build-path "/tmp/build1cdca0d02fcf3112936d1438c170697d.tmp" -warnings=default -prefs=build.warn_data_percentage=75 -verbose "/tmp/arduino_1cdca0d02fcf3112936d1438c170697d/sketch_mar03b.ino"
    /home/nick/Development/arduino-1.6.7/arduino-builder -compile -logger=machine -hardware "/home/nick/Development/arduino-1.6.7/hardware" -hardware "/home/nick/.arduino15/packages" -hardware "/home/nick/Arduino/hardware" -tools "/home/nick/Development/arduino-1.6.7/tools-builder" -tools "/home/nick/Development/arduino-1.6.7/hardware/tools/avr" -tools "/home/nick/.arduino15/packages" -built-in-libraries "/home/nick/Development/arduino-1.6.7/libraries" -libraries "/home/nick/Arduino/libraries" -fqbn=arduino:avr:uno -ide-version=10607 -build-path "/tmp/build1cdca0d02fcf3112936d1438c170697d.tmp" -warnings=default -prefs=build.warn_data_percentage=75 -verbose "/tmp/arduino_1cdca0d02fcf3112936d1438c170697d/sketch_mar03b.ino"
    "/home/nick/Development/arduino-1.6.7/hardware/tools/avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10607 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-I/home/nick/Development/arduino-1.6.7/hardware/arduino/avr/cores/arduino" "-I/home/nick/Development/arduino-1.6.7/hardware/arduino/avr/variants/standard" "/tmp/build1cdca0d02fcf3112936d1438c170697d.tmp/sketch/sketch_mar03b.ino.cpp" -o "/dev/null"
    "/home/nick/Development/arduino-1.6.7/hardware/tools/avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10607 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-I/home/nick/Development/arduino-1.6.7/hardware/arduino/avr/cores/arduino" "-I/home/nick/Development/arduino-1.6.7/hardware/arduino/avr/variants/standard" "-I/home/nick/Arduino/libraries/PID_v1" "/tmp/build1cdca0d02fcf3112936d1438c170697d.tmp/sketch/sketch_mar03b.ino.cpp" -o "/dev/null"
    "/home/nick/Development/arduino-1.6.7/hardware/tools/avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10607 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-I/home/nick/Development/arduino-1.6.7/hardware/arduino/avr/cores/arduino" "-I/home/nick/Development/arduino-1.6.7/hardware/arduino/avr/variants/standard" "-I/home/nick/Arduino/libraries/PID_v1" "/home/nick/Arduino/libraries/PID_v1/PID_v1.cpp" -o "/dev/null"
    "/home/nick/Development/arduino-1.6.7/hardware/tools/avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10607 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-I/home/nick/Development/arduino-1.6.7/hardware/arduino/avr/cores/arduino" "-I/home/nick/Development/arduino-1.6.7/hardware/arduino/avr/variants/standard" "-I/home/nick/Arduino/libraries/PID_v1" "/tmp/build1cdca0d02fcf3112936d1438c170697d.tmp/sketch/sketch_mar03b.ino.cpp" -o "/dev/null"
    ...
    "/home/nick/Development/arduino-1.6.7/hardware/tools/avr/bin/avr-ar" rcs  "/tmp/build1cdca0d02fcf3112936d1438c170697d.tmp/core/core.a" "/tmp/build1cdca0d02fcf3112936d1438c170697d.tmp/core/main.cpp.o"
    "/home/nick/Development/arduino-1.6.7/hardware/tools/avr/bin/avr-ar" rcs  "/tmp/build1cdca0d02fcf3112936d1438c170697d.tmp/core/core.a" "/tmp/build1cdca0d02fcf3112936d1438c170697d.tmp/core/new.cpp.o"
    "/home/nick/Development/arduino-1.6.7/hardware/tools/avr/bin/avr-gcc"  -Os -Wl,--gc-sections -mmcu=atmega328p  -o "/tmp/build1cdca0d02fcf3112936d1438c170697d.tmp/sketch_mar03b.ino.elf" "/tmp/build1cdca0d02fcf3112936d1438c170697d.tmp/sketch/sketch_mar03b.ino.cpp.o" "/tmp/build1cdca0d02fcf3112936d1438c170697d.tmp/libraries/PID_v1/PID_v1.cpp.o" "/tmp/build1cdca0d02fcf3112936d1438c170697d.tmp/core/core.a" "-L/tmp/build1cdca0d02fcf3112936d1438c170697d.tmp" -lm
    "/home/nick/Development/arduino-1.6.7/hardware/tools/avr/bin/avr-objcopy" -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0  "/tmp/build1cdca0d02fcf3112936d1438c170697d.tmp/sketch_mar03b.ino.elf" "/tmp/build1cdca0d02fcf3112936d1438c170697d.tmp/sketch_mar03b.ino.eep"
    "/home/nick/Development/arduino-1.6.7/hardware/tools/avr/bin/avr-objcopy" -O ihex -R .eeprom  "/tmp/build1cdca0d02fcf3112936d1438c170697d.tmp/sketch_mar03b.ino.elf" "/tmp/build1cdca0d02fcf3112936d1438c170697d.tmp/sketch_mar03b.ino.hex"
    Using library PID_v1 in folder: /home/nick/Arduino/libraries/PID_v1 (legacy)

    Sketch uses 6,484 bytes (20%) of program storage space. Maximum is 32,256 bytes.
    Global variables use 285 bytes (13%) of dynamic memory, leaving 1,763 bytes for local variables. Maximum is 2,048 bytes.

---

Of interest are the last couple - the `xxx.elf` file and the `xxx.hex` file (where xxx is your sketch name).

The `xxx.hex` file is what is uploaded to your Arduino (well, it is decoded by Avrdude).

The `xxx.elf` file can be used to get assembly output, like this:

    avr-objdump -Sz xxx.elf

That outputs to the screen. I usually output to a file:

    avr-objdump -Sz xxx.elf > /tmp/avr_dump.txt

---

Example output:

    void setup() {
          ec: 0f 93        push r16
          ee: 1f 93        push r17
      Setpoint = 100;
          f0: 80 e0        ldi r24, 0x00 ; 0
          f2: 90 e0        ldi r25, 0x00 ; 0
          f4: a8 ec        ldi r26, 0xC8 ; 200
          f6: b2 e4        ldi r27, 0x42 ; 66
          f8: 80 93 73 01  sts 0x0173, r24
          fc: 90 93 74 01  sts 0x0174, r25
         100: a0 93 75 01  sts 0x0175, r26
         104: b0 93 76 01  sts 0x0176, r27
      //turn the PID on
      myPID.SetMode(AUTOMATIC);
         108: 61 e0        ldi r22, 0x01 ; 1
         10a: 70 e0        ldi r23, 0x00 ; 0
         10c: 82 e3        ldi r24, 0x32 ; 50
         10e: 91 e0        ldi r25, 0x01 ; 1
         110: 0e 94 04 04  call 0x808 ; 0x808 <_ZN3PID7SetModeEi>

In this particular  case `Setpoint` was a double so it took 8 instructions to load a literal into it.


message:
Issues with AltSoftSerial

I have my arduino connected to my PC and another serial device.
This serial device sends a 3 line piece of info on bootup then if I trip a zone it will send information regarding the radio transmission.

When I first power up the device I see the information from the device in the serial monitor (SELFTEST-PASS) however that is the last information I receive from it until I powercycle the device.

I have connected it directly to my PC comport and verified information is being sent via Serial however the arduino seems to quit after the first bit of info... any idea where to proceed from here?
PS I have tried both SoftwareSerial and NewSoftSerial
Here is an example of the data sent from the serial device as viewed by hyperterminal:

    <1234 #3F->0000 1234->FFFF D_ALARM>
    <FFFF #3F->1234 FFFF->1234 P_ACK>
    <1234 #40->0000 1234->FFFF D_ZREST>

   Code that is currently not working:

     #include <AltSoftSerial.h>
     AltSoftSerial portOne;

    void setup() {

                    Serial.begin(4800);
                    while (!Serial) {; // wait for serial port to connect. Needed for native USB port only
                    }
                    // Start each software serial port
                    portOne.begin(4800);

                  }

    // the loop function runs over and over again forever
    void loop()
    {
      if (portOne.available())
      {
        Serial.write(portOne.read());
      }

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

body:
Try SoftwareSerial rather than AltSoftSerial.

I don't see the point in these lines, I think you can remove them:

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

---

> I have connected directly to a pic and verified the radio I'm connecting to does indeed continue to send data.

If that is the case, that it sends data anyway, then you could just use HardwareSerial. Connect the radio to Rx (D0 on the Uno) and leave Tx unconnected. Then just read from Serial, and write to Serial. You should see the results on the Serial Monitor. (Disconnect this wire when uploading new versions of the sketch).


body: Device connected to arduino had DTR/DSR. I had to jumper one to the other to convince it to flow data to the arduino.


message:
Why is the result of this product operation wrong?

I had a problem in a program where the result of product is not what it's supposed to be. For example: 775*775 gives 10801 instead of 6006025.

To try to isolate and resolve the problem, I made a simple sketch to test the result of different products. What I found is that if I do the same product in this way: 775/100.00*775/100.00 then multiply the result by 10000 I get the right value: 600625.00

The attached pictures illustrate what I said.

While I can use this solution in my initial program by I still want to do the multiplication directly as more operations means more time.

I would appreciate any help. Thank you.[![enter image description here][1]][1]

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

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

  [2]: https://i.stack.imgur.com/I8zD8.jpg

body:
Integer overflow. You're multiplying an `int` by an `int` then assigning it to a `long`.  Instead if you multiply a `long` by a `long`, or an `int` by a `long`, or a `long` by an `int`, it should work.

    unsigned long res = 775L * 775;

The `L` suffix tells the compiler to treat it as a long, not an int.


message:
Arduino serial port eats data for 3 seconds before it sends?

With the source code below, I'm getting what I think to be strange behaviour with the serial port output.

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

    int c = 0;
    void loop() {
      Serial.println(c++);
    }

Presumably what this will do is starting printing incrementing numbers, one on each line, starting from 0. However, my serial monitor only starts printing these numbers after the 3000 mark. I found this behaviour only after discovered in another sketch that I was losing data at the beginning.

Is this normal Arduino behaviour? Or a serial monitor problem? Or something else?

body:
Is this a Leonardo or Yun?  If it is, you have to wait until the `Serial` object says the USB connection is really ready:

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

Read [this](https://www.arduino.cc/en/Serial/IfSerial).

Because you did't wait, your `loop` is able to execute 3000 times before `Serial` actually sends something back to the PC.


message:
Possible to use the hardware serial port for peripheral on ATmega32u4 when using USB for programming?

I have a Arduino Pro Micro and use the USB port for programming. Is it possible to use the hardware serial port for connecting with a peripheral while I'm using the USB port (and hence the hardware serial port) for programming? Or must I disconnect the USB cable or otherwise reconfigure the hardware?

body:
I have a Teensy 2.0 with a ATmega32u4 and I can use both, with the USB as Serial.* and the hardware UART as Serial1.*

For the Arduino Pro Micro it is the same.  See https://arduino.stackexchange.com/q/1471/6628

For Teensy, see https://www.pjrc.com/teensy/td_uart.html


message:
Digital Vs. Analog Sensor

Background: I'm using an Atmega1284P to add sensors to an off road racing truck onto a CANBUS network. The standard automotive sensors are thermistors, but the Dallas 1 wire temp sensors (DS18B20) with an integrated ADC caught my eye. They don't, however, come in a package that would work for my purposes so I would have to build one. I haven't been able to find one waterproofed in an NPT fitting with only a 1" probe length.

My question: how much more accurate would the 1 wire be over a thermistor?
How much of a difference would it make for processor efficiency to not have to do the math involved with thermistors and just read the value from the 1 wire? I don't mind building them, I just want to make sure they're worth it first.

body:
To make an informed decision you first need to understand a few basic concepts and some pros and cons of each system.

Firstly there are the concepts of *precision* and *accuracy*. These are two very different properties and each is important in their own way. On the face of it they may sound the same, but they aren't.

**Precision**

This is how close to the real value your measurements are. This is the "±"  value that datasheets list. It's how close a match to the actual temperature the measured temperature is.  So a ±0.5° measurement could be anywhere within half a degree of the actual temperature.

**Accuracy**

This can also be considered as the *resolution* of the measurement. It is how fine a difference in temperatures the device is able to measure. For instance you may be able to detect 0.0125° differences.  This is mostly defined by the resolution of the ADC in the device.

And now the pros and cons:

**Digital**

**Pros**

These devices can be factory calibrated for a more precise reading. The accuracy is usually pretty good too, but is fixed by the design of the device. Communication is generally reliable and wire length doesn't generally affect the values reported.

**Cons**

Communication protocols can have some large overheads limiting the number of samples you can take per second (not just on one sensor but across the whole array of sensors). Excess EMI noise (especially from engines) can corrupt the communication signals over long connections unless extra care is taken (such as implementing a balanced line communication medium).

**Analog**

**Pros**

Very simple to connect up and samples can be read very rapidly. Accuracy is determined by the ADC you choose to use.

**Cons**

Wire length can have a detrimental affect on the values read unless special wiring and sensor schemes are used to cancel out the resistance of the wires. Noise induced into the wires is very hard to detect or cancel out and can give spurious results. Requires more complex mathematics to calculate a resistance.

**Summary**

So in short: Digital can give you more reliable communication of your sampled values over longer distances but at the cost of reduced sampling speeds.


body:
I fully agree with Majenko except for the cons for analog.
Basically it is not easy to get a (very) accurate ADC reading with an arduino.
The main problem is the reference voltage that fluctuates.

This is the main reason why I prefer digital to analog when it needs to be "correct"


message:
Not seeing frames returned from client when using ESP8266 Wifi Shield

I'm trying to make a web server using an Arduino R3 and Sparkfun ESP8266 Wifi Shield. I've built a webpage that has a form I would like to control the Arduino with.

Currently my sketch can successfully send the webpage, but when I use the form, 9 / 10 times I see no output on the serial monitor, and the 1/10 times I see the frame from the client the sketch seems to hang and the client keeps waiting for more data.

I'm using the Sparkfun ESP8266 libraries for the product I bought.

I don't think this is a hardware problem, I've visually inspected the Arduino and ESP pins and they seem ok. I don't think it's a memory problem.

I've put the salient part of the sketch below:

    void serverDemo()
    {
      // available() is an ESP8266Server function which will
      // return an ESP8266Client object for printing and reading.
      // available() has one parameter -- a timeout value. This
      // is the number of milliseconds the function waits,
      // checking for a connection.
      ESP8266Client client = server.available(1000);
      char clientline[BUFSIZ];
      int index = 0;

      if (client)
      {
        Serial.println(F("Client Connected!"));
        // an http request ends with a blank line
        boolean currentLineIsBlank = true;

        while (client.connected())
        {
          if (client.available())
          {
            char c = client.read();

            if( index < BUFSIZ ) {
              clientline[index++] = c;
            } // end of if

            if (c == '\n' && currentLineIsBlank)
            {
              clientPrintProgmemArray(htmlHeaderTable, htmlHeaderTableSize, client);
              clientPrintProgmemArray(webpageTable, webpageTableSize, client);
              Serial.println(F("Page sent"));
              break;
            } // end of if

            if (c == '\n')
            {
              currentLineIsBlank = true;
            } // end of if

            else if (c != '\r')
            {
              // you've gotten a character on the current line
              currentLineIsBlank = false;
            } // end of if
          } // end of if( client.available() )
        } // end of while ( client.connected() )
        delay(10);
        client.stop();
        Serial.println(F("Client disconnected"));
        Serial.print(F("Index: "));
        Serial.println(index);
        Serial.print(F("Clientline: \""));
        for( int i = 0; i <= index; i++)
        {
          Serial.print(clientline[i]);
        }
        Serial.print(F("\"\r\n"));
        if( strstr(clientline, "e=1") != 0) {
          Serial.println("hooray!");
        }
      }
    }

The header and webpage the Arduino sends to the client is:

    HTTP/1.1 200 OK
    Content-Type: text/html
    Connection: close
    <!DOCTYPE HTML>
    <html>
    <body>
    <form action="/?" method="get">
        <input name="e" type="submit" value="0">
        <input name="e" type="submit" value="1">
    </form>
    </body>
    </html>

The output I get on the serial monitor is:

    ESP8266 Shield Present
    Mode set to station
    Connected to: XXXXX
    My IP: 192.168.0.13
    Server started! Go to 192.168.0.13

    Client Connected!
    Page sent
    Client disconnected
    Index: 2
    Clientline: "
     "
    Client Connected!
    Page sent
    Client disconnected
    Index: 2
    Clientline: "
     "

I'd be very grateful if anybody has any advice on where the problem lies.

Thanks in advance

body:
So I figured out the answer to my own question.

It turns out there must be a mistake in the example sketches that come with the ESP8266 shield I bought, as the function to begin Arduino/ESP8266 communications didn't have any arguments when the function expected parameters. So it appeared to be trying to set their baud rate to 0!!

I edited the library to have a hard value of 57600 and now it seems to work far more reliably.


message:
A question about chars and Serial

I have the following code:

    int count = 0;
    char serial_char;
    char serial_message[96];

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

    void loop(){
      while(Serial.available() > 0){

        serial_char = Serial.read();
        if (serial_char == '\n' || serial_char == '\r'){

          serial_message[count] = 0; // <<-- What does this line do?
          count = 0;
          Serial.println(serial_message);

        }
        else{
          serial_message[count++] = serial_char;
        }

      }

    }
With this code, I can type a message into the serial monitor, and it will print the message back at me. So if I type 'Goodbye', it returns:

    Goodbye

If I send it another message 'Word', it returns:

    Word

However, my questions is when I comment out the line:

    serial_message[count] = 0;

And then I repeat the same sequence of actions before, 'Goodbye' returns 'Goodbye', but when next I enter 'Word', it returns:

    Wordbye

Could anyone explain this to me? I am really curious to know why this occurs. What does adding that 0 in the char array accomplish? Thank you.

body:
The zero-value, the "[null character](https://en.wikipedia.org/wiki/Null_character)", indicates the end of the string. For strings, you allocate some maximum space, in your case 96 bytes:

    char serial_message[96];

When storing variable-length strings in that, you need to indicate where the string ends. That's what the zero value does in a [null-terminated string](https://en.wikipedia.org/wiki/Null-terminated_string). (Note that `0` is really binary `0x00` here; it's not the ASCII *character* 48, `0x30`.) So, the 96 bytes allow for a string of at most 95 characters, followed by the terminator. When printing, it prints the memory contents until it finds that null character.


body:
There is a difference between char[] and String.
You are using char[] which is the best way to work on a small processor like the Arduino. However; it is also a bit more difficult.

Char array is just a piece of memory that can contain any data. Because we want to put a variable length string in there we need a convention to know what is the last character of the string. By convention this is a value 0.
This is why we speak about "null terminated strings".

This explains why after sending word (without adding the 0 at the end" you get "Wordbye" because the memory contains 'W' 'o' 'r' 'd' 'b' 'y' 'e' and 0.

The reason why it works OK with 'Goodbye' is because all memory gets set to 0 at startup of the processor.
So as long as the last send word is longer than the previous it works fine.

A last thing. The memory does not actually contain 'W' 'o' 'r' 'd' 'b' 'y' 'e'. The memory contains the ASCII values of the letters 'W' 'o' 'r' 'd' 'b' 'y' 'e'


message:
How to burn Arduino Bootloader on ATmega168PA-PU?

How can I burn the Arduino Bootloader on an ATmega168PA-PU with an Arduino Uno?

body:
The official Arduino documentation has detailed instructions on how to transform Arduino board into an ISP.

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


body:
I have a bootloader-programmer sketch here:

<http://www.gammon.com.au/bootloader>

Basically you connect up the boards like this:

    Arduino Uno         Target ATmega168PA

    D10 (SS)            Reset (pin 1)
    D11 (MOSI)          MOSI  (pin 17)
    D12 (MISO)          MISO  (pin 18)
    D13 (SCK)           SCK   (pin 19)

    Gnd                 Gnd   (pins 8 & 22)
    +5V                 +5V   (pins 7 & 20)

Then download the sketch from [GitHub](https://github.com/nickgammon/arduino_sketches) - the one you want is in the **Atmega_Board_Programmer** folder. Run that and follow the instructions in the Serial Monitor.

For more information see the link above.


message:
Arduino LiquidCrystal_I2C fast overwritting

I have an arduino board connected to 2 temperature sensors, 2 switch buttons and 1 lcd display.

When the switch button changes to off, "off" is printed on the lcd display. When the button state is on, the temperature is printed on the lcd display.

The problem is when it shows "off" its still possible to see the temperature value for "1 millisecond" each second. I don't know what is causing the "off" message to change for a millisecond.

Source code:

    #include <Wire.h>
    #include <LiquidCrystal_I2C.h>
    #include <OneWire.h>
    #include <DallasTemperature.h>
    #include <Streaming.h>

    #define DS18B20_SENSOR1 2               // pino de dados do DS18D20
    #define DS18B20_SENSOR2 4               // pino de dados do DS18D20

    int buttonState1 = 0;
    int lastButtonState1 = 0;
    int buttonState2 = 0;
    int lastButtonState2 = 0;

    float Temp1, Temp2;

    OneWire oneWire1(DS18B20_SENSOR1);       // Objeto do baramento One-wire
    DallasTemperature sensor1(&oneWire1);     // Objeto do sensor DS18D20

    OneWire oneWire2(DS18B20_SENSOR2);       // Objeto do baramento One-wire
    DallasTemperature sensor2(&oneWire2);     // Objeto do sensor DS18D20

    // Set the LCD address to 0x27 for a 16 chars and 2 line display
    LiquidCrystal_I2C lcd(0x27, 16, 2);

    void setup(void)
    {
      Serial.begin(3000);
      Serial << F("Teste do Sensor 1") << endl << endl;
      Serial << F("Teste do Sensor 2") << endl << endl;
      sensor1.begin();
      sensor2.begin();
      lcd.begin();
      lcd.setBacklight(HIGH);

      /*
       * Control Variables
       */

      pinMode(5, INPUT);
      pinMode(7, INPUT);
      pinMode(8, OUTPUT);
      pinMode(9, OUTPUT);
      pinMode(10, OUTPUT);
      pinMode(11, OUTPUT);
      pinMode(12, OUTPUT);
      pinMode(13, OUTPUT);
    }

    void turnAllOff1(){
      digitalWrite(11, LOW);
      digitalWrite(12, LOW);
      digitalWrite(13, LOW);
    }

    void turnAllOff2(){
      digitalWrite(8, LOW);
      digitalWrite(9, LOW);
      digitalWrite(10, LOW);
    }

    void printTemp1(){
      lcd.setCursor (0,0);
      lcd.print("Sensor1: ");
      lcd.print(Temp1);
      lcd.print("C");
    }

    void printOff1(){
      lcd.setCursor (0,0);
      lcd.print("Sensor1: ");
      lcd.print(" off   ");
    }

    void printTemp2(){
      lcd.setCursor (0,1);
      lcd.print("Sensor2: ");
      lcd.print(Temp2);
      lcd.print("C");
    }

    void printOff2(){
      lcd.clear();
      lcd.setCursor (0,1);
      lcd.print("Sensor2: ");
      lcd.print(" off   ");
    }

    void loop(){
      buttonState1 = digitalRead(5);
      buttonState2 = digitalRead(7);

      if(buttonState1 != lastButtonState1){
        if(buttonState1 == HIGH){
          sensor1.requestTemperatures();
          Temp1 = sensor1.getTempCByIndex(0);
          turnAllOff1();
          if(Temp1 < 36){
            digitalWrite(13, HIGH);
          }
          else if(Temp1 > 38){
            digitalWrite(11, HIGH);
          }
          else{
            digitalWrite(12, HIGH);
          }
          printTemp1();
        }
        else{
          printOff1();
        }
      }
      lastButtonState1 = buttonState1;

      if(buttonState2 != lastButtonState2){
        if(buttonState2 == HIGH){
          sensor2.requestTemperatures();
          Temp2 = sensor2.getTempCByIndex(0);
          turnAllOff2();
          if(Temp2 < 0){
            digitalWrite(10, HIGH);
          }
          else if(Temp2 > 2){
            digitalWrite(8, HIGH);
          }
          else{
            digitalWrite(9, HIGH);
          }
          printTemp2();
        }
        else{
          printOff2();
        }
      }
      lastButtonState2 = buttonState2;
    }

body:
You need to use INPUT_PULLUP pin mode and connect the buttons between the pins and ground.

    pinMode(5, INPUT_PULLUP);
    pinMode(7, INPUT_PULLUP);

Later on you will also have to debounce the button but that is another question (where you can find plenty of answers already).

Cheers!


message:
How does Arduino distinguish between SPI programming data and regular data?

The Arduino can be programmed using SPI without a boot loader. Without a boot loader, the Arduino starts running its sketch right away. So, how does the Arduino know that it is being programmed via SPI vs regular SPI traffic already present on the SPI bus? Was is the pin-level, electrical signal that let's the Arduino know the difference?

body:
In-system programmer is activated with RESET line. During normal operation reset line is not active and ISP module is disabled.

You can find detailed description of AVR ISP in this document:

http://www.atmel.com/images/doc0943.pdf


message:
Interfacing with desktop computer console software

Recently I bought the following USB to Serial cable: https://www.adafruit.com/products/954

This cable has grd, vcc, rx and tx lines.

I am looking to use this cable to interface with my desktop computer with a program like Tera Term or Hyperterminal so i can output messages for debugging purposes.

Also, I am trying to stay from using the Arduino IDE. I would prefer using C and flashing in the hex manually.

So, can anyone point me to a tutorial or explain how to make this happen?

thanks people.

body:
**For debugging:**

Configure the UART on the ATmega to output TTL serial. If you are using the Arduino libraries, then `Serial` is what you want. Connect the TX pin of the ATmega to the RX of the USB/Serial cable, and vice versa.

Open the serial device on your computer in the program of your choice. When you write to the UART on the ATmega, you should see the messages in your terminal.

Pretty straightforward.

**For programming:**

If you're going to be using C and flashing things manually, you'd best go and buy an AVR programmer so you can program the ATmega directly without messing about with a bootloader. A programmer is ~15USD, so you might as well buy one. Then you can use the GNU AVR toolchain, which is very easy to use. Compile code with `avr-gcc`, and program the device with `avrdude`.

If you really want to use programming over serial, you'll have to manually hit the reset button each time you program the chip, because (as Mikael pointed out), that serial cable lacks the lines necessary to automatically reset the chip (and drop to the bootloader).


message:
Advice for checking integrity of serial char strings?

I'm trying to create a flexible but reliable system for arduinos to interact using serial ascii strings.
I'm using a message structure comprised of Command[10] + (optional) Params[20] + (optional) Header[30] + '\0' (<CR> terminator).

Each arduino node looks for incoming serial Commands (plus any appropriate optional Parameters) that it must respond to.

During development and debugging it's sufficient to send Commands and Parameters using the IDE serial monitor without optional Header block or error-checking.

But for interactive node-to-node communications, an optional 'Header' (technically a Footer) block is automatically added to the end of the message.

If an incoming serial message includes a header block, it means that the message was sent automatically from another node (rather than manually from the IDE serial monitor), and consequently the message integrity should be checked against any relevent accompanying header contents, then an acknowledgement returned to the sender if the message was received ok.

Header contents can optionally contain any of the following, and in any order:- s(source)=nnn, d(destination)=nnn, i(id)=nnn, l(msg length)=nnn, and non-critical mixtures of commas and/or spaces can be used as delimters.

To test for message length, the transmitted l=nnn value (text representation) is padded to 3 digits with leading zeros, so the length stays the same whatever the value (eg:.anything from 000 to 999 still requires 3 digits).

So far so good. But although a length test is better than nothing, it doesn't trap for corrupt characters, and the plan is for nodes to communicate via UDP broadcasts, so some form of error-checking and acknowledgement is essential.

So the plan was to (also, or instead) use an optional c(checksum)=nnn in the header, whose value would be the mod sum of everything EXCEPT itself in the header entry. This is easily enough achieved for transmission by taking the mod sum of everything else when assembling the message, then adding the c=modsum on the end (or anywhere in the Header for that matter).

In theory, the receiving end just needs to remove the c=nnn entry (plus any preceding delimter) from wherever it is in the Header, then compare the remaining message's calculated mod sum value against the transmitted c=nnn value.

In practice, I don't know how to exclude the c=nnn entry from the header in order to calculate the remaining modsum, without being forced to accept and pander to unwelcome restrictive assumptions, such as the c=nnn value having to be the final entry, and having to use very strict delimiting.

I'm trying to keep things as flexible and informal as possible, so that other x=nnn type instruction options may be added anywhere to the header if needed without risk of breaking existing rigidity.

Perhaps I should add that this time a year ago I hadn't touched an arduino or C, and that this project has long ago changed from my original automation/security needs to become a goal for providing a simple-to-use interactive arduino distributed functionality cluster system suitable for anyone to use.

The end finally seems to be in sight, which is thanks to the help and advice from you guys (a quick look through my questions shows how far you've brought me), so hopefully your greater experience and wisdom may also be able to offer a more satisfactory integrity-test solution if it is possible.

I would also welcome any other comments that might help me improve on what I'm trying to do.

*ADDITIONAL INFO*

New incoming serial messages are received in char Buffer[64].
This gets split by delimiters into Command[10], Params[20] and Header[30], but these sizes are only arbitrary first guestimates which may change.

Commands and Parameters can be whatever the node has been programmed to respond to. A trivial 'Blink' example might be a couple of nodes, one looking for incoming "PING" Commands and responding by returning "PONG" Commands, and the other node vice- versa.

A more useful example could be an IR receiver node issuing instructions to a remote IR blaster node, so the "Command+Param+Header" string might be:-

"IRSEND 'NEC 0xFFEEAB99, 32', s=1, d=2, l=044"

The Command/Params parser accepts comma or space as delimiter except if they are contained within quotes. Quotes may be sent inside of quotes of the other type (single or double). Mr T's invaluable Header parser is slightly modified to also accept comma's or spaces as delimiters in the Header, therefore " ,  s=nnn,d=nnn, i=nnn    l=nnn , " all extracts ok.

All of the above is working ok in a very messy and disjointed proof-of-concept form.

        static char buffer[64];
        int msgpos = 0;
        int msglength;
        int quotes=0;
        int parseMode=0;
        bool echo=false;
        bool ack=false;
        byte chksum=0;
        int modchk = 0;

        char command[10];
        char param[20];
        char header[30];
        int snum=0, dnum=0, inum=0, lnum=0, cnum=0;

      void setup()
      {
        Serial.begin(9600);
        Serial.println("Ready");
      }

      int readline(int readch, char *buffer, int len) { //  If a CR terminated ascii string is received, returns string length, else returns -1
        static int pos = 0;
        int rpos;
        if (readch >0) {                               // if a valid ascii character
          msgpos++;
          if (msgpos == 1) resetBuffer();              // First chr, so reset everything to make a new start
          if (!(pos < len-1)) Serial.println("Error: Msg too big for buffer");
          else if ((readch !=10) && (readch != 13)) {
            buffer[pos++] = readch;
            modchk += readch;
            modchk %= 100;
        //  Serial.print("modsum%='"); Serial.print(modchk); Serial.println("'");
            buffer[pos] = 0;
          }  // end if (pos < len-1)
          switch(readch) {
          case 10: break;                                                                             // Ignore new-lines
          case 39: if (quotes==0) quotes=1; else if (quotes==1) quotes=0; else addChr(readch); break; // Turn on or off single-quotes
          case 34: if (quotes==0) quotes=2; else if (quotes==2) quotes=0; else addChr(readch); break; // Turn on or off double-quotes
          case 33: if (quotes==0) parseMode=-1; else addChr(readch); break;                           // ! Header info
          case 32: if ((quotes>0) || (parseMode==-1)) addChr(readch); else parseModeBump(); break;    // space delimiter
          case 44: if ((quotes>0) || (parseMode==-1)) addChr(readch); else parseModeBump(); break;    // comma delim
          case 13:                                                                                // CR stop char
            if (parseMode==0) {Serial.println("Error: blank or corrupt message"); pos=0;  return 0; }
            else if(quotes>0) {Serial.println("Error: open quotes not closed"); pos=0;  return 0; }
            else {// new msg recvd ready for processing. TODO: check if msglength and/or checksum sent, if so and if correct, return ack to sender
              rpos = pos;
              pos = 0;    // Reset position index ready for next time
              return rpos;
            }
            break;
          default:
            addChr(readch);
            break;
          }  // end case
        } // end if (readch >0);
        return -1;        // No end of line CR yet, so return -1.
      }

      void resetBuffer() {
        modchk=0; quotes=0; parseMode=0; command[0]='\0'; param[0]='\0'; header[0]='\0';
        snum=0; dnum=0; inum=0; lnum=0; cnum=0;
      }

      bool parseModeBump() {
        switch (parseMode) {
        case  0: parseMode=1; break;
        case  1: parseMode=2; break;
        case  2: parseMode=-1; break;
        case -1: Serial.println("Error: too many delimited parameters"); return false;
        }
        return true;
      }

      bool addChr(char readch)  {                  //
        char addch[2];
        bool ret=true;
        addch[0]=readch; addch[1]='\0';
        if (parseMode==0) parseMode=1;
        switch (parseMode) {
        case  1: strcat(command,addch); break;
        case  2: strcat(param,addch); break;
        case -1: strcat(header,addch); break;
        default:
          Serial.println("addChr Error: too many delimited parameters"); ret = false;
        }
        return ret;
      }

      void show() {
        Serial.print("SHOW: Command='"); Serial.print(command); Serial.print("'");
        Serial.print(" Parameter='"); Serial.print(param); Serial.print("' ");
        Serial.print(" Header='"); Serial.print(header); Serial.println("'"); Serial.println();
        Serial.print("Msg Length='"); Serial.print(msglength); Serial.println("'");
        if (snum) { Serial.print("snum="); Serial.println(snum); }
        if (dnum) { Serial.print("dnum="); Serial.println(dnum); }
        if (inum) { Serial.print("inum="); Serial.println(inum); }
        if (lnum) { Serial.print("lnum="); Serial.println(lnum); }
        if (cnum) { Serial.print("cnum="); Serial.println(cnum); }
      }

      /*
      bool padzeros() {  // Flawed - redo from scratch using 2 for loop passes
        char lengthstr[4]="7";
        Serial.print("lengthstr='"); Serial.print(lengthstr); Serial.println("'");
        int maxsize=sizeof(lengthstr);  // size of lengthstr array
        int steps=strlen(leng)+1;       // number of chars to be moved
        int hop=maxsize-steps;          // number of steps to be jumped over each move
        if((steps>1)&&(maxsize>steps)) {
          for (int pos=steps-1; pos >= 0; pos--) {
            lengthstr[pos+hop] = lengthstr[pos];
            lengthstr[pos]='0';
          }
        }
        Serial.print("lengthstr='"); Serial.print(lengthstr); Serial.println("'");
      }
      */

      unsigned int calcmodsum(char* s){
        unsigned int i = 0;
        int m=0;
        byte b;
        do { b = s[i]; m += s[i]; i++; }
        while (b != 0); //keep going until null terminator found at end of string
        m %= 100;                   //
        return m;
      }

      int getheader() {      // extract values from header
      //  char header[] = "s=123 d=789 c=463";
        ack=false; echo=false;
        char * ptr = header; // header string pointer
        char * eq = NULL;    // search char (=)
        int * num = NULL;    // empty at start
        int c = 0;
        while (1){
          eq = strchr(ptr, '=');
          ptr = eq;          // update the pointer
          if (ptr == NULL)  break;  // found no '=' chars
          switch (*(ptr - 1)){
            case 'd': num = &dnum; break;
            case 's': num = &snum; break;
            case 'i': num = &inum; break;
            case 'l': num = &lnum; break;
            case 'c': num = &cnum; c=3; break;
            default:  num = NULL;
          }
          ptr++;
          if (num == NULL) //unrecognized var
            continue;      // locate next = char
          *num = 0;
          while (*ptr && (*ptr != ' ') && (*ptr != ',') && isdigit(*ptr)) {  // while valid digit and end of string not yet reached
            *num *= 10;    // extract each int
            *num += *ptr - '0';
            c++;
            ptr++;
          }
        }                  // Now Process any extracted header values
        if (lnum) {
          Serial.print("Msg length="); Serial.print(strlen(buffer)); Serial.println();
          Serial.print("lnum="); Serial.print(lnum); Serial.println();
          if (lnum==strlen(buffer)) Serial.println("* Msg length OK"); else Serial.println("* Incorrect msg length");
        }
        if (cnum) {
          Serial.print("calcmodsum='"); Serial.println(calcmodsum(buffer));
          Serial.print("cnum='"); Serial.print(cnum); Serial.println("'");
          Serial.print("count='"); Serial.print(c); Serial.println("'");
          if (modchk==cnum) Serial.println("* Checksum OK"); else Serial.println("* Incorrect checksum");
        }
      }

      void loop() {
        //  Check for new received serial string
        msglength = readline(Serial.read(), buffer, 64);  // Returns length of new ascii string, or -1 while receiving, or 0 if received msg is corrupt
        if(msglength==0  ) { Serial.println("ERROR: received serial message was invalid and discarded");show(); resetBuffer();}
        else if(msglength > 0) {  // New msg to deal with
          if (header) getheader();
          show();

          msgpos=0;  // reset ready for new msg after finished with last msg
        }
      }

Once I can finalise a satisfactory c=nnn validity test, I shall tidy up this working 'receiver' part and move on to doing the 'sender' part, which I'm hoping should be quite trival in comparison.

I suppose it would be 'proper' to assemble the outgoing message into something like a  char outmsg[64] string, but I'm trying to keep resources minimal to maximise the resources available for the arduino's 'real' functionality, so perhaps it may be better just to send the outgoing msg as consecutive serial chunks, ie:-

 Serial.print(Command); Serial.print(Params); Serial.println(Header);

The header will be built up as required. If s=nnn (source) was received it will be assumed that an acknowledgement response is required by the source to prevent it repeating failed transmissions, so the received s=nnn would be used as the outgoing d=nnn destination to respond to - outgoing msgs need only include a source s=nnn if they requires a response back. The i=nnn (msg id) isn't yet used, but could eventually be for re-assembling individual chunks of larger msgs, or keeping track of msg order if multiple msgs are expected.

The l=nnn is a zero-padded count of all transmitted characters (excluding the terminating <CR>), so can be anywhere within the Header string.

It would be preferable if the zero-padded c=nnn checksum could also be anywhere in the Header, but this will require a checksum() calculator function to be able to apply its calculation to all Header characters except the nnn data characters of c=nnn.

As things are, I can jump straight to "c=" wearing blinkers, but that offers no relative position info, so leaves me oblivious of everthing before it.
And I'd prefer not having to split Header[] into seperate Left[] and Right[] chunks which would unnecessarily wastes at least [30+30] chars of memory.

So I think I must sequentially step through all Header characters looking for "=" while applying the mod sum calc to each, except for the 3 following chars when the preceeding char is "c", but I can't quite get my head around how to do that yet.

If the C string functions could return relative string positions instead of absolute * pointers it could all be so much more straightforward.

Does anyone know of any alternative string-relative functions that might be available?

* NEW INFO 2 *

Most "Hello world" examples (eg: IRlib) demonstrate functionality using the IDE serial monitor for user interaction. Whatever the functionality, they can all be considered as just a black box capable of recognising a few incoming serial plain-text commands and actioning as appropriate, possibly by also issuing serial text command responses of their own.

The aim of my project is for a user to easily turn that existing and already-proven serial user interaction into an automatic arduino to arduino serial interaction if wished. The headers are just an optional bolt-on for arduino to arduino reliability, but during dev and debugging the various optional header contents will still need to be read and written by users with the IDE serial monitor, which only allows ascii text interaction.

Although this sort of system would not be the preferred solution for experts, it offers much advantage for non-experts. Un-skilled hackers could create effective working solutions without needing to aquire any rocket science first, and without needing to worry too much about resource limitations, or the problems and complexity of trying to consolidate incompatable or conflicting functionality onto any single device.

If they have an arduino that can serially interact, they can use it as an interactive node. If two can interact over serial, then more can serially interact using RS485, or using serial Ethernet UDP slaves (ESP8266's are small and cheap).
Only nodes that 'recognise' an incoming command would respond to it.

A Triggers node could send ascii Alerts such as 'Mailbox Opened', 'Gate1 Visitor', Shed Door Opened' etc.  A Responder node could parse such incoming Alerts to match against entries in a config file, then parse the corresponding config entry for appropriate Response commands to be issued to other cluster nodes, such as 'Mailbox: Announce Mailbox Delivery', or 'Zone2: Announce Zone 2 Activity, CCTV: Select Zone2'.

This would allow new node functionality to be added easily just by updating the Responders appropriate config file entry to include any additional Response commands that become available from any new nodes. So adding an X10 node for instance might offer a new Response command such as 'X10, A12 ON', which only the newly added X10 node would be looking for and respond to.

A cluster system could be evolved into whatever sophisticated functionality was required, with minimal software skills and knowledge. Commands and parameters could be any plain-text names that the user prefers, which when matched during input parsing would branch to any required local function.
Despite any resulting complexity, all individual nodes could still just be considered as relatively simple black boxes capable of recognising a few incoming serial plain-text trigger commands and replying with plain-text responses.

Cluster nodes aren't even limited to being arduinos, because they could include ANY devices capable of receiving and responding to simple ascii command strings. This offers easy gradual progression to other platforms if wished without needing to abandon all existing efforts and start over again from scratch.

I knew I was biting off more than I could chew, but each time I play devils advocate trying to avoid wasting my time going up a dead-end, the more benefits become apparent to make the effort seem worthwhile. The forums are littered with questions and libraries aiming in a similar direction, but I haven't yet found anything which offers that simple black-box plain-text interaction capability, hence my continued struggle. I'm not a programmer so I'll never be able to offer an efficient library solution, but I must try to keep going until I've got something that is usable, and if others find it useful then maybe eventually it might offer incentive for someone to wish to optimise and improve on it.

Hopefully the following should do what I want as far as ignoring "c=nnn" from the mod checksum wherever it finds it.

    unsigned int calcmodsum(char* passedstr){     // calculates the mod sum of passedstr excluding the 3 "c=nnn" value digits
      int pos = 0;
      int modsum=0;
      byte b;
      do {
        b = passedstr[pos];
        if ((passedstr[pos]=='c')&&(passedstr[pos+1]=='=')&&(pos>2)) pos=pos+4; else modsum += passedstr[pos]; // skip next 3 digits after finding c=
        pos++;
      }
      while (b != 0); // keep going until null terminator found at end of string
      modsum %= 100;
      return modsum;
    }

body:
Hmm... the length of your question makes it difficult to focus an answer. I'll try by stating my interpretation, then I'll provide a *longer* answer ;-)

> Is there a way to wrap a text message between two Arduinos

>   (to increase reliability), but would still

>     allow me to do testing without the wrapper?

If I assume that's what you're asking, then the above comments have touched on various aspects of an answer: "Yes."

Let's progress through my interpretation:

* "Text" means ASCII values between 32 and 126 (SP and '~', the *printable* characters).
* "Wrapping a message" means sending some bytes before and possibly after the text.
* "Increasing reliability" means *detecting* and/or *correcting* characters that get corrupted.
* "Testing without the wrapper" means that you would like to use the Serial Monitor to send example commands while you're in a noise-free environment, testing the logic of the command execution, not the mechanism of communicating reliably.

###Wrapping
You're on the right path by prefixing the text with a binary header, and Nick's library shows how to use a "special" start and end byte to delimit the messages.  (This is also called message "framing".)  If the START byte can appear inside the message elsewhere, you will need to either (1) "escape" the START byte when it appears inside the message, (2) provide a second method of verifying that the message is framed correctly (e.g., an END byte and/or a length), or (3) decrease the odds of a false start by using a multiple-byte START sequence.

You appear to have chosen (2).  You are free to chose the bytes that follow the START byte.  Addressing, sequence number and message type are common.  Of course, the message length is in there somewhere.

###Reliability.
If you're happy to simply detect an error at the receiving end, a checksum is sufficient.  I'd like to suggest the [Fletcher checksum](https://en.wikipedia.org/wiki/Fletcher's_checksum), as it is simple, quick and fairly robust.  CRCs are more robust, but a little more expensive to compute.

But because they are calculated over the rest of the message (the "payload"), they almost always appear at the end, before any END sequence.  This also makes it easier for the receiver, because it can accumulate the checksum as the bytes are received, and reject the message if the received checksum does not match the calculated checksum.

You can also use error detection to help with acknowledgements, if you decide to implement them.  An alternative to ACK/NAK messages is to request the current state (a poll command), expecting that it should reflect the previous (unacknowledged) command.  If the state doesn't match, send the command again.

If you also want to perform error correction, there are [*numerous*](https://en.wikipedia.org/wiki/Error_detection_and_correction) ways to add that.  All of them will increase the size of the message, as well as the CPU time.  (Sorry, Nick, but sending complemented nybbles is not a very robust detection scheme, and it doubles the message size without adding correction capability.)

###Testing without the wrapper
You could use CR/LF as your message framing and assume that anything after CR/LF is the start of an unwrapped message.  If it starts unwrapped, set a `bool` flag that skips the checksum part and END byte.

###Final notes
Your current program is structured to hold the complete message in RAM for processing (sent or received).  This is not always feasible in the Arduino environment.  You don't put all the print chars in a buffer, then do one big `Serial.print( buffer )`, do you?

Just like breaking a `Serial.print` into several smaller prints, reception can be performed the same way.  You can watch for keywords, or accumulate parameter values *without* buffering the entire message.  While it saves a lot of RAM, it also saves CPU time because each received character is handled once.  With a buffered approach, each character is handled multiple times: `read()` into a buffer, then compared during a search, and maybe parsed.

One of my [recent posts](http://forum.arduino.cc/index.php?topic=384191.msg2650191#msg2650191) has some general structure information, snipped a little for here:

> Reading data on the Arduino is different from most PC applications.  Calling Serial.read() does not always return data.  Well, it returns -1 (or 0xFF) if no characters are available.  In a PC app, calling read will usually wait until a data has been received: the PC app is "blocked" until a character comes in.  That's not very noticeable because the PC has a nice multitasking OS so your pointer keeps moving and other windows respond, even though the one app is waiting for a character.
>
> On the Arduino, you can make it block the same way, but there's no OS that will let you do something else while you're waiting for data (yes, there are multitasking solutions, but let's avoid that for now).  So blocking on the Arduino can keep you from doing other things you may need to do, like blinking an LED or catching a button press.
>
> There are a few common ways to write an Arduino sketch that can cope with this speed disparity:
>
> 1) Force the Arduino to wait for each character (i.e., block), and write the sketch in a very linear, top-to-bottom fashion:
>
>     while (Serial1.available() == 0)
>       ; // wait
>       inByte1 = Serial1.read();
>
>       if (inByte1 == 0x3E){ // START byte
>         buffer[0] = inByte1;
>
>         while (Serial1.available() == 0)
>           ; // wait
>         inByte1 = Serial1.read();
>
>         if (inByte1 == 0x03){
>
> 2) Save each character in a buffer as it arrives until you have received an entire packet.  Then parse the packet all at once with similar linear code:
>
>     static uint8_t count = 0; // keeps its value across calls to loop
>
>     if (Serial1.available()) {
>       inByte1 = Serial1.read();
>
>       if (inByte1 == 0x3E) { // START character
>
>         // Next packet starting, process the current one we've been saving,
>         //   if we have saved enough bytes (skips small/bad packets).
>
>         if ((count > 6) && (buffer[0] == 0x3E)) {
>
>           // SNIP: handle previous packet
>
>         }
>
>         // Reset the count to start a new packet with the 0x3E we just received.
>         count = 0;
>       }
>
>       // Save the current byte
>       if (count < sizeof(buffer))
>         buffer[ count ] = inByte1;
>       count++;
>     }
>
> 3) Parse each character as it arrives, picking up where you left off after doing other things.
>
>   void loop()
>   {
>       // statics keep values across calls to loop
>       static uint8_t count         = 0;
>       static bool    skipping      = true;
>       static uint8_t messageLength = 0;
>
>       if (Serial1.available()) { // or 'while'
>
>           uint8_t inByte = Serial1.read();
>
>           if (inByte == 0x3E) { // START  byte
>
>               // Starting a new packet!
>
>               buffer[0] = inByte;
>               count    = 1;
>               skipping = false;
>
>           } else if (!skipping) {
>
>               // Saving a packet, store the current byte
>
>               if (count < sizeof(buffer))
>                 buffer[ count ] = inByte;
>
>               // Use the current byte, depending on 'count'
>               switch (count) {
>                 case 1:
>                   if (inByte != 0x03)
>                     skipping = true; // ignore other packet selector values
>                   break;
>
>                 case 2:
>                   messageLength = inByte;
>                   // Error check?
>                   if (messageLength != 40)
>                     skipping = true;
>                   break;
>
>                 case 3:
>                   // packetID = inByte; ?
>                   buffer[3] = inByte;
>                   break;
>
>                 case SNIPPED: other header information fields
>                 case SNIPPED: accumulate/parse payload
>                 case SNIPPED: verify checksum (ignore packet or execute packet)
>              }
>
>              count++;
>          }
>      }
>
>      // Do other things, too?
>  }
>
> Choice 1 is very linear.  The disadvantage is that it blocks and does not recover from data errors very well.
>
> Choice 2 is pretty easy to understand and it doesn't block; other tasks can do things while waiting for a complete packet.  The disadvantage is that all the packet processing happens when the last byte is received (actually, the first byte of the next packet in that code).
>
> Choice 3 is more difficult to understand, because the entire section is executed for each character, either starting a new packet or using the switch statement to handle each char.  Different cases do a little work, depending on the count.  The advantage is that the processing is spread out over each character, and you can decide to skip the rest of a packet at any point.

This is actually a [Finite-State machine](https://en.wikipedia.org/wiki/Finite-state_machine) approach, and Nick Gammon has a [great description](http://www.gammon.com.au/statemachine), too.


message:
What type of hardware could make a ball tilt or roll?

I wanted to know what type of component or module I could use to make a hollow ball move.  I have these hollow plastic balls (think empty easter eggs) that I was going to put a nano in and a sound detector and was just hoping to just get it to move.  I prefer a sort of a tilt left and right effect, but if it just rolls randomly that would work as well.

I was thinking just a simple vibration, but it doesn't really shift the ball at all, so I'm at a loss without building something quite complex with magnets or something.  Perhaps a motor stuck to the side?

body:
Maybe some sort of bristlebot?  Try a [hexbug nano][1] and see if it behaves acceptably.  The key behind them is a vibrating motor on top of a biased bristle that turns the vibration into a biased motion.

  [1]: https://www.hexbug.com/nano


body:
Read up on Muscle Wire! I'm sure this will be the easiest most elegant solution.
Basically apply a small voltage to a section of this wire in response to sound detection and it will deform, changing the centre of gravity of the ball at rest, making it move. Use two pieces and you will manage to get it to move or tilt in two directions!


body: Want to make a ball move? Maybe look at how sphero does it by looking at a tear down video. You have to use motors. The motor end has to be connected to a wheel which turns the outer shell. The centre which is not at all connected to the shell should be heavier than the shell.


body:
The ball moves are made by a simple physics principle called Conservation of Angular Momentum. The angular momentum is a property that has any object that rotates and is proportional to its mass and velocity.
To make a ball move you should play with this momentum, using its simplest application, the mechanical gyroscope.
The mechanical gyro is made of a heavy disc rotating at high speed, modulating its velocity you can change the momentum and create a force that will move your sphere.


message:
How to sync multiple arduinos?

I'm making a posture control experiment in which a series of images (stimuli) are presented to a person and I'm trying to measure the displacement of this person as a result of these stimuli. To do so I'm planning to use 3 Arduinos:

1) "Arduino Tx 1": an Arduino nano with an Xbee shield and an MPU unit attached for sensing displacement. This implementation has to be wireless because the subject must be able to move freely.

2) "Arduino Tx 2": an arduino uno for reading an analog signal that indicates when an image (stimulus) is presented to the person

3) "Arduino Rx": an arduino uno connected to a computer and reading data from both "Arduino Tx 1" and "Arduino Tx 2"

I want to make sure that signals coming from "Arduino Tx 1" and "Arduino Tx 2" are synchronised. That is: if an image is presented at *t=t0* (signal sensed by "Arduino Tx 2") then I want to be able to tell that the displacement sensed by "Arduino Tx 1" at *t=t0+dt* corresponds to this stimulus.

My question is: is it possible to ensure that signals coming from "Arduino Tx 1" and "Arduino Tx 2" are synchronised when read by "Arduino Rx"?

body:
Have TX2 also emit an infrared pulse that initiates the timing reported by TX1.  TX1 should report dt rather than t_tx1.

The common real-time clocks for for Arduino report at 1 second resolution, which does not sound as if it is accurate enough for your needs.


body:
IMHO the delays are negligible if you are detecting times in the range of milliseconds. Just give us some more info (e.g. what is the maximum error you can tolerate).

In any case you can implement a round-trip-time estimator. For instance

 - RX sends a packet (or even just a single byte) to one TX to set it in "RTT measuring mode".
 - TX reads the packet and sends an ack. This is required for avoiding errors when the TX is busy doing something else.
 - When the ACK is received, the RX sends a message and starts measuring the time.
 - When TX receives the message, immediately sends back a reply
 - When RX receives the reply, stops the timer. The communication delay is half the time measured

Just repeat this procedure for both TX1 and TX2; this way you will have an estimate on how long it takes to receive a message from each of them. Then, when you receive a packet, you know how much time passed since it was transmitted (and so you can synchronize them)


message:
Why does analog sensor "hum" when plugged into common ground?

I have the ground for an SD card module, LED, and piezo sensor all plugged into the same ground rail. When doing this I get a low "hum" in the piezo readings where instead of reading ground voltage (0) when there's no vibration, it cycles between 4 and 6.

However, when I switch the piezo's ground onto ground rail connected to different ground pin on my Arduino, the hum goes away. If I keep the piezo on original ground and move the SD card module's ground, the hum comes back.

I'm very new to electronics, so I'm wonder what's going on?

EDIT: Here's a diagram of the circuit.

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

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

body:
@Milliways remarked:

>You have a ground loop. Without seeing the actual physical layout it is impossible to determine the cause. This is a common problem in audio circuits. Fixing this is as much an art as a science. The usual solutions involve a single earthing point, earthing at one end only or in extreme cases common mode rejection techniques.
>
>Yours is an idealised diagram. These kind of problems are often related to the physical layout e.g. parallel wire runs. I agree that there appears to be nothing amiss. As I stated this is a black art. I would suggest separating the low level analog circuit from the rest of the wiring - i.e. DO NOT share any earth cabling with any other circuit. This appears to be what you have done when it worked. You should also minimise any other source of interference by using twisted wires to the sensor.


message:
Controlling arduino over webserver

I want to control arduino through Internet without using Ethernet shield. I know there is a way. So can you help me what things I'll be needing for that

body:
This is incredibly broad: you could use an Arduino Ethernet, which has built in Ethernet, or you could use an ENC28J60 Ethernet module, or any of the many, many WiFi peripherals.

Also, consider using the ESP8266, instead of an Arduino with an Ethernet/WiFi peripheral. The ESP8266 can be programmed directly from the Arduino IDE with Arduino-style syntax, and can also run the NodeMCU firmware (programmed in Lua).


message:
LCD not working with Arduino Uno

I am a new learner on Arduino. I am trying to learn how to control the LCD. I looked in the article, ["Hello World!"][1], and followed the instructions but it did not work (I checked it many times). The result I got is shown below (the text is not showing).

Please help me. Any help is appreciated.

[![Photo of LCD not displaying correctly][2]][2]

Here is my code:

<!-- language: c -->

        #include <LiquidCrystal.h>
        LiquidCrystal lcd(12, 11, 5,4,3,2);

        void setup() {
          // set up the LCD's number of columns and rows:
         lcd.begin(16, 2);

        lcd.print("hello, world!");
        }

        void loop() {
          // set the cursor to column 0, line 1
          // (note: line 1 is the second row, since counting begins with 0):
          lcd.setCursor(0, 1);
          // print the number of seconds since reset:
          lcd.print(millis() / 1000);
        }

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

body:
There are 3 things you can try.

**1.**
If you have any male pins, solder those to the lcd screen, then stick it in the breadboard. After that you can stick the wires in the breadboard appropriately. The first time I tried this the wires were either touching or not connected enough to the lcd screen.

**2.** Double check all the connections made. This also happened to me, just make sure all the wires are in their right places.

**3.** Have you tried adjusting the potentiometer? Thats what its there for. Try turning it **slowly** both directions to adjust the background and letter brightness.

From the looks of the picture, number 3 may be your problem. Try that step first, and if it doesn't work you can try the other two. Hope this helps!


message:
Arduino serial communication input string checking

I am trying to check whether the input string in my serial is inside my string array, but it seems like that the condition if(array[i]==inputString) does not print true.

So here is my code:

    String array[4]={"hey","jude","jane"},inputString,test;
    boolean stringComplete=false;
    void setup() {
      // put your setup code here, to run once:
      Serial.begin(9600);
    }

    void loop() {
      // put your main code here, to run repeatedly:
      //int store=0;
      serialEvent();
      if(stringComplete){
        Serial.println(inputString);
        for(int i=0;i<4;i++){
          Serial.println("..");
          //test=array[i];
          Serial.println(array[i]);
          if(inputString==array[i]){
            Serial.println("true");
            break;
          }
        }
      inputString="";
      stringComplete=false;
      }
       //Serial.println(store);
    }

    void serialEvent() {
      while (Serial.available()) {
        char inChar = (char)Serial.read();
        inputString += inChar;
        if (inChar == '\n') {
          stringComplete = true;
        }
      }
    }

body:
First, you declare an array of 4 items and provide an initializer for 3. Don't know how it can even compile, maybe it is tolerated but in doubt

    String [] array = {"hey","jude","jane","foo"};

Also, your serialEvent function appends `\n` to the string. Even if you receive string jane, you will compare `jane` from array with `jane\n` from serial

    char inChar = (char)Serial.read();
    if( inChar == '\n')
       stringComplete = true;
    else
       inputString += inChar


message:
Picking the time a led on an arduino should turn on, via android

I have created an app which is connencted to my arduino via bluetoth. The user of the app can turn on and off a led which is connented to the arduino. But I want to take it a step further... I want the user to be able to give the time and the date when the light should turn on and additionally the time that sould pass until the led turns off again. Is it significantly harder? I have thought of using an already existing alarm app but I am pretty stuck, so could anyone give me some suggestions?

body:
Make the Bluetooth message send how many seconds it is until the light should be on, and how many seconds it should stay on.

Then the arduino code can just handle everything with millis(). You know the millis() you were asked to start, add the delay, and wait for that time.

Delays less than 50 days (wrap around of millis ())  take no effort to handle it you embrace the overflow.

Handling delays greater than 50 days can be achieved by watching for millis() overflows and counting them. You could also make your own timer based counter.

*If* you care about recovery after power loss / reset you could use an RTC module. Depending on its complexity, it could interrupt you or you poll it to check for a date you saved to Arduino eeprom.  You would have to consider what the system should do it the alarm would have happened during the power loss...


message:
Why doesn't interrupt TIMER0_COMPA work with loops?

I need have two stepping motors working at the same time each with a different number of steps. But loops (`for`, `while`) don't work with this task using type of interrupt above. What is wrong?

[![Screenshot of update function][1]][1]

My code:

    class Driver {
        int pinStep;
        long times;
        int state;
        unsigned long previousTime;

      public:
        Driver(int pin, long interval) {
          pinStep = pin;
          pinMode(pinStep, OUTPUT);
          times = interval;
          state = LOW;
          previousTime = 0;
        }

        void update(unsigned long currentTime) {
          int iteration;
          while ((iteration < 5) & (currentTime - previousTime >= times)) {
            previousTime = currentTime;
            if (state == LOW) {
              state = HIGH;
            } else {
              state = LOW;
            }
            digitalWrite(pinStep, state);
            iteration++;
          }
        }
    };

    Driver drv1(5, 2);
    Driver drv2(7, 50);

    // set timer behavior
    void setup() {
      OCR0A = 0x80; // 128
      TIMSK0 |= _BV(OCIE0A);
    }

    // interrupt handler
    SIGNAL(TIMER0_COMPA_vect) {
      unsigned long currentTime = millis();
      drv1.update(currentTime);
      drv2.update(currentTime);
    }

    void loop() {
    }

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

body:
    void update(unsigned long currentTime) {
          int iteration;
          while ((iteration < 5)

Your code take a variable with an undefined value (`iteration`) and loops while it is less than 5. How is this useful? Perhaps set iteration to zero:

          int iteration = 0;

---

> But cycles (for, while) don't work with this task using type of interrupt above.

Please define what "don't work" means here. It does too much? Too little? Nothing at all?

---

>  And Serial.print prints out iteration value as "111111"

The only way that could happen is if `currentTime - previousTime >= times` is false. Which it would be.

      while ((iteration < 5) & (currentTime - previousTime >= times)) {

Do you mean: `currentTime - previousTime < times`?