# Question
Title: Is it possible to transmit Longitude and Latitude via RF433MHz?
I want to make a drone project, and to that I will use arduino as the platform. My plane is to use a Play Station controller to control the Drone in the air. In addition to that I want to connect a GPS-module. My question goes, is it possible to transmit the longitude and latitude from the GPS via the RF 433MHz to the receiver? When received the longitude and latitude how can I transmit them further to the Smartphone and display the data on google maps? I suggest it could be possible through the Xbee, but I am not sure.

I would like if someone can confirm my idea, if not bring me a better way to do that.

In the image below, you can see the diagram of my design.

# Answer
Your design suffers several redundancies that should be fixed. First of all, you have an Xbee (only one, not a pair) *and* a a 433 MHz transmitter/receiver combo. **Why not just add another Xbee to the drone and remove the RF combo?** That would save a little battery life for the receiver end, and a lot of your time. You'll also get two way communication with error checking. Although an Xbee would increase your project size a *little*, if you manually wired the Xbee instead of a shield (3.3V), it would save a lot of space.

As some people point out, Bluetooth is a viable option that's fairly small and low cost. However, it would suffer shorter ranges and it would need a special configuration on the host side for a BT stack.
> 0 votes

# Answer
If you are using Xbee modules in your project, why add 433MHz RF, just for the sole purpose of transmitting the location? With the 433Mhz, you will have to implement error-correction yourself.
> 2 votes

---
Tags: arduino-uno, sensors, xbee, android, map
---


title: Arduino time(milli) and pressure sensor

text:
# Question
Title: Arduino time(milli) and pressure sensor
I've succeeded to get an Arduino to work with a pressure sensor.

What I want to do is

* when I put pressure on the sensor, after 5 minutes the led lights on.
* it starts over again if there's no pressure on the sensor.

Here's the program:

```
// FSR is verbonden met analoog 0
int fsrAnalogePin = 0;
// De LED is verbonden met pin 11 (pmw pin)
int LEDpin = 11;
// De analoge waarde van de fsr spanningdeler
int fsrWaarde;
// De helderheid van de led tussen 0 en 255
int LEDhelderheid;

void setup() {
    // start de serial monitor
    Serial.begin(9600);
    pinMode(LEDpin, OUTPUT);
}

void loop() {
    fsrWaarde = analogRead(fsrAnalogePin);
    // print ‘Analoge waarde’
    Serial.print(“Analoge waarde = “);
    // print de fsrwaarde op de monitor
    Serial.println(fsrWaarde);

    // maak van getallen tussen 0 en 1023 getallen tussen 0 en 255
    LEDhelderheid = map(fsrWaarde, 0, 50, 0, 255);
    analogWrite(LEDpin, LEDhelderheid);
    delay(100);
}

```

I've got this for the pressure sensor... now I need to combine it with 5 minutes and the led lights on when it's reached that 5 min of pressure.

i managed to do this but it aint enough...

```
unsigned long currentTime;
unsigned long startTime;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  currentTime = millis();
  startTime = currentTime;
}

    void loop() {
  currentTime = millis();
  // put your main code here, to run repeatedly:
  Serial.println(currentTime);
  delay(1000);

  if(currentTime-startTime > 6000) {
Serial.println("1 minuut voorbij");
startTime = currentTime;
  }
}

```

# Answer
> 1 votes
Try this:

```
unsigned long pressureOnTime; //millis() time when pressure switch is first turned on

const unsigned long ledOnAfterTimeThreshold = 300000; //5 minutes * 60 sec * 1000 mSec
int pressureThreshold = 1; //minimum analog reading from pressure sensor considered to be "on"

const int fsrAnalogePin = 0;
const int ledPin = 11;

int ledState = LOW;
int pressureState = LOW;

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

void loop() {
    checkPressureSwitch();

    //do other stuff here
}

void checkPressureSwitch() {
    if( analogRead(fsrAnalogePin) >=  pressureThreshold )
    {
        handlePressureOn();
    }
    else
    {
        handlePressureOff();
    }

    digitalWrite(ledPin, ledState);
}

void handlePressureOn() {
    if ( pressureState == LOW )
    {
        //pressure switch was off, but is now on
        pressureOnTime = millis();
        pressureState = HIGH;
    }

    else if ( millis() - pressureOnTime >= ledOnAfterTimeThreshold )
    {
        ledState = HIGH;
    }
}

void handlePressureOff() {
    ledState = LOW;
    pressureState = LOW;
}

```

# Answer
> 0 votes
The very simplest way - not necessarily the best way - is something like:

> ```
> Keep re-reading the pressure sensor until it senses pressure;
> Read millis(), add 300000 (# of msec in 5 min) to it's value, and store that;
> Keep re-read millis() until it returns a number >= to that stored value;
> Read the pressure sensor;
> If it senses pressure,
>   turn on the alarm;
>   do nothing, forever;
> Otherwise, start over again;
>
> ```

It isn't the best way, because the Arduino does nothing else for the 5 minutes until the final sensor check. But as you're learning, you probably don't need it to do anything else - for now. When that time comes, there are better ways than dedicating your processor to watching the clock. But this will get you started, and you may figure out some of those ways on your own, by then. Good luck!

Update: I realized my answer does not account for the possibility that pressure is released from the sensor and reapplied some time later, if both occur within the 5 minute wait. How you treat that situation will depend on the needs of your application (which I'm guessing is for you to learn to work with time and physical data). I'll leave that as a further exercise for you.

---
Tags: arduino-uno, time, millis, timing
---


# Question
Title: Communication with two XBee's and Arduinos over serial
I have two XBee's connected to two Arduino Uno boards (one for each XBee). I connected each XBee to the X-CTU software, and have set the following:

*XBee 1*

`Pan ID = 4270
DL = 10
MY = 20`

*XBee 2*

`Pan ID = 4270
DL = 20
MY = 10`

*Both*

`DD = 10000
IC = FF
IR = 32`

Therefore, they should be on the same network and see each other as the 'other person' each is talking to. I'm using the TX and RX pins of the arduino and the XBee to communicate over the serial port.

When testing if each can hear the other, I loaded one arduino with this code:

```
#include <SPI.h>

void setup() {
// put your setup code here, to run once:
  Serial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
  Serial.print('x');
  delay(1000);
}

```

Then another with this:

```
#include <SPI.h>

void setup() {
// put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(7,OUTPUT);
  digitalWrite(7,LOW);
}
void loop() {
// put your main code here, to run repeatedly:
  if(Serial.available())
  {
    char getData = Serial.read();
    if(getData == 'x')
    {
      digitalWrite(7,HIGH);
      delay(500);
      digitalWrite(7,LOW);
      delay(500);
    }
  Serial.print(getData);
  getData = ' ';
  }
}

```

This works perfectly. One LED will light up on the correct arduino in half second intervals. However, when I try to make them both communicate at the same time to each other, nothing happens. Neither LED will light up. The code for both arduino's is:

```
#include <SPI.h>

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(7,OUTPUT);
  digitalWrite(7,LOW);
}

void loop() {
  // put your main code here, to run repeatedly:
  Serial.print('x');
  delay(1000);
  if(Serial.available())
  {
      char getData = Serial.read();
      if(getData == 'y')
      {
        digitalWrite(7,HIGH);
        delay(500);
        digitalWrite(7,LOW);
        delay(500);
      }
      Serial.print(getData);
      getData = ' ';
    }
}

```

But for one arduino I change the code to `Serial.print('y')` and `if(getData == 'x')` to listen for the other one. I also have tried delaying one arduino in the setup by one second to offset the sending and recieving, but that also doesn't help.

I need them to be able to listen and talk to each other, maybe even at the same time like this example. I'm trying to create a proximity sensor in, lets say the 'back', area communicate with the 'front' area, and an accelerometer and two switches from the 'front' communicate with the 'back'.

Is there any settings I can change in X-CTU, such as the baud rate or the amount of packets re-sent, to overcome this problem? Or is this merely a code issue?

I do have the power connected to the 3.3V pin of the arduino, and I'm using 470/220 Ohm resistors as voltage dividers for the output pins from the arduino to the XBee, so I don't think voltage is an issue here.

Also, I have disconnected the arduino from the computer. I'm powering it via the USB-A to USB-B cord -\> 13000 mAh 5V DC rechargeable battery, so there should be no interference with the serial data lines. Pin 2 (RX) of the XBee is connected to pin D0 (RX) of the arduino, and pin 3 (TX) of the XBee is connected to pin D1 (TX) of the arduino.

Thanks for your help.

# Answer
Did you set one of your modules into coordinator mode? Every xBee network needs a coordinator. Therefore, you need to put one of your Xbee modules into coordinator mode using the "Function Set" dropdown box in X-CTU. The coordinator has the fixed address 0, so you need to set DL and HL address parts of the other module to 0. On your coordinator, you can set DL to FFFF and HL to 0, which is the broadcast address.

Softserial won't help you. It's just a way to use some of the pins as an additional serial port. Don't use that if you can use a hardware serial port.
> 3 votes

---
Tags: c++, xbee
---


# Question
Title: Can Arduino Mega2560 Use this 24VDC Relay?
Can a Arduino MEGA 2560 R3 provide enough current out of its pin to activate the Songle srd-24vdc-sl-c relay? Will powering the Arduino with an external power supply help?

# Answer
> 1 votes
This relay cannot be **directly** commanded by any Arduino because its coil require **24V voltage** to be able to switch the contact; Arduino Mega pins output voltage is **5V**.

Regarding **current**, the **relay coil needs 15mA** ("high sensitivity" model) **or 18.7mA** (standard model), that would be OK for an Arduino Mega pin (**max current = 40mA**).

Anyway, you would have to add some circuit to adapt voltage between the Arduino pin and the relay. For this, first of all **you will need to get a second power supply** (in addition to the Arduino 5V supply used for Arduino) that can supply 24V.

Then you could use a MOSFET transistor between the Arduino pin and the relay. A MOSFET is often used in so-called **Solid State Relay** (SSR) because it can almost do the same as a coil relay but is 100% electronic-based (no moving parts); however, contrarily to a coil relay, it does not provide galvanic isolation between the input and the output circuits.

You can check out this question to find out further information on MOSFET.

Personnally, I would rather replace that relay with a 5V relay model, as that would make the circuit simpler, and would remove the need for a second power supply.

---
Tags: arduino-mega, relay
---


# Question
Title: Arduino Uno + Ardumoto + BT robot works from USB but not from baterries
My Arduino UNO board is part of a small robot that works when connected to the laptop by USB but it does not when plugged to the batteries. The baterries plug seems okay, it outputs 7.8 V. My UNO is connected to an ArduMoto board that manages the robot motors as well as a bluetooth chip. I have little experience with Arduino or electronics in general so I am stuck on the best course of action.

1) Can I find out what is wrong with the power supply without completely isolating UNO from the robot?

