# Question
Title: How to connect a 2 cell LiPo batter to Arduino Motor Shield?
I am trying to connect a 2 cell 7.4 volt LiPo battery into my motor shield. I am a beginner at robotics so I am not sure if I just connect the battery, via a connector of some sort, into the motor shield itself or do I use some 22 AWG wire and connect it via that way. Sorry if that sounds confusing.

# Answer
> 2 votes
From the Motor Shield page,

> External (non-USB) power can come either from an AC-to-DC adapter (wall-wart) or battery. The adapter can be connected by plugging a 2.1mm center-positive plug into the Arduino's board power jack on which the motor shield is mounted or by **connecting the wires that lead the power supply to the Vin and GND screw terminals, taking care to respect the polarities.**

So they provide the screw terminals for a battery, you should be able to insert two wires from your battery/pack into the terminals. If your battery has a connector on it, you'll need to either cut it off or find an adapter.

**Be extra careful:** if you have exposed leads from your battery and they touch, it'll get extremely hot and possibly catch fire.

# Answer
> 1 votes
it is up to you. Welded cable is better, but you will probably need a connector, so you should take care to use low-ipendance one that can hadle your current need, like `bullet connector` used by RC toys.

Also the battery should have a `discarge current` higher that the maximum current used by the engine: normaly this can be calculated by the discarge factor (labeled as 'C' on the hobbyst battery) multiplied by the capacity in Ah o the battery. Pay attention to this as this can damage the battery and alco cause lipo-fire, witch cannot pulled off with just water, you need an extinguer. (this is what happen when you short-circuit the + and -)

---
Tags: arduino-uno
---


# Question
Title: Changing pins used in ArduinoISP example
I have built my own ATTiny programmer, but made a bit of a mistake along the way - I didn't align the headers properly, and now instead of them plugging into pins 10, 11, 12 and 13 as per the ArduinoISP example - they now plug into pins 8, 9, 10 and 11.

If I use some jumper cables to wire the pins to match the ArduinoISP example, it all works fine, meaning the wiring on the actual board is OK, however, I want to be able to just plug my board I have made straight in, and thus need to get the bootloader burning and the uploading to work via pins 8, 9, 10 and 11 instead.

I have tried modifying the example myself by replacing the references to RESET, MOSI, MISO and SCK with my own pin numbers, but this doesn't seem to suffice. When I try to burn the bootloader now, I get the following error:

```
avrdude: stk500_program_enable(): protocol error, expect=0x14, resp=0x50
avrdude: initialization failed, rc=-1
         Double check connections and try again, or use -F to override
         this check.

avrdude: stk500_disable(): protocol error, expect=0x14, resp=0x51

```

If I try to upload a sketch using my version which has the custom pin numbers, I get this error:

```
avrdude: stk500_getsync(): not in sync: resp=0x00

```

The wiring of my programmer is the same as can be found here: http://highlowtech.org/?p=1706 except I want the programmer sketch to work with different pins.

Thanks

# Answer
> 7 votes
You can't change the pins.

ArduinoISP uses the SPI interface on pins 10-13 which is provided by the underlying AVR hardware.

# Answer
> 3 votes
As a practical matter, you're much better off correcting things so you're using the original pins, which correspond to hardware SPI.

However, it's not terribly hard to implement SPI in software (at a lower performance, of course):

```
static uint8_t
SPITransfer(uint8_t out)
{
    uint8_t in = 0;
    for (int i=0; i<8; ++i) {
        digitalWrite(MOSI, (out & 0x80) != 0);
        out <<= 1;
        digitalWrite(SCK, HIGH);
        in = (in << 1) | digitalRead(MISO);
        digitalWrite(SCK, LOW);
    }
    return in;
}

```

There are several SPI modes, but this implements the one used for ISP.

---
Tags: bootloader, isp, attiny
---


# Question
Title: What are the main differences between the Arduino Tre and the Intel Galileo?
I'm looking to find a suitable board for a robot I'm developing (it'll involve computer vision, else I'd be using my Arduino Micro) and I've come across two possibilities: The Intel Galileo and the Arduino Tre.

Now as I understand it, the Intel Galileo has a 400MHz Quark processor, whilst the Arduino Tre has 2 processors, an onboard 16MHz standard ATmega32u4 with the Arduino bootloader and then another 1GHz TI processor with Linux installed on it.

However, I'm not sure of the differences between both products, as price estimates appear to place them at approximately the same price (around $70) and the Intel Galileo doesn't appear to have any real advantage over the Arduino Tre (except for a full x86 instruction set).

Does anyone have any information on comparison of the two boards so I can make a better informed decision?

# Answer
## Biggest difference IMHO: Tre hasn't been released yet!

Besides that, there are a few different things that you should compare. Not much is available about the Tre as of now, but I'll update this post when it's released.

---

## *Basic Specs:* \[First sub-bullet is TRE, second Galileo; better spec in bold\]

* Microcontroller:
    + Texas Instrument Sitara AM3359AZCZ100 (ARM Cortex-A8) (**1 GHz,** 32 bit), Atmel ATmega32u4 (16 MHz, Secondary, found on Leonardo)
    + Intel® Quark SoC X1000 (400 MHz, 32 bit)
* RAM:
    + 512 MB SRAM (2.5 KB ATmega32u4)
    + 512 MB SRAM
* Pins
    + **14 Digital 5V, 7 of which are PWM, 6 analog 5V (additional 6 multiplexed) (32u4); 12 Digital 3.3V, 4 of those are PWM (Sitara)**
    + 14 5V digital, 6 of those are PWM, 6 analog 5V
* Networking:
    + Ethernet 10/100
    + Ethernet 10/100
* USB port:
    + 1 USB as slave, 4 USB host ports
    + Up to 128 devices as host, 1 USB slave
* Video
    + **HDMI (1920x1080), LCD header**
    + None that I can find
* Audio
    + HDMI, stereo analog audio input and output
    + None that I can find
* MicroSD card
    + Yes
    + Yes
* PCIe Slot
    + No
    + **Yes**

Sources (I combined a bunch of data for this): Galileo & Tre

---

**Conclusion:** If you need a board before the Tre comes out, which seems to be soon (Spring 2014), Galileo is your only option. Other than that, the Tre seems to be better all around in most aspects, minus the PCIe slot. I can't comment on power, but it seems like the Tre will be able to supply 4x the power per pin than the Galileo. The Galileo is getting older, and it doesn't seem like the Galileo can provide full Linux support like the Tre will.

Personally, I'd wait for the Tre. The *only* thing I can think that the Galileo would be better for would be either a.) lower power usage or b.) the PCIe slot for a WiFi adapter that works decently. The second one could be solved by doing a common WiFi router hack.

If you need a lot of processing power without the need of low latency, you should conciser sending data to a computer to process.

>

Source

>

Source
> 4 votes

---
Tags: robotics, arduino-galileo
---


# Question
Title: How to disable Arduino Yun to work as Access Point and set it to work as needed?
I am using Arduino Yun and I would like to disable it to work as Access Point. That is, I don't want that it is displayed in the list of available networks.

Then I would like to set and use it (separately) in the following scenarios:

a) Arduino Yun connected just over a given Wi-Fi network (Ethernet connection disabled).

b) Arduino Yun connected just over Ethernet (Wi-Fi connection disabled).

How can I make it?

**Note**: In my previous attempts I tried to customize and/or disable someway the Wi-Fi connection (through the LuCI panel) in order to reach what I am looking for but in all of these cases I had to restore my Arduino Yun from scratch because it did not work anymore.

# Answer
Yun expects wifi to be working and, if it's not, it will reboot itself after 60 seconds and return in access point mode.

In order to disable this check, edit file `/etc/rc.local` and turn `wifi-live-or-reset` into `#wifi-live-or-reset` (with a starting `#`).

