body:
I have downloaded BOSSA for Linux, and have run `bossash->scan`. I have also tried erasing and resetting the board before scanning. It does not work. According to the [Arduino website][1], the native USB port is connected directly to the chip.

Isn't the master branch BOSSA (Arduino IDE uses it's own modified version of BOSSA) working because of a problem with this specific board, or have Arduino modified something inside the chip which alters the behaviour of the native port?

  [1]: http://arduino.cc/en/Main/arduinoBoardDue

title: Why doesn't the master branch BOSSA work on Arduino Due?

Answers: 1

body: No Arduino did not alter the chip, custom chips are massively expensive. If they are using their own modified version of BOSSA, then there must be a reason for it, probably the support of Arduino's hardware platform. To find out what the difference is, you have to find the code base used for Due and the original version when the code was forked. Often in such cases a project like Arduino can provide a patch to the BOSSA project, and that patch may or may not be applied to the master tree. Only way to find out is to check the BOSSA project repository / bug  reports and documentation.


body:
Does anyone know where I can find a Chlorine Sensor to use with the Arduino? It would need to be water proof. I've googled, but I couldn't find anything.

**EDIT**
Requirements: relatively inexpensive (under $100us), works with Arduino, waterproof and used to detect chlorine in water.

title: A waterproof Chlorine Sensor

Answers: 2

body:
Your best bet would probably be to interface with a colorimeter.  There is a tutorial for an open source colorimeter here:

http://www.appropedia.org/Open-source_colorimeter

IORodeo also sells a shield:

http://www.iorodeo.com/colorimeter

Vernier sells a colorimeter that may be suitable for your project & Sparkfun sells a shield to interface with Vernier sensors.

If a colorimeter doesn't work you would have to use an electrode, which is pretty expensive and has a shelf life.

body: Maybe measure conductivity instead?  I think, in freshwater pools, one of the active parts of working chlorine is an OCL ion - which I guess is conductive.


body:
My goal is to have my Arduino fire two stepper motors.  They need not be simultaneous. I'm using an Arduino Uno with 2 motor shields - specifically, the [Seeed Studio Motor Shield v1.0][1]. I know this shield uses D8-13.

Question is, how can I get the Arduino to use both shields?  Is there a way to make one of the shields take D0-D7?  If I could do that that'd be great. As far as I can tell, there's no way. The motor shields cannot be physically mounted either.

  [1]: http://www.seeedstudio.com/depot/Motor-Shield-p-913.html?cPath=73

title: Seeed Studio motor shield

Answers: 1

body: Some shields let you use jumpers or something to change the pin assignments, but I don't believe the Seed motor shield does.  What you can use is a [go-between shield](https://www.sparkfun.com/products/11002) between the two shields to remap the pins on the top shield.  Then in your code, you just initialize the second instance using different pins.  You just have to make sure the alternate pins have the features you need, like pwm.


body:
I got some code to receive characters from Bluetooth and code and print it back to the LCD display.

However, want to detect the *`Enter`* *character* to be the input signal, in other words, not to print nothing to the display until Enter is pressed.

An strange character is shown at display for Enter but I can't *catch it*.

This is my code:

    #include <Wire.h>
    #include <LiquidCrystal_I2C.h>

    LiquidCrystal_I2C lcd(0x20,16,2);

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

    }

    void loop()
    {

      while (Serial1.available())
      {
        char dato= Serial1.read(); //Comprobamos el dato

         lcd.print(dato);

        switch(dato) {
        case '#':
          Serial.println("GATO...");
        break;
        case 'e':  digitalWrite(13,LOW);

        Serial1.println("Led apagado");
        break;
          case 'r':
          digitalWrite(13,HIGH); delay(200);
          digitalWrite(13,LOW); delay(200);

          Serial1.println("Led intermitente");
          break;
      } //fin switch

    }//serial disponible

    }//fin programa

title: How to catch the Enter key received by Bluetooth?

Answers: 1

body:
It depends on what the enter key sends. It may be just CR (carriage return), LF (line feed), or both. You can check the [ASCII table][1] for the hex values for those characters.

LF is 0x0A and CR is 0x0D. Those are the characters you're looking for, you can add a `if` for these cases in order to guard the call to `lcd.print(dato)`:

    char dato= Serial1.read(); //Comprobamos el dato
    if (dato != 0x0A && dato != 0x0F)
        lcd.print(dato);

  [1]: http://www.cdrummond.qc.ca/cegep/informat/professeurs/alain/images/ASCII1.GIF


