text:
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?

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 can easily upload code to my Nano and Uno.

I would be programming it with a pc. I was just wondering if I could power it from the OTG cable and still be able to connect it to the pc. The OTG cable has a micro usb, female usb for connection and male usb for power.

USB voltage is below the 6v minimum specified voltage for Vin (on a 5v board).  It might still work to a degree, but beware that what you are recommending is out of spec.  Your reference to OTG has nothing to do with what they poster is talking about, they are proposing what is basically a Y cable, that could be used with something like an Android device, but instead they want to use it with a PC, USB powerbank and the Nano - no Android involved.

@ChrisStratton My bad, I misunderstood the description. I updated the answer.


text:
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.

Also see answer to a compiled code size question,  and see Does the compiler generate intermediate assembler?,

Thanks, that's helpful.  I think my question is more of how though?  I can see in the Visual Micro project properties how to pass flags to the compiler, but it doesn't seem to recognize the --save-temps=obj flag.  Its probably another question but I don't know how to pass flags from the Arduino IDE either.

The 2nd post in Assemler results, where? at forum.arduino.cc mentions the  -S switch and gives a batch file for Windows.  Note, probably won't apply to Visual Micro, but to set Arduino IDE to save temp files, click 'Save when Verifying or Uploading' on preferences page -- you could try both ways and see what flags get used

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.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
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());
  }
}

What pin do you have the device connected to on the Arduino? What Arduino do you have? What baud rate do you have set in the Serial Monitor?

8,9 - uno 4800.   When I first power up unit is see the self test but nothing further. I have connected directly to a pic and verified the radio I'm connecting to does indeed continue to send data.

Which is Rx and which is Tx?

One way displayed junk when I booted up the device so I swapped the pins and that showed me the bootup message. 9=tx 8=rx

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

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).

Thank you for the information Nick, in my original post I stated I had tried both SoftwareSerial and AltSoftSerial.  Also I believe the snippet of code you specified allows me to send a character from the serial monitor to the serial device hooked up to the software serial port... Yes?

Yes, but does the device need to receive data?

I can trigger a response from the radio but sending a character to it. However I am not seeing anything after the initial boot up message. I can connect directly to of serial and interact np, but the arguing only gives me the initial power up message.

See amended answer.

Now I'm totally stumped.

This works the same way, I put in code as you stated, I still see the power on message but no following messages. I've plugged in another serial monitor and verified the serial data is being sent and it is but when I plug in the device to the arduino I get the bootup and nothing else.  Serial parameters are 4800 8-N-1 Flow: Off

Seems like there must be something different about the arduino serial compared to the PC serial.... I can't figure it out. I can unplug it from the arduino and directly into my computer and see the data flow but then hook it into the arduino and nothing.

Serial input is "passive". The sending device doesn't know if you are receiving or not (ie. the Rx pin is high impedance). So either it stops sending (for some reason) or you are receiving but somehow ignoring it. I can trigger a response from the radio but sending a character to it. - well, send a character to it then. Try going back to AltSoftwareSerial, and send a newline or something every few seconds.

I went back on looked at the Device, it has 6 pins, GND, RX, TX, DTR DSR +12v (supplied from device)
I put a jumper between DTR and DSR and suddenly I see the information streaming. I'm guessing i need to hook that to the arduino somehow so I can interupt the DTR and then send my character then turn the DSR back on... Thank you for persevering on this with me.

Can't you leave them jumpered? In the olden days we used to just jumper stuff together until it worked. It's not as if you are looking at DTR/DSR anyway.

Nick, After more research yes your right it appears I can just leave it jumpered. I can now see all the information from the information. The next step is I need to pass the letter d to the arduino. When I have the device connected to hyperterminal I press 'd' and nothing else and it gives me a status report... I've tried a hundred different things but can't seem to get this part going. should I open a new question so I can post the code? I'm pretty new here.

Yes, this sounds like a different question. Can you please take steps to let the Stack Exchange system know this question is answered? Either accept my answer, or post your own answer to your question along the lines of: Problem solved by jumpering together DTR/DSR - that way the next person with this problem will find a solution here.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
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.

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.


text:
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?

Is it consistent? Does it always begin at 3000? And does it continue as expected (3001,3002,...) after that?

There are many Arduino models. It helps considerably to state in the question which one you are using.

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.
Because you did't wait, your loop is able to execute 3000 times before Serial actually sends something back to the PC.