2) If I separate UNO, how can I find out with certainty if my UNO power supply is damaged or not? Is there something in particular that I could measure with my multimeter?

UPDATE

After fully charging my batteries I observed that the LEDs attached to the motor outputs are blinking fast. They blink for about one minute then nothing happens anymore. On USB everything works as expected. Those LEDs show that signal is going towards the motors, but why is it so different to USB? On USB power, the LEDs blink only when I command the robot to move through the BT board while under baterries they blink furiously for a minute and that is all that happens.

I also don't know what happened to the batteries, they seem to be fully drained in just one minute, but I don't know how to test that, they appear to still have high voltage.

I use two LC 18650 4800 mAh 3.7 V UltraFire baterries. The motor shield is Ardumoto Keyes\_L298P, very similar to Sparkfun's Ardumoto shield.

I do not have the actual code that is on my Arduino. It must be similar to the code on this page, since I am using their Android app for BT communication with my robot, and it works on USB power supply.

# Answer
> 1 votes
Are you powering the motors with a separate supply, and not direct from the Arduino? Motors should be powered separately and the power only switched by the Arduino. Otherwise, their current draw could be pulling down your battery voltage. And even with USB power, they could be drawing more current than spec'd for either the USB power source or the Arduino's regulator or output pins. The chip itself is spec'd for a maximum current of 40mA per pin and 200mA total.

---
Tags: arduino-uno, shields, power, arduino-motor-shield
---


# Question
Title: Simple Script controlled by Raspberry not working
I can't figure out why the next script is not working. I have attached the Arduino to one USB port of the raspberry pi, in which I've installed pyserial. I just want to turn off/on a led depending of the number I write on the Raspi console (1-\> on, 2-\> off).

```
    int led=13;

void setup(){
  Serial.begin(115200);
  pinMode(led,OUTPUT);
}
void loop(){
  if(Serial.available()){
     mode(Serial.read() - '0');
  }
}
void  mode(int n){

    if (n== 1){
         digitalWrite(led,HIGH);
    }
    if (n== 2){
        digitalWrite(led,LOW);
    }
  }

```

PS: I double checked and the baudrate is configured also at 115200 at the raspi side. In addition, if I place digitalWrite(led,HIGH) just before the line "mode(Serial.read() - '0');" the led turn on when I send some information from the raspi shell (so, works well).

# Answer
> 1 votes
Finally I've found the error, it was the serial communication baud rate: 115200. It seems that at higher speeds it not works properly, lowering it to 9600 do the trick.

---
Tags: serial, led
---


title: Reverse turning of Stepper motor

text:
# Question
Title: Reverse turning of Stepper motor
I have a stepper motor connected to my Arduino like this using the ULN2003A Darlington Array:

(Ignore the potentiometer)

And I have programmed it with the following code:

```
#include <Stepper.h>

int in1Pin = 22;
int in2Pin = 23;
int in3Pin = 24;
int in4Pin = 25;

Stepper motor(512, in1Pin, in2Pin, in3Pin, in4Pin);

void setup()
{
    pinMode(in1Pin, OUTPUT);
    pinMode(in2Pin, OUTPUT);
    pinMode(in3Pin, OUTPUT);
    pinMode(in4Pin, OUTPUT);

    motor.setSpeed(25);
}

void loop()
{
    int steps = 360;

    motor.step(steps);
    delay(500);
}

```

At the moment the motor rotates clockwise, how could I have it so it rotates in the opposite direction?

My code was copied and edited from here.

---

The problem was that I had the two middle wires the wrong way round as said here: http://forum.arduino.cc/index.php?PHPSESSID=kvi8dt2b5en5hhk02dlmjrotl5&topic=143276.msg

# Answer
The answer is simple. Just pass a negative number of steps as an argument to `motor.step();`.

Another note: You forgot a semicolon on your second to last line. IIRC this doesn't matter in C, but **it's just bad practice to do this.** If you add a line of code below that, then it won't work.

Example code:

```
#include <Stepper.h>

int in1Pin = 22;
int in2Pin = 23;
int in3Pin = 24;
int in4Pin = 25;

Stepper motor(512, in1Pin, in2Pin, in3Pin, in4Pin);

void setup()
{
    pinMode(in1Pin, OUTPUT);
    pinMode(in2Pin, OUTPUT);
    pinMode(in3Pin, OUTPUT);
    pinMode(in4Pin, OUTPUT);

    motor.setSpeed(25);
}

void loop()
{
    int steps = 360;
    motor.step(steps);
    delay(100);

    steps = -360;
    motor.step(steps);
    delay(500); //Semicolon added
}

```
> 2 votes

---
Tags: programming, motor
---


# Question
Title: Arduino 1 can somehow support 32-bit audio?
I wanted to take the audio from a device such as the PC, insert it through different ADC in arduino, processing them with DSP and DAC REnter all through to the other speakers, reading here and there on the internet but some people were put in difficulty because Arduino has a data bus to 10 bits. What problems can cause this? I can not send the same 10 bits at a time, until you arrive at 32?

# Answer
> 1 votes
First of all,*what is the point of this?* I'm afraid this is a XY question. You won't get that good of quality with Arduino. If you're hoping to create some sort of an amp, learn electronics and do that directly. Maybe you should just send data via serial.

Anyway, that aside, here's a chart I drew:

(Excuse my poor image alignment, PowerPoint was being a little mean today)

The bottom is all the "channels" the PC can send. The top is all the "channels" the Arduino can recieve. As you can see, there's a *huge* degradation in quality. Not to mention, I made this that 1 bit = 1 "channel," yet it's very much more than that.

A standard Arduino (Uno, Leonardo, etc.) has a 10 bit ADC that can read values 0-1023. The computer can output 0-4294967295! (It' exponentially grows due to permutations). You can see why I very much simplified my chart! :P

DSP won't really work well, unless you are trying to do some weird alien sounding modifications or a cheesy echo to. You probably will want to add an external 32 bit ADC. I would recommend, additionally, adding a Due or Galileo that can process 32 bit integers without emulating a bigger chip, thus greatly reducing performance and giving you a low framerate.

tl;dr: It'll work fine, but it'll have horrible sound quality. You can't send the same 10 bits until 32, since the computer changes that 32 bits into a voltage (sent to Arduino), and the Arduino translates that voltage into 10 bits.

---
Tags: arduino-uno
---


# Question
Title: Custom Arduino board beeps and process freezes while I'm uploading a sketch to it. Why?
The strangest thing is happening to a standalone Arduino board that I designed and built. The board (whose schematics are below) has the following features:

1. It has a ATmega328P with a 5V voltage regulator and usual circuitry when set up as a standalone controller.
2. It controls a scoreboard with several 7-display digits linked through the connectors on the right (JP1 through JP12).
3. It has cursor buttons decoded using a voltage ladder through ANALOG\_0 (A0).
4. It has a Real Time Clock to keep time when it's turned off.
5. It has an RF receiver module.
6. It has a UART header (JP17) so I can program the board using a serial port.
7. It has a speaker attached to digital pin 3 (D3).

I upload sketches to it using a RS232-to-TTL adapter that I've also built (schematics also below) and a Serial-to-USB cable. When programming it, the board behaves much like a Severino board.

What's strange is that, when I upload a sketch, the process is paused in the middle and then the speaker starts to beep continually. It pauses with the following avrdude messages:

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:\arduino-1.0.3\hardware/tools/avr/etc/avrdude.conf"

     Using Port                    : \\.\COM1
     Using Programmer              : arduino
     Overriding Baud Rate          : 115200

```

When I press reset on the board, avrdude continues outputting its messages (such as below), the beep stops, the upload continues and the sketch is uploaded successfully to the board.

```
avrdude: Send: 0 [30]   [20]
avrdude: Send: 0 [30]   [20]
avrdude: Send: 0 [30]   [20]
... messages and upload continue and completes successfully.

```

I don't have the rest of the messages handy here, but I hope you get the idea.

So, my questions are:

1. **What is making the upload process pause?**
2. **Why is the buzzer beeping when the process pauses?**

# Answer
> 4 votes
> What is making the upload process pause?

Well, given all the comments made under your question, this is definitely a tricky one. You might want to try to add a decoupling capacitor as suggested by @jfpoilpret, though your schematics look alright to me… (maybe ask a review of it on EE SE).

I'd also advice you to copy the `avrdude` command from Arduino IDE output (you'll find it at the top), and run it in the command shell with lower bitrate:

```
avrdude -v -v -v -v -C "C:\arduino-1.0.3\hardware/tools/avr/etc/avrdude.conf" -P COM1 -patmega328 -U… -B3 -b115200

```

the higher the `-B` value is the lower your bitrate is. and `-b` to the correct baudrate for your bootloader (are you *sure* this is 115200? it's more common to see 57600).

Did you also set fuses correctly? You might as well want to check the values of the fuses to see if the clocks are correctly set up:

```
avrdude -U lfuse:r:-:i -U hfuse:r:-:i -U efuse:r:-:i

```

which will output the values of the fuses. Then to make the values readable, put the values at the bottom of the form on the fuse calculator site, after choosing the `Atmega328P` MCU from the dropdown list.

Double check that:

* you have enough size for the bootloader (usually the more you give it the better it is) ;
* you have correctly set up the cristals configuration for your design (which may not be compatible with default Uno settings as setup by the Arduino IDE), checking if you correctly set up the external crystal at 16MHz…

> Why is the buzzer beeping when the process pauses?

It's because when the processor does not have the output set up, the values within the registers are in an undefined and unpredictable state. Which means that usually it keeps the last value it had before a reset, or changed state because of some electrostatic weirdness, or is giving some weird PWM output because of the influence of a clock nearby.

So basically, there's something wrong happening when you're uploading your code and that wrong thing has an indirect effect on the audio. I wouldn't worry much about that stuff, but more about the cause of the pausing.

Sadly, I don't have a direct answer for you, but at best a few paths you should investigate more. HTH

# Answer
> 3 votes
I finally found what was causing the problem: the reset signal from pin 4 (DTR - Data Terminal Ready) on the DB9-Female connector was spiking up to 10V before going to 0V and was triggering high-voltage programming on the ATmega. Below is a scope shot showing the situation:

The yellow trace is `DTR` signal while the green trace is the `RESET` signal on the ATmega.

According to Atmel's Atmel AVR042: AVR Hardware Design Considerations application note, one should add an ESD diode between ATmega's `RESET` and `Vcc` to prevent the reset signal from triggering high-voltage programming mode, like so:

After adding such a small signal diode (1N4148) like the app note recommended, I got the issue fixed. See below the scope shot taken after the diode was added.

Now the 10V peak is gone.

That was a tricky one!! But I could never find what was wrong without research and the right tools. Money on a scope is money well spent!!

# Answer
> 1 votes
I'm not sure but the problem may also be related to the auto-reset feature of the converter board.

I copied the converter board design from the Arduino Severino and according to its manual, the serial communication must be set to 19,200 bps for the auto-reset feature to work.

> Be sure that computer COM Port speed is set to 19200bps otherwise auto reset will not work properly.

Well, I'm using 115,200, so that must be a problem.

---
Tags: severino, serial
---


# Question
Title: Getting the contacts/ storing contacts to SIM card
I have the GSM shield and is there any ways to get the stored contacts on the SIM card? It seems that the GSM library does not support writing data onto/ reading data from the SIM card?

My aim is to store the SIM card's phone number and some variables onto the SIM card itself, such, I would not need to change the program from time to time.

All I need to do is enter all the variables in the SIM card via any mobile phone (perhaps by storing the variables as contacts, as phone book function should be very common on phones).

# Answer
What have you researched so far? Following the link you have given for the shield, about the third line of the description is a reference to the AT Command Set used by the chip.

I just did a couple of quick searches through it and found:

> `2.2.4 ATD><n>` Originate phone call to number in memory
>
> `3.2.26 AT+CPBF` Find phone book entries
>
> `3.2.27 AT+CPBR` Read current phone book entries
>
> `3.2.28 AT+CPBS` Select phone book memory storage

probably a good place to start.
> 6 votes

# Answer
Thanks to @Madivad for the AT command inspiration. I am not very familiar with GSM and Arduino. But anyway, the below worked for me.

Credits to @Madivad and people from the arduino forum.

```
#include <GSM.h>
GSM gsmAccess(true);
int sizer = 200;
char myNumber[200];
int timeout = 5000; // in milli seconds

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

  boolean notConnected = true;

  Serial.println("Connecting to the GSM network");

  while(notConnected){
    if(gsmAccess.begin() == GSM_READY) // Note: I do not require PIN #
      notConnected = false;
    else {
      Serial.println("Not connected, trying again");
      delay(1000);
    }
  }

  Serial.println("Connected");

  theGSM3ShieldV1ModemCore.println("AT+CPBS=\"SM\"");
  int start1 = millis();
  while((millis() - start1) < timeout){
    Serial.print(theGSM3ShieldV1ModemCore.theBuffer().read());
  }
  Serial.print("Set to look at SIM card storage");

  // search for contact name "test"
  theGSM3ShieldV1ModemCore.println("AT+CPBF=\"test\"");
  start1 = 0;
  start1 = millis();
  while((millis() - start1) < timeout && !theGSM3ShieldV1ModemCore.theBuffer().extractSubstring(",\"", "\",", myNumber, sizer)){
    Serial.print(theGSM3ShieldV1ModemCore.theBuffer().read());
  }
  Serial.print("Got contact number");

 // print out the phone of "test"
 Serial.println(myNumber);

}