Once done, use LuCI (the advanced configuration panel) to configure network interfaces.
> 2 votes

---
Tags: arduino-yun, wifi, networking, ethernet
---


title: Arduino stopwatch, which board to use?

text:
# Question
Title: Arduino stopwatch, which board to use?
I am planning on making a simple stopwatch with:

* A display
* One or two additional buttons to start the stopwatch and stop the stopwatch and maybe reset it.

The problem is that it has to be as small as possible. With all those different Arduino boards out there, I don't know which one I should buy (mini, micro, nano, ...).

I am not sure how many pins I need for the LCD since I have read that in fact not all pins are mandatory for the LCD. I have done something earlier with an LCD and I found the pot meter for the LCD contrast level a bit of waste of space. Could I just replace it with a certain resistor or something?

How many pins in the end would I need and which board would be fitting for this little project?

# Answer
**By that photo you posted, you pretty much answered a decent part of your question.** You'll need six pins for the LCD, and one or two for the button. That means that you need a *total* of 8 pins. That Uno pictured has 20 (analog can act as digital, too).

As far as the boards, if you feel comfortable with some extra work, I'd recommend an ATtiny. From what I can find, it seems like you can drive a LCD with a 44 or an 84 (similar, but the 84 is more powerful).

>

*Source for image and how to program chip*. I'm not going to go into the details for this method, as the link has the necessary files...

---

That's the smallest way to do this\*, however, if you want to use a real Arduino board, then I'd recommend the Micro for a few reasons.

First of all, it has the newer ATMEGA32u4 chip, found on the Leonardo. I do *not* recommend the Mini because, although it's the smallest of the three, it doesn't feature on board USB. You would have to buy another adapter to program it. If you're already using a breadboard, the extra 2cm (or so) is worth not having to spend *more* to buy both of those components. The Nano is the equivalent of the Mini, only with USB. Also, the Nano and the Micro are roughly the same size, one a little bit longer and one a little bit wider.

However, the Nano and Micro are roughly the same as far as processing power, so I'd recommend that, if you can get one significantly cheaper, to go with that. It doesn't really matter that much.

\*If you're building this on a breadboard, it won't be smaller. If you're transferring to a PCB, then you should use an ATtiny.

---

As far as the pot goes, I'd recommend getting a *trimmer* with an equivalent value. Some of them are very small, as I have one that fits on the USB connector part of my thumb drive. They need a screwdriver to adjust, but I would recommend it. I've had issues moving it from a dark room to in the sun and not being able to see it clearly. Spend the two cents and the 2 cm2 and have an opportunity to change it if needed.

For the battery, I would recommend any rechargeable battery (under ~3.5V) **if and *only* if** you add a proper chip to not waste energy in the conversion. I talked about this in this post.
> 1 votes

---
Tags: arduino-nano, system-design, arduino-pro-mini, arduino-pro-micro
---


title: Analog average sample wind speed sensor

text:
# Question
Title: Analog average sample wind speed sensor
I have wind speed sensor that can measure max speed upto 30 m/s with analog out put 0-5v. I have simple code calling from the loop. When I put the wind speed average code, the web server is not working and it just hangs. If I comment out web server it's working fine. Let me know What makes my web server hang or not get connected. Is there any way I can change average taking code?

**Working code should like below:**

```
if wind speed exceed 30 m/s
   mode =stow
else
   mode =track

```

My code. And how can write average of windload of day to SDcard

```
#include"wind.h"
#include"mode.h"

float sampleAverage(void)
{
  float accumulator = 0;
  for (int i = 0; i < SAMPLE_COUNT; i++)
  {
    accumulator += sample[i];
  }
  return accumulator / SAMPLE_COUNT;
}

void Wind_calc()
{

  static unsigned long lastSampleTime = 0;
  unsigned long currentTime = millis();

  // check if time for new reading
  if (currentTime - lastSampleTime >= SAMPLE_RATE)
  {
    lastSampleTime = currentTime;
    int sensorValue = analogRead(SENSOR_PIN);
    float voltage = sensorValue * (5.0 / 1023.0);
    /* Serial.print("voltage: ");
     Serial.println(voltage);*/
    // add the newest reading at the oldest pointer
    sample[sampleIndex] = voltage;
    // advance to next index which is now oldest
    sampleIndex++;
    // check for and handle rollover
    if (sampleIndex == SAMPLE_COUNT)
    {
      sampleIndex = 0;
    }
    // the sample array now contains the last ten readings
    // sampleIndex now points to the oldest reading
    // it will be replaced with the newest next time

    float average = sampleAverage();
    /*Serial.print("average:");
     Serial.println(average);*/
    Wind_Speed = (6 * average);
    Wind_Kmph = 3.6 * Wind_Speed;
    /*    Serial.print("Wind_Speed:");
     Serial.print(Wind_Speed);
     Serial.println("m/s");

     Serial.print("Wind_Exceed_count:");Serial.println(Wind_Exceed_count);Serial.println(".................");
     Serial.print("Wind_Kmph:");
     Serial.print(Wind_Kmph);
     Serial.println("KMPH");
     */
    if((Wind_Speed>4.0)&&(Stow_flag==0))
    {
      Wind_Exceed_count=Wind_Exceed_count+1;

      //Serial.println("Wind_Exceed_count");Serial.print(Wind_Exceed_count);
      if(Wind_Exceed_count<5)
      {
        Stow_flag=0;
      }
      else
      {
        Stow_flag=1;
        MODE=STOW;
      }

    }
    else
    {
      Redo_Wind_calc();
    }

  }

}

void Redo_Wind_calc()
{
  //  Serial.println("Wind_Exceed_count");Serial.print(Wind_Exceed_count);
  if(Wind_Speed>4.0 &&Stow_flag==1)
  {
    Wind_Exceed_count=Wind_Exceed_count+1;
    if(Wind_Exceed_count<=10)
    {
      MODE=STOW;
    }
    else
    {
      MODE=TRACK;
      Wind_Exceed_count=0;
      Stow_flag=0;
    }

  }
}

void loop()
{
 Wind_calc();
webcontrol();
}

void webcontrol()
{

//Web control function are defined here

}

```

# Answer
What arduino board is being used? I find that some webserver code takes up a lot of the SRAM and in an UNO this leaves very little space for other code.

To save SRAM use the F macro on all the Serial.print statements that have quoted text. i.e:

```
Serial.print("Some text you want output");

```

This takes up SRAM when running. 1 byte per letter and space.

```
Serial.print(F("Some text you want output"));

```

This takes up no SRAM as it is stored in program space and is makes a big difference.

Search for a `freeRam()` and use that in debugging your sketch to see how much free space you have.

Relevant question: What can I do if I run out of Flash memory or SRAM?
> 3 votes

---
Tags: arduino-uno, web-server, analogwrite
---


# Question
Title: GSM library getIPaddress returns local network address 10.X.X.X
I have a Mega board and a GSM shield. I'm using Arduino's example "TestWebServer". The serial monitor shows that the GSM is connected, and returns a IP.

However, the IP is always 10.X.X.X. Isn't that a internal network IP address? How should I get the SIM cards IP? Thanks!

# Answer
> 1 votes
The SIM card does not have an IP address. When the data connection is made to your GSM APN it is assigned an IP in a similar way to DHCP. Often the address is the same after the first connection as the service provider will link that to your SIM for audit purposes. If you setup a private APN then you can arrange to have specific range allocated to your SIM card(s). This is normally only done for security of volume reasons.

---
Tags: gsm
---


# Question
Title: Why does my wired button always read HIGH?
I have made a simple Arduino program that uses a potentiometer to dim a LED.

This program also makes a second LED blink.