text:
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?

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 Arduino Pro Micro, get data out of Tx pin?
For Teensy, see https://www.pjrc.com/teensy/td_uart.html


text:
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.

Without addressing the issue about which would be "best" or more accurate, there is quite a bit of CPU work involved with "talking to" the 1-Wire devices. Probably a lot more than a couple of calculations with a thermistor. As for which is more accurate, you would need to look at the DS18B20 datasheet, and compare it to the datasheet for a particular thermistor, to be able to say about that for sure. How about a thermocouple instead?

Judging by a few datasheets I found, the DS18B20 is accurate to ± 0.5 °C, and one of my thermistors is ± 1 °C. So yes, the DS18B20 is more accurate than this thermistor, but is 0.5 °C important in this particular application?

Another usefull feature is the fact they come factory calibrated, according to datasheet.

@NickGammon half a degree doesn't matter, no. I don't think I'll end up being able to use the DS18B20 though, as a few of my sensors need to be able to go up to 300F. With thermocouples, I would need an additional IC per sensor such as the MAX31885, correct?

I haven't tried using thermocouples apart from the one on my multimeter. There are various types, and I gather that they output low voltages which may need amplification and interpretation.

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.

I'd say accuracy is about how close a reading is to the actual/true value, while precision is related to differences when repeatedly getting a reading for the same actual value. And resolution would be a separate thing altogether, I'd say, indeed kind of describing how many digits are produced.

I'd call what you term precision "variance". Anyway, regardless of what one part of the world calls something compared to another (which we can argue over all day and get nowhere) it's the concepts that are important not the names.

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"

Since the ADC inside of something like the DS still relies on the 5V from the Arduino, would it not drift just as much as the Built in ADC?

There are tricks around like doing a comparative read, measure at a lower voltage, capacitors, giving the ds it's own power suply ...

I don't know this particular DS but the data sheet should be able to tell you.

Internally though, there must be an analog reference somewhere, right? You can get precision analog voltage references. I looked into some here.

Nick; I know it can  be done. Basically the tricks I mentioned above can be used with arduino as with any other device. My point is that it is not so easy to get very accurate analog readings. There is needed more than the Arduino analog read example. As such "no matter how accurate the Analog signal is; you still have to account for the accuracy of the ADC"


text:
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

At for( int i = 0; i <= index; i++), I don't believe you've initialized clientline[index] anywhere, so the final iteration will print an undefined character. I don't know if this is the error, but I think it is an error. You could instead set clientline[index] = \0; (i.e. NUL-terminate the line), and replace the for-loop with Serial.print(clientline);, letting Serial.print() print the whole string for you.

Hi @JRobert, thanks for the advice. I've made those changes, but the serial output is still the same.

You're welcome. I wasn't convinced that was it, but now it's one less possibility! So now you know that coming out of the while loop, clientline contains two characters, one of which is some kind of whitespace, likely a space, and a '\n' (because the terminal line-feeds). You may need to be debugging the client at this point. Are you sure it is sending what you think it should be?

@JRobert I've checked communication on Wireshark and it looks OK. Every time the client refreshes the webpage it should send a message to the ESP8266 that should be picked up by client.read()
I think the problem lies in getting the frame from the ESP8266 to the Arduino, as the system is successfully sending the webpage as requested.

It looks like I have the same problem. I used the "ESP8266_Shield_Demo_Sparkfun" and often the webpage shows not a proper output ("AT.." commands instead). How did you adapt the baud rate in the "SparkFunESP8266WiFi.h"?
Thanks!

Hi, sorry for taking so long to reply, I haven't looked on here in a while. If it's still helpful to say, I didn't change the header file, I use the setBaud function from SparkFunESP8266WiFi.h straight after using begin()

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.


text:
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.

Try sending a 96 character string and a 97 character string so your code tries to read and then write outside its buffer.

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'

The zero-value, the "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. (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.

Oops. I changed it and forgot to change all of it. I have edited it to be correct. Thank you!

Note that the serial_message[96] is initialized with zeros at the beginning, providing default null terminations for strings up to 96 characters long.  What might be interesting is what would happen if one sends strings 96 or more characters long.  At 96, the Serial.println() wouldn't stop printing until it hits a null in whatever is after the buffer in memory, and if you sent more than 96 characters, it could write over important RAM and crash.


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

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 - 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.