void loop()
{

}

```
> 2 votes

---
Tags: gsm
---


# Question
Title: Figuring out some numbers for a mini pump
I'm just now getting into electronics (I don't know why I waited so long) and I'm just figuring out some stuff. I picked up an Arduino kit from Vilros.com and a few other parts for my project.

I'm currently trying to work on a project that is basically a humidor keeper. Living in So.California, it's extremely dry here and I would like a perfectly controlled environment for my humidor. I purchased a few things like some humidity sensors (as an input obviously), a humidifier (basically a water canister with a sponge and tubes) some tube splitters and twist valves and most importantly, a small air pump.

The small air pump is what I'm having problems with at the moment. This is the pump. Obviously it's a 3v pump. I will be using the supplied 9v battery cable when the project is ready, so I understand I'll have to use resistors to bring the voltage down so I don't burn out the pump. As I said, I'm new to this, so I'm trying to figure out ohms law to find out what kind of resistor(s) I will need. The problem is, I don't know the amperage. Where would I find this?

I looked at the details for the pump and what looks like amps (or milliamps) is really just the product number. Can anyone help me out?

Right now, I have my equation as r=6v / ?i But where do I find the current?

# Answer
There are two serious problems with your approach, which you will need to change in order to end up with a sound solution.

* If by "9v battery cable" you mean that you intend to use a 9v battery, this is highly unsuitable for motor applications given its low power storage capacity and high internal impedance - without extreme care to use sleep modes, it probably can't even run the Arduino alone for a week. It would be much more appropriate to use a larger capacity lower voltage source - 4 or 5 C or D cells for example. A power supply could be another option, though given the water involved, be very careful to pick an isolated one and use a ground fault protected outlet.
* Resistors are a poor way of reducing the supply voltage to a motor, as they are not only wasteful, but the applied power will depend too much on the load. A professional solution would use pulse with modulation to apply the supply voltage at a reduced duty cycle - something you can try with one the various motor shield, but you will need to be careful not to overheat the motor by using too high a duty cycle.

Probably your best bet would be to buy a pump with a 6 or 7v motor (as is showing up in the associated products at the bottom of that page), or even replace the standard-form-factor motor in that pump with a higher voltage one. A 7v or so supply voltage can then be a compromise solution for running both the motor and the arduino.
> 2 votes

# Answer
Unlike voltage, which depends on the source, the current depends on the motor itself. To find the current, you need to run the motor and measure it with a multimeter:

```
              +------------+
    +---------+ Multimeter |
    |         +--------+---+
+---+---+              |
| Motor |              |
+---+---+  +--------+  |
    |      | Power  +--+
    +------+ source |
           +--------+

```

Note that when the motor is actually pumping, it will draw more current.
> 1 votes

---
Tags: arduino-uno
---


# Question
Title: client.connect() fails except the first time
I am communicating with the Web server's database via Arduino GSM shield + GPRS connectivity

```
void loop()
{
  if (client.connect(server, port))
     {
       .......
      }
  else
     {
      Serial.println("Server not found");
      }
  delay(1000);
}

```

The first time when the loop() runs in the serial port, the code works perfectly and stores in my server's db. The second time when the loop() runs after some delay, It is unable to connect to the server and results "server not found" . I don't know what is the problem.

Please let me know if there is a way to connect continuously. Thank you

# Answer
> 2 votes
You have to disconnect before being able to connect again otherwise the controller will crash due to memory starvation. Every connect you do takes some memory to register state information. Not sure of the exact commands involved, but it'd look a bit like this:

```
   if (client.connect(server, port))
     {
       .......
       client.disconnect( .... );
      }
  else
........

```

Alternatively you can check if you are already connected, and only do a reconnect when necessary, but I don't know which library you are using, let alone if there is a proper check available in it.

# Answer
> 1 votes
```
void loop()
{
 if (client.connect(server, port))
 {
   .......

   client.stop();
  }

 else
 {
  Serial.println("Server not found");
  }
 delay(1000);
 }

```

# Answer
> 0 votes
If possible, do a check, if it's still connected with the server. Close the connection when work is done. You might also keep using the open connection, just try whatever works best for you.

But avoid opening a second connection, when you still have an open one. As an example:

```
void loop()
{
    if(!client.connected())
    {
        if (client.connect(server, port))
        {
            ...
            client.disconnect();
        }
        else
            Serial.println("Server not found");
    }
    else
        client.disconnect();
    delay(1000);
}