body:
On the documentation of Arduino, I quote:

> http://playground.arduino.cc/Learning/Memory
> Note: Flash (PROGMEM) memory can only be populated at program burn time. You can’t change > the values in the flash after the program has started running.

And on the PROGMEM description:
> http://arduino.cc/en/Reference/PROGMEM
> Store data in flash (program) memory instead of SRAM. There's a description of the various types of memory available on an Arduino board.
>
> The PROGMEM keyword is a variable modifier, it should be used only with the datatypes defined in pgmspace.h. It tells the compiler "put this information into flash memory", instead of into SRAM, where it would normally go.

So can we or can't we? Or it's not the same thing?

title: Can I write to Flash Memory using PROGMEM?

Answers: 1

body:
The short answer is no: PROGMEM data is read-only.

**Flash memory limitations**
The first thing to understand is that Flash memory (where program space lives) is designed for long-term fixed storage. Reading from it is very fast and precise. However, generally speaking, you can't modify it on a byte-by-byte basis (e.g. changing a specific variable). You usually have to erase and re-write it in large blocks. That makes it completely impractical for run-time manipulation, because you'd have to store a lot of redundant information somewhere else while you do the erase and write cycle.

**What PROGMEM actually does**
Any literal data specified in your code (such as strings and numbers) always reside in program space at first (i.e. in Flash). However, when your sketch actually wants to use that data at runtime, it normally has to allocate some space for it in SRAM and copy it over. That means you end up with two copies: the fixed original in Flash, and the temporary copy in SRAM.

When you use the PROGMEM modifier, you're telling it not to make that second copy in SRAM. Instead, your sketch will simply access the original in Flash. That's very useful if you only ever have to *read* the data, as it avoids the allocation and copy operations.

However, copying it to SRAM is essential if you want to modify the data. Aside from the Flash limitations I mentioned above, it's also a question of code safety.

If you're able to modify the **data** stored in program space, then it follows logically that you could also modify the **code** stored in program space. That would mean that a simple mistake (or in theory a malicious attack) could result in your sketch being partially or fully rewritten at run-time. This could have very unpredictable results, ranging from simply ceasing to work, through to damaging/destroying any connected equipment.

**More information**
You can learn more about the low-level PROGMEM stuff from here:

 * http://www.fourwalledcubicle.com/AVRArticles.php

An older version of the same PROGMEM tutorial is available here:

 * http://www.avrfreaks.net/index.php?name=PNphpBB2&file=viewtopic&p=243018


body:
I want to measure the SPI clock (pin 13) using the Arduino example code for the SPI library (very simple example). Basically independent from the `loop` function, the clock should be fired continuously.

I deployed the Arduino SPI example code on the board and measured pin 13 on an oscilloscope, but nothing was found, always zero volt.

title: Arduino Uno and Leonardo SPI clock can't be measured

Answers: 1

body:
Please note the SPI clock will only be active while it is shifting data. So simply put the spi.transfer in a hard loop

    #include <SPI.h>

    void setup() {
      SPI.begin();
      while (1) {
        SPI.transfer(0x00);
      }
    }


body:
I was trying out a basic button tutorial on my new Arduino UNO. But for some reason, the Arduino was detecting the button as on (pressed) even when it was off (unpressed).

After some experimentation, I found that the digital pins were flickering between `HIGH` and `LOW`, even if there was just a loose wire plugged in with nothing at the other end. And the state of the button, etc. wasn't making any difference. I tried this with pins 5,6 and 7, and it's happening with all of them, even when the neighbouring pins are connected to the ground.

**Is this behaviour normal or is there something wrong with my input pins?**

*Since I'm new to Arduino, there might also be something wrong with my testing code. Here's what I used...*

    const unsigned int LED_PIN = 12;
    const unsigned int BUTTON_PIN = 7;
    const unsigned int INDICATOR_PIN = 13;

    void setup() {
      pinMode(LED_PIN, OUTPUT);
      pinMode(LED_PIN, OUTPUT);
      pinMode(BUTTON_PIN, INPUT);
      digitalWrite(LED_PIN, LOW);
    }

    void loop() {
      const int BUTTON_STATE = digitalRead(BUTTON_PIN);

      if (BUTTON_STATE == HIGH) {
        digitalWrite(LED_PIN, HIGH);
        digitalWrite(INDICATOR_PIN, LOW);
      }
      else if (BUTTON_STATE == LOW) {
        digitalWrite(LED_PIN, LOW);
        digitalWrite(INDICATOR_PIN, HIGH);
      }
    }