The official Arduino documentation has detailed instructions on how to transform Arduino board into an ISP.
https://www.arduino.cc/en/Tutorial/ArduinoISP


text:
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;
}

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!

No sir, that doesn't solve the problem. I even looked up on the debounce problem. If I use "INPUT_PULLUP" it won't recognize the state of the button hence not showing the "off" message.

You also need to change the button logic (buttonState2 == LOW) as pushing the button will given a LOW signal with PULLUP.


text:
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?

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


text:
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.

Just use the Arduino IDE, and enable verbose output in the settings. All the needed commands will be visible in the output window. After that you can ditch the IDE.

Which aspect do you want to know about? Wiring the adapter? Programming the UART code, or compiling a program and uploading on the command line?

"This cable is not good for Arduino re-programming such as a Boarduino, MENTA, Monochron, etc. because it does not have the DTR/RTS wire necessary for initiating the bootloader reboot sequence. "

@MikaelPatel But one can still hold the reset button and release it before the upload sequence begins.

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).

The bootloader is really not an obstacle, and using it is entirely compatible with the GNU AVR toolchain - after all, that is what the Arduino IDE uses.  There is no interdependence of the arduino bootloader and any arduino runtime components, you can use either without the other.


text:
Interrupts detach
I need to stop 1st interrupt from 2nd interrupt till 2nd interrup finish work... How can I do that?
Here is my 2nd interrupt:
void CHECK_IR(){
  detachInterrupt(0);
  if (irrecv.decode(&results)) {
    switch(results.value){
      case 16753245:
      Serial.println(results.value);
      if(level == 1){
       level = 1;

      }else {
        level = 1;
      }
      break;
      case 16724175:
      level = 1.6;
      break;
      case 16718055:
      level = 3;
      break;
      case 16743045:
      level = 5;
      break;
      case 16716015:
      level = 9.9;
      break;
    }
    irrecv.resume();
  }
}

1st interrupt:
void zero_crosss_int() {

   delayMicroseconds(level*1000);
  digitalWrite(AC_LOAD, HIGH);
    delayMicroseconds(100);
  digitalWrite(AC_LOAD, LOW);

}

Here I detachInterrupt(0); detach 1st interrupt, but it is not right because I need it to work again, so i need interrupt 1st to sleep till 2nd intrrupt finish switch statment. Any solution for this?

Please describe your design and what you want to achieve. You are asking for a solution to a problem that might just be a misunderstanding of how this works.

In my 1st interrupt I have delayMicroseconds it cause if switch never run... It is the problem. I added above 1st interupt..

You can re-attach the other interrupt at the end of your interrupt handler.

How? I tried but not working... Also is there any way to avoid delay?


text:
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' ( 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 ), 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;
}

I dont see any problem with your approach. Checksum values are usually last (or close to last) and this doesnt restrict anything. Provide a sample of a command with parameters and a header. How are the commands and parameters stored in your program? You should also post the part of your code concerned with assembling the commands in a buffer.

I wrote a library for helping with RS485 communications that seems to have most of what you are describing. Variable length messages, and check sums for integrity.

@TisteAndii, I've replied in the ADDITIONAL INFO which has beed added after the original msg.

Would you be willing to try a different approach to sending commands parameters and header values? What if you send numbers instead of strings? It would make TX, RX, and processing easier and also allow for expansion in future. Also reduce size of payload and reduce chances of UDP losses, not to mention more straightforward code.

Thanks @TisteAndii, I've replied again at end of original msg with more info.

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, 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 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 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 approach, and Nick Gammon has a great description, too.

Thanks for some good info and links @slash-dev, it has helped clarify some previously vaque suspicions and intuitions.   I may even try implementing a swapout f=oxAABBCCDD fletcher checksum version for increased reliability once everything else is working.

@Electroguard, I was nervous that I didn't understand your question.  That Fletcher code is dead simple.  Slip me some o' that green checkmark by my answer?  Thanks!


text:
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?

A motor with an asymmetric weight will do it. Or, you could be more sophisticated: look at the Sphero BB-8 teardown.

That sounds like a good idea.  I assume you mean attaching the motor to the side, and the asymmetric weight will cause it to rock back and forth.  I will try that, though the motor I ordered off Aliexpress will probably take a month to get here.  :P