```

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


# Question
Title: If I put a shield on an Arduino, can I use the Arduino for anything else?
I did some basic Arduino examples in the recent past, but I have never actually seen a shield for Arduino firsthand.

So I wonder: If I put a shield on an Arduino (for example, the Adafruit Motor Shield), does it "block" the entire Arduino, including all input and output pins?

Is it possible to use a shield, and still connect additional components that would usually connect directly to the Arduino (say, a potentiometer, or anything similar)? Does this depend on the type of Arduino, or on the type of the shield, or is it not possible at all?

# Answer
Normally, yes, you may plug other components to your setup after you plug your shield, but it depends on the shield exposing the unused Arduino pins through additional female headers.

Some shields even provide a little protoboard or perfboard to make it convenient for plugging or soldering additional components. Below are some examples:

Arduino shields are normally designed to be stackable, so you can plug one on top of the other. See more on Arduino shields from this WikiPedia article. See below one example of stacked shields, shamefully stolen from this great answer by RedGrittyBrick.

<sup>*Photo by John Boxall*</sup>

But note that **you need to study carefully what pins each of the shields use to avoid conflicts between the boards**. Such conflicts may lead to damages.
> 15 votes

# Answer
There are several distinct concerns to consider:

* **Physical interference:** are headers provided to make it possible to stack the two shields on top of one another? Do any protruding components block stacking? Do any components have metal shield cans (for example the USB connector on the Uno itself) which can short out an adjacent PCB?
* **Pin assignments:** generally you cannot use the same pin for two different purposes. Many shield provide a way to alter the pins used in order to avoid those used by another shield. Sometimes you can share a pin, for example two SPI devices can usually share their clock and data lines provided they have separate selects, and you may be able to even use those signals for other purposes while the SPI select is de-asserted. Sometimes you can move a part from an unavailable hardware peripheral to a software emulated one, for example using software serial, bitbang SPI, or interrupt based PWM.
* **MCU resources:** Not specifically the shields themselves, but driver libraries may end up consuming large amounts of program memory or RAM, using up timer channels, needing interrupts frequently services with low latency, etc, so combinations may not be possible or may require alterations to library code.
> 7 votes

# Answer
As long as the shield uses stackable headers (or provides alternate headers) it doesn't block *any* (broken out) pins, either input or output. It is possible to add more shields or components, but the circuit must still be "valid" (all inputs must be either be connected to an output or have the pullup enabled, no more than one push-pull output connected together, etc.), otherwise components may be damaged.
> 3 votes

# Answer
Yes, but sometimes it interferes with the output and the input pin, and most shields use up the CS, MOSI, MISO, SCK pin. Even through on some shields like wireless SD shield you can switch from USB to MICRO, this is going to interfere with your program. Say, when you want to access the info on your SD card to run your Motor Shield.
> 1 votes

---
Tags: shields
---


# Question
Title: Set up an Arduino Cellular Shield SM5100B
I'm trying to set up an Arduino Cellular Shield SM5100B to send SMS.

My setup is:

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

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

# Answer
```
/*
 Band Management

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

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

 Circuit:
 * GSM shield

 created 12 June 2012
 by Javier Zorzano, Scott Fitzgerald

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

 // initialize the library instance
 GSMBand band;

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

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

 };

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

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

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

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

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

```
> 1 votes

---
Tags: gsm
---


title: Arduino Yún console clear

text:
# Question
Title: Arduino Yún console clear
I'm having a problem. I want to clear the screen on the connected console. And after the clear, I want to rerun my code. But I can't seem to figure out how to do it. Below is some part of the code:

```
#include <motorStyring.h>
#include <Bridge.h>
#include <YunServer.h>
#include <YunClient.h>
#define PORT 6666
motorStyring mt;
int cm;

  YunServer server(PORT);
  const int pingPin = 9;
  int led = 13;
    void setup() {

    Serial.begin(115200);
    Bridge.begin();
    server.noListenOnLocalhost();
    server.begin();
 }
    void loop() {
    long duration, inches, cm;
    pinMode(pingPin,OUTPUT);
    digitalWrite(pingPin,LOW);
    delayMicroseconds(2);
    digitalWrite(pingPin, HIGH);
    delayMicroseconds(5);
    digitalWrite(pingPin,LOW);
    pinMode(pingPin, INPUT);
    duration = pulseIn(pingPin,HIGH);
    cm = microsecondsToCentimeters(duration);
    h();
   }
    void h()
   {
    YunClient client = server.accept();
     if (client.connected()) {
      String question = "What would you like to drink?\nyou have 4    choises:\n1)Juice\n2)Vodca\n3)Soda\n4)Mix\n";
client.write((uint8_t*)&question[0], question.length());
String response;
while (client.connected()) {
  if (client.available()) {
    char cmd = client.read();
    if (cmd == '\n') {
      break;
    } else {
      response += String(cmd);
    }
  }
}
if (response == "juice") {
  juice();

} else if (response == "vodka") {
  vodka();

} else if (response == "soda") {
  soda();

} else if (response == "mix") {
  mix();

} else {

  String error = "you didn't select anything that corrospond to an option. \n try agin";
  client.write((uint8_t*)&error[0], error.length());
 }
   String awnser = "Here is your " + response;
   client.write((uint8_t*)&awnser[0], awnser.length());
 }
 delay(1000);
}

```

**...**

Is there a way to clear the screen on the console, so that all of the text from the previous code is not disturbing the user?

# Answer
> 1 votes
Perhaps you could count the number of lines in the console and the print out enough carriage returns (`"\n"`) to fill it with empty whitespace.

For example, with a console with 100 lines:

```
for(int iter = 0; iter < 100; iter++) {
   client.write('\n');
}

```

---
Tags: arduino-yun
---


# Question
Title: XBee, external libraries and passing structures as arguments
I have very weird problem with a library I am creating. The library will be used to communicate between Arduino modules using XBee Series 1 modules. Library is very simple wrapper library around Arduino XBee library.

I have one function that reads received packet and sends it back. At the moment it is implemented as a simple "echo" service - the function just displays the data received and sends it back to per-defined address.

At the moment I have three versions of this function, out of which one is not working.

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

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

Code:

**ExampleLib.h**

```
#ifndef ExampleLib_h
#define ExampleLib_h

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

#define ADDRESS_BROADCAST 0xffff
#define ADDRESS_PC 0x3333

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

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

#endif

```

**ExampleLib.cpp**

The value read in line `byte* packetData = rx16.getData();` is wrong when we trigger `processPacket(valuesStruct valuesStructData)` function. In other cases the behavior is correct.

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

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

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

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

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

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

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

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

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

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

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

```

**Arduino sketch**

```
#include <XBee.h>
#include <ExampleLib.h>

ExampleLib exampleLibObj = ExampleLib();

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

void loop()
{

  boolean isPacketReceived = exampleLibObj.tryReceivePacket();

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

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

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

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

```

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

Thanks!

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

---
Tags: c++, library, xbee, struct
---


# Question
Title: arduino 16u2 stk500v2_command(): command failed
I'm trying to fix arduino uno r3 that was burned-out. I changed m16u2 chip on it. and now I need burn in: `Arduino-COMBINED-dfu-usbserial-atmega16u2-Uno-Rev3.hex` I'm using stk500v2 and connecting it to isp of arduino. Output log file of avrdude:

```
C:\>avrdude -c stk500v2 -P COM4 -p m16u2 -U flash:w:1.hex -vvvv

avrdude: Version 6.1, compiled on Mar 13 2014 at 00:09:49
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\WinAVR-20100110\bin\avrdude.conf"

         Using Port                    : COM4
         Using Programmer              : stk500v2
avrdude: Send: . [1b] . [01] . [00] . [01] . [0e] . [01] . [14]
avrdude: Recv: . [1b]
avrdude: Recv: . [01]
avrdude: Recv: . [00]
avrdude: Recv: . [0b]
avrdude: Recv: . [0e]
avrdude: Recv: . [01]
avrdude: Recv: . [00]
avrdude: Recv: . [08]
avrdude: Recv: A [41]
avrdude: Recv: V [56]
avrdude: Recv: R [52]
avrdude: Recv: I [49]
avrdude: Recv: S [53]
avrdude: Recv: P [50]
avrdude: Recv: _ [5f]
avrdude: Recv: 2 [32]
avrdude: Recv: t [74]
avrdude: stk500v2_getsync(): found AVRISP programmer
         AVR Part                      : ATmega16U2
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PC6
         RESET disposition             : possible i/o
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page
      Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  Max
W   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ---
-- ---------
           eeprom        65    20     4    0 no        512    4    128  9000  90
00 0x00 0x00
                                  Block Poll               Page
      Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  Max
W   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ---
-- ---------
           flash         65     6   128    0 yes     16384  128    128  4500  45
00 0x00 0x00
                                  Block Poll               Page
      Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  Max
W   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ---
-- ---------
           lfuse          0     0     0    0 no          1    0      0  9000  90
00 0x00 0x00
                                  Block Poll               Page
      Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  Max
W   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ---
-- ---------
           hfuse          0     0     0    0 no          1    0      0  9000  90
00 0x00 0x00
                                  Block Poll               Page
      Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  Max
W   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ---
-- ---------
           efuse          0     0     0    0 no          1    0      0  9000  90
00 0x00 0x00
                                  Block Poll               Page
      Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  Max
W   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ---
-- ---------
           lock           0     0     0    0 no          1    0      0  9000  90
00 0x00 0x00
                                  Block Poll               Page
      Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  Max
W   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ---
-- ---------
           calibration    0     0     0    0 no          1    0      0     0
 0 0x00 0x00
                                  Block Poll               Page
      Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  Max
W   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ---
-- ---------
           signature      0     0     0    0 no          3    0      0     0
 0 0x00 0x00

         Programmer Type : STK500V2
         Description     : Atmel STK500 Version 2.x firmware
         Programmer Model: AVRISP
avrdude: Send: . [1b] . [02] . [00] . [02] . [0e] . [03] . [90] . [86]
avrdude: Recv: . [1b]
avrdude: Recv: . [02]
avrdude: Recv: . [00]
avrdude: Recv: . [03]
avrdude: Recv: . [0e]
avrdude: Recv: . [03]
avrdude: Recv: . [00]
avrdude: Recv: . [02]
avrdude: Recv: . [15]
avrdude: Send: . [1b] . [03] . [00] . [02] . [0e] . [03] . [91] . [86]
avrdude: Recv: . [1b]
avrdude: Recv: . [03]
avrdude: Recv: . [00]
avrdude: Recv: . [03]
avrdude: Recv: . [0e]
avrdude: Recv: . [03]
avrdude: Recv: . [00]
avrdude: Recv: . [02]
avrdude: Recv: . [14]
avrdude: Send: . [1b] . [04] . [00] . [02] . [0e] . [03] . [92] . [82]
avrdude: Recv: . [1b]
avrdude: Recv: . [04]
avrdude: Recv: . [00]
avrdude: Recv: . [03]
avrdude: Recv: . [0e]
avrdude: Recv: . [03]
avrdude: Recv: . [00]
avrdude: Recv: . [0a]
avrdude: Recv: . [1b]
         Hardware Version: 2
         Firmware Version Master : 2.10
avrdude: Send: . [1b] . [05] . [00] . [02] . [0e] . [03] . [94] . [85]
avrdude: Recv: . [1b]
avrdude: Recv: . [05]
avrdude: Recv: . [00]
avrdude: Recv: . [03]
avrdude: Recv: . [0e]
avrdude: Recv: . [03]
avrdude: Recv: . [00]
avrdude: Recv: U [55]
avrdude: Recv: E [45]
         Vtarget         : 8.5 V
         SCK period      : 0.1 us

avrdude: Send: . [1b] . [06] . [00] . [0c] . [0e] . [10] . [c8] d [64] . [19]
[20] . [00] S [53] . [03] . [ac] S [53] . [00] . [00] 5 [35]
avrdude: Recv: . [1b]
avrdude: Recv: . [06]
avrdude: Recv: . [00]
avrdude: Recv: . [02]
avrdude: Recv: . [0e]
avrdude: Recv: . [10]
avrdude: Recv: . [c0]
avrdude: Recv: . [c1]
avrdude: stk500v2_command(): command failed
avrdude: initialization failed, rc=-1
         Double check connections and try again, or use -F to override
         this check.

    avrdude: Send: . [1b] . [07] . [00] . [03] . [0e] . [11] . [01] . [01] . [00]
    avrdude: Recv: . [1b]
    avrdude: Recv: . [07]
    avrdude: Recv: . [00]
    avrdude: Recv: . [02]
    avrdude: Recv: . [0e]
    avrdude: Recv: . [11]
    avrdude: Recv: . [00]
    avrdude: Recv: . [01]

    avrdude done.  Thank you.

```

My question is what block with error does? can it be I shorted due soldering? or maybe burned chip? any issues? how I can check?

ps. programmer works perfect. checked!

# Answer
> 1 votes
Here’s a decoding of the crucial pair of messages exchanged here. Protocol is documented on Atmel’s site.

Your machine sends:

```
[1b]                              Beginning of message
[06]                              Message sequence number
[00] [0c]                         Message body length (big endian)
[0e]                              Beginning of message body
[10]                              Command: CMD_ENTER_PROGMODE_ISP
[c8] [64] [19] [20] [00]          Various programming parameters
[53]                              Response value to look for
[03]                              Response index
[ac] [53] [00] [00]               Enter programming mode command
[35]                              Checksum

```

This causes the programmer to send the 4 bytes `0xAC 0x53 0x00 0x00` to the MCU, and look for the value `0x53` in the third of the 4 response bytes, as specified on page 260 of the data sheet. However, the programmer answers:

```
[1b]                              Beginning of message
[06]                              Sequence number (matches message previously sent)
[00] [02]                         Response body length
[0e]                              Beginning of response body
[10]                              Command: CMD_ENTER_PROGMODE_ISP (Matches message)
[c0]                              STATUS_CMD_FAILED (This is the error message)
[c1]                              Checksum

```

That means that tyne very first command sent to the microcontroller “failed” (most likely by not returning the expected answer byte).

---
Tags: avr, avrdude
---


# Question
Title: Is the Sparkfun RedBoard pre-loaded with a blink sketch?
As soon as I plugged my brand new RedBoard (Sparkfun's Uno) into my computer, I saw the onboard LED (for pin 13) blink on and off every 1 second. This was before I even sent the first demo sketch to blink the LED. After I uploaded a sketch to change the blink time, the LED's blink cycle changed as I expected.

But why was the LED blinking *before* I sent my very first sketch? Is the RedBoard pre-loaded with a sketch?

# Answer
> 2 votes
Yes, the RedBoard is preloaded with the blink sketch (or at least the two that I've purchased have been).

---
Tags: arduino-uno
---


# Question
Title: How to read a Text file from server and store to a separate variable?
I am working on reading a text file from the server, using http://arduino.cc/en/Reference/GSMClientConnected. It gives me this code:

```
char path[]="/asciilogo.txt"

```

I want to store only the contents that are inside the text file to a variable (String). But `client.read();` only reads a single character at a time. Also, it takes all the HTTP, GET, TIME parameters together.

How to store only the contents that are present in the text file to a string variable?

# Answer
> 2 votes
Here is what I found:

You need to have a special character like "\*" (a delimiter), from which important data will flow through.

```
char z = '*';
int s=0;

void setup()
{
  // usual initialization
}

void loop()
{
  if (client.available())
  {
    char c = client.read();
    // Serial.print(c);
    if (z == c)
    {
      s=1;
    }

  if(s == 1)
  {
    int i=0;
    k[i] = c;
    i=i+1;
    // Serial.print(k);
  }

  place +=k;

  Serial.print(place);

  }

.......
}

```

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


# Question
Title: Arduino sizeof Servo array objects is.. wrong?
After searching *for a quite long while* over the internet, I have no choice but to try asking someone if they can explain me this apparently strange situation.

I'm doing some tests using some servo motors, trying to move them almost together using `millis()` and `Servo` object.

It is, of course, working either for single Servos and multiple servos.

The case, more detailed, is about this:

1. Move one, two or more servo motors together.
2. Force them to take ALMOST the same time to accomplish any action.
3. Have a dynamic number of servos.

About the first two points I had no problems to solve them, I was easily able to make a function and then make a library to accomplish such a job.

However, since I'm NOT that used to C++ and I was wondering if it actually was possible to create an array of Servo objects, like you can actually do, on arduino, with strings:

```
String stringArray[] = {"string1", "string2", "and so on, I love it."};

```

So, after wondering a while, I've tried this:

```
Servo servObject;
Servo servObject_2;
Servo servObject_3;

Servo servos[] = {servObject, servObject_2, servObject_3};

```

And you know what's cool? my function is actually working correctly by forcing the amount of elements of the servos array.

What I mean by that is that if I force my function to know that it is going to have 3 elements into the array it will, of course, work; However, for some reason, if I use `sizeof(servos);` the value returned, surprisingly, is `2`.... Moreover, if I only push two servo objects instead of three into the servo array, its `sizeof` returns `6`.

By googling, I've found out a couple of discussions about the fact that, for some reasons, in some cases, sizeof returns an incorrect value (if I'm not wrong it was the correct value -1), but in my case it apparently is not following any logic at all.

The board I'm using is an Arduino nano w/ ATMEGA 328.

Any idea of why it is not returning the correct value? Am I actually going totally wrong because I shouldn't make an array of servo objects?

ps: I didn't post the whole code because it would've been useless, since the sizeof is the first function called in the `loop()`

Regards,

briosheje

# Answer
> 7 votes
What you describe seems to be a common issue that many C or C++ developers can get (or have got) with `sizeof`.

Take a look at the following code:

```
char a[3];

int size(char b[]) {
    return sizeof b;
}

void setup() {
    int size1 = sizeof a;
    int size2 = size(a);
}

```

In that code, `size1` will be evaluated, by the compiler, to `3` which is the real size of `a` variable, whereas `size2` will be `2`.

## Why so?

This is just because `sizeof a` is evaluated by the compiler, and the compiler *knows* that `a` is an array of 3 `char`; but when `a` is passed as an argument to function `size()`, it is converted to a pointer (to the first element of the array), hence its size is the **size of a pointer**, which is `2` bytes on AVR ATmega MCU.

This subtlety of `sizeof` may explain strange values as you describe.

## How to fix the issue?

Most C functions that take an array as argument will require another argument that tells the size of the array; that's the way (the only one I think) to deal with this problem.

Here is a sample code:

```
Servo allServos[] = {...};
#define NUM_SERVOS (sizeof(allServos) / sizeof(Servo))
...
void handleServos(Servo *servos, int numServos) {
    for (int i = 0; i < numServos; i++) {
        servos[i].write(...);
        ...
    }
}

void loop() {
    handleServos(allServos, NUM_SERVOS);
}

```

It is common practice in C to **declare an array** and immediately after, **define its size** as above.

---
Tags: c++
---


# Question
Title: How Do I Properly Ground my Arduino Leonardo using Capacitive Sensor?
Hi we are using Arduino Leonardo with some electric paint and Capacitive Sensor Libraries. We have a lot of variance in our Serial output from our sensors, we believe if we grounded the Arduino we would have more concrete values.

On the Capacitive Sensor doc, it reveals to use a small capacitor to put on one of the pins. More details! Another guide somewhere says to wrap the Arduino in plastic and tin foil. These are vague, and we have not landed success when we tried.

Has anyone had success grounding Arduino Leo? Thank you.

# Answer
> 3 votes
The documentation for that library is recommending that you place a 100 pF capacitor between the sense pin and ground.

However, I personally suspect you will get the best results when the user's presence affects at small mutual capacitance between a sense surface and a ground surface.

One idea could be to have a large ground plane, and on it a smaller insulated "sense" plate.

Another could be to run two parallel traces in a spiral filling a large area

Do take care to secure you wires - they are part of your sensor too, and if they move relative to each other they will alter the baseline. Any other mobile cables in the vicinity can have the same effect, especially if they contain a ground that can exhibit capacitance to the sense node.

# Answer
> 0 votes
The simplest way to ground an Arduino is to attach the ground pin, found on the power header, to a grounded surface, like a metal pipe. As for the capacitor you mentioned, that is called a smoothing capacitor. It is a small capacitor, about 1microfarad, and goes between the supply of the sensor and the ground line.

# Answer
> -1 votes
It might help if you follow the diagram for connecting a button, that way the value of the capacitor sensor wont fluctuate...

*Photo from http://arduino.cc/en/tutorial/button*

---
Tags: arduino-leonardo
---


# Question
Title: digital pin's current limit, ohm's law and DC motor
A digital pin's output voltage on an UNO board is 5V, which is equal to the output from the VCC. I read that the DC current limits of those pins are 40mA and 200mA respectively, and that a higher current could damage the board. Now, since **V=RI**, I expect to get the same current whether I connect a DC motor to the VCC or to a digital pin. But, the motor spins slower when connected to the digital pin. Therefore, I'm not getting the same current, and the only thing I could think of in order to explain this apparent contradiction with ohm's law is that there must be some mechanism to keep the current flowing through a digital pin inferior to 40mA. But I also read somewhere (can't find/remember the source) that there are no such mechanisms (except for a fuse concerning the USB)... So as you see, I can't understand what's going on. It will be really nice if someone could explain that to me... thanks in advance!

# Answer
> 2 votes
The ATmega (or any other processor that could reasonably be used on an Arduino) output pins consist of a `Totem Pole` driver with a PMOS transistor which can drive the output towards Vdd and an NMOS transistor which can drive it towards ground. Each of these can be modeled as a switch which has a small resistance when "on", and due to device physics the PMOS transistor has a higher resistance than the NMOS.

The 40ma figure is an "Absolute Maximum" rating - a limit above which damage could be possible. At some current less than that, it is likely the voltage drop across the PMOS transistor will start to be great enough that the output voltage can only marginally be considered a logic "high" - it **will be notably less than the supply**.

Connecting your motor to an ATmega pin is an extreme, **far out of spec**. When you do that, the voltage drop across the PMOS transistor is much larger, making the output voltage quite low. Additionally, the current flowing through the resistance produces heat within the chip, which can (at least as a rule-of-thumb concern) lead to damage. Finally, your motor will produce `inductive kickback`, "spike" voltage possibly high enough to pierce the gate oxide of the MOS gates in the chip, destroying it. `Latchup` is another possibility - a *sometimes temporary* condition where the bulk of the die ends up biased to conduct in the wrong direction and the chip effectively shorts out its power supply, turning it into a *miniature space heater*.

**There really are no components on your typical Arduino board designed to directly control a motor.**

Instead, for unidirectional control you should use a circuit with an `NPN` bipolar transistor, `NMOS FET`, magnetic relay, or solid state relay. The latter are commonly available pre-assembled on shields. With a transistor solution driving the motor in only one direction, it is generally advisable to pick an NPN transistor or NFET and place it in the negative lead of the motor, as the N devices work better due to the greater mobility of electrons than electron-holes.

For bidirectional control, look for a `motor shield` based on an `H bridge` IC such as the `TB6612FNG` or the less efficient bipolar `L298` or `L293`/`SN754410`. This basically puts a high current `Totem Pole` driver on each lead of the motor, allowing you to drive them high & low for one direction or low & high for the other.

---
Tags: arduino-uno, motor, voltage-level, current
---


# Question
Title: Receive SMS example gives me a garbage values
When I run my Receive SMS example code, By default every time I get the same thing.I am trying to send sms to my sim card present in the Arduino GSM shield. I don't want this message. How to solve this problem ?

I

# Answer
> 2 votes
Most Telecom operators agree for sending advertisements and promotions to their customers for certain business and some money. You can stop these promotion for your mobile by making (Do Not Disturb)DND active. In India, just do the following for DND Activation

```
 ( Fully Blocked Category )

 Send SMS at START 0 to 1909 or Call at 1909

 Partial Blocked Category

Send SMS at START 1 to 1909 to block Banking – Insurance – Financial Products – Credit Cards
Send SMS at START 2 to 1909 to block Real Estate
Send SMS at START 3 to 1909 to block Education
Send SMS at START 4 to 1909 to block Health
Send SMS at START 5 to 1909 to block Consumer Goods & Automobiles
Send SMS at START 6 to 1909 to block Communication – Broadcasting – Entertainment – IT
Send SMS at START 7 to 1909 to block Tourism

```

---
Tags: arduino-uno, shields, gsm
---


# Question
Title: Can I turn off a device using the 5V and analog pins?
Could I connect a device that requires minimum 5V 1A from the 5V Pin to the Ground and somehow turn it off inside a sketch?

edit: I'm using a Due based boad, the digix http://digistump.com/wiki/digix/tutorials/basics

# Answer
You would use a transistor. Something like this would work.

In this case the Arduino controls a transistor to drive a brushless motor.

Source: Arduino Cookbook: (https://www.inkling.com/read/arduino-cookbook-michael-margolis-2nd/chapter-8/figure-8-9)

Update: For the sake of clarity I should point out that the TIP102 is the device to use for the 1A required (not the 2N2222). And as pointed out by others the 5V supply of most Arduino boards would not be sufficient to supply 1A, so an external supply would be advised.
> 7 votes

# Answer
*Short answer: NO*. It would fry your Arduino.

*Long answer:*

The current of Arduino pins is very limited (40mA max on UNO).

If you need to draw 1A, then you need a *transistor* between the Arduino pin and your device.

In such case, what you would normally do is:

* connect any Arduino logical pin to the transistor base (through a resistor),
* plug your device between a 5V supply (capable of 1A current providing) and the transistor collector,
* connect the transistor emitter to the Arduino GND pin (and connect that pin also to the 5V-1A supply)

Note that **you don't need to use an analog pin** for that, a logical pin is enough if you just want to switch the device on or off.

Now notice that I specified **a 5V 1A supply**, that should normally be **distinct** from the 5V pin of the Arduino.

So the next question is: **can you draw 1A out of the Arduino 5V pin?**

The Arduino UNO page does not specify the current limitation on that pin. However it mentions the following:

> 5V.This pin outputs a regulated 5V from the regulator on the board. The board can be supplied with power either from the DC power jack (7 - 12V), the USB connector (5V), or the VIN pin of the board (7-12V).

So the max current on this pin depends on 2 factors:

* what is the power supply for the board: it is either USB, or an external power supply, which can be connected to the power plug or to the Vin pin.
* the specs of the 5V regulator voltage on the Arduino board

If you use USB as power supply, then you are limited to **500mA** as stated in the Arduino UNO page:

> The Arduino Uno has a resettable polyfuse that protects your computer's USB ports from shorts and overcurrent. Although most computers provide their own internal protection, the fuse provides an extra layer of protection. If more than 500 mA is applied to the USB port, the fuse will automatically break the connection until the short or overload is removed.

If you use an external power supply that provides at least 1A, then we have to find out the max current by ourselves.

If we take a look at Arduino UNO schematics, then we see that this regulator is referenced as "**NCP1117ST50T3G**" (this is "**U1**" on the top-right corner).

The spec sheet for this regulator mentions that it can supply **1.0A**.

So in theory, that should work, however, you also have to consider that this regulator **also** supplies current to the Arduino borard itself and all its pins.

If you love your Arduino and don't want to fry it, you should probably stay away from using its 5V pin for your purposes.

Now if you're open to experiment, you may try it :-)
> 4 votes

# Answer
The simpler solution is to power Arduino from some external supply, then fork that power through a relay to controlled device.

Then you can switch the device by controlling that relay through your digital pin.
> 2 votes

# Answer
Have you try using a digital potentiometer name AD5220, it let you adjust the resistance with using your hand. You can find more info about it at www.analog.com. I would upload an image of the schematic but i just don't know how.
> -1 votes

---
Tags: programming, pins, power, voltage-level, analogwrite
---


title: SMS in modem's memory

text:
# Question
Title: SMS in modem's memory
I am working on SMS communication with my phone and Arduino. My intension is simple. When somebody send an SMS, the Arduino should read a text file located on my server and forward the content to the same number.

The problem here is, when I send an SMS to my Arduino, which is waiting for my message, it does not read my message. But when I separately run this example code, I see my SMS is received. It means my SMS is already present in the modem memory. But why does this happen? How to solve this? Here is my code:

```
// libraries
#include <GSM.h>

// PIN Number
#define PINNUMBER ""

// APN data
#define GPRS_APN       "GPRS_APN" // replace your GPRS APN
#define GPRS_LOGIN     "login"    // replace with your GPRS login
#define GPRS_PASSWORD  "password" // replace with your GPRS password

// initialize the library instance
GSMClient client;
GPRS gprs;
GSM gsmAccess;
GSM_SMS sms;

// URL, path & port (for example: arduino.cc)
char server[] = "yourdomain.com";
char path[] = "/current.txt";
int port = 80; // port 80 is the default for HTTP

char k[30];
char z = '*';
int s=0;
String place;
char remoteNum[20];  // telephone number to send sms

void setup() {
    // initialize serial communications and wait for port to open:
    Serial.begin(9600);
    while (!Serial) {
        ; // wait for serial port to connect. Needed for Leonardo only
    }
    Serial.println("SMS connected");
    // connection state
    boolean notConnected = true;
    while(notConnected) {
        if((gsmAccess.begin(PINNUMBER)==GSM_READY) &
           (gprs.attachGPRS(GPRS_APN, GPRS_LOGIN, GPRS_PASSWORD)==GPRS_READY))
            notConnected = false;
        else {
            Serial.println("Not connected");
            delay(1000);
        }
    }
    Serial.println("GPRS connected...");
    Serial.println("Server Connecting.");
    // if you get a connection, report back via serial:
    serverr();
}

void loop() {
    if (sms.available()) {
        Serial.println("Message received from:");
        sms.remoteNumber(remoteNum, 20);
        Serial.println(remoteNum);
        sms.flush();
        Serial.println("MESSAGE DELETED");
    }
}

void smss() {
  // I just want phone number
    if (client.available()) {
        char c = client.read();
        //***************************************************
        //       Filtering a specific message
        //**************************************************
        if (z==c) {
            s=1;
        }
        if(s == 1) {
            int i=0;
            k[i] = c;
            i=i+1;
            // Serial.print(k);
        }
        place +=k;
        //Serial.print(place);
    }
    //***************************************************

    if (!client.available() && !client.connected()) {
        sms.beginSMS(remoteNum);
        Serial.print("Place =");
        Serial.print(place);
        sms.print(place);
        sms.endSMS();
        sms.flush();
        Serial.println("MESSAGE DELETED");
        Serial.println();
        Serial.println("disconnecting.");
        client.stop();
        // do nothing forevermore:
        for(;;)
            ;
    }
}

// if you didn't get a connection to the server:
// Serial.print(server);

void serverr() {
    if (client.connect(server, port)) {
        client.print("GET /current.txt");
        Serial.print("GET /current.txt");
        client.println(" HTTP/1.1");
        Serial.println(" HTTP/1.1");
        client.println("Host: www.yourdomain.com");
        Serial.println("Host: www.yourdomain.com");
        client.println("User-Agent: Arduino");
        Serial.println("User-Agent: Arduino");
        client.println("Accept: text/html");
        Serial.println("Accept: text/html");
        client.println("Connection: close");
        Serial.println("Connection: close");
        client.println();
        Serial.println();

        Serial.println("\nCOMPLETE!\n");
        //client.stop();
    } else {
        Serial.println("connection failed");
        Serial.println("\n FAILED!\n");
    }
}

```

# Answer
I see one problem with the global structure of your program; everytime `loop()` is run, it:

1. checks if an SMS is present, and gets the originating phone number if present, otherwise it just goes on, ie `smss()` function returns **without** modifying `remoteNumber`
2. send an SMS to `remoteNumber`

One problem here is that your `loop()` will repeatedly try to send an SMS to the same `remoteNumber` even if no SMS was received; actually, to solve this issue, you should modify `smss()` to:

* either **wait (forever) for an SMS to be received** and return only in this situation
* or **return a value (eg `bool`) that indicates whether an SMS was received** or not; then an SMS should be sent if and only if an SMS was just received.

Here is an example:

```
void setup()
{
    GSM and GPRS initialization
    Connection to server
}

void loop()
{
    if (smss())
    {
        Reading the txt file content in server

        sms.beginSMS(remoteNum);
        sms.print(txtMsg);
        sms.endSMS();
    }
}

bool smss() // I just want phone number
{
    if (sms.available())
    {
        Serial.println("Message received from:");
        sms.remoteNumber(remoteNum, 20);
        Serial.println(remoteNum);
        sms.flush();
        Serial.println("MESSAGE DELETED");
        return true;
    }
    return false;
}

```

Note that this code does not integrate error support as it should; indeed `sms.remoteNumber()` may return error codes (any value `>1`), in which case you should consider no SMS was received at all.
> 1 votes

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


# Question
Title: Can I load programs through the RS232 pins?
Can I upload new programs onto a MEGA2560 through a serial port connected to pins 2&3? (through the correct RS232\<-\>TTL level shifters)

I know the 16U2 chip acts as a USB-\>serial converter and it also asserting the reset which starts the bootloader running on the 2650. Does it do anything else?

As long as I can time the reset correctly, is there anything else preventing reprogramming directly through the RX/TX pins?

And if I do this, will the application program still be able to use the serial channel?

# Answer
> 1 votes
The stock bootloader will accept the load of new programs on PE0(RX input) and PE1(TX output) (of the ATmega2560) just after reset. Note PE0/1 on the Arduino correspond to pins D0 and D1. Not D2 and D3. You could change the Boot loader if desired.

There is a 1K series resistor between the 16U2 and 2560's PE0/1. So you can directly connect your external TTL serial port's TX(out) to PE0(D0), without harm. And correspondingly connect PE1(D1) to the TTL Serial port's RX(in).

Next you need to synchronize the bootloader. Either by manually synchronizing the Reset of the 2560 with the starting of the download (of AVRdude). Or by connecting the DTR(out) of the TTL Serial Port through a 100nF capacitor to the RESET pin of the Arduino.

I would also recommend putting the 16U2 into reset, to get it out of the way. Simply place a jumper between ICSP1's RESET2(pin5) and GND(pin6).

---
Tags: arduino-mega, uploading, bootloader
---


title: What's the deal with Uno's pin 13 LED?

text:
# Question
Title: What's the deal with Uno's pin 13 LED?
(I have a Sparkfun RedBoard, but this question seems to apply to R3 Unos and Uno-compatible boards.) As I was building the first circuit in my SIK guidebook (add a resistor, LED, hook it up and make it blink from code), I noticed a blue LED on the board itself did everything that the circuit's LED did - blinking according to the programming.

Why is this LED here? What use cases is it for?

What kind of circuits will I have to adjust to account for this LED?

Is pin 13 traditionally a debug or a troubleshooting pin? Where did this convention come from?

# Answer
The LED on pin 13 is used by the **optiboot** loader (the one used on **UNO**):

* at Arduino **boot time** (the LED blinks a few times)
* when **uploading a sketch** to Arduino

I haven't checked other bootloaders, they may provide the same behavior as the optiboot.

For optiboot, there are optional defines (at compile time) to modify this behavior:

* `LED_START_FLASHES` defines the number of flashes of pin 13 LED at boot time (can be set to `0`)
* `LED_DATA_FLASH` will use pin 13 LED during sketch upload if **defined** at compile-time

These defines are explained in `hardware/arduino/bootloaders/optiboot/optiboot.c` from within your Arduino IDE install directory.

If you want to change these, you will have to recompile the optiboot loader first and then burn it to your Arduino through an **ISP programmer**.

I guess one other reason for the LED on pin 13 was to simplify the demonstration of the "*Hello World*" sketch for Arduino, namely the `Blink` sketch, without the need for any extra component.
> 11 votes

# Answer
> What kind of circuits will I have to adjust to account for this LED?

You'll need to take it into account if you're using that pin as a digital input.

> NOTE: Digital pin 13 is harder to use as a digital input than the other digital pins because it has an LED and resistor attached to it that's soldered to the board on most boards. If you enable its internal 20k pull-up resistor, it will hang at around 1.7V instead of the expected 5V because the onboard LED and series resistor pull the voltage level down, meaning it always returns LOW. If you must use pin 13 as a digital input, set its pinMode() to INPUT and use an external pull down resistor. Arduino - DigitalPins
> 10 votes

# Answer
What everyone else said, plus: if you find the digital-13 LED gives you a problem, you can always remove it from the circuit, either by removing the LED, or the series resistor.

This might be useful if you are running out of digital I/Os, or you want several contiguous I/O bits and don't want one of them to behave differently from the others.
> 4 votes

# Answer
Yes, pin 13 is traditionally an output pin that drives an LED. But the blue LED should not be blinking as it is the "power on" indicator - do you have a grunty power supply to your board?

You can experiment with PWM to the pin13 LED, which will control its apparent brightness. There are plenty of example sketches on the web.
> 1 votes

---
Tags: arduino-uno
---


# Question
Title: How to map PID output to actuator control?
I'm building a control system for the heating of a house. A sensor reads the temperature inside and is then used as the input in the PID control. The temperature is then controlled by a servo which opens and closes a shunt were water runs to the radiators. I understand all the inner workings of the PID library for Arduino and PID in general, but **the thing I don't understand is what I'm exactly supposed to do with the output signal I receive. In what way should the output signal correspond to how open or closed the shunt is?**

I understand I can simply map the output signal to the servo signal, but is this the correct way? And with what angle coefficient should I map it with, cause that is basically set with the P parameter, isn't it? Is there some standard way to map the output signal to the actuator "signal", so that that tuning parameters are somewhat "standard".

Hope someone understands anything of what I tried to explain :)

# Answer
I don't think you would need to use a PID library (or any control loop for that matter) to control a radiator. You could use a simple threshold code, like this:

**Pseudocode:**

```
Check temperature
If radiator is off and temperature > (ideal temp - threshold)
  turn radiator on
If radiator is on and temperature > (ideal temp + threshold)
  turn radiator off

```
> 2 votes

# Answer
If you can't find some actual info regarding applying PID to a water-based radiator system, then I'd suggest the following principles.

First, I assume that the output of the PID algorithm appears as an An Arduino PWM output at some rate. This could be a fast rate, like in the hundreds of Hz (if the load is DC), or fractions of Hz, or even 10 sec or more cycle time.

Next, I assume that the PID algorithm is likely designed to expect that a linear change in output has a linear effect on the heating output. That is to say, as though it's controlling an electric heater, where, for example, 25% ON-time produces 25% of full heat output.

If these are true, then you need to determine how that relates to what you can control on your shunt valve.

Is it acceptable for the valve to be turned full on/off on a proportion-of-10-seconds basis? Probably not.

Can the valve be set to an intermittent position if fed with a 10 Hz or 100 Hz PWM signal, perhaps so.

If the latter, then a further question is how does the PWM range of values correspond to actual angle of the valve, and more to the point, how does it correspond to flow rate, and ultimately to heat delivery. Perhaps a 33% PWM signal is required to deliver 25% of the full-range heat, for example.

(At a guess, I'd assume that heat delivery is proportional to flow, but as I think you anticipate, flow is not proportional to valve angle.)

You might just mock up your system, program the Arduino to output particular PWM values to the valve, and measure the resulting flow, and if possible, heat delivery. Then, interpose in the PID library the inverse function, perhaps as a lookup table.

So when the PID library wants to command 25%, that number gets looked up in the table, which (continuing my example) translates it to a 33% PWM signal, and your program sends that value to the PWM output.

Hope that provides some ideas.
> 2 votes

---
Tags: servo, pid
---


title: Yún boot from SD card

text:
# Question
Title: Yún boot from SD card
I have an Arduino Yún, and it only has 16mb flash onboard for the Linux. I was wondering of it is possible to put a bootloader on the flash that uses the sd card as a rootfs? i want to be able to do more projects on it than those that can fit in 16 MB flash.

# Answer
> 5 votes
And the Arduino team finally figured it out:

http://blog.arduino.cc/2014/05/06/time-to-expand-your-yun-disk-space-and-install-node-js/

# Answer
> 4 votes
I am using Yun as well for my projects. I don't boot from SD card, but I store a lot of Python code there and it works for me. I've also seen this article that might be interesting for you. I haven't tried to do it on my Yun but I think it should work... This is example how to install node.js on the Yun (SD card), so in theory you could use the same approach for all additional software you want to run.

http://linino.org/doku.php?id=wiki:nodejs

---
Tags: arduino-yun, linux, bootloader
---


title: Calculating location with 4 piezo's

text:
# Question
Title: Calculating location with 4 piezo's
i've got the following problem i'd like to get solved and i'm breaking my head, so please help!

I have a rectangle with the following size 40 cm * 50 cm. On each corner of this rectangle I placed a Piezo element (it's an electronic element which measures the vibration)

The rectangle is defined as followed: the left upper corner = A the left lower corner = B the right lower corner = C the right upper corner = D

I'm trowing a ball on the surface and I'd like to calculate it's X and Y axis. The outcome of the piezo elements are as followed:

A,B,C,D - 0 lowest vibration, 1023 highest vibration These values can be mapped to a number I can decide, so that means I can make it whatever we need it to be. Example: map 0,1023,0,100, meaning the new mapping will be 0 - 100.

I found a possible solution here: http://mathafou.free.fr/pbg\_en/sol114.html The problem I got is that i don't know where the ball will be and therefor I don't know the angle it will fall on.

The thing I do now is:

Example: We trow the ball. The outcome could be ABC or what would be best ABCD results.

I thought Pythagoras could come in handy here. The thing I did was: A\*A+B\*B=C\*C (to get the square calculation done) A+B = AB, B+C = BC, A+C= AC, (to get the sides of a triangle) AB\*BC=AC (We don't know AC but we can square root the outcome of AB\*BC)

But then i realised I just know how long the side is and I still don't know where the ball landed :(

The following I already implemented to scale it when it works (maybe not relevant now) A+B+C+D = Total outcome we can possibly get at that point (as we are relying on vibration) A,B,C,D/Total = the scale we need to calculate with

I call this A1,B1,C1,D1 so I can re-use this in the code The reason I do this, is the follow up I need it for. Im going to use a projector to project a video on the exact X/Y position. But that's not relevant I guess for now.

I'm programming this in Processing 2 : http://processing.org

# Answer
You might want to look into how LORAN works, as I believe you can do something similar.

First premise: You want to look for the **initial transient** caused by the impact propagating to sensors in various places on the periphery. The signal in the material will end up bouncing around quite a bit before it dies out, but the leading edge of the initial transient should be unambiguous, so use that.

Second premise: You have *no idea* when the ball actually hits - you can also measure the **difference in timing** between when various sensors first detect it.

So take any two sensors, measure the time lag between when they detect the ball, and convert that via the speed of sound in your material. This yields the *difference* in the distance of the impact point from the two sensors. If you know the position of the two sensors, and plot the curves of points which satisfy the equation of the measured difference in distance from each of them you can a class of conic section called a `hyperbola`.

But so far you do not have an answer, but only a pair of curves along which the impact must lie. So now take at least one new sensor, and repeate the exercise generation a new equation.

Combine the equations and solve to find the intersection of the curves - this is your point of impact. It is possible to have more than one mathematical solution, but I think you will find that only one possible solution lies in the area between the sensors.

(Unfortunately, the ATmega328p A/D converter probably isn't fast enough to do a good job of this - at 10KSPS each sample is around 34mm in air, and around half a meter in typical solids - so you either need a much faster A/D, or else tune a comparator circuit to detect pulses and measure them with ATmega timer channels.)
> 5 votes

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


# Question
Title: Using 3.3V XBee with Arduino Pro Mini 5V Version
The Xbee requires a 3.3V power input and the Arduino Pro Mini (5V version) only provides a regulated 5V.

**Question:** What will be the simplest way to provide a 3.3V rail to the XBee from the Arduino Pro Mini?

If we use a voltage divider consisting of 2 resistors, the ratio should be 66/100, but how do we choose the resistor values?

If we choose a 3.3V voltage regulator, will the STMicroelectronics L78L33ACZ be suitable?

Between the voltage divider and voltage regulator, which is the preferred method? Is there a better alternative?

# Answer
This is part of a Fritzing circuit I used to control the x'mas tree lights (the relays and sensors have been snipped out) with an XBee. This circuit uses a 3.3v LDO you may have to change the capacitor values depending on your regulator specs. I chose to use a separate 5V regulator (not shown) but it will work off the Pro Mini's +5V power rail.

There are two FETs that do the actual level shifting, the bonus transistor allows you to reset the Arduino and thus gives you the ability to program it over the air via the XBee (beyond the scope of the question, but if you want to go wireless, go wireless all the way - do the Google for wireless programming over XBee if needed). Note the 0.1uF across the XBee power pins, I recommend this capacitor be placed as close to the XBee as possible to minimize noise (I solder it across the back of the XBee interface board).
> 5 votes

# Answer
You can use a voltage regulator to get the supply voltage down to 3.3v.

For the Serial Lines, the best way forward is to use a good level convertor like https://www.sparkfun.com/products/11978 from sparkfun.

If you don't want to buy it, you can also make it using a couple of Mosfet's and resistors. Here's the schematic from Sparkfun.
> 1 votes

# Answer
**The simplest way**, as you ask, is probably a resitor-based voltage divider; its main drawback is the waste of energy in the resistors.

To calculate the "best" resistor values, you'll need to know the amount of **current** needed by the XBee module.

So you have:

* `Vin` = **5V**
* `Vout` = **3.3V**
* `Iout` = to be determined (check XBee spec sheet for that)

Then you have to resolve the following equations to calculate the resistor values you shall use:

```
R1 = R2 x (Vin - Vout) / Vout
Iout = (Vin - Vout) / R1 - Vout / R2

```

These equations simply come from applying Ohm's law and Kirchhoff's circuit laws.

This site calculates the ideal resistor values for you.

For `Iout` = **100mA**, it gives the following values:

* `R1 = 17 Ohm`
* `R2 = 33 Ohm`

Another **simple way** is to use a **3.3V zener diode** if you have one on hand. You can google for good circuit examples.
> 1 votes

---
Tags: xbee, voltage-level, arduino-pro-mini
---


# Question
Title: Allocate object memory statically; intialize it dynamically?
I have an object whose constructor gets passed a parameter. If I know the parameter value at compile time, I can construct the object statically:

`static FOOOBJ foo(3);`

(I understand that it isn't really done statically, i.e. by the compiler, but is actually done during setup).

But if I don't know the parameter value at compile time, I'd still like to pre-allocate space for the object but construct the object in that space at run time. Can it be done without a separate `.initialize()` method?

# Answer
> 3 votes
Using an `initialize()` method to a class is contrary to the principle of a class constructor, i.e. once a class instance has been **constructed**, it should be "**ready to use**".

As suggested by Ignacio's answer, C++ placement syntax is much better for your purpose.

However, with Arduino libraries, placement syntax is not supported "out of the box", so you have to implement it yourself; don't fear, that is quite straightforward:

```
void* operator new(size_t size, void* ptr)
{
    return ptr;
}

```

Placement syntax can be a complex beast in C++, but for your specific purpose, its usage can be rather simple:

```
static char buffer[sizeof FOOOBJ];
static FOOOBJ* foo;

void setup() {
    ...
    foo = new (buffer) FOOOBJ(3);
    ...
}

```

The difference with your current code is that `foo` is now a pointer, hence any method call will use `->` instead of `.`.

If you absolutely want to keep using `foo` as an instance and not a pointer, then you can do it (but I don't advise it as explained later) by using a **reference** instead:

```
static char buffer[sizeof FOOOBJ];
static FOOOBJ& foo = *((FOOOBJ*) buffer);

void setup() {
    ...
    new (buffer) FOOOBJ(3);
    ...
}

```

The problem with this code, is that you cannot know if `foo` has already been constructed with a real `FOOOBJ` instance or not; using a pointer, you can always check if it is `0` or not.

Using placement syntax, you must be aware that you cannot `delete` the `foo` instance above. If you want to destroy `foo` (i.e. ensure that its destructor is called), then you have to explicitly call the destructor:

```
foo->~FOOOBJ();

```

# Answer
> 4 votes
You can use placement syntax to specify an existing allocation in which to instantiate the class.

```
FOOOBJ foo(0);

 ...

  FOOOBJ *f = new (foo) FOOOBJ(3);

```

---
Tags: programming, c++
---


# Question
Title: What is the advantage of using a motor shield if I want to use a stepper motor?
I know that it is possible to connect a stepper motor directly to an arduino (as displayed here). I know that another option is to use a motor shield (for example the Arduino Motor Shield or the Adafruit Motor Shield).

What I would like to know: What are the actual advantages of using a motor shield?

Is it just a question of convenience? Or does a motor shield do something that could not easily performed without a shield? Does it allow me to connect more motors than I could connect directly without a shield (power supply comes to mind)?

# Answer
> 9 votes
The example you linked to isn't actually connecting the Arduino *directly* to a stepper motor. It's going via a ULN2003A driver. That's a very common Darlington transistor array, which basically just lets you use a small current to switch a larger load.

That's necessary because the Arduino pins can't safely source enough current to drive the stepper motor directly. It might work for a while, but it would damage your Arduino sooner or later.

Motor shields usually have a similar driver in them, but can also provide additional functionality which you might find useful. For example, the Adafruit shield you linked to is controlled by the I2C bus, and has its own on-board PWM. That means you can control several motors without needing any extra output pins on your Arduino.

In short, motor shields aren't necessary. They can be helpful though, especially if you aren't familiar with the underlying electronics, or you don't want to build it yourself.

# Answer
> 5 votes
Mechanical stability of the whole thing is probably the main advantage. I'd personally opt for a generic module or loose components. The main disadvantage of shields is pin conflicts when using more than one shield.

# Answer
> 4 votes
I'm using a adafruit motorshield v2 for my solar tracker project with two stepper motors atm. i'm quite a new to arduino and coding and i think the shield made it a lot easier for me to get a hang of it - easy to code and nicely stack able on the ardiuno (little soldering to assemble but not too difficult).

---
Tags: shields, motor
---


# Question
Title: Adafruit motor shield + Adafruit stepper not working
I have the Adafruit Motor Shield V2 and an Adafruit stepper motor. I have not soldered the shield onto the Arduino (which is an Uno) yet because I don't want to make anything permanent yet. I have the Arduino plugged into a DC wall adapter and have the VIN jumper in the shield, and the green power light on the shield is lit. This is how the stepper is connected.

As you can see in the picture, all the wires from the stepper are plugged in. The order of the wires is what it says it should be on the website, which is `orange-pink-red-blue-yellow`. My sketch's code is an adapted version of the StepperExample from the Adafruit motor library. Here's the full code

```
#include <Wire.h>
#include <Adafruit_MotorShield.h>
#include "utility/Adafruit_PWMServoDriver.h"

Adafruit_MotorShield AFMS = Adafruit_MotorShield();

Adafruit_StepperMotor *myMotor = AFMS.getStepper(513, 2);

void setup() {
  Serial.begin(9600);
  Serial.println("Stepper test!");

  AFMS.begin();
  myMotor->setSpeed(5);
}

void loop() {
  myMotor->step(100, FORWARD, SINGLE);
}

```

But the stepper still doesn't move. Can anyone point out what I'm doing wrong here?

# Answer
> 5 votes
As far as I know, you have to solder the header pins. Here is a nice video demonstrating the assembly: Motorshield V2 assembly

---
Tags: arduino-uno, shields, motor
---


# Question
Title: How to make XBee module interrupt/wake arduino
What I am trying to do is, to have arduino in low power mode and waking up only when a packet is received and is available to be read from the buffer.

A scenario : Zigbee XBee module is not receiving anything, arduino is asleep. Once this particular module receives any data from any other module, it makes the arduino wake up and process this packet.

I've looked almost everywhere possible about this, and people say they do not have a 100% working solution.

Does the XBee module produce a particular output on a specific pin when it receives data? If so, can I connect that pin to the interrupt enabled pin on arduino and with that interrupt arduino or wake it up? do I need arduino mega for that or is the uno a good enough option?

# Answer
The pin number 9 and 13 on the Xbee are DTR/RTS used for hardware handshaking. You can connect it to the interrupt pins on the Arduino and program the arduino to wake when the pulse changes. Enable the DTR/RTS feature from X-CTU and it should work. Check this for more information.
> 3 votes

---
Tags: arduino-uno, arduino-mega, xbee, interrupt
---