*This code makes the lights always in opposite states: when one is on, the other is off. When I ran the code, both lights seemed on, which meant they were probably flickering, which meant that there was some interference in the input pin.*

title: Interference at digital input (UNO)

Answers: 1

body:
It sounds like you're seeing entirely normal behaviour. If you leave a digital input unconnected (or connected to an open button) then it's 'floating'. That means it can pick up interference from all sorts of things, and may appear to drift between high and low.

The usual way to resolve this problem is using a pull-up or pull-down resistor. This is usually a high-ohm resistor (e.g. 10,000 Ohm or more) which will gently pull the pin HIGH or LOW in the absence of any other signal. When another signal comes in (e.g. from a button being pushed), it should have a much stronger effect than the resistor, so that is what the input will see.

Your Uno has built-in pull-up resistors which you can use for this, although it will require a couple of changes. In your `setup()` function, you can enable the pull-up on your input pin like this:

    pinMode(BUTTON_PIN, INPUT_PULLUP);

That will cause the input to appear HIGH when the button is **not** pushed. That means you'll need to wire the other end of your button to ground (negative) instead of the voltage supply (positive). If you've set it up correctly, the input should appear LOW when the button is pushed.


body:
Using an Arduino and an L293D IC, can I control the number of rotations a DC motor makes? Or can I only control the direction and speed of the motor?

I purchased a two-wheeled robot platform to learn Arduino programming and electronics. The platform is here: http://www.robotshop.com/en/dfrobot-2wd-mobile-platform-arduino.html

Each wheel is controlled by a DC motor. I followed Adafruit's tutorial (https://learn.adafruit.com/adafruit-arduino-lesson-15-dc-motor-reversing) to control the motors with the help of an L293D IC.

Now I realize that I can't directly control the rotations of the motor. I can control the direction, voltage, and time of the rotation. For example: turn forward at 50% voltage for 500 milliseconds.

But that's difficult to translate into actual rotations. The speed of the motor varies according to voltage (like if I switch from 2AA batteries to 4AA's) and weight (adding sensors slows the motors down). Every time I change voltage or weight, I have to guess how much voltage/time causes a single rotation.

I think I should just buy stepper motors. Before I do that, I'll ask the community: Is there a way to control DC motors by rotations rather than time?

title: Control/count rotations of a DC motor

Answers: 2

body:
Stepper would be heavy and battery consuming, as Ignacio says.

Pololu makes an encoder for a wheel: http://www.pololu.com/product/1217, but obviously you can implement this in other ways too.

body: As you've discovered, there are a lot of variables involved, so you need *some* sort of feedback.  A popular way to do this is with an encoder, but depending on your needs, other kinds of sensors can make do.  For example, if your problem is keeping the robot going in a straight line, an electronic compass can help.  For a line following robot, the line sensors are usually enough.  Range sensors can track your distance.  You get the idea.


body:
I am able to control my monitor and most other applications by giving serial input to python through arduino.
Arduino code:

    void setup()
     {

      pinMode(2, INPUT);
      pinMode(3, INPUT);
      pinMode(4, INPUT);
      pinMode(5, INPUT);
      pinMode(6, INPUT);
      pinMode(7, INPUT);
      Serial.begin(9600);

    }

    void loop()
    {
      if(digitalRead(2) == HIGH)
      {
        delay(5);
      }
      else
      {
        Serial.println("up");
      }
      if(digitalRead(3) == HIGH)
      {
        delay(5);
      }
      else
      {
        Serial.println("down");
      }
      if(digitalRead(4) == HIGH)
      {
        delay(5);
      }
      else
      {
        Serial.println("left");
      }
      if(digitalRead(5) == HIGH)
      {
        delay(5);
      }
      else
      {
        Serial.println("right");
      }
      if(digitalRead(6)== HIGH)
      {
        delay(5);
      }
      else
      {
        Serial.println("space");//orange
      }
      if(digitalRead(7)==HIGH)
      {
         delay(5);
      }
      else
      {
        Serial.println("nitro");//brown
      }
     }