The motor (and weight) could be inside the ball. If you slowly increase the speed of the motor. The ball should begin to roll, since the center off mass would be displaced (I believe). You could indeed just fully power the motor, making your ball shake and rock (and be totally out of control).

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.

Maybe some sort of bristlebot?  Try a hexbug nano 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.

These sound interesting. Do you have any recommended/preferred sites/pages that you could link to in your answer?

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!

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.


text:
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"?

What do you mean "are synchronized"? If you get signals that arrive at the same moment, that would be synchronized wouldn't it?

What level of accuracy are we talking about? What is the reaction time? 1-10 ms would imply with 1% error 10-100 us. I would suggest broadcasting a start message, measuring and then fetching the results.

Why is the image indication analog?
You should get a digital pulse (with interrupt) to time when the picture is shown. And you can then, from that point measure the displacement.

Even though one is wireless and hence will be using a battery: can't the Arduinos simply send continuously?

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.

Most RTC devices also have a 32,768kHz output which should be more than precise enough.

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)


text:
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.

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.

I have added a diagram of the circuit. How could this result in a ground loop?

This 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.

I copy-paste @Milliways comment as an answer. Please, accept it to close your question.

@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.

I suggest that you make this a Community Wiki answer.

It's not my answer. I'm not qualify in this subject.

I refer to this post by Nick Gammon.


text:
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

I know there is a way. - what is this way of which you speak?

I don't want to use Ethernet shield

Well, what do you want to use?

I want to control lights through wamp server

Ah, great! Go down to the corner store and buy yourself a WAMP server.

I have a wamp server running in my system.. So how can I connect using php script

Your question - both of them - is really too vague to answer in any but a vague way. Say more about what you do want to do. You need to connect to the internet in some way; what ways will you consider? You've mentioned "a wamp server running in my system" - what system, and how do you intend for it to participate in this project? There's really not enough here for anyone to be able to offer much help.

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).


text:
Why After instancing TinyGPS , serial stop working?
I have GSM shield (and Arduino UNO) works fine with this code :
#include <GPRS_Shield_Arduino.h>
#include <SoftwareSerial.h>
#include <Wire.h>
#include <Suli.h>

#define PIN_TX    7
#define PIN_RX    8
#define BAUDRATE  9600

#define MESSAGE_LENGTH 160
char message[MESSAGE_LENGTH];
int messageIndex = 0;

char phone[16];
char datetime[24];

GPRS gprsTest(PIN_TX,PIN_RX,BAUDRATE);//RX,TX,PWR,BaudRate

void setup() {
  Serial.begin(9600);
  while(0 != gprsTest.init()) {
      delay(1000);
      Serial.print("init error\r\n");
  }
  delay(3000);
  Serial.println("Init Success, please send SMS message to me!");
}

void loop() {
   messageIndex = gprsTest.isSMSunread();
   if (messageIndex > 0) { //At least, there is one UNREAD SMS
      gprsTest.readSMS(messageIndex, message, MESSAGE_LENGTH, phone, datetime);
      //In order not to full SIM Memory, is better to delete it
      gprsTest.deleteSMS(messageIndex);
      Serial.print("From number: ");
      Serial.println(phone);
      Serial.print("Datetime: ");
      Serial.println(datetime);
      Serial.print("Recieved Message: ");
      Serial.println(message);
      String msassages = message;
        if(msassages == "Hello"){
          gprsTest.sendSMS(phone,"hello to you");
        }
   }
}

After adding #include <TinyGPS.h> ;  it works fine too but after adding TinyGPS gps; (and nothing else) to the code header, everything stop working and i can't see anything in terminal and the program stop sending SMS back. I should mention , TinyGPS works fine individually.
Why this happen ?

Check how much memory if free. Is there memory enough for the TinyGPS as well? Reduce memory usage by using F() for all string literals. Reduce the buffer size, etc.


text:
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!", 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.

Here is my code:
    #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);
    }

It could be the fact that you are not using a soldered header pins. Any slightly movement may break your connections. Do you have any male pins you can solder to LCD?

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!


text:
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;
    }
  }
}

could you please change the image by actual text for the code ? Thanks.

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

No reason to doubt, just look it up.  See paragraph 19 (the “all subobjects that are not initialized explicitly shall be initialized implicitly the same as
objects that have static storage duration” sentence) in part 6.7.9 of the ISO/IEC N1570 C++ standard.  The 4th item of String array[4] will be initialized to a null pointer if only three initializers appear.