Finally, I have added a button that controls a third LED; this part of my program does not work: the 3rd LED is always lit as the button always reads HIGH.

Here is the code:

```
//sensePin is wired up to the FSR
int sensePin = 2;

//this is wired up to an LED
int ledPin = 9;

//Wired up to a button
int inputPin = 1;

int val = 0;

//I was broed so added the default Blink
int ledPinX = 13;

//Wired up to a second LED
int ledPinY = 7;

void setup() {
  Serial.begin(9600);
  pinMode(ledPin, OUTPUT);
  pinMode(inputPin, INPUT);
  pinMode(ledPinX, OUTPUT);
  pinMode(ledPinY, OUTPUT);
  val = digitalRead(inputPin);
}

void loop() {
  if (val == HIGH){
    //This should ask "If your button is pressed, then do the code below
    digitalWrite(ledPinY, HIGH);
    //but for some reason the light is always on. I've tried it with more than one button
  }
  else if(val == LOW){
    digitalWrite(ledPinY, LOW);
  }
  int value;

  /*
 The rest of this stuff works. Well, it did before adding in the button. Now the FSR acts as a digital input. Please help.
   */
  value = analogRead(sensePin) / 4;
  analogWrite(ledPin, value);
  digitalWrite(ledPinX, HIGH);
  delay(500);
  digitalWrite(ledPinX, LOW);
  delay(500);
}

```

What did I do wrong in this code?

EDIT:: diagram and pic at: instagram.com/p/m3AmHWmp4e

# Answer
> 2 votes
You read the button once, in `setup()`. The function is not called every time the variable's value is read, only when the line is executed and the variable assigned to. Move the `digitalRead()` call and assignment into `loop()`, before you check the variable's value.

# Answer
> 1 votes
The main problem with your code is that you read the button state **only once** at the beginning of your program in `setup()`, so it keeps the initial value forever.

You should modify `loop()` as follows:

```
void loop() {
  digitalWrite(ledPinY, digitalRead(inputPin));
  ...
}

```

You can also remove the `val` variable, it is totally useless here; then you must also simplify `setup()`:

```
void setup() {
  Serial.begin(9600);
  pinMode(ledPin, OUTPUT);
  pinMode(inputPin, INPUT);
  pinMode(ledPinX, OUTPUT);
  pinMode(ledPinY, OUTPUT);
  // val = digitalRead(inputPin);
}

```

# Answer
> 0 votes
Pin 1 is used for the serial output and can't be used if you enable serial using `serial.begin(9600)`.

Change button to pin 2.

---
Tags: button, led, debugging, potentiometer
---


# Question
Title: What's the fastest way to periodically communicate via serial?
I will be using an Arduino as a bridge between a computer high-level Java client and some low-level hardware computing units (e.g. other Arduinos). I need to find a solution to **periodically** communicate in **both** ways. It should be possible to send digital, analog inputs to the PC and receive digital, analog outputs from the PC via serial.

I have very specific requirements for my project to work:

1. Lowest possible latency in both ways. High latency would cause instability of controlled systems.
2. Extremely constant, possibly user-defined update period. Varying sample rate would cause inaccuracies in the control.

I need a very fast solution possible for update frequency of 100 Hz and higher.

So far I have tried to send data via Firmata to my java client using time interrupt.

```
ISR(TIMER1_COMPA_vect) {
  Firmata.sendAnalog(analog, analogRead(analog));
}

```

The messages however don't come at a very constant rate and are sometimes held up for twice the sample period or more which is unnaceptable. For higher frequencies this happens even more often. I suspect some kind of a buffer. Do you have any idea where should I look for bottlenecks? Would it be benefiting to design my own communication protocol and ditch Firmata?

EDIT: Look at the attached diagram. Blue lines are "inputs", green lines "outputs". Right now I am trying to design the "Arduino (Bridge)"

# Answer
> Lowest possible latency in both ways. High latency would cause instability of controlled systems.

the fact that you are using a not-real-time OS introduce a lot of unpredictable latency, the use of a visrtual machine over that os then add a bit more. Fast communication can be obtained increasing the baudrate, that will decrease the latency between the sample and the elaboration. Also sending RAW data instead of string will be faster (no convertion AND less byte send), and finally decreasing the overhead caused by the protocol.

For example Firmata by default use a low baudrate AND will add a lot of overhead to send WHAT kind of operation is doing. Writing your own communication protocol is better.

For example: analogRead use 10bit, so you may send a raw int, 2 byte, 16bit, so 6 bit are lost.. or you can "compress" with a bit of bitwise operation 4 read (40 bit) into 5 byte (40bit, no bit loss) instead of 8(int size * 4)!

AnalogRead is a really slow operation by default on arduino (~200us), but can be faster if you set up a lower prescaler (attention, lower prescaler means less ADC precision. at prescaler 16 guaranteed precision is 8bit, if my memory is good)

> Extremely constant, possibly user-defined update period. Varying sample rate would cause inaccuracies in the control.

On the PC side, if you need micro/nano second precision you need a `real time os`, newest linux kernel add a new special schedule but i think is still hard to find documentation. If less precision is ok, just use a timer.

On the arduino side, using a hardware timer is the best way, see LeOS for a nice scheduler on arduino

Please note HardwareSerial on the arduino side use interrupt to send data, so using it inside an ISR (like you are doing now or with LeOS) is really usafe and deadlock prone. Also ISR will "slow down" each others, as they cannnot be executed parallel; and analogRead is a realtivly slow operation.. I would use timer to set up a flag, and in the loop if i see the flag, start the analogread, Serial.write and finally Serial.flush (to be sure to not fill Serial buffer, causing a lot of trouble on the arduino reprogrammation reset)
> 1 votes

# Answer
could you be more specific with your question ? From what I understood:

* you have a client java program acting as the "brain" of your system
* your control is time sensitive. You have a PID or other regulation loop running on the pc
* you have or plan to have multiple arguing boards on your system and you need to communicate with them.
* you are dealing with analog IOs

## bridging

If you want to stick to serial port,you have to use RS485 or RS422. Those can work as a bus. Protocol on top of that can be Modbus. Note that this has a higher latency and you need at least 2 serial ports on your bridge

I2C. Lower latency 2 wires bus. Command oriented,runs at 400 kHz. So you have plenty of time to send/receive data

SPI even lower latency as bytes are sent as stream .arduino mega has 5 pins for it. Note that you have to deal with the addressing yourself in this case.

Arduino like many micro controllers is bad as doing many tasks at the same time like for the bridging case. I would avoid using an arduino in this case

## latency

As already answered, ADC conversion takes time and you cannot nest interrupt. Your minimum latency can be computed from the specifications of the arduino. The maximum latency is a value you fix yourself. Knowing the amount of time to send one byte on the communication port, You can decide between options like

* run the AD conversion in a loop outside interrupt, put the value inside a variable and do the communication a synchronously inside an interrupt
* run the AD conversion interrupt based and the communication in the main loop of operation

## conclusions

Don't do hardware in the loop using a PC. The latency and lack of strict timing possibilities worsened by the use of java make it a dead end with your current setup.

Use a stronger micro controller like an AVR32 with USB running the brain of your system. You can also use a raspberries pi or a beaglebone. Those runs "standard" Linux distributions and so you can use a PC like approach.

In any case guidelines are :

* try to stay as close to the micro controller as possible and avoid abstraction libraries and OSes
* don't use a pc for hardware in the loop
* try to make your task run a synchronously as much as possible
* keep your interrupt routines as small as possible
> 1 votes