Python code:

    import serial
    from pymouse import PyMouse
    from pykeyboard import PyKeyboard

    k = PyKeyboard()

    ser = serial.Serial('COM7', 9600)

    #sp.write("AT\r\n".encode('ascii'))

    while True:
        p=ser.readline()
        print p
        if ('up' in p):
            k = PyKeyboard()

            k.tap_key(k.up_key)

        if ('down' in p):
            k = PyKeyboard()

            k.tap_key(k.down_key)

        if ('right' in p):
            k = PyKeyboard()

            k.tap_key(k.right_key)

        if ('left' in p):
            k = PyKeyboard()

            k.tap_key(k.left_key)

        if ('space' in p):
            k = PyKeyboard()

            k.tap_key(k.space_key)

        if ('nitro' in p):
            k = PyKeyboard()

            k.tap_key(k.enter_key)

My problem is that..I am not able to play games such as NFS and other similar games using these controls..
What should i do??

title: How to control Keyboard inputs using arduino(serial monitor) and python keyboard libraries?

Answers: 2

body:
Your examples of sending input to the Arduino IDE monitor and to Python involve the Arduino sending data via "Serial over USB" convention. However this is not seen by the operating system (Windows, MacOS) as legitimate keyboard/mouse/joystick input.

There are separate USB conventions (device types) for keyboard/mouse/joystick. Only Arduinos where the USB interface is programmable are able to present those conventions, and some more easily than others, and require understanding some USB client libraries.  The link provided by Chris Stratton has some useful background.

A particularly easy way to get into this is with the PJRC Teensy, https://www.pjrc.com/teensy/, which comes with libraries and examples that let you do this out-of-the-box. See the "Teensyduino" section of their website for USB Keyboard, Mouse, Joystick and so on. These pages are useful background even if not using Teensy. It has attracted a small following of users interested in this area. Plus the various Teensies are conveniently small boards that fits nicely in some user-interface device you might want to build.

body: I'm later, but, I think you should redesign your python and arduino code, to make messages like "start up", "end up", and if message is "start *", hold that key, if "end *", release that key. This should work as intended. I will pin python and arduino code later here. (Also sorry for my english, i'm russian)


body:
I'm a bit new to electronics/Arduino projects, so am looking for some help on some wiring needed for a project involving this Pull Chain: http://proto-pic.co.uk/pull-chain-switch/

The chain works like a fan chain would.

I am using an Arduino UNO

I have wired up the pull chain to a mini breadboard with a light that turns on and off just to test it's working. What I want to do, is get an analog/digital read each time the chain is pulled?

Is this possible? If so, would you be able to help me with how it would be wired up, as I am completely new to the electronics side of Arduino. I simply need to get a reading each time the chain is pulled, I don't need it to switch a light on.

Thanks all!

title: Pull Chain Switch

Answers: 1

body: Connect it between ground and an interrupt pin configured as an input with the pullup enabled. Configure the interrupt to trigger on any state change. Check the digital value of the pin in the ISR.


body:
I am using this device for my Arduino that connects to the [OBD-II][1] port of my car to get various information such as speed, rpm, etc. I am using this for a digital [Nixie tube][2] speedometer using the smart Nixie tube from a [Kickstarter][3] 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][4] 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][5] 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);
        tens = ((input_number/10));
    }

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

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

  [1]: http://en.wikipedia.org/wiki/On-board_diagnostics#OBD-II
  [2]: http://en.wikipedia.org/wiki/Nixie_tube
  [3]: http://en.wikipedia.org/wiki/Kickstarter
  [4]: http://arduino.cc/en/Main/ArduinoBoardUno
  [5]: http://arduino.cc/en/Main/arduinoBoardMega2560

title: Super slow serial (UART) communication on Arduino

Answers: 3

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

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

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


body:
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)?

title: How can I convert Arduino String to C string type?

Answers: 3

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

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

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

1. a bit faster than working with `String`
2. no dynamic memory allocation/deallocation (`String` does a lot of these) which might lead your program to **[heap fragmentation][1]** 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)

  [1]: https://arduino.stackexchange.com/questions/763/im-using-too-much-ram-how-can-this-be-measured/787#787