Thanks for the input, but then even with the sentence it's not entirely clear to me. 4th item will be initialized to nullpointer or String with empty constructor ?

The empty string (ie. String with the default constructor).

It occurred to me after commenting that "null pointer" might be incorrect for String objects, but didn't know offhand.

A String object isn't a pointer, so it can't contain a null pointer, per se.


text:
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?

All you will need is an RTC module, you set an alarm with the module; it will trigger an interrupt when the time and data you set is reached. Then you light up the LED and use a timer to keep track of the length of time its on.

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...


text:
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?

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() {
}

Try moving both instantiations of Driver into volatile memory - voltatile Driver drv1(5, 2); - and again for drv2.

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?

Thanks for answer.
I initialized iteration variable as zero but loop doesn't work correctly: stepping motor is moving all the time, not on certain steps (5). And Serial.print prints out iteration value as "111111" See screenshot: http://i.stack.imgur.com/1uyPO.jpg

I don't see any Serial.print in your code.


text:
Low-Pulse Occupancy and Voltage Divider
I have a PPD42NS dust sensor I'd like to hook up to an ESP8266-01 microcontroller. The ESP8266 uses 3.3v logic, but the PPD42NS uses 5v. The PPD42NS uses low pulse occupancy as output.
I'd like to use parts I have on hand, and I was wondering if a simple voltage divider built from 2 resistors can reliably shift the voltage without distorting the signal.
If not, could an NPN transistor do the job instead?

That should work. You just don't get very crisp edges on the signal. But I don't think that a problem with the PPD42NS as it probably uses relatively slow speeds.

While the PPD42NS has a 5-pin connector, it is shown at seeedstudio.com and howmuchsnow.com connected up with three wires: +5V, Ground, and an LPO or “Low Occupancy Output” signal, which goes low when a particle occludes an LED beam path.  LPO is used as an input to let sketches measure the fraction of time the beam's  occluded, which correlates with number of dust particles.
Yes, a resistive voltage divider will let you use the 0-to-5V occupancy signal as an input to your 3.3V-tolerant ESP8266.
What values of resistors should be used?  Because input pin capacitance is small (eg under 10 pF), signal "crispness" should be about the same over a broad range of resistances – say from a 100Ω+200Ω divider up past 1KΩ+2KΩ;  even 10KΩ+20KΩ might be ok.
The Grove_-_Dust_sensor.pdf data sheet at seeedstudio.com says:

Output Method  Negative Logic, Digital output,
  Hi : over 4.0V(Rev.2) Lo : under 0.7V
  (As Input impedance : 200kΩ) OP-Amp output, Pull-up resistor : 10kΩ