# Answer
I have had great success removing serial from such an example and setting up a closed network and then Ethernet enabling all the arduino devices. I then have a DCHP and SNTP server in the closed network. The PC etc are all in the closed network. I then setup a MQTT server (see www.mosquitto.org) and use the arduino PubSub library on the arduino. I get extremely short round trips with pretty consistent response times and this has the advantage that multiple sources can publish or subscribe to the data steams created. The SNTP server is used so that all the devices get the same time reference to use and I time stamp all messages and can then work out message sequence etc even if they are physically delayed slightly by an Ethernet collision! although in a closed network this is minimized.
> 0 votes

---
Tags: serial
---


# Question
Title: ArduinoUno+LcdKeypad+ArduinoWifi=Pins Problems
Is it possible to connect these two shields to my Arduino Uno? After a research on the internet, I discovered that they use some of the same pins. Even so, is it still possible for me to connect the LcdKeypad and the ArduinoWifi on my Arduino Uno? (the LCD would be on top)

Here are the pic of the shields, and some information:

LDC KEYPAD

Arduino WIFI

WiFi shield info:

> The Arduino communicates with the processor WiFi shield with the microSD card by SPI (Eurotherm the ICSP bus) that is on pins 11, 12 and 13 at Uno. The pin 10 is used to select the HDG104 and pin 4 to the microSD card(i dont need the pin 4 cause i wont use SD). These pins can not be used for input and output. The digital pin 7 is used for initialization of the communication protocol between the shield and Arduino WiFi and should not be used.

LCD info:

> This shield we will have to use the following sequence to initialize the library LiquidCrystal: LiquidCrystal lcd (8,9,4,5,6,7);

As you guys have noticed, there is the pin 7 on both shields that I need to use. How would it work? Can I do this? If i can't, is there any solution that I can expand my pins that would not result buying a Mega?

I still have to connect two INFRA-RED sensors and a motor (using pins 0, 1, and 2). I don't know if i can connect on the pins TX and RX (they seem to work).

# Answer
> 1 votes
**So here are your needs:**

* WiFi, which uses pins 4, 10, 11, 12, 13. I know you said that you don't need pin 4 since no SD, but because that pin switches on/off the SD card, if you use it at all. Note: As Connor Wolf points out, it's not really relevant when there's no SD card. If you're facing problems with the Ethernet shield using the LCD additionally, you might have to reroute pin 4.
* LCD, which uses pins 4, 5, 6, 7, 8, 9. The standard Arduino LCD library can use any pins, but your shield is hard wired to use those. As mentioned before, you can reroute them if you want to. Below is the method for rerouting pins.

---

## Rerouting pin 7 (you need to do this!):

* Bend pin 7 on the LCD shield and the WiFi shield outward so it doesn't make contact with the header
* Use `LiquidCrystal lcd(8,9,3,5,6,2);` if you're rerouting pin 4, or `LiquidCrystal lcd (8,9,4,5,6,2);` in your code if you're not rerouting
* Attach a jumper between the pin 7 on the header of the WiFi shield and the pin 7 on the Arduino Uno
* Attach a jumper between the pin 2 of the WiFi shield (or the Uno, if that's easier) and the pin 7 of the LCD using the free space of the pin bent above it.

This will isolate pin 7 on the LCD, still send the pin 4 signal to the WiFi shield, and reroute the signal from pin 2 on your Arduino to pin 7 on the LCD shield.

---

## Rerouting pin 4 (optional):

* Bend pin 4 on the LCD shield and the WiFi shield outward so it doesn't make contact with the header
* Use `LiquidCrystal lcd(8,9,3,5,6,2);` in your code
* Attach a jumper between the pin 4 on the header of the WiFi shield and the pin 4 on the Arduino Uno
* Attach a jumper between the pin 3 of the WiFi shield (or the Uno, if that's easier) and the pin 4 of the LCD using the free space of the pin bent above it.

This will isolate pin 4 on the LCD, still send the pin 4 signal to the WiFi shield, and reroute the signal from pin 3 on your Arduino to pin 4 on the LCD shield.

---

For number of pins, you should be fine. You can use pins 0 and 1 (TX/RX) **as long as you aren't connecting to the computer or any other UART device** (i.e. using the `Serial()` library). Don't forget you can use the analog pins as digital pins by referencing them as `A0` to `A5`.

---
Tags: arduino-uno, pins, shields, wifi
---


# Question
Title: Why doesn't the master branch BOSSA work on Arduino Due?
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, 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?

# Answer
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.
> 1 votes

---
Tags: arduino-due, bootloader, bossa
---


# Question
Title: XBEE WiFi S6B RSSI for Smartphone localization
I am building an early prototype, proof of concept, network monitoring tool. A big part of it uses localization of a Smartphone. It seems that the best way to do this is using RSSI from multiple points. I plan to do this using several Arduino Fios with Xbee WiFi (S6B) cards.

My current setup has a network running from my smartphone (it is running DHCP) with a laptop monitoring all the traffic on the network.

What I need is for my Fio Xbees to dump the RSSI of the "access point" (Smartphone) onto the network so my laptop can pull the data.

Thus, to/from is not important as far as the packet is concerned, I just need the data dropped on the "wire" for my laptop to later parse, which is good because Serial.print\* sends out a broadcast to 255.255.255.255:fffff.

I can make my devices broadcast any integer, but when I go into AT mode nothing aside from the initial DHCP handshake gets put on the wire. Any ideas?

```
void setup() {
  Serial.begin(9600);
  Serial.flush();
  delay(1000);//enter AT mode start
  Serial.print("+");//AT
  Serial.print("+");//AT
  Serial.print("+");//AT
  Serial.flush();
  delay(1000);//enter AT mode finish
  while(Serial.available()>0){
    Serial.write(Serial.read());
  }

}

void loop(){
  Serial.println("ATDB");

  while(Serial.available()>0){
    Serial.write(Serial.read());
  }
  delay(750);//3/4 a sec
}

```

Note, `Serial.println("ATDB");` should cause the xbee to drop the RSSI on the wire; see XBee\_WiFi\_AT\_Commands.pdf at digi.com.

The three "+"s at the start are how you move the device into AT mode; see Digi\_International\_90002124\_G.pdf at mouser.com.

Once again what I am trying to do is get the collected RSSI information dropped onto a wifi connection from multiple xbee WiFi S6B equipped Fios.

# Answer
> 1 votes
Just incase anybody stumbles onto this page googling, I am posting my solution below (I *think* it will work for any xbee radio)

Basically for some reason the RSSI values are getting nulled out before I can read them, both in my API mode tests and AT commands. I'm not convinced that there is not some way around this in API mode at least, but it is irrelevant for my current purpose.

What I did was wire pin 6 on the xbee to a digital pin on the Arduino (I used 7) then use a pulse detector to find the period of the wireless signal coming in.

```
int pin = 7;
unsigned long period;

void setup(){
  Serial.begin(9600);
  pinMode(pin, INPUT);
  Serial.println("Getting started");
}

void loop(){
  delay(100);
  period = pulseIn(pin, HIGH);
  Serial.println(period);

}

```

It is not perfect, but for now it works, might help someone else in the future.

---
Tags: wifi, xbee
---


# Question
Title: How do I initialize a servo object in my own library?
I'm trying to make my first library for Arduino and want to use a servo object in my library. How can I do this?

# Answer
This should give you an idea of how to create a custom library which you can use in your project. I actually compiled it with Arduino IDE 1.0.5 on Mac OsX. I did not run it on an Arduino board, but have similar code in a production project, that works just fine.

Start a new Arduino sketch, name it as you like.

Go to the folder where you saved that file.

Add a new file called MyServoLib.h parallel to your main project file.

In your main file, include the servo library from Arduino and your custom library like so:

```
#include <Servo.h>
#include "MyNewLib.h"

```

If you close and reopen your project, it the Arduino IDE will automatically load your custom library file as well.

Copy the following simple stub code into your custom library file:

```
#ifndef MY_SERVO_LIB_H__
#define  MY_SERVO_LIB_H__

#include <Servo.h>
#include <Arduino.h>

class MyServoLib
{
public:

  MyServoLib()
    : _servoPin(9)
    , _attached(false)
  {}

  void attach()
  {
    if (_attached)
      return;

    _attached = true;
    _servo.attach(_servoPin);
  }

  void detach()
  {
      if (! _attached)
          return;

      _attached = false;
      _servo.detach();
  }

  void setPin(int pin){
    _servoPin = pin;
  }

private:

  bool _attached;
  Servo _servo;
  int _servoPin;

};

#endif

```

Your main file should look like this:

```
#include <Servo.h>
#include "MyNewLib.h"

// use your custom lib here
MyServoLib myServo;
int MyServoPin = 5;

void setup(){

  pinMode(MyServoPin, OUTPUT);
  myServo.setPin(MyServoPin);
  myServo.attach();

  // your additional setup code here
}

void loop(){

  // your main code here

}

```

That's it!

Upload it to an Arduino board and give it a try. The servo won't move, but it should get powered on.
> 2 votes

# Answer
**This is a simple solution.** All you need to do is declare a *global variable* (i.e. make it accessible everywhere in your sketch), and then add some additional code to "share" the servo between the different parts of the code.

## Code you need:

**Your library:**

```
Servo servoname;
void foo() {
  //Some code here!
}

void bar() {
  //More code here!
}

```

The methods `foo()` and `bar()` are irreverent to the code, you just need to declare it.

**Your library header file (`name.h`):**

```
extern Servo servoname;

```

All you need to do then is import your new library and use `servoname`. You will have to still call `servoname.attach([pin]);` before you can use the servo, but then you just need to use the servo.

*Source*
> 1 votes

# Answer
If your question is about **including library A inside library B and then including library B in your main program**, then you need to be aware of a limitation of Arduino IDE (discussed in this answer to a similar question).

Arduino IDE (at least 1.0.x, I have not checked with 1.5) for an obscure reason will not include libraries included by other libraries.

The only way to work around this issue is to include ALL libraries (direct **and** indirect) in your main program file (`.ino` file):

```
// Needed by library "B"
#include "A.h"
// Needed by your program
#include "B.h"

void setup() {
    // You can use B stuff here
}

void loop() {
    // You can use B stuff here
}

```

Another workaround is to trash Arduino IDE and use a better (I mean a real) IDE: many good options have been discussed in this question.
> 0 votes

---
Tags: library
---


# Question
Title: How to catch the Enter key received by Bluetooth?
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

```

# Answer
> 4 votes
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 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);

```

---
Tags: bluetooth, display
---


# Question
Title: Can I write to Flash Memory using PROGMEM?
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?

# Answer
> 9 votes
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:

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

---
Tags: progmem, memory-usage
---


title: Interference at digital input (UNO)

text:
# Question
Title: Interference at digital input (UNO)
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.*

# Answer
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.
> 5 votes

---
Tags: arduino-uno, pins
---


# Question
Title: Arduino Uno and Leonardo SPI clock can't be measured
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.

# Answer
> 4 votes
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);
  }
}