body:
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](http://www.rfduino.com/product/rfd22301-rfduino-ble-smt/)
For now on, we are planning to use this battery [500 mAh LiPo battery](http://www.adafruit.com/products/1578) (approx. 4V at full charge) with this voltage regulator [Micrel MIC5209-3.6YS](http://www.mouser.com/ds/2/495/mic5209-239527.pdf) (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.

title: Which voltage regulator should I use?

Answers: 1

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


body:
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][1], 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][2].
* And the board with whom it is connected: [Gboard][3]
* 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.

  [1]: https://github.com/adafruit/Adafruit-GPS-Library
  [2]: http://www.adafruit.com/products/746
  [3]: http://imall.iteadstudio.com/im120411004.html

title: Simultanous read and read/write on two serial connections

Answers: 5

body:
[`Adafruit_GPS.h`](https://github.com/adafruit/Adafruit-GPS-Library/blob/master/Adafruit_GPS.h) (line 132-), which is included in [`Adafruit_GPS.cpp`](https://github.com/adafruit/Adafruit-GPS-Library/blob/master/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.

body:
The solution to your problem might be to combine [AltSoftSerial][1] 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.

  [1]: https://www.pjrc.com/teensy/td_libs_AltSoftSerial.html

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

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

body:
I've done exactly this.  The secret sauce for me was the [SoftwareSerial.listen()](http://arduino.cc/en/Reference/SoftwareSerialListen).

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


body:
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][1]

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

  [1]: http://www.seeedstudio.com/wiki/Seeeduino_v3.0#How_do_I_configure_the_Arduino_IDE.3F

title: SeeedDuino/Grove and the story of not being able to upload programs

Answers: 1

body:
OK mystery solved!

I ended up getting [Visual Micro Debugger][1] 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()

  [1]: http://www.visualmicro.com/


body:
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][1] 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?

  [1]: http://www.gsmlib.org/download.html

title: Check contents of buffer after serial read

Answers: 1