This suggests (but doesn't clearly indicate) that some sort of open-drain output might be used.  If so, instead of using a voltage divider one could remove the 10kΩ pull-up on the sensor, and pull the output to 3.3 V instead of 5 V, via either an external resistor or using an INPUT_PULLUP pinmode setting (if available on the ESP8266).
Edit: Regarding the comment, “I'm considering use it in conjunction with an MCP23017 I/O expander IC. The GPIO pins on the chip appear to be rated at a max capacitance of 50 pF. Will that affect the range of resistors available? How does resistor choice affect the crispness of the signal, and how can I determine it for myself?”:
The “max capacitance of 50 pF” spec, which is parameter D101 in table 2.1 of the MCP23017 spec sheet, refers to “Capacitive Loading Specs on Output Pins”, ie, how much capacitance MCP23017 outputs can drive.  It doesn't refer to input pin capacitance, so isn't relevant here.
In general, when a signal edge (a rise or fall) arrives at an input pin, the input pin's voltage doesn't change instantaneously.  The input pin's capacitance needs to charge or discharge.  (It charges for a rising edge, discharges for a falling edge.)  The speed of change depends on the RC time constant of the circuit.  A delay occurs, probably 1–3 time constants long, before the pin starts to switch.  (The switch may take a few tens or hundreds of nanoseconds.)
For example, if input circuit capacitance is 10 pF and its effective resistance is 100kΩ, RC = 10 pF · 100kΩ = 10⁻¹¹·10⁵ = 10⁻⁶ seconds = 1 microsecond.  Whether that's large enough to matter for your measurements depends on how many time constants have to occur before the pin starts switching, and on how narrow the LPO signals are.
In short, compute RC, and if it's more than a few microseconds, use a smaller value of R.  Alternately, if you have access to an oscilloscope, attach it to the input and try various resistance values in the voltage divider, to get a feel for how the signals degrade as the resistors in the divider get bigger.
Note, using a voltage divider causes different RC values for falling edges than for rising edges.  For example, suppose an actively driven 0-5V signal enters a divider with 10KΩ in series with 20KΩ, and the 0-3.3 V signal is taken from the resistors' junction.  Then R is 10KΩ for a rising edge, and 20KΩ for a falling edge.  If the 0-5V signal weren't actively driven high, but instead pulled up via a pullup resistor R' when a transistor turns off, then the rising edge R value would be R'+10KΩ for this example.

I'm considering use it in conjunction with an MCP23017 I/O expander IC. The GPIO pins on the chip appear to be rated at a max capacitance of 50 pF. Will that affect the range of resistors available? How does resistor choice affect the crispness of the signal, and how can I determine it for myself?

@user1569339, see edit


text:
Arduino hangs on second GSM message (was GSM based led matrix display)
Friends, my team and I are working on a gsm based wireless display as a part of our project. We are using Arduino UNO as the microcontroller which is interfaced with a sim900 module. Upon arrival of a new sms in the gsm module, its contents will be passed on to the dot matrix led display through SoftwareSerial. We almost got the code working but the problem we now encounter is the reception of new sms. The code works fine for the first sms but to display the next new sms, we had to manually reset the Arduino every time. Can you guys help me? This is the code:
#include <SoftwareSerial.h>
#include <SPI.h>
#include <DMD.h>
#include <TimerOne.h>
#include "SystemFont5x7.h"
#include "Arial_black_16.h"

#define DISPLAYS_ACROSS 1
#define DISPLAYS_DOWN 1
DMD dmd(DISPLAYS_ACROSS, DISPLAYS_DOWN);

int temp=0,i=0,x=0,k=0;
char str[160],msg[160];
void ScanDMD()
{
  dmd.scanDisplayBySPI();
}

SoftwareSerial SIM900(0, 1);

void setup()
{

   Timer1.initialize( 5000 );
   Timer1.attachInterrupt( ScanDMD );

   dmd.clearScreen( true );
   Serial.begin(9600);

   SIM900.begin(9600);
   void SIM900power();
   delay(20000);

     SIM900.print("AT+CMGF=1\r");
  delay(100);
  SIM900.print("AT+CNMI=2,2,0,0,0\r");
  delay(100);
}

  void SIM900power()

{
  digitalWrite(9, HIGH);
  delay(1000);
  digitalWrite(9, LOW);
  delay(7000);
}

void loop(){
for(unsigned int t=0;t<60000;t++){
  void serialEvent();
  if(temp==1)
  {
    x=0,k=0,temp=0;
    while(x<i)
    {
      while(str=='#')

      {
        x++;
        while(str!='*')

        {
          msg[k++]=str[x++];
        }
      }
      x++;
    }
   }
  }
     const char* dchars;
      dchars=msg;
     dmd.clearScreen( true );
   dmd.selectFont(Arial_Black_16);

  for(unsigned int i=0;i<=300;i++){
   dmd.drawMarquee(dchars,strlen(dchars),(32*DISPLAYS_ACROSS)-1,0);
   long start=millis();
   long timer=start;
   boolean ret=false;
   while(!ret){
     if ((timer+30) < millis()){
       ret=dmd.stepMarquee(-1,0);
       timer=millis();
     }
   }
 }
}

void serialEvent(){
  while(Serial.available())
  {
    char ch=(char)Serial.read();
    str[i++]=ch;
    if(ch == '*')
    {
      temp=1;
    }
  }
}

The DMD library was found on the net.

Please use the code format button to format the code properly.

i did @Avamander

Surely you have noticed there are syntax errors in your code?

The code compiled successfully i can't find errors.can u pls pin point them

I have confusions in value passing through buffer and once this buffer value enters dmd loop there is no way out, hw can i improve that

Does nothing clear 'i' at the end of a message?  If not, then long/unexpected/multiple messages can overflow your str[160] buffer.
It also looks like writing to the msg[160] buffer isn't well protected from overflow.

How can i protect msg(160) from overflow,can you please share the code

strncopy() is made for copying strings up to the length of a buffer.  I'd set a const int buffermax = 160; and use that as one limit on incrementing the buffer indices.