```

---
Tags: arduino-uno, arduino-leonardo, spi
---


title: Pull Chain Switch

text:
# Question
Title: Pull Chain Switch
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!

# Answer
> 2 votes
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.

---
Tags: arduino-uno
---


title: Which voltage regulator should I use?

text:
# Question
Title: Which voltage regulator should I use?
A friend and I are working on building a smartwatch on a budget, so it’s a (very) low power project, but we are currently having a problem with the power supplying. We already chose this board, because of its size and the BLE chip: RFduino BLE SMT For now on, we are planning to use this battery 500 mAh LiPo battery (approx. 4V at full charge) with this voltage regulator Micrel MIC5209-3.6YS (the board supports 3.6V max.).

But the problem is that the Voltage Regulator will apparently drain by itself too much energy from the battery (by heating), reducing drastically the autonomy.

So we would like to know if you guys can help us, if you can tell us exactly what (type of) regulator would be the best or if we need to find another battery.

# Answer
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.
> 1 votes

---
Tags: battery, bluetooth, electronics
---


# Question
Title: SeeedDuino/Grove and the story of not being able to upload programs
I am new to the arduino world and wanted to start playing with the micro controllers, I am a .NET developer by trade so not completely new to this kind of world.

I purchased a seeedduino v3 and a Grove started kit (No soldering skills here) and can't even get the basics to work.

I am setting up a simple button to light up the LED program. I have had it run once or twice but it seems really hit or miss on whether or not the Arduino IDE actually gets the program onto the seeedduino.

***Arduino IDE (1.5.6-r2) set-up:*** Followed setup instructions found here: SeeedDuino v3

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

***Program:***

```
int button = 3;
int LED = 7;

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

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

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

```

Upload Verbose Message:

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

avrdude done.  Thank you.

```

I have only had the LED from this program turn on twice, then reloading it ruins it.

***SIDE NOTE***

If I try and run Burn BootLoader I get this message-

```
avrdude: Version 5.11, compiled on Sep  2 2011 at 19:38:36
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2009 Joerg Wunsch

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

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

```

# Answer
> 4 votes
OK mystery solved!

I ended up getting Visual Micro Debugger plug-in for my Visual Studio 2013 since I am native .NET programmer. I could see that the code was indeed loaded onto the board and when I pressed the button it was indeed getting to the line of code for setting the digital LED to HIGH.

It was a very unfortunate case of trying different components and learning I actually had 3 dead LEDs and one bad cable. After getting functioning ones it's all good. :) unlucky me just had 4 bad parts in my kit.

Output from Visual Studio Debugging:

```
Legend:
line 12 = button state check
line 16 = button pressed turn on LED
line 20 = button not pressed turn off LED

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

```

---
Tags: uploading, bootloader
---


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

```
#define BFFSZ 90
char bffr[BFFSZ];
char bffridx;

void loop()
{
   readline();

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

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

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

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

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

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

```

The debug-line makes that I can see the data flowing, eg when I phone the SIM.

But it looks like the buffer isn't tested properly. The first two will work, but the last test fails. It is part of a larger string: `$0,7,j,BLINK,567^` But I thought the `strstr(1,2)` searches for 2 in 1. And as `0,7,j,BLINK,` is within the haystack I assume it wil return true. But apparently not...

The `gsm.SimpleRead2()` comes from GSMlib and is my altered version of gsm.SimpleRead(). Instead of printing the char, I just return it so we can buffer it in the `readline` function.

```
void SIMCOM900::SimpleRead()
{

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

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

```

Does anyone know the answer to this?

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

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

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

```
String buffer_string_serial;

void setup() { //code here }

void loop() { //code here }

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

```

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

---
Tags: arduino-uno, programming, sketch, string, testing
---


# Question
Title: How can I convert Arduino String to C string type?
I got a `String` which as I understand is an Arduino object, and got some C++ code:

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

LiquidCrystal_I2C lcd(0x20,16,2);

boolean borrar = false;
String IP;

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

}

void loop() {

  while (Serial1.available()) {

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

    switch(caracter) {

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

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

                IP.concat(caracter);
                break;

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

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

  } //fin switch

}//serial disponible

}//fin programa

```

However, this won't compile because of this line:

```
int num= atoi(IP.c_str())

