text:
Super slow serial (UART) communication on Arduino
I am using this device for my Arduino that connects to the OBD-II port of my car to get various information such as speed, rpm, etc. I am using this for a digital Nixie tube speedometer using the smart Nixie tube from a Kickstarter project.
I pass the information to the Nixie tubes through serial and get information from the OBD-II through serial as well. I am getting speed updates about every 20 seconds and that is incredibly slow when the device can supposedly update up to 100 times per second.
I originally was using an Arduino Uno and using software serial for the tubes, but I figured the slowdown was due to interupts interfering with the hardware serial, so I switched to the Arduino Mega 2560 to use a second hardware serial pin to hopefully fix the problem, yet the same issue is occurring.
Here is my code... There must be something I'm doing wrong. Serial2 is for the Nixie tubes.
#import <Arduino.h>

#include <OBD.h>

int ones = 0;
int tens = 0;

int kphValue = 0;
int mphValue = 0;

int rpmValue = 0;

String onesString;
String tensString;
String payloadString;
String rpmString;
COBD obd;

void setup(){
    Serial2.begin(9600);
    obd.begin();

    //Initiate OBD-II connection until success
    while (!obd.init()){
        Serial2.print("$0,Y,Y,255,255,000,000$0,Y,Y,255,255,000,000!");
        delay(1000);
        Serial2.print("$0,Y,Y,000,000,000,000$0,Y,Y,000,000,000,000!");
        delay(1000);
    }
}

void loop(){
    onesString = String(ones);
    tensString = String(tens);
    payloadString;
    rpmString;

    if(obd.read(PID_RPM, rpmValue)){
        if (rpmValue < 3000){
            rpmString =",N,N,255,000,255,000";
        }
        else if (rpmValue >= 5000){
            rpmString = ",N,N,255,255,000,000";
        }
        else if (rpmValue >= 3000){
            rpmString = ",N,N,255,255,030,000";
        }
    }

    if (obd.read(PID_SPEED, kphValue)){
        kphToMPH();
        payloadString = "$" + onesString + rpmString + "$" + tensString + "rpmString" + "!";
        Serial2.print(payloadString);
    }
}

void splitDigits(int input_number)
{
    ones = (input_number%10);
    tens = ((input_number/10)%10);
}

void kphToMPH()
{
    mphValue = kphValue * 0.621371;
    splitDigits(mphValue);
}

EDIT:
I am using the following library: https://github.com/stanleyhuangyc/ArduinoOBD

The call to Serial2.available() looks suspicious, what happens if you remove it? That calls checks for incoming data, not that it's OK to send data.

I will edit that out.  I added that to see if it would help because without it I'm still getting slow responses.

Seem to be missing the source for obd.read() there.

Can you add some sort of indication, like blink an LED, to show what's delaying? Is it that the code waits between reads, that the reads happen really slowly (low baud rate? faulty comms routine? long negotiation period?) or that the car waits a long time to respond? etc. etc.

The read is a relatively high baud rate.

the statement payloadString; doesn't do anything useful

Thank you.  I was changing things around and probably forgot to fix that.

Do the example sketches that come with the library also perform slowly? If so the slowdown might just be the ECU not sending data very fast.

Would having matching baud rates for each device help as well?
So my nixie tubes would have the same baud rate as the OBDII adapter

Which ODB library are you using? http://sourceforge.net/projects/obdcon/files/ ? https://github.com/stanleyhuangyc/ArduinoOBD ? Something else?

Project was scrapped but for the possibility of helping someone else I was using the github project.  I'll edit the question to reflect the library I was using and the device.

I think the problem is not so much in the update speed, but in the fact that you loose accuracy in your calculation. The following lines are the culprit:
int kphValue = 0;  // [-32768:32767]
int mphValue = 0;
mphValue = kphValue * 0.621371;

Make sure the calculation will be entirely in integers to prevent calculation errors:
uint16_t kphValue = 0;  // [0:65535]
uint16_t mphValue = 0;
mphValue = ( kphValue * 621 ) / 1000;

This limits kphValue to just over 100, if you want to go higher than that there are two option:

multiply by 62 and divide by 100;
use longer integers int32_t [-2147483648:2147483647], which comes with enough room for multiplying by 621371 and dividing by 1000000, but will perform slower and with a larger memory footprint. Do you really need that accuracy?

Yes and what about the computation delay added by the usage of floating point numbers with a MCU that has no floating point support.

Not sure if the first part is correct, while I normally wouldn't write it that way I'd expect kphValue would be converted to a double for the calculation phase. Just gave it a quick try on a PC C++ compiler and result was 621 for an input of 1000.

@Blup1980 - It will be slower but even a very slow micro should be able to do those calculations in a jiffy. If you were doing the conversion 1000 times per second then you might notice a delay.

@Blup1980 where do you see floating point numbers in my answer?

@jippie You said that your implementation using integers is better because of the better accuracy. But I wanted to add that it's also better in term of speed because there is no floating point. But it would even be better if you multiply by 636 and divide by 1024 where the divide can be computed as logical shifts instead of a multi cycle divide operation.

True @Blup1980, I didn't think of that one.

try this:
#import <Arduino.h>
#include <OBD.h>

int kphValue = 0;
int rpmValue = 0;

COBD obd;

//array of character arrays, see http://arduino.cc/en/Reference/string
const char* rpmStrings[] = {    ",N,N,255,000,255,000",
                                ",N,N,255,255,030,000",
                                ",N,N,255,255,000,000" };

void setup(){
    Serial2.begin(9600);
    obd.begin();

    //Initiate OBD-II connection until success
    while ( !obd.init() ) {
        Serial2.print("$0,Y,Y,255,255,000,000$0,Y,Y,255,255,000,000!");
        delay(1000);
        Serial2.print("$0,Y,Y,000,000,000,000$0,Y,Y,000,000,000,000!");
        delay(1000);
    }
}

void loop() {
    if ( obd.read(PID_RPM, rpmValue) && obd.read(PID_SPEED, kphValue) )
    {
        int rpmStringIndex = determineRpmIndex(rpmValue);
        int mphValue = kphToMPH(kphValue);

        //payloadString = "$" + onesString + rpmString + "$" + tensString + "rpmString" + "!";
        //using Arduino String objects is generally not a good idea due to memory constraints
        //it's probably ok, but I'd rather use character arrays and/or print a bit at a time rather than trying to assemble a giant string
        Serial2.print("$");
        Serial2.print(mphValue % 10); //ones
        Serial2.print(rpmStrings[rpmStringIndex]);
        Serial2.print("$");
        Serial2.print(mphValue / 10); //tens - integer division, don't need modulo

        //do you really want to append the string "rpmString!" or did you want the contents of the variabe rmpString+"!" ?
        //I'm pretty sure you meant the latter
        Serial2.print(rpmStrings[rpmStringIndex]);
        Serial2.print("!");
    }
    else
    {
        //obd read error
        //add debugging output here to see if obd failed to respond correctly/on time
    }
}

int kphToMph( int kphValue ) {
    //return a value rather than updating a global variable
    return ( int ) ( kphValue * 0.621371 );
}

int determineRpmIndex( int rpmValue ) {
    if ( rpmValue >= 5000 )
        return 2;

    if ( rpmValue >= 3000 )
        return 1;

    return 0;
}

Looks good and learned a lot... I will upload when I get a chance and let you know!