body:
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();`](http://arduino.cc/en/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.


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

title: Matching Baud Rates

Answers: 2

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

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


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

title: Detect and stream if a chair is occupied

Answers: 6

body:
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][1].

  [1]: http://arduino.cc/en/Main/ArduinoWiFiShield

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

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

 1. Force sensor on base of chair: Can tell you how much weight is on a chair (Sparkfun SEN-09376)
 2. IR or sonic sensor on back of chair to detect distance ([example][2])
 3. Vibration/shock sensor to detect if someone has sit down ([example][3])
 4. 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.

  [2]: https://www.sparkfun.com/products/242
  [3]: https://www.sparkfun.com/products/9197

body:
You could use [the awesome CapSense-Library][1]. 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)
  [1]: http://playground.arduino.cc/Main/CapacitiveSensor?from=Main.CapSense

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

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


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

title: How to test the sleep / enable function of Stepper Driver?

Answers: 1

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


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

title: How to use components that don't have a shield?

Answers: 1

body:
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][1] and [I2C][2]. From a quick peek at the [driver interface sheet][3], it looks like they're using SPI. Well, your [Arduino already supports that][4] 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.

  [1]: http://en.wikipedia.org/wiki/Serial_Peripheral_Interface_Bus
  [2]: http://en.wikipedia.org/wiki/I²C
  [3]: http://www.pervasivedisplays.com/products/2inch
  [4]: http://arduino.cc/en/Reference/SPI


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

title: Manchester Library Won't Compile for Attiny85

Answers: 3

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

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

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


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

![My workside][1]

Screenshot of my Android web browser

![Android Phone Screen][2]

Serial Monitor output

![Arduino IDE & Serial Monitor][3]

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

  [1]: https://i.stack.imgur.com/MFCwt.jpg
  [2]: https://i.stack.imgur.com/tH4Jq.png
  [3]: https://i.stack.imgur.com/vba5T.png

title: Arduino Mega & WiFi Shield; why web server every time says my A7 pin reads 0V?

Answers: 2

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

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


body: 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)?

title: Connect Arduino with fischertechnik TX Controller

Answers: 1

body:
As described in the [Wire library][1] 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][2] 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.

  [1]: http://arduino.cc/en/Reference/Wire
  [2]: http://playground.arduino.cc/Main/SoftwareI2CLibrary


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

title: Understanding the compilation/linking/upload process (so I don't have to use the IDE)

Answers: 2

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

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


body:
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][1] 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][3]. 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!

  [1]: http://www.pololu.com/product/114
  [3]: http://www.amazon.com/dp/B00JR6IY4M/ref=wl_it_dp_o_pC_S_ttl?_encoding=UTF8&colid=FUN60MOL7TVV&coliid=I4943V9GBF96U

title: How can I connect the Tamiya double gearbox to Arduino Uno?

Answers: 2

body:
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](http://www.makershed.com/Official_Arduino_Motor_Shield_p/mksp12.htm?gclid=CIyNjIKygb4CFe5aMgodpQcAuw)) 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.](http://www.pololu.com/product/2130)

![][1]

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

>![][2]

>![][3]

>![][4]
*(Click to enlarge ^^^)**

*I added a little text to this image.

  [1]: https://i.stack.imgur.com/adDy1.jpg
  [2]: https://i.stack.imgur.com/t7iEx.png
  [3]: https://i.stack.imgur.com/vwiM4.jpg
  [4]: https://i.stack.imgur.com/DyuR1.png

body:
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][1]. They are not high current motors.

  [1]: https://www.jameco.com/z/FA-130RA-2270-Mabuchi-Motor-Company-1-5-3V-DC-Motor-6990-RPM_2192755.html


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

title: Level detection of 3.3V from 5V arduino

Answers: 2

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

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


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

title: Servo won't stop rotating

Answers: 2

body:
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][1], 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).

  [1]: http://www.feetechrc.com/product/analog-servo/micro-1-3kg-cm-360-degree-continuous-rotation-servo-fs90r/

body:
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
    }


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

title: RFID/NFC (13.56 MHz), is it possible to send raw bytes and receive response?

Answers: 2

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

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


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

 1. A function taking no arguments: void processPacket()
 2. A function taking structure as a value as an argument: void processPacket(valuesStruct valuesStructData) - THIS VERSION OF THE FUNCTION IS NOT WORKING!
 3. 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!

title: XBee, external libraries and passing structures as arguments

Answers: 1

body: 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!


body:
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][1], 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?

  [1]: http://www.instructables.com/id/Arduino-Cellular-Shield-Tutorial/?lang=en

title: Set up an Arduino Cellular Shield SM5100B

Answers: 1

body:
    /*
     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;
     }


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

title: is it possible to backup an uploaded program?

Answers: 0


body:
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][1] 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();
        }
      }
    }

  [1]: http://www.nxp.com/documents/data_sheet/MFRC500.pdf

title: How do I use RFID-RC522 with an Arduino?

Answers: 3

body:
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**](http://en.wikipedia.org/wiki/Radio-frequency_identification) 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

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

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


body:
I am tracking a bug in the [Marlin][1] source code.

**Background**

Just for those who is not familiar with Reprap 3D printer and G-code: Marlin is firmware that controls a [RepRap][2] 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][3] link for the reference. However,
the version I actually use is [this fork][4] from the RepRap Pro team. I was just following the [Melzi][5] 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][6] 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 `grep`ed 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.

  [1]: https://github.com/reprappro/Marlin
  [2]: https://en.wikipedia.org/wiki/RepRap_Project
  [3]: https://github.com/ErikZalm/Marlin
  [4]: https://github.com/reprappro/Marlin
  [5]: http://reprap.org/wiki/Melzi#Melzi_Arduino_Pin_Numbers
  [6]: https://en.wikipedia.org/wiki/Interrupt_handler

title: Default value of global variables is not set

Answers: 2

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

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


body:
I am in the process of building my own [sous vide machine][1] and like to replace the pump typically found in most commercial machines with a [magnetic stirrer unit][2]. 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.
![Photo of a commercial magnetic stirrer used in laboratories][3]

  [1]: http://en.wikipedia.org/wiki/Sous-vide
  [2]: http://en.wikipedia.org/wiki/Magnetic_stirrer
  [3]: https://i.stack.imgur.com/ysulU.jpg

title: Which motor (type) to use for an arduino controlled magnetic stirrer?

Answers: 2

body:
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](http://quantumdevices.wordpress.com/2010/08/27/brushless-motors-vs-brush-motors-whats-the-difference/).

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](http://arduino.cc/en/reference/servo) 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)](http://www.pololu.com/product/2130) 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](https://arduino.stackexchange.com/questions/1314/how-can-i-connect-the-tamiya-double-gearbox-to-ardunio-uno/1315#1315).

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

body:
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](http://www.ika.de/owa/ika/catalog.product_detail?iProduct=3907500&iCS=1&iProductgroup=188&iSubgroup=1).