```

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

# Answer
> 3 votes
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** 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)

# Answer
> 6 votes
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.

# Answer
> 2 votes
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.

---
Tags: c++, data-type
---


title: Control/count rotations of a DC motor

text:
# Question
Title: Control/count rotations of a DC motor
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?

# Answer
> 2 votes
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.

# Answer
> 3 votes
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.

---
Tags: motor
---


title: Seeed Studio motor shield

text:
# Question
Title: Seeed Studio motor shield
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. 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.

# Answer
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 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.
> 1 votes

---
Tags: motor
---


title: Matching Baud Rates

text:
# Question
Title: Matching Baud Rates
So I am working on speeding up a nixie tube speedometer, in this question: , but this brought up another question. Would having matching baud rates for multiple external devices speed up processes.

In the case of the other question the OBD-II device is running at 38400 where the Nixie Tubes are running at 9600. Since I'm taking the info from the OBD-II connector and doing a little math and sending it to the Nixie Tubes, would it be beneficial to have the same baud rate for both devices?

Now... before you down-vote this question for making some sort of "duplicate" this also answers a question about having a "master" serial hub and having communication between different "slave" serial devices.

# Answer
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.
> 2 votes

# Answer
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.
> 0 votes

---
Tags: arduino-uno, serial, uart
---


# Question
Title: How to use components that don't have a shield?
I recently started messing around with an Arduino and I have made a few "gadgets" using shields. I then wondered how I would go about using things I can't find shields for.

One specific thing I want to do is to be able to use the larger e-paper displays from Pervasive Displays (7'' and 10'') but a brief consultation with Google found no Arduino kits or shields. I then looked through the documentation of the timing controller for the 7'' display and found the information required to be able to use it (initiation, sending data to be drawn, opcodes, etc.). I then decided to check the Github repo for the examples for the 2'' displays and they seem to just do what the documentation says to do.

Is my observation naive here? Is it really as straightforward as following the documentation? No magic sauce?

Note: I don't have a clue how complex using the 7'' display actually is, I just used it as an example because I had just looked it up...

# Answer
Your observation is correct. Everything breaks down to some number of physical connections and some protocol for communicating with the device. Shields and libraries associated with them do most of the work for you, but not everything comes in a shield.

There are some common protocols for interfacing with devices, including SPI and I2C. From a quick peek at the driver interface sheet, it looks like they're using SPI. Well, your Arduino already supports that so you can hit the ground running with this display. You just need to know what commands to send to it, which you can find from the display's datasheet.

**Note:** It looks like the 2" screen requires 3.3V while the 7" one supports up to 7V.
> 4 votes

---
Tags: shields
---


# Question
Title: How do I use the timers on an Arduino Uno R3?
I want to make a simple circuit which returns the time/delay between two, consecutive loud sounds (i.e, a mic reading of ~600) coming from a speaker. I have set up and ADMP 401 microphone for this purpose. How do I measure the time it takes for this application?

# Answer
Your question is probably not as simple as it may seem.

One approach I would use if I was to address this same problem would consist in:

1. converting the analog output of the mike into a digital value (based on a threshold to determine)
2. connect this digital signal to one Arduino pin that can trigger an interrupt when its level changes

Let's first start with the easy part: Arduino program.

Let's say we have a digital signal that raises to 1 as soon as a sound of too high amplitude is captured by the mike; it shall stay 1 as long as the sound does not reduce amplitude enough. We will connect this signal to Arduino pin 3; then we can use `attachInterrupt()` to have a function called whenever this pon level raises to 1:

```
volatile static bool started = false;
volatile static unsigned long timing = 0;
volatile static bool finished = false;

void loud() {
    if (started) {
        timing = micros() - timing;
        started = false;
        finished = true;
    } else {
        timing = micros();
        started = true;
        finished = false;
    }
}

void setup() {
    pinMode(3, INPUT);
    attachInterrupt(1, loud, RAISE);
}

void loop() {
    if (finished) {
        // Do something with timing
    }
}

```

Now the hardest part: electronics!

A first issue we have to deal with is related to the fact that the raw mike signal will have same wave shape as the sound it captures, this wave has a frequency that can vary between 10Hz (bass) and 20KHz (treble).

Indeed, if we convert the mike analog output to a logical value (`1` when the analog value is above a threshold we'll call `Vt`, `0` when it is under `Vt`) fast enough, then, if the environmental sound as an amplitude above `Vt`, the logical input connected to your Arduino will oscillate at the same frequency as the sound! This would make our efforts pointless as you would measure the period of the sound wave instead of the elapsed time between two distinct sound bursts.

That means that we should probably first "smoothen" the analog sound signal in order to avoid disturbance of its frequency.

Hence point 1 will have to deal with these 2 aspects:

* smoothen analog input value
* compare smoothened value with `Vt` threshold and provide a logical value from this comparison

Comparison can rather easily be performed by an op-amp used as a comparator.

However, the main difficulty you may have with an op-amp is the need for a symetric voltage supply (e.g. +5V/-5V) although it is possible to use a single supply but that raises further limitations (outside the scope of my answer).

Smoothening the signal is potentially more complex, although it can be done with a simple capacitor, because smoothening the signal generally means weakening it, thus you would lose the initial amplitude of the sound signal.

So how can we deal with that?

A Schmitt trigger is probably a good solution for this problem but further experiment will be needed to confirm that.
> 2 votes

# Answer
When you mentions "loud sounds (i.e, a mic reading of ~600)" I'm guessing that means you've successfully connected the mic to an ADC input and you are referring to analog readings, right? (If not you may need to clarify). I won't worry about scaling or offset biasing the inputs, assuming you have that part down and you can test the Analog input to detect loudness.

If your Arduino can be dedicated to making this measurement (ie: doesn't need to do anything else while doing it), then the simplest solution might be a loop comparing the ADC input with some threshold you have determined, and using micros() to check the time different. The micros() function has only 4 uS resolution, but the loop time will add more time than that anyway, and actually the limited bandwidth of your audio signals (speaker and mic both) will make any microsecond level measurement suspect anyway. So the simple loop might be as accurate as you need.

For example:

```
const int THRESHOLD = 600; // adjust
const int MINDELAY = 1000;  // adjust

long
takeMeasurement() {
    while(analogRead(A4) < THRESHOLD); // wait for first trigger
    long start = micros();
    delayMicroseconds(MINDELAY); // let first noise die down
    while(analogRead(A4) < THRESHOLD); // wait for second trigger
    return micros() - start;
}

```

You would call this function when you were ready to take a measurement. To keep the loop time short (when it's waiting for a loud sound), it has no timeout, so it won't return until it does detect two loud sounds. Depending on your need, you might need to change that and have an escape from the loops. There are several ways that might be done:

* test for micros() exceeding some timeout within the loop
* decrement a counter in the loop and exit if it goes to zero (or if the sound is detected)
* test a flag (volatile byte) in the loop, which gets set by a timer interrrupt

Which is best depends on other aspects of your overall design.
> 1 votes

---
Tags: arduino-uno, timers
---


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

# Answer
As described in the Wire library that brings supports I²C support to Arduino, except for the **DUE** that has 2 pairs of pins for 2 I²C buses, **other Arduino boards support one I²C connection**.

However, this is when you want to use hardware facilities of ATMEL chips that these limitations apply; there is a software I²C library exists that allows using other pins for I²C. One major drawback, though, is that it is very slow; not sure if this is a problem in your situation.

One important thing though: the principle of I²C is to be able to plug several slave devices (more than 100) to one master device. In general, Arduino is the master device, but the Wire library can be used as master or slave. Wouldn't that fit your requirements?

In this situation, you could just use the same I²C bus for everything, including connection to Fischertechnik TX controller.
> 0 votes

---
Tags: robotics, i2c
---


# Question
Title: Arduino Mega & WiFi Shield; why web server every time says my A7 pin reads 0V?
I have got Arduino Mega 2560, Arduino WiFi Shield and resistor 1.5K.

Now PWM 2 is attached to the resistor then attached GND. 5V is attached between PWM2 and resistor's up point. I want to read the Arduino Mega's A7 analog input point in order to print this value on an Android Phone's web browser but, I get zero value every time surprisingly. It should be like 235, 350 something like integer or float kinds as usual.

According to Android Phone's Google Chrome Web Browser Page, why there are too many zeros in the HTML? It should be different from zeros because I have already added a short wire to Analog A7 so as to make an antenna.

A photo of my setup:

Screenshot of my Android web browser

Serial Monitor output

My code:

```
#include <SPI.h>
#include <WiFi.h>