I was found solution with
Serial.setTimeout(100);
Like this (https://www.arduino.cc/en/Serial/SetTimeout) setTimeout was 1000ms default.
the check serial port per 1000ms.
I referenced this https://stackoverflow.com/a/28892086/929740


text:
How can I convert Arduino String to C string type?
I got a String which as I understand is an Arduino object, and got some C++ code:
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <string.h>

LiquidCrystal_I2C lcd(0x20,16,2);

boolean borrar = false;
String IP;

void setup()
{
  lcd.init();
  lcd.backlight();
  pinMode(13,OUTPUT);
  Serial.begin(9600);
  Serial1.begin(9600);

}

void loop() {

  while (Serial1.available()) {

    char caracter = Serial1.read(); //Comprobamos el caracter

    switch(caracter) {

    default:
                if (borrar) {
                              IP = "";
                              lcd.clear();
                }

                lcd.print(caracter);
                delay(125);
                borrar = false;

                IP.concat(caracter);
                break;

    case '\r':
    case 0x0F:
    case 0x0A:

                String res = "";
                borrar = true;
                int num= atoi(IP.c_str());
                if (num < 127)
                  res="Clase A";
                if (num == 127)
                  res="Direccion reservada";
                if (num > 127 && num < 192)
                  res="Clase B ";
                if (num >= 192 && num < 224)
                  res="Clase C ";
                if (num >= 224 && num < 240)
                  res="Clase D ";
                if (num >= 240 && num < 255)
                  res="Clase E ";
                break;

  } //fin switch

}//serial disponible

}//fin programa

However, this won't compile because of this line:
int num= atoi(IP.c_str())

As IP is a String and such method works for string. How can I make it compatible (convert it)?

Your code could be improved by removing the use of IP string altogether, and directly calculating its numeric value while characters come in through Serial1:
...
boolean borrar = false;
int IP = 0;
...

void loop() {
  while (Serial1.available()) {
    char caracter = Serial1.read(); //Comprobamos el caracter
    switch(caracter) {

    // NOTE it is better to replace default by the list of all digits...
    case '0':
    case '1':
    case '2':
    case '3':
    case '4':
    case '5':
    case '6':
    case '7':
    case '8':
    case '9':
                if (borrar) {
                              IP = 0;
                              lcd.clear();
                }

                lcd.print(caracter);
                delay(125);
                borrar = false;

                IP *= 10;
                IP += (int) (caracter - '0');
                break;

    case '\r':
    case 0x0F:
    case 0x0A:

                String res = "";
                borrar = true;
                int num= IP;
                if (num < 127)
                  res="Clase A";
                if (num == 127)
                  res="Direccion reservada";
                if (num > 127 && num < 192)
                  res="Clase B ";
                if (num >= 192 && num < 224)
                  res="Clase C ";
                if (num >= 224 && num < 240)
                  res="Clase D ";
                if (num >= 240 && num < 255)
                  res="Clase E ";
                break;

  } //fin switch

}//serial disponible

}//fin programa

This way would bring you 2 advantages:

a bit faster than working with String
no dynamic memory allocation/deallocation (String does a lot of these) which might lead your program to heap fragmentation and eventually crash.

Note that I have not further refactored your code as I guessed it was just a snippet, not the complete code for your program. Otherwise, I would have performed further refinement like:

remove num variable since it is the same as IP now
replace res from String to const char* (to further reduce heap fragmentation due to String usage)

Try
unsigned char z[100];
IP.getBytes(z, 100);
z[IP.length()] = 0;
int n = atoi(z);

To retrieve bytes inside the string. This assumes IP string's length is shorter than 100.

I tried and got:
BluetoothLCD.cpp:51:35: error: invalid conversion from ‘char*’ to ‘unsigned char*’ BluetoothLCD.cpp:51:35: error:   initializing argument 1 of ‘void String::getBytes(unsigned char*, unsigned int, unsigned int) const’

I have updated char to unsigned char

Something weird is going on, now I obtain:
BluetoothLCD.cpp:53:33: error: invalid conversion from ‘unsigned char*’ to ‘const char*’ BluetoothLCD.cpp:53:33: error:   initializing argument 1 of ‘int atoi(const char*)’

If it does not support, IP.toCharArray(z, 100); may be used.

How would code look like?

God, I think its done NOW

Try updating to the latest version of the Arduino libraries/IDE.
The c_str() method was introduced to the Arduino String class quite recently, I believe. That line of code certainly works fine for me on Arduino IDE 1.0.5.

I'm using Linux IDE how would I do it?

@diegoaguilar - I think you'd have to manually update your Arduino core libraries. You can get them from GitHub: https://github.com/arduino/Arduino

Version 1.0.5 has c_str() it can be downloaded for linux from the official Arduino site: http://arduino.cc/en/Main/Software

source: Stack Exchange

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

sort: votes


text:
Which voltage regulator should I use?
A friend and I are working on building a smartwatch on a budget, so it’s a (very) low power project, but we are currently having a problem with the power supplying.
We already chose this board, because of its size and the BLE chip: RFduino BLE SMT
For now on, we are planning to use this battery 500 mAh LiPo battery (approx. 4V at full charge) with this voltage regulator Micrel MIC5209-3.6YS (the board supports 3.6V max.).
But the problem is that the Voltage Regulator will apparently drain by itself too much energy from the battery (by heating), reducing drastically the autonomy.
So we would like to know if you guys can help us, if you can tell us exactly what (type of) regulator would be the best or if we need to find another battery.

Duplicate: http://electronics.stackexchange.com/questions/107827/which-voltage-regulator-to-use

What does this have to do with Arduino?

@sachleen the OP mentioned he is using an Arduino clone, so I guess that's OK for arduino.SE (although I admit this may be borderline)

I don't see any reason to close this question as off-topic. The OP is asking us about dimensioning a battery power supply for an Arduino clone. That's pretty on-topic to me. Just the cross-posting with EE.SE that is not ok.

I've created a meta post to discuss this topic. Please post your opinions in that thread.

IGND which is mentioned on page 4 of the datasheet is apparently proportional to the output current. This accounts for about 2-5% of the total current drawn by the regulator, depending on its load. With the maximum voltage drop of 4 - 3.6 = 400mV, a switching regulator will make no real difference. I think your only option is to find another regulator that has better efficiency.

Hi,
Thank you for your fast answer. I just thought : we can't use a linear regulator because it won't let the current pass through below 3.6V, right ? (the chip works down to 1.9V) So, maybe a switching regulator would be better after all. Perhaps you know a reference of one that would fit our needs ?

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


text:
Simultanous read and read/write on two serial connections
At the moment I'm using two softserials to connect to a GPS and an GSM module.
It seems not possible to have two open software-serials. So I was looking for an solution
After the initial-setup, the GPS module is only needed to be read from; while the GSM module needs to be bidirectional. So:
GPS > listen only
GSM > listen and write

Now I came across the GPS library from Adafruit, which uses an interrupt to receive data. Is this instead of a software serial. Or do I again run into the limitation?
An other solution might be to use the D0 and D1 to attach eg the GPS module. But than I won't be able to see the debug messages in my serial monitor. Is that correct?
Sorry in advance for these n00b questions. But I'm frustrated the things dont work as I want :)
edit

This is the adafruit GPS board.
And the board with whom it is connected: Gboard
The Sim900 is connected to D2/D3 and the GPS is connected to A2/A3.
D0/D1 are connected to a FTDI breakout board, which is plugged into my USB.

About the debug massages when using D0/D1, you'll at least have to provide the spec sheet and circuit diagram for the GPS module and Arduino Uno.

I update the OP with the boards en connections I use.

In case you weren't aware, Mega2560 has four UARTS, which could make life easier.

@gwideman That's a better solution, but for now I have to work with the Gboard. Next version of this device is going to be with at least two UARTS and separeted sim900 and GPS module.

So you want three serial ports: upload/debug (hardware serial), GSM (software serial) and GPS (software serial).  Unfortunately, two SoftSerial ports are not going to work at the same time (or even send and receive at the same time on one SoftSerial port).  In your current configuration it's not going to be solvable.
If you can wire the GPS to different pins, there are a couple of options to try.  One would be to disconnect the FTDI when running (reconnect to program) so you can use the hardware serial port for either GSM or GPS (probably the former).  If you need some print statements for debugging, you could use SoftSerial or AltSoftSerial (and connect the FTDI differently).  Reconnecting between upload/debug and run phases would be a pain but it comes with the platform you are choosing and the number of serial ports you need; you might be able to wire up a DPDT switch externally to do the switching rapidly.
The other and perhaps easier approach would be to connect the GPS to pins 8 and 9, and use AltSoftSerial for the GPS; as long as your baud rate to the GSM is high enough that might work.  (SoftSerial for the GSM will turn off interrupts for excessive periods of time at low baud rates).  Using AltSoftSerial makes use of the single 16 bit timer (Timer1), so this won't work if you use any other library which requires Timer1.

All right! at te moment I am bound to this board/setup, but in the future I'll use the bigger chip with 4 UARTS. For the time being I'm going to use the HWs for the GPS and use the switch-technique. Because after the setup works, I won't be needing the  debug messages as there won't be a computer connected to it.

Am I right that I would be able to use both HW an SS connections at the same time?

Yes, you can use both, with some caveats.  The HW serial library could miss a received byte if interrupts are off too long; and the SS library inhibits interrupts while timing the bits.  If the HW receive rate is much faster than the SS rate, this could be a problem.

Both are 9600 Baud, so that wouldn't be a problem. In the meantime I got it working with the GSM on SS and the GPS on the HWS; it was easier to use the library for the GPS on the HWS.

Adafruit_GPS.h (line 132-), which is included in Adafruit_GPS.cpp (line 13) refers in turn to the SoftwareSerial library on AVR platform and Arduino IDE version > 100.
#ifdef __AVR__
#if ARDUINO >= 100
    SoftwareSerial *gpsSwSerial;
#else
    NewSoftSerial *gpsSwSerial;
#endif
#endif

This means it uses software serial on an Uno. It also means if your problem is indeed with Software Serial, that is the library to check for bugs / updates or commit a patch to.

So the only solution might be to use the hardware RX/TX, with the downside being not able to see the debug messages.

@stUrb Depends on the hardware I guess. I am not familiar with the GPS module.

The solution to your problem might be to combine AltSoftSerial with SoftwareSerial. I haven't done it myself (yet) but I have the same problem as yours.
SoftwareSerial does busy wait for counting time between two bits, so it can't read simultaneously from two ports (some bits could be lost).
AltSoftSerial was created to overcome some of these limitations. It's interrupt-based. Unfortunately, it's harwired for one port (and pins 7 & 8). My understanding is that you can combine it with SoftwareSerial to read from 2 simultaneous ports. Pins 7 & 8 aren't what you need, from the description of the GBoard, but AltSoftSerial is open source, you can change the pin numbers (and possibly some masks) in the source code.
Hope this helps.

I've done exactly this.  The secret sauce for me was the SoftwareSerial.listen().
Before running your GSM commands you have to make sure the GSM module's SoftwareSerial port is "listening".  Then when you're done you have to listen() again to the GPS.
This is, of course, not terribly efficient, while the GSM port is listening any GPS data will be lost, but at least in my case the impact was negligible.
My code is here: https://github.com/lectroidmarc/gsm-tracker
As an aside, I have also considered plugging the GPS into the UART and running debug messages to a SoftwareSerial serial port, to be monitored during testing with another Arduino.  I'm just not sure the benefit would be there.

There is a working example of this, using the Adafruit Ultimate GPS, and the Arduino GSM shield
http://www.mallinson-electrical.com/shop/gpsgsm
I hope this helps

Generally it's not a good idea to post link-only answers. If the link goes down or moves, the answer becomes useless. Please expand by adding some more information (code sample) to the answer.


text:
SeeedDuino/Grove and the story of not being able to upload programs
I am new to the arduino world and wanted to start playing with the micro controllers, I am a .NET developer by trade so not completely new to this kind of world.
I purchased a seeedduino v3 and a Grove started kit (No soldering skills here) and can't even get the basics to work.
I am setting up a simple button to light up the LED program. I have had it run once or twice but it seems really hit or miss on whether or not the Arduino IDE actually gets the program onto the seeedduino.
Arduino IDE (1.5.6-r2) set-up:
Followed setup instructions found here: SeeedDuino v3

Board: Arduino Duemilanove or Diecimila
Processor: ATmega328
Port: COM4 [this is what popped up once device was plugged in]
Button is installed on D3
LED is installed on D7

Program:
int button = 3;
int LED = 7;

void setup()
{
  pinMode(button, INPUT); //define button on INPUT devices
  pinMode(LED, OUTPUT);   //define LED on OUTPUT device
}

void loop()
{
  int buttonState = digitalRead(button); //read the status of hte button

  if(buttonState == HIGH) //also used (buttonState == 1)
  {
    digitalWrite(LED, HIGH); //also used digitalWrite(LED, 1)
  }
  else
  {
    digitalWrite(LED, LOW); //also used digitalWrite(LED, 0)
  }
}

Upload Verbose Message:
avrdude: verifying ...
avrdude: 1070 bytes of flash verified
avrdude: Send: Q [51]   [20]
avrdude: Recv: . [14]
avrdude: Recv: . [10]

avrdude done.  Thank you.

I have only had the LED from this program turn on twice, then reloading it ruins it.
SIDE NOTE
If I try and run Burn BootLoader I get this message-
avrdude: Version 5.11, compiled on Sep  2 2011 at 19:38:36
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2009 Joerg Wunsch

         System wide configuration file is "C:\Program Files (x86)\Arduino/hardware/tools/avr/etc/avrdude.conf"

         Using Port                    : usb
         Using Programmer              : stk500v2
avrdude: usbdev_open(): did not find any USB device "usb"

You had a USB-problem too: 'avrdude: usbdev_open(): did not find any USB device "usb"'. Always verify if your device actually got the port assigned you expect it to have assigned. Not sure if you can assign a device a static COM-port on Windows, I know it is possible on Linux.

Yeah I had ended up forcing it to be COM251 to be consistent. Thanks.

OK mystery solved!
I ended up getting Visual Micro Debugger plug-in for my Visual Studio 2013 since I am native .NET programmer. I could see that the code was indeed loaded onto the board and when I pressed the button it was indeed getting to the line of code for setting the digital LED to HIGH.
It was a very unfortunate case of trying different components and learning I actually had 3 dead LEDs and one bad cable. After getting functioning ones it's all good. :) unlucky me just had 4 bad parts in my kit.
Output from Visual Studio Debugging:
Legend:
line 12 = button state check
line 16 = button pressed turn on LED
line 20 = button not pressed turn off LED

=================OUTPUT====================
14:01:04.372 SeeedDuinoPlayground.ino, line 12  loop()
14:01:04.372 SeeedDuinoPlayground.ino, line 16  loop()
14:01:04.481 SeeedDuinoPlayground.ino, line 10
14:01:04.481 SeeedDuinoPlayground.ino, line 12  loop()
14:01:04.592 SeeedDuinoPlayground.ino, line 16  loop()
14:01:04.592 SeeedDuinoPlayground.ino, line 10
14:01:04.696 SeeedDuinoPlayground.ino, line 12  loop()
14:01:04.697 SeeedDuinoPlayground.ino, line 20  loop()
14:01:04.804 SeeedDuinoPlayground.ino, line 10
14:01:04.804 SeeedDuinoPlayground.ino, line 12  loop()
14:01:04.912 SeeedDuinoPlayground.ino, line 20  loop()


text:
Check contents of buffer after serial read
I would like to test the contents of data received over a serial connection. In my loop() I store the data in bffr; and afterwards I would like to test to see if there are some predefined words in it.
#define BFFSZ 90
char bffr[BFFSZ];
char bffridx;

void loop()
{
   readline();

   //- Test the bffr
       if(strstr(bffr, "CLOSED")){ //- WORKS
          Serial.println("> conn. closed");
          digitalWrite(A1, HIGH);
       }else if(strstr(bffr, "RING")){ //- WORKS
          Serial.println("> Someone is ringing");
          digitalWrite(A2, HIGH);
       }else if(strstr(bffr, "0,7,j,BLINK")){ //- Doesn't work
          Serial.println("> Blink");
          digitalWrite(A2, HIGH);
          delay(300);
          digitalWrite(A2, LOW);
       }
}

void readline()
{
   memset(bffr,0,sizeof(bffr));
   char c;
   int i =0;
   bffridx = 0; // start at beginning

   long previousMillis = millis();
   while (1) {
     unsigned long currentMillis = millis();
     if(currentMillis - previousMillis > 20000) {
       Serial.println("TIMEOUT");
       return;
     }
     delay(2);

     c=gsm.SimpleRead2();
     //- debug only, to see if there is something received.
     Serial.write(c);

     if (c == -1)
       continue;
     if (c == '\n')
       continue;
     if ((bffridx == BFFSZ-1) || (c == '\r')) {
       bffr[bffridx] = 0;
       return;
     }

     bffr[bffridx++]= c;
     delay(2);
   }
}

The debug-line makes that I can see the data flowing, eg when I phone the SIM.
But it looks like the buffer isn't tested properly. The first two will work, but the last test fails. It is part of a larger string: $0,7,j,BLINK,567^ But I thought the strstr(1,2) searches for 2 in 1. And as 0,7,j,BLINK, is within the haystack I assume it wil return true. But apparently not...
The gsm.SimpleRead2() comes from GSMlib and is my altered version of gsm.SimpleRead(). Instead of printing the char, I just return it so we can buffer it in the readline function.
void SIMCOM900::SimpleRead()
{

 char datain;
 if(_cell.available()>0){
   datain=_cell.read();
   if(datain>0){
     Serial.print(datain);
   }
 }
}
char SIMCOM900::SimpleRead2()
{

 char datain;
 if(_cell.available()>0){
   datain=_cell.read();
   if(datain>0){
     return datain;
   }
 }
}

Does anyone know the answer to this?

Did you check that gsm.SimpleRead2() never returns non-printable characters (ASCII 0x00-0x1F)? That could explain why you don't see anything in the debug with Serial and the searched string can then not be found.

By the way, where does this GSM library SimpleRead2 come from? Could you provide a link?

@jfpoilpret I've added the simpleread functions and a link to the library.

So there might be some strange characters in the bffr which causes the test to fail. How can I strip a string with non-printable characters?

If there are strange characters in the GSM output, then it is quite easy to check and skip: you can use isPrintable(c) to check it and add c to bffr only in that case. This is part of standard C library, there are many other isXxxx(c) functions defined in WCharacter.h.

After a serial.read();, the data [as far as I can tell] is pretty much destroyed. You have two main options to accomplish this:

Store the data in a string when read and then reference this later. I'd do this with a global variable, that is declared outside of a method and accessible throughout your whole sketch.
I haven't read throughout your whole code, but, if you only need to read one character, you can use serial.peek();. This only works if you need the first character of the buffer.

Most likely, your only option would be the first bullet. I'd implement this by adding a method something like this:
String buffer_string_serial;

void setup() { //code here }

void loop() { //code here }

int serial_read_buffer() {
  while(serial.avaliable() > 0) {
    buffer_string_serial = buffer_string_serial + serial.peek();
    return serial.read();
  }
}

Then, just use serial_read_buffer();. That will act similar to serial.read();. The only difference is it will fill up the buffer_string_serial string. You'll have to clear that out after you used all the data so it doesn't get full.

That's what I've done with the readline() It stores everything in a global bffr. And afterwards I try to test it; but the testing doesn't work.

@stUrb Test it with expressions? I'd recommend verifying the string is exactly what you want and revisiting your testing code. Maybe print the string before testing to the serial window?

Checking for an exact match is not easy. The protocol consists of an unique integer at the end, describing a job id: $0,7,j,JOB,ID^ so everything except the ID is know and can be tested. Does Arduino/C has some kind of regular expression test/match?

@stUrb I can't find built in support in the Arduino core libraries for regex, but this library here for Arduino (with pretty good documentation) might help you.


text:
Matching Baud Rates
So I am working on speeding up a nixie tube speedometer, in this question: , but this brought up another question.  Would having matching baud rates for multiple external devices speed up processes.
In the case of the other question the OBD-II device is running at 38400 where the Nixie Tubes are running at 9600.  Since I'm taking the info from the OBD-II connector and doing a little math and sending it to the Nixie Tubes, would it be beneficial to have the same baud rate for both devices?
Now... before you down-vote this question for making some sort of "duplicate" this also answers a question about having a "master" serial hub and having communication between different "slave" serial devices.

It all depends on how often speed is being reported via the OBD-II connection. If the report rate is faster than the update rate of the tubes then yes, increasing the speed of the tube circuit (not necessarily the connection itself) can have an effect (as long as the tubes themselves can keep up, of course). If the speed is being reported slower than the tubes then don't bother unless you have other reasons for increasing it, since both bit rates are already so much faster than the human mind can see, much less process.

If you are using different serial ports for each device (eg: using software serial for at least one of them on a Uno, or using separate hardware serial on a Mega2560), then it really doesn't matter whether they use the same baud rate or not.
If you are somehow multiplexing the same serial port (eg: input only from one device, output only to the other; or some external multiplexing hardware) then there might be a slight gain in not needing to change the baud rate when switching between devices, but probably not noticable.
If either or both devices have some option to communicate faster, that might speed up your system - independent of whether they use the SAME rate.


text:
Detect and stream if a chair is occupied
I am planning to build a device able to detect and tell a server via Wi-Fi if a chair is occupied. How would you do it? And how cheap do you think the device could be?

For those who voted to close this question as too broad: I think it's pretty specific. With a few reasonable assumptions about the chair being rigged with the device, I would hazard a guess that one would need an Arduino board, an Wi-Fi shield and a suitable pressure sensor. Can anyone more knowledgeable than me layout a more detailed answer along those lines?

Do you have an Arduino board yet? Are you planning on using a specific one?

I'm just thinking at how this could be done ;-) My idea is to build something like a internet-based service to map where there are free spots in cafes

Oh wow !! brilliant idea..was just thinking about the same. This way we can implement those chairs with sensors in offices and can sense the average hour of an employee sitting on a chain and compare it with the effort time he have given to some project.

@gre-gor was changing the capitalization pattern of a single term nearly 4 years after the fact really worth bumping the question to the top of the page?

Oh wow, so many ways you could do this.  To start, get an arduino with a wifi shield to transmit and read data.  Familiarize yourself with how the arduino works with the shield, and how to read it on the other end.  Then it's time to look at sensors you could use.  Here's a couple ideas, I would recommend using more than one and cross-checking:

Force sensor on base of chair: Can tell you how much weight is on a chair (Sparkfun SEN-09376)
IR or sonic sensor on back of chair to detect distance (example)
Vibration/shock sensor to detect if someone has sit down (example)
Load sensor: literally a scale in a sensor. (Sparkfun SEN-10245)

The optimal solution if you had the cash would be to put all of them on the chair and use the arduino to compute all of the sensor values into one boolean.  However, if you only could have one sensor I would recommend the load sensor which would definitely be the most reliable of all the examples I gave.

What's the difference between 1 and 4? Also, I don't know how well the vibration sensor would work, as if someone were to reposition themselves or if they were laughing really hard.

Yeah, the vibration sensor would only be useful as an additional check combined with at least one other sensor.  As for the force sensor vs the load sensor, the load sensor works more mechanically and can measure a greater weight.

For a soft seat you could sense occupancy with an LED and photo-sensor at opposite ends of a short somewhat flexible tube that gets flexed when the cushion compresses, interrupting the light. That or a microswitch would have to be the cheapest means of sensing.
Getting from there to the server depends a little on how much work you're willing to do, from rolling your own micro-controller+WiFi PCB to purchasing off the shelf parts, which may in turn, depend on whether you need to monitor one chair or a whole auditorium.

I'm not going to answer this directly, because then you wouldn't learn anything! However, here are a few suggestions:

Use a pressure sensor on the seat of the chair or
Put a distance sensor (IR or ultrasonic) pointing at the chair.
Use the official Arduino WiFi shield.

That's what I meant in my comment to the OP: if there's not enough information on the original post, just point the poster to the right direction. No need to close a perfectly decent question. Good answer! +1

@Ricardo Yeah, I guess I'm too used to Stack Overflow. If a question like this were asked on Stack Overflow, it would be closed within ten minutes.

Right! It would have been closed quickly on EE.SE, too. With good reasons, I guess. But we are not them, right? We can make our site the way we like it. Arduino questions are always welcome here. That's my motto!

Actually, the OP didn't even mention Arduino anywhere in his or her question. But that's implied :D

You could use the awesome CapSense-Library. Additionally to the Library you only need a thin piece of conducting material e.g. aluminium foil and two pins on your arduino. The only thing you have to do is experiment with different resistors to reliably distinguish between someone sitting on the chair or not. Advantages of this method are:

virtually no costs at all
easy to implement
not subject to wear and    tear
should work with any kind of chair independent of material e.g.
hard or soft surface
consumes next to no power (I assume the whole device runs on battery since it's attached to a movable chair)
could even sense a person in the process of seating her-/himself and enable you to start the music faster (my stereo for example takes a second or so to start up)

You could use Electric Field Sensing, it allows you to detect the presence and position of conductive objects even if the sensor is covered by an opaque object. The technology is used in cars to detect if someone is sitting in a seat so the car can beep at you to put your seat-belt on. However, if all you want to do is detect presence then this is no better than using CapSense.
http://web.media.mit.edu/~jrs/efs.html
https://en.wikipedia.org/wiki/Electric_field_proximity_sensing
To communicate with a server over WiFi you could use the Arduino WiFi shield, the Arduino Yun (which has on-board WiFi) or buy a ethernet WiFi adapter and use it with an Arduino board which has ethernet.
http://arduino.cc/en/Main/ArduinoWiFiShield
http://arduino.cc/en/Main/ArduinoBoardYun
(Arduino board with on-board WiFi)
http://arduino.cc/en/Main/ArduinoBoardEthernet

conductive foam as sensor. it chg resistance when compressed.
or use image from camera to determine if seat is occupied. only one source for all data.


text:
How to test the sleep / enable function of Stepper Driver?
I am currently using an Arduino Mega 2560 to run this stepper motor driver (Big Easy Driver, ROB-11876 from sparkfun) https://www.sparkfun.com/products/11876.
I am trying to use the sleep or enable function on this chip to decrease the power consumption when I am not using the motor. I have all the rest of the driver working properly (steps, direction etc.) but when I hook up a wire to either the sleep or enable section and send a respective high or low it doesn't appear to do anything. (Chip works as normal, power consumption stays the same).
I have tested to see that the Arduino is outputting correctly and it seems to be. But other than this I'm kinda at a loss on what might be wrong.
Does anyone have any suggestions on why this might be or other things to test to try to narrow down the problem?

Found my answer from Sparkfun - see below

glad you were able to figure it out. When you are able to, please post it as an answer.

Since you should be able to add an answer now, can you add it as an answer?

Just for future reference if anyone needs it I got the following from SparkFun:
On the Big Easy Driver Board, the Step, Dir, Sleep, Reset, and the Microstep pins are all >pulled high with 20kΩ resistors, while Enable is pulled low with the same. So sleep is >disabled (until explicitly enabled) and the stepper is enabled (until explicitly disabled).
For much of the use of this board, there is no real need to adjust these settings, but If you >want to achieve a low-power state you would pull the sleep pin low. This should disable much >of the internal circuitry on the IC. In order to reduce power, Enable should be pulled high >to disable the output FETs.
To test that the sleep function is working on the chip you can just jump it to low (ground). For me it turned out to be an error with the Arduino code rather than the chip. Here is also a good reference about pull-down / pull-up resistors. http://www.bit-101.com/blog/?p=3813


text:
How to use components that don't have a shield?
I recently started messing around with an Arduino and I have made a few "gadgets" using shields. I then wondered how I would go about using things I can't find shields for.
One specific thing I want to do is to be able to use the larger e-paper displays from Pervasive Displays (7'' and 10'') but a brief consultation with Google found no Arduino kits or shields. I then looked through the documentation of the timing controller for the 7'' display and found the information required to be able to use it (initiation, sending data to be drawn, opcodes, etc.). I then decided to check the Github repo for the examples for the 2'' displays and they seem to just do what the documentation says to do.
Is my observation naive here? Is it really as straightforward as following the documentation? No magic sauce?
Note: I don't have a clue how complex using the 7'' display actually is, I just used it as an example because I had just looked it up...

You discovered the secret of Arduino and its shields. Don't tell anyone black magic does not exist in Arduino-universe.

Your observation is correct. Everything breaks down to some number of physical connections and some protocol for communicating with the device. Shields and libraries associated with them do most of the work for you, but not everything comes in a shield.
There are some common protocols for interfacing with devices, including SPI and I2C. From a quick peek at the driver interface sheet, it looks like they're using SPI. Well, your Arduino already supports that so you can hit the ground running with this display. You just need to know what commands to send to it, which you can find from the display's datasheet.
Note: It looks like the 2" screen requires 3.3V while the 7" one supports up to 7V.


text:
Manchester Library Won't Compile for Attiny85
I am creating a wireless sensor using an Attiny85.  I want to send the data to an arduino uno, so I purchased the 315mhz rf link kit from spark fun.  Since the Attiny85 does not have a TX I decided to use the Manchester library however it won't compile on the Attiny85.
I followed the steps from this blog :
http://mchr3k-arduino.blogspot.mx/2012/01/wireless-sensor-node-part-2.html?showComment=1338749638806#c853067277980266192
Here is the code I am using:
    #include <WProgram.h> //otherwise it says it can't find Arduino.h
    #include <Manchester.h> //include the library to comunicate
    #define TxPin 2 //the pin that is used to send data

 int sensorPin = 4;
 int ledPin = 3;
 int count = 50;

 void setup(){
  pinMode (ledPin, OUTPUT);
  man.workAround1MhzTinyCore(); //add this in order for transmitter to work with 1Mhz Attiny85/84
  man.setupTransmit(TxPin, MAN_1200); //set transimt pin
}

void loop(){
  if (count == 50){
   digitalWrite (ledPin, HIGH);
   count = 0;
   }
   int data = analogRead(sensorPin);
   man.transmit(data); //transmits and reads the data
   delay (100);
   count ++;
 }

Here is the error message:
/Users/joelsimonoff/Documents/Arduino/libraries/MANCHESTER/Manchester.cpp: In function 'void MANRX_SetupReceive(uint8_t)':
/Users/joelsimonoff/Documents/Arduino/libraries/MANCHESTER/Manchester.cpp:366: error: 'TCCR2A' was not declared in this scope
/Users/joelsimonoff/Documents/Arduino/libraries/MANCHESTER/Manchester.cpp:366: error: 'WGM21' was not declared in this scope
/Users/joelsimonoff/Documents/Arduino/libraries/MANCHESTER/Manchester.cpp:368: error: 'TCCR2B' was not declared in this scope
/Users/joelsimonoff/Documents/Arduino/libraries/MANCHESTER/Manchester.cpp:368: error: 'CS21' was not declared in this scope
/Users/joelsimonoff/Documents/Arduino/libraries/MANCHESTER/Manchester.cpp:369: error: 'OCR2A' was not declared in this scope
/Users/joelsimonoff/Documents/Arduino/libraries/MANCHESTER/Manchester.cpp:379: error: 'TIMSK2' was not declared in this scope
/Users/joelsimonoff/Documents/Arduino/libraries/MANCHESTER/Manchester.cpp:379: error: 'OCIE2A' was not declared in this scope
/Users/joelsimonoff/Documents/Arduino/libraries/MANCHESTER/Manchester.cpp:380: error: 'TCNT2' was not declared in this scope

Which package are you using for ATtinyX5 Arduino support?

I tried the one from the blog I referenced but after google searching I found that the MIT High Low Tech Group had one so I tried that one as well.  The one from MIT High Low Tech is from this page http://highlowtech.org/?p=1695

I performed all of Joel's and Ignacio's suggestions concerning using the arduino-tiny library instead of the attiny master from the MIT high low tech group page. I've finally got the ATTINY85 boards to show up in my board menu, but I'm still getting the error "man not declared in scope" with the above code. Any suggestions?

Did you import the manchester library into the Arduino IDE? or Place it in the libraries folder?

attiny is missing an option required to allow the Manchester library to function properly on ATtinyX5 devices, specifically definition of __AVR_ATtinyX5__ when a device is selected. In fact, it's missing quite a few things.
The package I use for ATtinyX5 support is arduino-tiny. I have verified that it defines that symbol properly. I recommend that you dump your current support package and install arduino-tiny instead.

I downloaded the arduino-tiny-0150-0020.zip.  Unzipped the file then dragged the folder named tiny into the hardware folder I created inside the arduino folder.  However when I went to the ide I searched under boards and the Attiny series of boards did not show up.

What is the correct way to add the package to the ice?

Which version of the IDE are you running?

Arduino1.0.5 on mac osx 10.9.2

Then you'll need to download the support package for 1.0.x instead of the one for 1.5.x.

I just downloaded the package  arduino-tiny-0100-0018.zip  and inserted the folder tiny into my hardware folder and the boards are still not loading.

this is the file path /Users/joelsimonoff/Documents/Arduino/hardware/tiny

I renamed the file from tiny to attiny and the file prospective boards to boards and the boards now show up in the ide

the file just compiled successfully I am gonna try to hook it up to the chip

Having struggled through this myself, I can confirm that Joel's solution works.
There are quite a lot of posts around that suggests that you can't get the Manchester to work with Arduino1.0x and you need 0020. But you can.
The key is to use the arduino-tiny from the link above, put the tiny folder which you get from there in /hardware and then rename it to attiny and “prospective boards” to boards.
I realise that this doesn’t say any more than Joel already has, but there is so much conflicting and contradictory information around I thought it would be worth adding in my experience

Got the same problem using this lib with a 8 MHz Trinket, but managed to solve it by adding #define __AVR_ATtinyX5__ to the file hardware/attiny/variants/tiny8/pins_arduino.h. I'm using the Adafruit support package for ATtiny. Perhaps a bit of a hack, but I can still build for the UNO, by selecting board in Arduino IDE 1.0.5.


text:
Arduino Mega & WiFi Shield; why web server every time says my A7 pin reads 0V?
I have got Arduino Mega 2560, Arduino WiFi Shield and resistor 1.5K.
Now PWM 2 is attached to the resistor then attached GND. 5V is attached between PWM2 and resistor's up point. I want to read the Arduino Mega's A7 analog input point in order to print this value on an Android Phone's web browser but, I get zero value every time surprisingly. It should be like 235, 350 something like integer or float kinds as usual.
According to Android Phone's Google Chrome Web Browser Page, why there are too many zeros in the HTML? It should be different from zeros because I have already added a short wire to Analog A7 so as to make an antenna.
A photo of my setup:

Screenshot of my Android web browser

Serial Monitor output

My code:
#include <SPI.h>
#include <WiFi.h>

char ssid[] = "Connectify-me";
char pass[] = "***";
int status = WL_IDLE_STATUS;
float PPG = analogRead(A7);
boolean door_status = false;
WiFiServer server(80);
void setup() {
  Serial.begin(9600);
  while ( status != WL_CONNECTED) {
    Serial.print("Yazdigin SSID araniyor: ");
    Serial.println(ssid);
    status = WiFi.begin(ssid, pass);
    delay(10000);
  }
  server.begin();
  printWifiStatus();
}
void loop() {
  WiFiClient client = server.available();
  if (client) {
    Serial.println("Deger gonderildi");
    Serial.print(PPG);
    while (client.connected() & client.available()) {
          client.println("");
          client.println("");
          client.println("
");
          client.print(PPG);  //The value should different from zeros but everytime 0
          client.println("
");
          client.println("
");
          client.println("");
          client.println("");
      }
    }
    delay(3000);
      client.stop();
      Serial.println("client disonnected");
  }
  void printWifiStatus() {
  Serial.print("Baglandigimiz SSID: ");
  Serial.println(WiFi.SSID());
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Addressi browserda ac: ");
  Serial.println(ip);
  long rssi = WiFi.RSSI();
}

Step 1 in troubleshooting is to create a minimal example. The Serial.print(PPG); shows 0, so all the web server stuff is irrelevant. You need to narrow your scope to isolate the problem.

Use images that add information to you question. A screendump of the code and a screendump from 0-values doesn't add to the information, it even distracts. A proper circuit diagram would normally be welcome, but after analyzing your writing and the picture I concluded that all this question  is about, is a dangling wire. Don't put up a smoke screen, as sachleen mentioned, it is very important to narrow down to what you actually want to know and that is not limited to minimal code to reproduce the issue. It took me several minutes (and considering to leave the question unanswered) to understand

The capacitor in the sample-and-hold circuit in the ADC frontend is tied to ground and it is very leaky. Unless you have a low or medium impedance output connected to it, you will always read the ground value. An antenna is a very high impedance device.

You are reading the input pin float PPG = analogRead(A7); only in the startup code of your program. Move that into the loop to have it updated before using it.

Yes, I have already did this. Still, not a remedy for me.


text:
Connect Arduino with fischertechnik TX Controller
Is it possible to cinnect the Arduino with a fischertechnik TX Controller? Maybe with I²C, but i want to use I²C for something else on the arduino. So are there multiple I²C Ports on the Arduino (I haven't got one yet)?

As described in the Wire library that brings supports I²C support to Arduino, except for the DUE that has 2 pairs of pins for 2 I²C buses, other Arduino boards support one I²C connection.
However, this is when you want to use hardware facilities of ATMEL chips that these limitations apply; there is a software I²C library exists that allows using other pins for I²C. One major drawback, though, is that it is very slow; not sure if this is a problem in your situation.
One important thing though: the principle of I²C is to be able to plug several slave devices (more than 100) to one master device. In general, Arduino is the master device, but the Wire library can be used as master or slave. Wouldn't that fit your requirements?
In this situation, you could just use the same I²C bus for everything, including connection to Fischertechnik TX controller.


text:
Understanding the compilation/linking/upload process (so I don't have to use the IDE)
I have started to play with and arduino UNO quite recently (without any prior experience with micro-controllers). I would like to use emacs instead of the IDE, and I'd also like to know what the IDE does under the hood, in order to be able to write my own makefile. The tutorials I've found are either outdated, or are presented as a series of steps without any explanation. I'd appreciate it if someone could explain to me how the whole compliation/linking/upload process works using gcc-avr and avr-dude, and how it is used by the IDE.

You can take a look under the hood by "Show verbose output during: ☑ compilation ☑ upload" Under File → Preferences.

Almost duplicate: Compiling code via terminal. See the links to arduino-builder and Sudar Muthu' Makefile in my answer to that question.

You can use Emacs in combination with PlatformIO. See also my answer to a related question. I'm using --ide vim when initialization the project in my example, but that command also support emacs.

If you want an exact duplication of what the IDE does but want it driven from the command line, that's what Ino is for. The full Arduino build process involves copying a lot of files from a lot of places, and is generally not trivial to duplicate.
If you're ready to let go of .ino files and the Arduino libraries, you get a much simpler toolset. avr-gcc compiles, avrdude uploads, and you're done. Here's one of my makefiles from a simple project:
CC=avr-gcc
CXX=avr-c++
CXXFLAGS=-Wall -Wextra -mmcu=atmega1284p -Os
CFLAGS=$(CXXFLAGS)
BINARY=ledmatrix
OBJECTS=

all: $(BINARY)
↹@avr-size $<

$(BINARY): $(OBJECTS)

clean:
↹@rm -f $(BINARY) $(BINARY).hex $(OBJECTS)

upload: $(BINARY).hex
↹@avrdude -c usbasp -p m1284p -U flash:w:$<:i

%.hex: %
↹@avr-objcopy -j .text -j .data -O ihex $< $@

.PHONY: all clean upload

If copying-and-pasting, be sure to replace all "↹" with tab characters.
EDIT:
I have created a repository with my buildsystem on Github.

Thanks, your makefile is pretty much what i was trying to come up with. But i guess getting rid of the libraries means that i wont be able to use functions such as digitalWrite()? In that case, where should i look to learn their plain C equivalents?

The Arduino libraries would contain their equivalents, but they can be a bit erudite to read. I recommend finding a low-level AVR tutorial to work through that will explain to you the various registers and peripherals. Oh, and the datasheet. Always get the datasheet.

Here is a high-level overview of Arduino's compilation process, for folks like me who found this post while hunting for one:
The compilation process
The arduino code is actually just plain old c without all the header part (the includes and all). when you press the 'compile' button, the IDE saves the current file as arduino.c in the 'lib/build' directory then it calls a makefile contained in the 'lib' directory.
This makefile copies arduino.c as prog.c into 'lib/tmp' adding 'wiringlite.inc' as the beginning of it. this operation makes the arduino/wiring code into a proper c file (called prog.c).
After this, it copies all the files in the 'core' directory into 'lib/tmp'. these files are the implementation of the various arduino/wiring commands adding to these files adds commands to the language
The core files are supported by pascal stang's procyon avr-lib that is contained in the 'lib/avrlib' directory
At this point the code contained in lib/tmp is ready to be compiled with the c compiler contained in 'tools'. If the make operation is succesfull then you'll have prog.hex ready to be downloaded into the processor.
https://www.arduino.cc/en/Main/Documentation

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


text:
How can I connect the Tamiya double gearbox to Arduino Uno?
I'm working on building my first robot. this is my first foray into DIY electronics. I already have an Arduino Uno, and I have ordered the Tamiya double gearbox here. My goal is to control the gearbox to move the robot, but from what I've already read, I need to have something between the Ardiuno and the motors. It seems like people have trouble doing that because the included motors are low voltage, so the Arduino motor shield won't easily work.
I'm looking for a clear solution to making this thing run, in the simplest way possible. One thing I'm considering is replacing the motors in the gearbox with these motors. If I do that, am I right in thinking I could run them from the Arduino motor shield?
If there is a simpler (or cheaper!) way of making it work than being stuck on the Arduino Motor shield, I'm game for that. I've just gravitated to that solution because it seems simpler as an electronics noob. (I haven't bought that shield yet.) But I'm really open to other solutions, so if you can, I'd appreciate the advice!

Here's what I've found about both the motor shield and the motors:

Motors are 3-6V and will use a lot of amperage. This may be a problem with a mobile robot. You'll have to figure out a power source that can provide 4+ amps... on battery power that's a lot. Personally, I would go with a continuous rotation servo for a compact, light robot.
Motor sheild can provide 2x 2A channels at 5-12 V (Source) using the two + and - terminals on the bottom left side of the shield. You must connect external power, because USB can't provide enough power. I can't find if the motor shield will limit current if it goes over, but if you do use the gearbox, I'd recommend another route for control that's 1/6rd the price.

This chip was recommended by Pololu on the product page.

Time to whip out your soldering iron! Really, soldering is a great investment and you'll get to a point soon where you'll need one; there will be no other alternative. Luck for you, you only have to solder 16 joints. Headers are included.
Diagrams from Pololu's site:

  *(Click to enlarge ^^^)**

*I added a little text to this image.

Thanks! For clarification, if I use the controller you mention above, then I can just use the included motors, correct?

Glad I could help! Yes, @Steven, you can use the included motors. Also, the controller is linked from the motor product page FYI.

Great. One last question—if I'm following the controller's datasheet correctly, in code on the arduino I simply set the pin connected to Ain1 to HIGH to go forward. Do you think that's correct? One of my reasons for trying to stay within official Arduino stuff earlier was that I'm a bit intimidated by going off-reservation code-wise! You've emboldened me, though!

@Steve Glad I could help. Umm for the datasheet, it says on page eight, table two, that one pin does forward, the other one backward, and both is to brake. If no power is applied to either pin, it'll be free to rotate randomly.

The FA130 type electric motors in the Tamiya Double Gearbox Kit (No. 70168) are 1.5v-3v DC motors with current ratings of 0.20A (no load), 0.66A (@ max. efficiency) and 2.2A (stall), see 1.5-3V DC Motor 6990 RPM. They are not high current motors.

Hi Andre, and welcome to Arduino:SE.  'High current' is very much a relative term.  That stall current of 2.2A may be too much for a 2A line on a motor shield.


text:
Level detection of 3.3V from 5V arduino
A quick question about microcontroller digital level on I/O pins. I have a photo interrupter which is powered at 3.3V which is interfaced to Arduino UNO running at 5V.
For microcontroller to detect high or low level is determined by signal higher than 5V*(2/3) = 3.33V is high and signal lower than 5V*(1/3) is low. What I don't understand is that arduino is able to detect the level change from the photo interrupter. Doesn't the supply on pins have to be greater than (2/3) or Vcc in order for it to detect logic high? The circuit works and I am able to count pulses from the interrupter but I want to know why that works considering the photo interrupt only gets about 3.23V.
Please clarify

You've... misread the datasheet. The '328 input high voltage (VIH) for most pins is 0.6VCC minimum for devices with a 2.4-5.5V supply. This means that a 5V device has a 3V threshold.

You know the voltage at which the interrupter is connected is not a steady 3.3V. I was keeping track on the voltage and I saw it fluctuated to lowest value of 3.1V. Why doesnt it matter when the Threshold is 3V. The difference is only 0.1V. How come is still works?

The actual numerical difference is irrelevant. As long as the threshold is met, that's what counts.

The designed threshold of the '328 logic is 45% of Vcc for all supply voltages, except the tolerance reduces from +/-25% of Vcc {<3V} to +/-15% of Vcc{>3}  This tolerance is due to temperature and process variation.
Keep in mind that the smaller the difference between the "actual" threshold and your input is your immunity to noise and it will work if there is low noise. Thus 45+15% = 60%* 5V=3V is guaranteed.  What is not guaranteed, is the accuracy of your 5V regulator which if say 10% high will increase the threshold 10% above  3V or 3.3V.   So then 3.1 would not be guaranteed. So ensure accuracy of 5 V is below 5.04 minus your noise immunity requirements.


text:
Servo won't stop rotating
I have an Arduino Uno R3 board and after some time not in use it seems to have corrupted. My code is below, basically I want to rotate a servo 90 degrees every 12 hours but as soon as I plug it in the servo starts rotating non-stop. Have tried multiple delay steps and shortening and lengthening the write but the same effect happens.
#include <Servo.h>

Servo myservo;

void setup {
  myservo.attach(10);
}

void loop() {
  myservo.write(90);
  delay(3600000);
}

I guess that is a continuous servo. In this situation, with your code what you observe is expected: the servo runs forever at constant speed. If it was a normal servo your code would not work either, as you never change the 90 degrees value, hence the servo would stay forever in that position.

Note that your Arduino UNO is probably in perfect shape, anyway.

Not related to the servo issue, but I think your delay is 10hrs.

I suppose you are using a continuous servo otherwise you wouldn't be able to make it turn 90° more than twice (a normal servo has a varying angle of only 180°).
Now if you are using a continuous servo, you have to be aware that the value you pass to myservo.write() does not represent an angle anymore!
With a continuous servo, the value passed to myservo.write() now means a speed of rotation where, but the range of acceptable values is the same as for a normal servo, i.e. [0; 180]:

0 means max speed clockwise
90 means no motion
180 means max speed counter-clockwise

Now if you want to turn the servo exactly 90°, then you must know the max speed of the servo, and from that, compute the time during which you must let it turn:
// Start turning clockwise
myservo.write(0);
// Go on turning for the right duration
delay(TURN_TIME);
// Stop turning
myservo.write(90);

The problem here is to compute TURN_TIME. For this, you must check the datasheet of your servo.
On my own servo, a Feetech Micro 1.3kg Continuous Rotation Servo FS90R, the max speed is:

0.12s/60° when powered with 4.8V
0.10s/60° when powered with 6V

However, with the Arduino UNO, the supplied voltage should be exactly 5V, neither 4.8V, nor 6V.
If we take a linear approximation, then we can apply the following formula to find out the speed T (in s/60°):
T = (0.12 - 0.10) * (V - 4.8) / (4.8 - 6.0) + 0.12

Hence, for 5V, we can take it for granted that the max speed should be:
T = (0.12 - 0.10) * (5.0 - 4.8) / (4.8 - 6.0) + 0.12 = 0.116667

Since we need 90°, this means we must run the servo at its max speed during:
T' = T * 1.5 = 0.175s

Hence we now have the following program:
#include <Servo.h>

#define TURN_TIME 175

Servo myservo;

void setup {
    myservo.attach(10);
    // Initially the servo must be stopped
    myservo.write(90);
}

void loop() {
    // Start turning clockwise
    myservo.write(0);
    // Go on turning for the right duration
    delay(TURN_TIME);
    // Stop turning
    myservo.write(90);

    // Wait for 12h
    delay(12 * 3600 * 1000);
}

Of course, you will need some experiments to find the exact right values; you may also find out that the servo may be sensitive to noise and even when it should not move (value = 90), it does move (not fast, but still it moves).

Also note: The arduino crystal is not a reliable time source. It can be expected to lose or gain up to a minute per day, not including the offset of the actual time taken to execute the program. If you want accurate time, buy a real Time Clock (RTC) module, and set an alarm on it, which can then trigger a function on the Arduino every 12 hours.

don't know why, but mine FS90R continuous servo is stopped with servo.write(95);

That was useful.
I was getting the same rotation thing when I had servos at 90. What I did to stop that was use the detach command. Using the Particle Photon with a continuous servo attached.
bool state = LOW;

Servo servo1;
Servo servo2;// create servo object to control a servo
                // a maximum of eight servo objects can be created

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

void setup()
{
  servo1.attach(D0);
  servo2.attach(D1);
  Spark.function("test", testFunction);
  servo1.attach(10);
  servo1.write(90);
  servo2.attach(10);
  servo2.write(90);
}

void loop()
{
    servo2.detach(), servo1.detach();
    delay (25);
    servo2.attach(D0), servo1.attach(D1);
    delay (25);
    servo1.write(0), servo2.write(180);
    delay (1000);
    servo2.write(180), servo1.write(0);
    delay (1000);
    //I did this to make the servo not move when it is at 90.
    servo2.detach(), servo1.detach();
    delay (25);
    servo1.write(90), servo2.write(90);
    delay (1000);
    //end
    //You must attach the servos again to make them move again.
    servo2.attach(D0), servo1.attach(D1);
    delay (25);
    //end
    servo1.write(180), servo2.write(0);
    delay (1000);
    servo2.write(180), servo1.write(100);
    delay (1000);

}

int testFunction(String args) {

    return 200; // This is checked in the web app controller for validation
}


text:
RFID/NFC (13.56 MHz), is it possible to send raw bytes and receive response?
I'm trying to implement a card reader (i.e. credit cards) for shopping purposes, and AFAIK those cards are ISO 14443-A compliant (Mifare Classic 1K). I already made an Android app that can send custom APDU to read specific sectors by using raw SendBytes().
Since I need to build a circuit with a custom antenna, I chose Arduino-uno with a NFC module (was thinking about StrongLink SL013), I wanted to know if it's possible to send raw bytes and receive the response from the tag. I only found some higher-level implementation (readSector, writeSector and so on).

Have you gone through the technical specifications? Have you read the ISO-14443-A definitions? This should be directly answerable from the specifications.

I found it's not part of the ISO specifications, it depends on the specific chipset/shield i'm using. NXP PN532 supports it.

RFID protocols require either passive or active tags.  Depending on which you use, either the tag or reader regularly transmits pulses.  Check www.rfidreader.com for more info.  https://www.rfidjournal.com provides valuable resources as well.
Many companies invest heavily in developing RFID technology.  You would be well advised not to reinvent wheels without reeeeally deeeeeep pockets.

This would differ per device/reader.
Currently, I'm in a project with a TRF7970a RFID reader. I've seen it it's datasheet that it does have options to send RAW values as it does not support every protocol (NXP has patent on one?) thus the chip doesn,t parse it, but can send it to the mcu completely.
In short, yes this is possible.
But using a reader that is compliant with your protocol might supress your development cost/time


text:
XBee, external libraries and passing structures as arguments
I have very weird problem with a library I am creating. The library will be used to communicate between Arduino modules using XBee Series 1 modules. Library is very simple wrapper library around Arduino XBee library.
I have one function that reads received packet and sends it back. At the moment it is implemented as a simple "echo" service - the function just displays the data received and sends it back to per-defined address.
At the moment I have three versions of this function, out of which one is not working.

A function taking no arguments: void processPacket()
A function taking structure as a value as an argument: void processPacket(valuesStruct valuesStructData) - THIS VERSION OF THE FUNCTION IS NOT WORKING!
A function taking pointer to the structure as an argument: void processPacket(valuesStruct* valuesStructData)

At this moment I noticed strange behavior in the 2nd version of the function. I do nothing with the passed argument - the content of all three functions is the same. In 2nd case the function reads wrong values from received XBee packet. In the 1st and 3rd case the function performs correctly.
Code:
ExampleLib.h
#ifndef ExampleLib_h
#define ExampleLib_h

#include "Arduino.h"
#include <XBee.h>

#define ADDRESS_BROADCAST 0xffff
#define ADDRESS_PC 0x3333

typedef struct
  {
    int valA;
    int valB;
    int valC;
  } valuesStruct;

class ExampleLib
{
public:
    ExampleLib();
    void setSerial(Stream &serial);
    boolean tryReceivePacket();
    void processPacket();
    // THIS FUNCTION IS NOT WORKING!
    void processPacket(valuesStruct valuesStructData);
    void processPacket(valuesStruct* valuesStructData);
private:
    XBee xbee;
    Rx16Response rx16;
};

#endif

ExampleLib.cpp
The value read in line byte* packetData = rx16.getData(); is wrong when we trigger processPacket(valuesStruct valuesStructData) function. In other cases the behavior is correct.
#include "Arduino.h"
#include <XBee.h>
#include "ExampleLib.h"

ExampleLib::ExampleLib()
{
    xbee = XBee();
    rx16 = Rx16Response();
}

void ExampleLib::setSerial(Stream &serial)
{
    xbee.setSerial(serial);
}

boolean ExampleLib::tryReceivePacket()
{
    xbee.readPacket();

  if (xbee.getResponse().isAvailable()) {
    // got something

    if (xbee.getResponse().getApiId() == RX_16_RESPONSE) {
      // got a rx packet

      xbee.getResponse().getRx16Response(rx16);
      return true;
    }
    else {
      return false;
    }
  }
  else if (xbee.getResponse().isError()) {
    //nss.print("Error reading packet.  Error code: ");
    //nss.println(xbee.getResponse().getErrorCode());
    // or flash error led
    return false;
  }

  return false;
}
void ExampleLib::processPacket()
{
  byte* packetData = rx16.getData();
  byte dataLength = rx16.getDataLength();
  Serial.print("START L:");
  Serial.println(dataLength);
  for (int i = 0; i < dataLength; i++) {
    Serial.print(packetData[i]);
    Serial.print(" - ");
  }
  Serial.println("END");

  //16-bit addressing: Enter address of remote XBee, typically the coordinator
  Tx16Request tx = Tx16Request(ADDRESS_PC, packetData, sizeof(packetData));
  xbee.send(tx);
}

void ExampleLib::processPacket(valuesStruct valuesStructData)
{
  processPacket();
}

void ExampleLib::processPacket(valuesStruct* valuesStructData)
{
  processPacket();
}

Arduino sketch
#include <XBee.h>
#include <ExampleLib.h>

ExampleLib exampleLibObj = ExampleLib();

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

void loop()
{

  boolean isPacketReceived = exampleLibObj.tryReceivePacket();

  if (isPacketReceived) {
    // leave only one section, the rest should be commented

    //Section 1: working
    exampleLibObj.processPacket();

    //Section 2: not working
//    valuesStruct test;
//    test.valA = 0;
//    test.valB = 0;
//    test.valC = 0;
//    exampleLibObj.processPacket(test);

    //Section 3: working
//  valuesStruct* test;
//  test->valA = 0;
//  test->valB = 0;
//  test->valC = 0;
//  exampleLibObj.processPacket(test);
  }
}

I am really puzzled why in this one case function is performing differently. Looking forward to any suggestions to that issue.
Thanks!

This does seem to be very puzzling.

I've read through your code 3 times now and all I've managed to glean is that your question (and your code's behaviour) seems to be beyond me

If the second isn't working, it may be best to use the other 2. Especially on the Arduino with limited RAM, you will not have enough if you pass a full struct to a function. Passing a pointer is less memory-intensive, and if it works, use it!

Thanks! I have actually made some tests using MemoryFree library and in that case memory is not an issue at all. What actually happens is, for some reason, copied version of the object, that we use in a function is written in the area of a memory, where XBee packet resides. In later tests the same happened to me with option 3 and passing a pointer - a copy of a pointer would corrupt the packet structure. Further investigation led me to the way of initializing XBee object to be the possible culprit.

Following those instructions - link - I managed to fix the problem in both cases, but I still don't know why the problem occurred in the first place.


text:
Set up an Arduino Cellular Shield SM5100B
I'm trying to set up an Arduino Cellular Shield SM5100B to send SMS.
My setup is:

Arduino UNO R2
SM5100B
"Movistar" SIM Card (Chile)

I've uploaded a code similar to the one described here, but when communication is supposed to star it cannot find a network. I suspect the problem is I haven't setup correctly the GSM band. But when I issue the command (AT+SBAND=7, same as in the US), it doesn't respond. How can I check in what band I'm on? And change the band?

How are you issuing the command to it? Do you have a new line after the command? Maybe it needs CR+LF. You can tweak those options in your serial terminal program.

/*
 Band Management

 This sketch, for the Arduino GSM shield, checks the band
 currently configured in the modem and allows you to change
 it.

 Please check http://www.worldtimezone.com/gsm.html
 Usual configurations:
 Europe, Africa, Middle East: E-GSM(900)+DCS(1800)
 USA, Canada, South America: GSM(850)+PCS(1900)
 Mexico: PCS(1900)
 Brazil: GSM(850)+E-GSM(900)+DCS(1800)+PCS(1900)

 Circuit:
 * GSM shield

 created 12 June 2012
 by Javier Zorzano, Scott Fitzgerald

 This example is in the public domain.
 */
 // libraries
 #include <GSM.h>

 // initialize the library instance
 GSMBand band;

 void setup()
 {
   // initialize serial communications and wait for port to open:
   Serial.begin(9600);
   while (!Serial) {
     ; // wait for serial port to connect. Needed for Leonardo only
   }

   // Beginning the band manager restarts the modem
   Serial.println("Restarting modem...");
   band.begin();
   Serial.println("Modem restarted.");

 };

 void loop()
 {
   // Get current band
   String bandName = band.getBand(); // Get and print band name
   Serial.print("Current band:");
   Serial.println(bandName);
   Serial.println("Want to change the band you’re on?");
   String newBandName;
   newBandName = askUser();
   // Tell the user what we are about to do…
   Serial.print("\nConfiguring band ");
   Serial.println(newBandName);
   // Change the band
   boolean operationSuccess;
   operationSuccess = band.setBand(newBandName);
   // Tell the user if the operation was OK
   if(operationSuccess)
   {
     Serial.println("Success");
   }
   else
   {
     Serial.println("Error while changing band");
   }

   if(operationSuccess)
   {
     while(true);
   }
 }

 // This function offers the user different options
 // through the Serial interface
 // The user selects one
 String askUser()
 {
   String newBand;
   Serial.println("Select band:");
   // Print the different options
   Serial.println("1 : E-GSM(900)");
   Serial.println("2 : DCS(1800)");
   Serial.println("3 : PCS(1900)");
   Serial.println("4 : E-GSM(900)+DCS(1800) ex: Europe");
   Serial.println("5 : GSM(850)+PCS(1900) Ex: USA, South Am.");
   Serial.println("6 : GSM(850)+E-GSM(900)+DCS(1800)+PCS(1900)");

   // Empty the incoming buffer
   while(Serial.available())
   Serial.read();

   // Wait for an answer, just look at the first character
   while(!Serial.available());
   char c= Serial.read();
   if(c=='1')
     newBand=GSM_MODE_EGSM;
   else if(c=='2')
     newBand=GSM_MODE_DCS;
   else if(c=='3')
     newBand=GSM_MODE_PCS;
   else if(c=='4')
     newBand=GSM_MODE_EGSM_DCS;
   else if(c=='5')
     newBand=GSM_MODE_GSM850_PCS;
   else if(c=='6')
     newBand=GSM_MODE_GSM850_EGSM_DCS_PCS;
   else
     newBand="GSM_MODE_UNDEFINED";
   return newBand;
 }


text:
is it possible to backup an uploaded program?
I have a cute robot built on Arduino Uno and Ardumoto, and I am trying to reverse engineer it first, and to add some new sensors afterwards.
I am stuck at how to deal with its program. I don't have the source code but I do not want to loose the program, yet in order to reverse engineer it I must write my own code and see if I can make it work.
Beware, I am a n00b to microcontrolers, and pretty lame to electronics (full of enthusiasm though).

Welcome to Arduino SE! The question here is a duplicate of this question. Although downloading and backing up are slightly different, the other post has answers that fit your criteria. If you feel that they are not duplicates, please edit this post using the edit button to specify what exactly you want. Thanks!


text:
How do I use RFID-RC522 with an Arduino?
I am working on a project for my local Makerspace, we have limited budget so I was hoping to use the RFID-RC522 el'cheap'o RFID/NFC readers on eBay, I received a couple of SPI based boards, they work, however the code examples for them are limited.
I have found several different libraries and settled on this one: https://github.com/ljos/MFRC522
The trouble is that all the code available online seem to spawn from some Chinese guys Python code that people have translated, and hacked into an Arduino library.
The code works, but Mifare cards are meant to have 4, 7 or 10 byte UIDs and the example/library is returning a 5 byte serial number.
There is no documentation and the NXP datasheet is incomprehensible... Additionally it seems to work with most cards, but it doesn't work with Mastercard PayWave cards which conform to the ISO 14443 standard. The more expensive RDM880 reader which is based on the MFRC500 works fine and has a nice library but the cost makes the implementation impossible.
So, can someone help me to get this NXP MFRC522 based unit reading the UID from all ISO 14443 cards.
#include <SPI.h>
#include <MFRC522.h>

#define RFID_SS  10
#define RFID_RST 5

MFRC522 rfid( RFID_SS, RFID_RST );

void setup() {
  SPI.begin();
  Serial.begin(115200);
  rfid.begin();
}

void loop() {
  byte data[MAX_LEN];
  byte uid[5];

  if ( rfid.requestTag( MF1_REQIDL, data ) == MI_OK ) {
    if ( rfid.antiCollision( data ) == MI_OK ) {
      memcpy( uid, data, 5 );
      for ( int i = 0; i < 5; i++ ) {
        Serial.print( uid[i], HEX );
        Serial.print( ' ' );
      }
      Serial.println();
    }
  }
}

This is probably not the problem, but your uid array is of length 5. Did you try using a larger array since you want a 10 byte result?

Yes, I did but it didn't help, in fact the other reader seems to only return 4 byte numbers and it's a different make with decent example code, very confused.

Sorry, but I must disagree with your 'NXP datasheet is incomprehensible'. From the FIRST PAGE of the MFRC522 datasheet:
'Remark: The MFRC522 supports all variants of the MIFARE Mini, MIFARE 1K,
MIFARE 4K, MIFARE Ultralight, MIFARE DESFire EV1 and MIFARE Plus RF
identification protocols'
Here it says the MFRC522 covers just a part of ISO/IEC 14443. The following are missing fron the NXP RC522:
*MIFARE DESFire EV1 (includes AES encryption)
MIFARE DESFire EV2 (includes MIsmartApp, Transaction MAC, Unlimited Applications
MIFARE Plus drop-in replacement for MIFARE Classic with certified security level (AES 128 based))
MIFARE SAM AV2 (secure access module that provides the secure storage of cryptographic keys and cryptographic functions)*
These are probably the ones used in bank cards. Again, from the FIRST PAGE of the MFRC500 datasheet:
'All protocol layers of the ISO/IEC 14443 A are supported.'
You'll have to plow through all the different MIFARE / ISO/IEC 14443 specs to find out how many ID bytes there are for the different types (I suspect diferent types return a different quantity of bytes).
So, basically, you're screwed. Spring for the expensive MFRC500-based reader. I assume that with the higher cost you also get a high-class API, documentation and examples or even (gasp!) tech support.
Cheers

You are right that the MFRC522 doesn't support this, but you are wrong that the MFRC500 is the solution, that device only supports MIFARE Classic, MIFARE 1K (S50) and MIFARE 4K (S70) cards.

Also the MFRC522 module is <£3 and the MFRC500 is £30.

The MFRC522::requestTag() returns the card type in the first two bytes of the 2nd parameter (data in your example above).  You will need to look at this value to determine which sort of card it is.  Use this information to print out the required N bytes of ID.
At a pinch, you could dump out the full 16 bytes (MAX_LEN), and test them with your various card types to see which bytes are changing in a deterministic manner, thus allowing you to determine the correct length of the ID.
And in case it saves you some time, if you call that library's self-test functions - getFirmwareVersion() and digitalSelfTestPass(); it's necessary to call MFRC522::begin() again, otherwise it's not possible to read RFID IDs (at the time of writing of course.)

Try using the most popular one.
https://github.com/miguelbalboa/rfid
This is working for me. It returns the uID as what you desire. Just remove the other functions just the getting of the uid from its example.

The fifth byte from the RC522 is just a checksum.
For instance, a possible return value (taken from https://github.com/miguelbalboa/rfid/issues/604#issuecomment-1885042556 ) is:
8B 65 66 B9 31
and if you do the binary xor of the first four numbers, you get precisely the fifth:
In [1]: hex(int("8B", 16)^int("65", 16)^int("66", 16)^int("B9", 16))[2:]
Out[1]: '31'

(Indeed, if you compare the first four bytes from the RC522 with the four bytes from the other reader, they should coincide)


text:
Default value of global variables is not set
I am tracking a bug in the Marlin source code.
Background
Just for those who is not familiar with Reprap 3D printer and G-code: Marlin is firmware that controls a RepRap 3D printer. It receives G-code from a host computer (or read from SD card). Here the important thing is that if you send the "M114" command, it would report information about axis positions. Here, I extended this command to make it print some internal variable as well.
The Problem
In Marlin.ino file there is a line that says:
volatile int extrudemultiply=100; //100->1 200->2

However my RepRap keeps extruding (and worse, ejecting back) a huge amount of filament. So I added some debug output for M114 command to output this value. It turns out this value is not the default value, 100, but something like 12374.
I thought somewhere inside the setup() function this value might be changed. So I defined another variable,
volatile int orig_extrudemultiply = 100;

And then at the first line of setup() function, I added the following line.
orig_extrudemultiply = extrudemultiply;

Finally, I output this value for the M114 command. Still, it is not 100. So it looks like the default value is not effective.
The Question
Although I have experience in C programming, I am new to Arduino development. How is a global variable being initialized in Arduino? In my case, what is the proper way to initialize this value?
Versioning
I originally posted the official Marlin link for the reference. However,
the version I actually use is this fork from the RepRap Pro team. I was just following the Melzi entry of the RepRap wiki, because my board is Melzi. I am not sure whether the latest version of Marlin works for my board.
Further details
As the commenter said, the first thing I thought of was memory corruption. So I wanted to narrow the problem down. Since that value is configurable through M302 SXXX command, I tested this command, and it works without difficulty. This means there is nothing in the loop function or the ISRs can affect this value when it is running stably. So I consider the problem must be in the setup function or earlier.
Further tests shows that setting this value at the end of setup or even at the beginning of setup still works fine. This means the setup function may not be the problematic one. The test in "The Problem" session was the last step, which, in my opinion, means the course of the problem must being run before entering setup.
UPDATE
Further examination shows that although it looks like it works when I set the default value in the first line of setup(), but that it is just luckily being 100. So once I add more padding variables it stops working until I move the default setting after the following line in setup():
EEPROM_RetrieveSettings(); // Loads data from EEPROM if available

However, since I greped for extrudemultiply before any test, and I didn't figure out this function, this function should not change this value. I guess there is some data overflow inside this function, so the value was changed expectationally.
I got to figure out what is wrong in this function.

Problems like this are almost always the variable being corrupted by other code rather than not being initialized properly.

Initial values of global variables like that are typically setup by toolchain provided initializers, and it actually is possible for toolchain usage mistakes to leave them out, but you'd probably notice other problems as well.  Ignacio's corruption hunch is a good one - it can be interesting to try declaring a dummy variable before or after the subject one, and see if the nature of the problem changes by thus steering the mistaken writes differently - though that should not be mistaken for a fix!

It seems you use a pretty old version of Marlin, as this declaration of extrudemultiply has changed Dec 3rd 2012! I suggest you update to a more recent version.

This variable is declared volatile which is generally meaning that it can be modified by an Interrupt Service Routine (ISR).
So it is perfectly possible that this ISR gets called before your setup() function gets called and then it may modify this variable.
In C and C++, variables defined as type variable = xxx; are guaranteed to be initialized before any of your code starts to run.
So this means you must look for the root of the problem somewhere else.
Don't forget that it is perfectly possible that some code gets run before setup() is called.
You may try to search for the code that runs before setup(); unfortunately it can be hard to find out this code:
Indeed, in C++, there are a lot of possibilities for code to execute even before the main() function gets called; for instance, declaring an instance of a class as a global variable, will call the class constructor before main().
So you would have to find out all class instances declared as global variables in all source files, and then check the class constructor that gets called for each instance.
Another way could be to check the assembly produced for your program and find all calls occurring be fore main(), but it can be harder if you can't read assembly.

Thanks your advise. I have updated the question to include some of my observations and opinions. Can you please have a look. Most importantly, where can I find the code that get run before setup() being called?

I've updated my answer to include hints on finding out that code. Even though you have already found the real source of the issue (I'm glad you found it!), I think it was useful to edit my answer anyway.

I accept this answer because although my own answer solves the problem, this answer actual answers the question. The new knowledge I learn from this answer is that Arduino IDE just another C IDE. Except the fact it is to be compiled as Arduino machine code there is not much different with other C/C++ environment. So my common sense about C/C++ is still good.

Thanks for this, @Earth-Engine, I'm glad my answer could bring you useful knowledge. However, considering people having a similar issue as yours in the future, I would suggest you accept your own answer as it is the right answer to your question. Cheers.

My theory is that here is the place to ask about Arduino, not ask about software/firmware bug. So people get to this page because they want to know how global variables being set in Arduino, not because they have problem with Marlin. If people wanted to find solution about bugs in Marlin, they should look at the Reprap pro github page for issues (I have created a pull request for this so people will find it).

The problem of this version of Marlin can be shown in the following piece of code (which is inside EEPROM_RetrieveSettings function):
  for (short i=0;i<4;i++)
  {
    axis_steps_per_unit[i]=tmp1[i];
    max_feedrate[i]=tmp2[i];
    max_acceleration_units_per_sq_second[i]=tmp3[i];
    max_length[i]=tmp4[i];
  }

Here max_length is an array of 3 elements, not 4 (the X,Y and Z axes have a max length to avoid hitting the edge, but the extrude axis does not have such a limit - you should be able to extrude as many filament as you can supply), so the last statement in the loop overrides other variable(s).
The solution is
  for (short i=0;i<4;i++)
  {
    axis_steps_per_unit[i]=tmp1[i];
    max_feedrate[i]=tmp2[i];
    max_acceleration_units_per_sq_second[i]=tmp3[i];
    if(i<3)
        max_length[i]=tmp4[i];
  }

Or
  for (short i=0;i<4;i++)
  {
    axis_steps_per_unit[i]=tmp1[i];
    max_feedrate[i]=tmp2[i];
    max_acceleration_units_per_sq_second[i]=tmp3[i];
    if(i < sizeof(tmp4)/sizeof(tmp4[0]))
        max_length[i]=tmp4[i];
  }

Greate thanks to the answer writer and commenter. Without your help I couldn't follow the right track.

Buffer Overrun strikes again. Make sure you don't need that fourth element though.


text:
Which motor (type) to use for an arduino controlled magnetic stirrer?
I am in the process of building my own sous vide machine and like to replace the pump typically found in most commercial machines with a magnetic stirrer unit. I figured the easiest way would be to use a motor to spin a permanent magnet (instead of creating a strong rotating magnetic field electrically). I first started experimenting with some 12V DC fans leftover from an old computer. By either lowering the input voltage or via PWM I was able to obtain appropriate rotational speed (don't ask me about exact speeds, I guess around 300rpm or so). With the project maturing I am not sure which motor (type and/or exact model) to use. I hoped some of you might point me in the right direction for the type of motor or even better, could suggest a specific model. I considered stepper motors or continuous  servo motors. My criteria for the motor are:

easy to control rotational speed between 0 and around 500 or so rpm (for ramp up and variation of speed to increase turbulent flow)
ability to rotate both clockwise and counter clockwise
enough torque at all speeds to spin a disk with magnets attached (weight and inertia probably negligible, the to be used alnico magnets create a field strong enough to lift 0,4kg each)
small axial dimensions
reasonably priced and long lasting
quiet

The following picture shows a commercial magnetic stirrer found in your average laboratory. The blurry white object in the glass beaker is the the so called stir bar or "fish", a PTFE coated permanent magnet. It spins due to the rotating magnetic field created by the actual device underneath the beaker.

After reading more than the first few questions on this site (and reading some meta as well) I wonder if my question should by moved to EE since it isn't really a  arduino specifiy question. Reading and answering on another topic led me to believe asking this rather broad question was still okay-ish. (Maybe it is still interesting for the community since there appears to be a lot of confusion about motors and controlling them in general).

What's the purpose of the magnets? Waterproofing?

I am sorry if my initial question was unclear on the details: The magnets are glued to a disk that is than spun by the motor to create a rotating magnetic field. This field is used to spin a small magnetic rod inside a bowl atop the device. The vortex created by the rod stirs the fluid in the bowl.  I added a picture to the question to clarify the matter

Ahh, I understand now. Writing an answer as we speak...

I'd personally recommend a continuous rotation servo or a brushed DC motor. Personally, for this kind of load, I think it would be easier and cheaper to go with the brushed DC motor. You have to remember a continuous rotation servo is a DC motor with some circuitry so you can send pulses to it to control the speed (although it's not directly proportional to the signal you send).
A servo is the only other option besides a brushless motor; both require a little more circuitry than the brushed motor/continuous servo. The additionally cost more. This blog post covers the differences between brushed and brushless motors.
For driving a continuous, you hook it up to power [depends on your servo voltage], ground, and another Arduino pin and use the servo library to send a signal as a degree (90 = no speed, 180 = full speed forward, 0 = full speed backward).
A brushed you would need a h-bridge that allows you to either send voltage, send no voltage, or send reverse voltage (for backward). This chip (~$5) does that for two motors and allows PWM for different speeds. It also includes a brake function, although that doesn't seem necessary for you. It can handle up to a "2.4 A continuous (4 A peak)." I talk about this in this answer of mine.
Quick note, if you want to control the exact RPM of the device and not just manually adjust it to a good rate, you'll need some sort of a rotary encoder or similar. A reed switch (sends current depending on magnetic fields) would work perfectly for this purpose, just mount it below the magnets and figure out the degrees rotated by the motor for each "pulse."

I feel kind of biased towards something brushless since the whole thing is a gift and thus eliminating parts that wear and tear is probably a good idea. One thing I didn't mention in the question is that I have to control up to three motors (big bowl of water). Do you think in that case using servos to minimise surrounding electronics is the way to go?

@Sascha You have to pick that, I can't pick that for you. From experience, steppers (like brushless, just a little differently configured) are 5 times as much as a brushed. Ignoring money, brushless are better, but they are more complex to run. Although this might not work, I personally might just say If a motor goes out, I can fix it or whatever, but I don't know your situation exactly.

currently I am checking ebay (germany) but can't find anything useful since almost every motor appears to be either way to overpowered or just build for insanely high rpm. Any great resource for that kind of stuff?

@Sascha I don't really know how to read German but this motor is about 20 euros and ships free to Germany... but max 80 RPM and too much voltage for the driver. I just listed that as a reference; you might need a bigger driver.

What I am unsure of at the moment is how a geared DC motor would behave if used with lower input voltage or PWM to rotate slower than the rated speed. See for example: http://www.ebay.com/itm/12V-DC-300-RPM-High-Torque-Gear-Box-Electric-Motor-NEW-/220817730384?pt=LH_DefaultDomain_0&hash=item3369c32b50

If you need to rotate huge loads, a permanent magnet coupled to the axis of a brushless DC motor, driven by an electronic speed controller (used for model aircrafts, multicopters, etc.) could be an option. This is the mechanical principle used in standard magnetic stirrers used in the lab, particularly when the stirrer has an additional heating.
Small (and flat) magnetic stirrers without heating, similar to the one in your image, however often have no (rotating) mechanical parts at all, but use a set of coils periodically powered in sequence. Here, the only mechanically rotating part is the stirring bar itself. A commerically available model would be this one.


text:
Larger NFC antenna?
Goal: I would like to be able to transfer some information to an Arduino Uno board via an NFC shield/antenna. The situation requires that the NFC tag may potentially hit anywhere within a circular area about a 12 inches in diameter.
Is it possible to increase the size of an NFC antenna? Possibly creating a loop antenna whereby the tag could be read from anywhere inside the loop.
I was thinking maybe if that isn't possible, it might be better to create an antenna array spanning the size of the area needed. Though I may have problems with overlap or double reads this way.
Has anyone attempted this before?
Note: I am not worried about increasing the z distance from the plane, just the x/y range. In fact, I still want the z distance to be very short as to not interfere with other antennas nearby.

http://en.wikipedia.org/wiki/Hilbert_curve

Welcome to Arduino.SE, aowie1! I'm a reviewer on this site, and we deal with Arduino questions here, so I'm wondering how your question relates to Arduinos. Maybe you could edit your question to tell us how Arduinos relate to your setup, or maybe we should just migrate your question to a more appropriate site (I'm thinking EE.SE, but I'm not sure it's on-topic there either).

In general the size and geometry of the antenna is directly related to the carrier frequency. The antenna is tuned to the output signal of the transmitter/receiver. If you change an optimized antenna, it is no longer optimized and its performance will drop. So you can't keep extending an antenna, trying to improve its range.
The important question to be asked is if the existing antenna is already optimally sized for the transmitter/receiver. With these small things transmitter/receiver and antenna are usually closely matched. Even if the antenna is smaller than expected by math, the transmitter/receiver connected to it may be compensated for that.
With a receiver or a low* power transmitter, there is no harm in testing another antenna, but you'll probably won't improve performance much.

*) Notice that a high power transmitter can blow its output stage when connected to an unmatched load/antenna, but that is unlikely with NFC.

While you can't simply change the size of an antenna, it is generally possible to design a physically larger antenna which has a greater range, either by intercepting more field energy or by being more directional - but this requires a real understanding of how an antenna works.  It may also be possible to combine an array of several somewhat independent sub-antennas in order to have one of them be in the near field of a greater volume of potential transmitter positions.