char ssid[] = "Connectify-me";
char pass[] = "***";
int status = WL_IDLE_STATUS;
float PPG = analogRead(A7);
boolean door_status = false;
WiFiServer server(80);
void setup() {
  Serial.begin(9600);
  while ( status != WL_CONNECTED) {
    Serial.print("Yazdigin SSID araniyor: ");
    Serial.println(ssid);
    status = WiFi.begin(ssid, pass);
    delay(10000);
  }
  server.begin();
  printWifiStatus();
}
void loop() {
  WiFiClient client = server.available();
  if (client) {
    Serial.println("Deger gonderildi");
    Serial.print(PPG);
    while (client.connected() & client.available()) {
          client.println("<html>");
          client.println("<body>");
          client.println("<li>");
          client.print(PPG);  //The value should different from zeros but everytime 0
          client.println("</li>");
          client.println("<br />");
          client.println("</body>");
          client.println("</html>");
      }
    }
    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();
}

```

# Answer
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.
> 2 votes

# Answer
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.
> 2 votes

---
Tags: arduino-mega, shields, wifi, web-server, web-service
---


# Question
Title: High precision timing on Arduino for serial communication
I am using an Arduino Uno to send time and voltage information over the serial port to Python to plot. However the interval timings between successive time stamps appears to be increasing over time, affecting my plotting. This is especially true when the baud rate is set to 9600, where my initial time differences maybe 1320 and increases to 16400 after a relatively short period of time. When this rate is put to maximum of 115200 bps the change is slower and less noticeable, from around 1340 to 1500 even after a relatively long run of sending. All times are given in microseconds.

I would like to know if I can reduce or eliminate this effect, and if not understand why it exists. I have read things about interrupts and delays causing this, but I do not fully appreciate the complexity of the electronics at hand and would like to know:

1. Can I get greater precision in the timing?
2. What causes this change in timing?

Here is what I currently have:

```
#include <eHealth.h>

extern volatile unsigned long timer0_overflow_count;
float fanalog0;
int analog0;
unsigned long time;

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

void loop() {
  while (Serial.available()>0){
    serialByte=Serial.read();
    if (serialByte=='S'){
      while(1){
        fanalog0=eHealth.getECG();
        // Use the timer0 => 1 tick every 4 us
        time=(timer0_overflow_count << 8) + TCNT0;
        // Microseconds conversion.
        time=(time*4);
        //Print in a file for simulation
        //Serial.print(time);
        //Serial.print(" ");
        Serial.print(fanalog0,5);
        Serial.print("\n");

        if (Serial.available()>0){
          serialByte=Serial.read();
          if (serialByte=='F')  break;
        }
      }
    }
  }
}

```

# Answer
> 4 votes
Use a timer and ISR (interrupt service routine) to make timing more accurate.

Take a look at my 1ms timed interrupt Proof of Concept. The idea is to have a reasonably accurate 1ms 'heartbeat' in the system that can be used to trigger other events. In the PoC it is used to blink an LED at ½Hz, but having access to the new variables `millisecondCounter` and `secondCounter` enables you to trigger events in the main loop at arbitrary (but accurately timed) moments.

# Answer
> 3 votes
I can think of a few things that can impact the "consistency" of the serial write timings:

* size of the data to be printout

this may be the most obvious thing to think of, but indeed the more you print, the more it'll take to handle it.

Solution: print format the string into a string of known length.

* using buffered serial

on unix you can access the serial port using a buffered or an unbuffered way. Using the buffered way for a long time may make it a bit slower as the buffer fills, usually it happens when data is incoming faster than you're reading it…

Solution: use the unbuffered serial line (*e.g.*: on Darwin/OSX it's `/dev/cu.usbmodemXXX` instead of `/dev/tty.usbmodemXXX`)

* priority of the timers

it looks like your using a TC interrupt, and AVRs have priorities in the way interrupts are handled, I don't know the order of priority for the Atmega328, and it's not one of the most documented feature around, so I don't know how safe is TC0 versus the UART interrupt.

Solution: look up further in the documentation/datasheet about interrupt priorities and change the timer if needed ; and/or do a test without having the other timer running.

* the data you're reading from takes more time to read from over time

some drivers need to average or do some operations over the previous values, so the more values you measure, the longer the buffer is, and the longer it takes to calculate the value, until you've reached the maximum size of the buffer.

Solution: look at the source code of the library you're using, and either optimize it, remove the calcul if there's one or take that increasing processing time into account.

* avoiding the arduino framework overhead

but if you *really* want to optimize serial output from the arduino, you should avoid using the arduino overhead… But it's way less elegant and comfortable to use.

I'm pretty sure there are other points I'm missing, but that's the first things that I'd check before digging further.

HTH

# Answer
> 2 votes
Your code includes the duration of the output in subsequent measurements. Thus depending on the length of the output you will measure different times. This can be fixed by formating to fixed length output.

The next issue is that the UNO has a very poor timebase. Have a look here for a comparison of different Arduino types vs. the DCF77 time reference.

Conclusion: if you need precise timing either get an Arduino with crystal or go for an RTC. I can highly recommend DS3231 / DS3232 RTCs since these usually achieve 2 ppm accuracy out of the box.

---
Tags: arduino-uno, serial, time
---


title: Level detection of 3.3V from 5V arduino

text:
# Question
Title: Level detection of 3.3V from 5V arduino
A quick question about microcontroller digital level on I/O pins. I have a photo interrupter which is powered at 3.3V which is interfaced to Arduino UNO running at 5V.

For microcontroller to detect high or low level is determined by signal higher than 5V\*(2/3) = 3.33V is high and signal lower than 5V\*(1/3) is low. What I don't understand is that arduino is able to detect the level change from the photo interrupter. Doesn't the supply on pins have to be greater than (2/3) or Vcc in order for it to detect logic high? The circuit works and I am able to count pulses from the interrupter but I want to know why that works considering the photo interrupt only gets about 3.23V.

Please clarify

# Answer
> 8 votes
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.

# Answer
> 4 votes
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.

---
Tags: voltage-level
---


# Question
Title: Serial.read has garbled data after a Serial.write
I'm using the `Serial1` of the Arduino Leonardo to send and receive data with another MCU. The following code will always retrieve garbled data:

```
byte streamReadResponse;
Serial1.begin(115200);
Serial1.setTimeout(9000);
Serial1.print(cmd);
Serial1.print('\r');
Serial1.flush();  //wait for all the data to be sent to the serial
streamReadResponse = Serial1.readBytesUntil('>', data, dataLength);

```

But, if I add a `delay(50)` before the Serial1 read, I would get the expected output. The value 50 was found by trial and error.

What am I missing? Why is the `flush()` command not working as expected?

# Answer
> 2 votes
I've finally found that when the MCU to which Arduino is talking to was initialized, it would send spurious data to the Serial - I guess it would start first with a lower baud rate, and then switch to the programmed baud rate of 115200.

To fix this, I had to `flush` the Arduino serial RX before sending any data. So:

```
byte streamReadResponse;
Serial1.begin(115200);
Serial1.setTimeout(9000);
while (Serial1.read() >= 0)
           ; // do nothing
Serial1.print(cmd);
Serial1.print('\r');
Serial1.flush();  //wait for all the data to be sent to the serial
streamReadResponse = Serial1.readBytesUntil('>', data, dataLength);

```

# Answer
> 0 votes
Usually, this kind of issue is the result of the several times by time unity of loop statements execution, with the baudrate defined for your serial i/o it's very possible that the flush are override by the new information input and the result are the "garbage" on that.

On my sketches, ever I put "idle function calls" in some points of the code to avoid this and works succesfully.

---
Tags: serial, arduino-leonardo
---


title: Larger NFC antenna?

text:
# Question
Title: Larger NFC antenna?
Goal: I would like to be able to transfer some information to an Arduino Uno board via an NFC shield/antenna. The situation requires that the NFC tag may potentially hit anywhere within a circular area about a 12 inches in diameter.

Is it possible to increase the size of an NFC antenna? Possibly creating a loop antenna whereby the tag could be read from anywhere inside the loop.

I was thinking maybe if that isn't possible, it might be better to create an antenna array spanning the size of the area needed. Though I may have problems with overlap or double reads this way.

Has anyone attempted this before?

Note: I am not worried about increasing the z distance from the plane, just the x/y range. In fact, I still want the z distance to be very short as to not interfere with other antennas nearby.

# Answer
In general the size and geometry of the antenna is directly related to the carrier frequency. The antenna is tuned to the output signal of the transmitter/receiver. If you change an optimized antenna, it is no longer optimized and its performance will drop. So you can't keep extending an antenna, trying to improve its range.

The important question to be asked is if the existing antenna is already optimally sized for the transmitter/receiver. With these small things transmitter/receiver and antenna are usually closely matched. Even if the antenna is smaller than expected by math, the transmitter/receiver connected to it may be compensated for that.

With a receiver or a **low*** power transmitter, there is no harm in testing another antenna, but you'll probably won't improve performance much.

---

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

---
Tags: arduino-uno, sensors, proximity
---


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

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

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

# Answer
I'd personally recommend a continuous rotation servo or a brushed DC motor. Personally, for this kind of load, I think it would be easier and cheaper to go with the brushed DC motor. You have to remember a continuous rotation servo is a DC motor with some circuitry so you can send pulses to it to control the speed (although it's not directly proportional to the signal you send).

A servo is the only other option besides a brushless motor; both require a little more circuitry than the brushed motor/continuous servo. The additionally cost more. This blog post covers the differences between brushed and brushless motors.

For driving a continuous, you hook it up to power \[depends on your servo voltage\], ground, and another Arduino pin and use the servo library to send a signal as a degree (90 = no speed, 180 = full speed forward, 0 = full speed backward).

A brushed you would need a h-bridge that allows you to either send voltage, send no voltage, or send reverse voltage (for backward). This chip (~$5) does that for two motors and allows PWM for different speeds. It also includes a brake function, although that doesn't seem necessary for you. It can handle up to a "2.4 A continuous (4 A peak)." I talk about this in this answer of mine.

Quick note, if you want to control the *exact* RPM of the device and not just manually adjust it to a good rate, you'll need some sort of a rotary encoder or similar. A reed switch (sends current depending on magnetic fields) would work perfectly for this purpose, just mount it below the magnets and figure out the degrees rotated by the motor for each "pulse."
> 2 votes

# Answer
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.
> 1 votes

---
Tags: motor
---


# Question
Title: Default value of global variables is not set
I am tracking a bug in the Marlin source code.

**Background**

Just for those who is not familiar with Reprap 3D printer and G-code: Marlin is firmware that controls a RepRap 3D printer. It receives G-code from a host computer (or read from SD card). Here the important thing is that if you send the "M114" command, it would report information about axis positions. Here, I extended this command to make it print some internal variable as well.

**The Problem**

In Marlin.ino file there is a line that says:

```
volatile int extrudemultiply=100; //100->1 200->2

```

However my RepRap keeps extruding (and worse, ejecting back) a huge amount of filament. So I added some debug output for `M114` command to output this value. It turns out this value is not the default value, 100, but something like 12374.

I thought somewhere inside the `setup()` function this value might be changed. So I defined another variable,

```
volatile int orig_extrudemultiply = 100;

```

And then at the first line of `setup()` function, I added the following line.

```
orig_extrudemultiply = extrudemultiply;

```

Finally, I output this value for the `M114` command. Still, it is not 100. So it looks like the default value is not effective.

**The Question**

Although I have experience in C programming, I am new to Arduino development. How is a global variable being initialized in Arduino? In my case, what is the proper way to initialize this value?

**Versioning**

I originally posted the official Marlin link for the reference. However, the version I actually use is this fork from the RepRap Pro team. I was just following the Melzi entry of the RepRap wiki, because my board is Melzi. I am not sure whether the latest version of Marlin works for my board.

**Further details**

As the commenter said, the first thing I thought of was memory corruption. So I wanted to narrow the problem down. Since that value is configurable through `M302 SXXX` command, I tested this command, and it works without difficulty. This means there is nothing in the `loop` function or the ISRs can affect this value when it is running stably. So I consider the problem must be in the `setup` function or earlier.

Further tests shows that setting this value at the end of `setup` or even at the beginning of `setup` still works fine. This means the `setup` function may not be the problematic one. The test in "The Problem" session was the last step, which, in my opinion, means the course of the problem must being run before entering `setup`.

**UPDATE**

Further examination shows that although it looks like it works when I set the default value in the first line of `setup()`, but that it is just luckily being 100. So once I add more padding variables it stops working until I move the default setting after the following line in `setup()`:

```
EEPROM_RetrieveSettings(); // Loads data from EEPROM if available

```

However, since I `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.

# Answer
> 2 votes
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.

# Answer
> 2 votes
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.

---
Tags: programming, variables
---


# Question
Title: How to test the sleep / enable function of Stepper Driver?
I am currently using an Arduino Mega 2560 to run this stepper motor driver (Big Easy Driver, ROB-11876 from sparkfun) https://www.sparkfun.com/products/11876.

I am trying to use the sleep or enable function on this chip to decrease the power consumption when I am not using the motor. I have all the rest of the driver working properly (steps, direction etc.) but when I hook up a wire to either the sleep or enable section and send a respective high or low it doesn't appear to do anything. (Chip works as normal, power consumption stays the same).

I have tested to see that the Arduino is outputting correctly and it seems to be. But other than this I'm kinda at a loss on what might be wrong.

Does anyone have any suggestions on why this might be or other things to test to try to narrow down the problem?

---

Found my answer from Sparkfun - see below

# Answer
> 1 votes
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

---
Tags: pins, arduino-mega, motor
---


# Question
Title: How can the Arduino Uno support up to 12 servos if it only has 6 digital PWM pins?
According to this:

> The Servo library supports up to 12 motors on most Arduino boards and 48 on the Arduino Mega. On boards other than the Mega, use of the library disables analogWrite() (PWM) functionality on pins 9 and 10, whether or not there is a Servo on those pins. On the Mega, up to 12 servos can be used without interfering with PWM functionality; use of 12 to 23 motors will disable PWM on pins 11 and 12.

However, according to this:

> Digital I/O Pins 14 (of which 6 provide PWM output)

So how can the Uno control more than 6 servos if it only has 6 digital I/O pins that can provide PWM output?

# Answer
Although I haven't looked at the source myself, in these types of situations they usually use interrupt timer 1, which in PWM mode would have been associated with pins 9 and 10. This would explain why you can't use pulse width modulation on those pins. In fact, you can use any of the three timers for PWM on any digital pin, although it's not as good as the built in PWM options.

> <sub>(source: bansky.net)</sub>

*(Source)*

The above image accurately describes how the signals are sent to the servo motor. Such a waveform is similar to a standard PWM. The servo library can translate a degree to a waveform that the servo's IC will be able to use to adjust the motor's position with it's motor and potentiometer.
> 5 votes

---
Tags: arduino-uno, pins, motor, pwm, servo
---