# Question
Title: Trouble with variable types and integrating DHT11 temperature sensor
I am trying to modify this sketch; https://github.com/itsallvoodoo/home\_automation/blob/master/Arduino\_HVAC\_Controller/HVAC\_Controller/HVAC\_Controller.ino

But I have a different temperature sensor, a DHT11, and I am using the libraries from Adafruit.

The DHT11 can't be constantly polled, 1 second intervals is the maximum rate.

I am currently working (fighting) with the portion towards the bottom in the section:

```
boolean getTemp() {

```

As my sketch stands, I have "currentTemp" statically assigned to 79 degrees. When I upload, the arduino acts as I would expect it to given that data.

If I change it to 0 (zero) and try to set the temp by reading the sensor in the section starting at line 237 like this;

```
boolean getTemp() {

  currentTemp = 0;
  long temp = 0;

  if ((millis() - TempLastCheck) > 2000) {
    TempLastCheck = millis();
    //  currentTemp = dht.readTemperature(true);
      temp = dht.readTemperature(true);
     Serial.println(dht.readTemperature(true));
  }

```

The LCD is blank after it restarts, and the arduino triggers the "heat" relay because the temperature is 0 (zero)

I'm sure I'm missing something simple, because the DHT11 outputs floats, or something... I'm too new to this language to know what I'm missing. Any help will be greatly appreciated.

```
// name:     HVAC_Controller.ino
// author:   Chad Hobbs

// -------------LIBRARIES---------------- THESE ARE REQUIRED TO BE IN YOUR SKETCHBOOK\LIBRARY FOLDER FOR COMPILING ----
#include <Wire.h>                   // Protocol to communicate with I2C devices
#include <Adafruit_MCP23017.h>      // LCD protocol
#include <Adafruit_RGBLCDShield.h>  // LCD + Button shield protocol
#include "DHT.h"                // DHT11 Temp/Humidity Sensor
// --------------PARAMETERS---------------------
int heat = 55;                    // This is the default heater trigger temp setting
int cool = 70;                    // This is the default cooling trigger temp setting
int buffer = 1;                   // This is the range away from the setpoint the heat or AC will overcool/heat to prevent shorter cycles
int heatPin = 7;                  // Digital pin used for turning on the heater relay
int coolPin = 8;                  // Digital pin used for turning on the AC relay
int cycleTime = 60;               // The length of time to delay running the AC or heat to prevent short cycling
boolean heatRunning = false;      // Stores whether the heater is currently running or not
boolean coolRunning = false;      // Stores whether the AC is currently running or not
long currentTemp = 0;             // Current room temperature

int serialSpeed = 9600;           // Default serial comm speed
long oldTemp = 0;                 // Used to only update the currentTemp if the temp has changed
unsigned long timeOut;            // Backlight timeout variable
boolean editable = false;         // Determines whether or not button presses will do anything, used to avoid accidental changes
char* menu[] = {"Cooling", "Heating"};  // Menu display for either setting the high point or the low point of the temp range
int menuPosition = 1;             // Current position in the setting menu
unsigned long heatLastRan;        // Stores the time the heater last ran
unsigned long coolLastRan;        // Stores the time the AC last ran
unsigned long TempLastCheck;      // Stores the last sensor reading ran

// -------------Library Interaction--------------
// Create our LCD Shield instance
Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();
#define ON 0x7            // For single color LCD, set on to white
#define OFF 0x0           // For single color LCD, set off to black

#define DHTTYPE DHT11   // DHT 11
#define DHTPIN 4     // what pin we're connected to
DHT dht(DHTPIN, DHTTYPE);

// ----------------------------------------------------------------------------------------
// Function Name: setup()
// Parameters:    None
// Returns:       None
// Description:   This function executes housekeeping duties and staging for the loop() function; executed once
// ----------------------------------------------------------------------------------------
void setup() {

  //  pinMode(busPin,INPUT);  // Designate temperature bus pin data direction
  pinMode(heatPin, OUTPUT);               // Heat circuit relay
  pinMode(coolPin, OUTPUT);               // Cooling circuit relay
  Serial.begin(serialSpeed);

  lcd.begin(16, 2);       // set up the LCD's number of columns and rows
  lcd.setBacklight(ON);   // Start off with backlight on until time-out
  timeOut = millis();     // Set the initial backlight time
  TempLastCheck = millis();  // Set the initial sensor timing

  dht.begin();
}

// ----------------------------------------------------------------------------------------
// Function Name: loop()
// Parameters:    None
// Returns:       None
// Description:   This is the main executing block of the program, calling all ancillary functions to operate the Arduino
// ----------------------------------------------------------------------------------------
void loop() {
  if ((millis() - timeOut) > 30000) {                   // Turn on backlight for 30 seconds, else turn it off
    lcd.setBacklight(OFF);
    editable == false;
  } else {
    lcd.setBacklight(ON);
  }

  lcd.setCursor(0, 1);                  // Starting position of character printing

  uint8_t buttons = lcd.readButtons();  // Constantly check to see if something has been put on the bus

  // --------------Handle updating Temp Change Display---------------------
  if (getTemp()) {                      // Constantly check to see if the temperature has changed, and update appropriately
    lcd.clear();
    lcd.print("Temp:");
    lcd.print(currentTemp);
  }

  // --------------Handle Button Presses---------------------
  if (buttons) {
    timeOut = millis();
    lcd.setBacklight(ON);

    if (buttons & BUTTON_SELECT) {      // Allow parameters to be changed only if the Select button has been pressed first
      editable = true;
    }
    if (editable) {                     // go to buttonHandler to handle menu switching and parameter manipulations
      buttonHandler(buttons);
    }
  }

  // --------------Handle Heat and Cooling Cycles---------------------
  powerControl();

}

// ----------------------------------------------------------------------------------------
// Function Name: powerControlHandler()
// Parameters:    None
// Returns:       None
// Description:   This function will handle turning AC or Heat off and on based on current temp, timers, and setpoints
// ----------------------------------------------------------------------------------------
void powerControl() {

  // TODO: Add in fan relay control

  // This executes if the heater is running and it gets warm enough to turn off.
  if (heatRunning && (currentTemp > (heat + buffer))) {
    heatRunning = false;
    heatLastRan = millis();
    digitalWrite(heatPin, HIGH);
    return;
  }

  // This executes if the AC is running and it gets cool enough to turn off
  if (coolRunning && (currentTemp < (cool - buffer))) {
    coolRunning = false;
    coolLastRan = millis();
    digitalWrite(coolPin, HIGH);
    return;
  }

  // This executes if it gets cold enough and the heater has not run for a minimum time (short cycle protection)
  if ((currentTemp < heat) && ((millis() - heatLastRan) > cycleTime)) {
    digitalWrite(heatPin, HIGH);
    heatRunning = true;
    return;
  }

  // This executes if it gets hot enough and the AC has not run for 10 minutes (short cycle protection)
  if ((currentTemp > cool) && ((millis() - coolLastRan) > 60)) {
    digitalWrite(coolPin, HIGH);
    coolRunning = true;
    return;
  }

  return;
}

// ----------------------------------------------------------------------------------------
// Function Name: buttonHandler()
// Parameters:    None
// Returns:       Boolean, True if the temperature has changed, else False
// Description:   This function polls the temp sensors, retrieves the values, and then returns
// ----------------------------------------------------------------------------------------
boolean buttonHandler(uint8_t buttons) {

  // --------------PARAMETERS---------------------
  int heatModifier = 0;
  int coolModifier = 0;

  // --------------SETUP---------------------
  lcd.clear();

  // If the UP Button is pushed, increasing the setpoint
  if (buttons & BUTTON_UP) {
    if (menuPosition == 0) {
      coolModifier = 1;
    }
    if (menuPosition == 1) {
      heatModifier = 1;
    }
  }

  // If the Down Button is pushed, decreasing the setpoint
  if (buttons & BUTTON_DOWN) {
    if (menuPosition == 0) {
      coolModifier = -1;
    }
    if (menuPosition == 1) {
      heatModifier = -1;
    }
  }

  // If the Left Button is pushed, change the menu context
  if (buttons & BUTTON_LEFT) {
    if (menuPosition == 1) {
      menuPosition = 0;
    } else {
      menuPosition = 1;
    }
  }

  // If the Right Button is pushed, change the menu context
  if (buttons & BUTTON_RIGHT) {
    if (menuPosition == 1) {
      menuPosition = 0;
    } else {
      menuPosition = 1;
    }
  }

  // If anything has been modified, update accordingly
  heat = heat + heatModifier;
  cool = cool + coolModifier;

  // Print proper menu title and setpoint
  lcd.setCursor(0, 0);
  lcd.print(menu[menuPosition]);
  lcd.setCursor(0, 1);
  lcd.print("Setpoint: ");

  if (menuPosition == 0) {
    lcd.print(cool);
  }
  if (menuPosition == 1) {
    lcd.print(heat);
  }

}

// ----------------------------------------------------------------------------------------
// Function Name: getTemp()
// Parameters:    None
// Returns:       Boolean, True if the temperature has changed, else False
// Description:   This function polls the temp sensors, retrieves the values, and then returns
// ----------------------------------------------------------------------------------------
boolean getTemp() {

  currentTemp = 79;
  long temp = 0;

  if ((millis() - TempLastCheck) > 2000) {
    TempLastCheck = millis();
    //  currentTemp = dht.readTemperature(true);
     //temp = dht.readTemperature(true);
     Serial.println(dht.readTemperature(true));
  }

  /////////////////////////////////////////////////////////////////////////////////////////////////////
  //  sensors.requestTemperatures(); // Send the command to the device to get temperatures

  // Go through devices and read the temperatures
  //  for(int x = 0; x < numOfDevices; x++){
  //   temp = sensors.getTempF(addrs[x]);
  //  if(temp != currentTemp){
  //   currentTemp = temp;
  //    }
  //  }
  /////////////////////////////////////////////////////////////////////////////////////////////////////
  // Check to see if temperature has changed
  if (currentTemp != oldTemp) {
    oldTemp = currentTemp;
    return true;
  }
  else {
    return false;
  }
}

```

# Answer
First of, you read the temperature and put it into local variable `temp`. You need to copy the value from `temp` into `currentTemp`.

Secondly, you are reading the temperature twice in a row. Once to assign it to `temp` and again for the `Serial.println`.

```
  if ((millis() - TempLastCheck) > 2000) {
    TempLastCheck = millis();
    currentTemp = dht.readTemperature(true);
    Serial.println(currentTemp);
  }

```

When setting the `currentTemp` to 0 inside `getTemp`, getTemp never return `true`, because you initialized the value of `currentTemp` with 0 (`long currentTemp = 0;`). So it never changed, and the lcd is never updated. Just change it to something like:

```
long currentTemp = -100;

```
> 1 votes

---
Tags: programming, sensors, variables
---


# Question
Title: Concatenation of non constant character array with a string
I have an Arduino Duemilanove.

I read this page on string concatenation. Yet, it didn't include my case.

I have a non constant character array, that later gets a value.

```
char clat[11];
dtostrf(gps.location.lat(), 11, 6, clat);

```

I want to output this:

```
Latitude: 20.653425

```

So basically I want a final string that contains: "Latitude:" + the value of the nonconstant array.

Is it possible?

# Answer
> 6 votes
```
char clat[10+11+1] = "Latitude: ";
dtostrf(gps.location.lat(), 11, 6, clat+10);

```

Since you've named the buffer 'clat' I'm assuming it will always be used for latitude, so we've pre-initialized its size and contents, and we know where to begin the latitude value.

By the way, don't forget to size string buffers one more byte than the length of the maximum length string you intend to put in it.

Update 6/23/14:

From your other question and your comment to this answer, I'll revise my suggestion to this. The ..printf() functions are particularly easy to use, saves you (mis)counting buffer positions, and don't add much lot more code than the Serial() object already includes:

```
char outbuf[40+1];      // wider than nec, easier than counting
char clat[15+1]; clong[15+1]; // workspaces

sprintf(outbuf, "Latitude/Longitude: %s %s",
    dtostrf(gps.location.lat(), 10, 6, temp),
    dtostrf(gps.location.lng(), 10, 6, temp) );

```

This works because dtostrf() returns the address of the buffer you gave it; sprintf then takes that string (two of them in this case) when building your final output string.

The printf() functions are often deprecated for embedded systems. They're large (but see my comment about that above); and they're non-reentrant, so don't do that! In these low-end systems we don't often multi-thread anyway - just be aware of that if you do. And even if you have to remove them later and go back to printing piece by piece, they can save you a lot of headaches during development.

Here's another way that avoids both printf and the 32 bytes of work buffers:

```
char outbuf[40+1];

 strcpy(outbuf, "Latitude/Longitude: ");
 dtostrf(gps.location.lat(), 12, 6, outbuf+strlen(outbuf));
 dtostrf(gps.location.lng(), 12, 6, outbuf+strlen(outbuf));

```

We can't initialize outbuf unless it is 1) static, and 2) not going to be used more than once, since its initial conditions won't be the same the second time around. I've increased the field-widths of dostrf() to be sure the outputs of the won't be run-together for large values.

# Answer
> 3 votes
It's possible and very easy to do. You can convert a character array to a string object with the `String(char_array_name_here)` function.

To do this you can just do this:

```
String output = "Latitude: " + String(clat);  //Make sure to add a space so it's not "Latitude:20.653425"

```

You can do this with any string, just remove the `String()` part because you don't need to convert a string to a string!

One thing to note: you can just do this code if you're outputting it to the serial console:

```
Serial.println("Latitude: " + clat);

```

*Summary of edits: found a function I was searching for yesterday but couldn't find. Much simpler*

---

## Other links:

---
Tags: programming, string
---


# Question
Title: Input a signal from a sensor to an Arduino Due
I'm working with Arduino Due and I have a sensor that outputs a square signal with voltages in the range of 0-5V.

In the Due specs there is a warning that says:

"Warning: Unlike other Arduino boards, the Arduino Due board runs at 3.3V. The maximum voltage that the I/O pins can tolerate is 3.3V. Providing higher voltages, like 5V to an I/O pin could damage the board."

Is it possible to connect it to the board?

Thanks.

# Answer
This is a tough one. If it was digital IO sensor, a simple level shifter would suffice. However, since it's analog, you have limited options.

The cheapest route (and the easiest) would be to use a voltage divider. They only take two resistors, and they divide linearly. That means 1/2 of 5V would be divided into 1/2 of 3.3V. You can then use the full range of the Due (be careful not to use 0-1023, as it has a 12 bit ADC: it'll give you weird numbers).

More on voltage dividers. Even more on voltage dividers.

To build one:

> From Sparkfun (link at bottom)

That's four different ways to build one. R1 would be 1700 ohms and R2 would be 3300 ohms. Vin would be from the sensor and Vout would be to the Due.
> 2 votes

---
Tags: sensors, arduino-due
---


# Question
Title: Duemilanove serial TX/RX: which is what?
I want to use the GSM shield. For my project, I will hook it up directly to pins `0` and `1` (TX/RX). Will it work right away? Do I have to know which is TX and which RX and declare it?

I will not be using SoftwareSerial.

# Answer
> I will not be using SoftwareSerial

That means you'll use the standard `Serial()` library.

> Do I have to\[...\] declare it?

Not if you use the standard `Serial.begin()` instruction. The Duemilanove uses pins 0/1 automatically for TX/RX

> Do I have to know which is TX and which RX?

Kinda... you have to know which one is which so you wire it correctly. The TX of the board should go to the RX of the GSM shield, and vice versa. Pin 0 is RX and 1 is TX.
> 2 votes

---
Tags: serial, arduino-duemilanove
---


title: appending string to char and vice versa

text:
# Question
Title: appending string to char and vice versa
Some days ago i started a thread. concatenation of non constant character array with a sting

I have a different question but on the same nature (string and chars)

what i want is one variable (string or char) that will hold a standard text and the value of gps coordinates latitude and longitude

The format is this: "latitude/longitude: 30.111111 20.111111"

What i have is a char that holds the standard text and the latitude: "Latitude/Longitude: 30.111111"

I also have another char that holds the second value (longitude)

The chars were generated with dtostrf():

```
char clat[10 + 20 + 1] = "Latitude/Longitude: ";
char clng[10 + 1];
dtostrf(gps.location.lat(), 10, 6, clat+20);
dtostrf(gps.location.lng(), 10, 6, clng);

```

I can also make the chars strings:

```
string1 = String(clat);

```

What have i tried: 1.Assigning clng to clat directly via dtostrf()

```
char clat[10 + 20 + 10 + 1] = "Latitude/Longitude: ";
dtostrf(gps.location.lng(), 10, 6, clng+31);

```

It didnt work and got unexpected output

1. making clat a string and assign clng via for loop

string1 = String(clat); for (int i=0; i\<10; i++) string1\[i+32\]=clng\[i\];

This doesnt append it

I run out of ideas here. Any help from more experienced guys?

# Answer
> 1 votes
solved it. was simple actually. dont know how to do it with chars, but with strings there is the addition operator. So i converted both to string and used the + operator.

```
char clat[10 + 20 + 1] = "Latitude/Longitude: ";
char clng[10 + 1];
String string1, string2, finalstr;

```

and inside the loop:

```
dtostrf(gps.location.lat(), 10, 6, clat+20);
dtostrf(gps.location.lng(), 10, 6, clng);
string1 = String(clat);
string2 = String(clng);
finalstr = string1 + string2;

```

Maybe that was too much work? If you have any smarter alternatives, please provide!

# Answer
> 1 votes
One thing I noticed is you do not need the `+` in:

```
char clat[10 + 20 + 1] = "Latitude/Longitude: ";

```

You can just do this:

```
char clat[31] = "Latitude/Longitude: ";

```

**A much simpler way to do this is this:**

Variables to initialize:

```
char subfinal[40] = "Latitude/Longitude: ";
String final = ""; //You don't need this, you could always use `String(subfinal)` instead

```

The code inside a function:

```
dtostrf(gps.location.lat(), 10, 6, subfinal+10);
subfinal[29] = " ";
dtostrf(gps.location.lng(), 10, 6, subfinal+30);
final = String(subfinal);

```

I haven't tested it, so let me know if it doesn't work.

---
Tags: programming, string
---


title: Issues with a basic circuit

text:
# Question
Title: Issues with a basic circuit
I am having some issues with a simple circuit. I would expect this circuit to light up this LED constantly when the Arduino is plugged in. I have the Blink tutorial sketch loaded, but I don't think that should matter with the pins I am using.

This is what I think I have going on: Arduino 5V Power --\> BB power --\> 100 Ohm resistor --\> BB line 25 --\> this LED --\> BB line 30 --\> BB Ground --\> Arduino Ground

Please check out this picture for confirmation:

Thanks in advance for any help that you can provide!

# Answer
> 6 votes
Figured it out - stupid mistake as expected. The power and ground lines on my bread board don't go all the way across. They break right in the middle, as the lines show. I moved my ground connection to the left a few slots and it worked. Thanks for working through it with me jfpoilpret!

---
Tags: led
---


# Question
Title: Controlling an LED with the 74HC4067E multiplexer
I am testing a 74HC4067E MUX setup with my Arduino Uno which I would like to use to selectively light up many LEDs, one at a time. For this first test, I am using a modified version of the blink tutorial. Essentially, I am setting the 4 control pins to digital LOW and setting the input to HIGH, through a resistor appropriate for my LED. I am also providing 5V to the Vcc pin on the MUX. I don't really know why I am doing this, but it seems to work. Here is my code:

```
int led_input = 0;
int led_ctrl_1 = 1;
int led_ctrl_2 = 2;
int led_ctrl_3 = 3;
int led_ctrl_4 = 4;

void setup() {
    pinMode(led_input, OUTPUT);
    pinMode(led_ctrl_1, OUTPUT);
    pinMode(led_ctrl_2, OUTPUT);
    pinMode(led_ctrl_3, OUTPUT);
    pinMode(led_ctrl_4, OUTPUT);
}

void loop() {
    // control signal
    digitalWrite(led_ctrl_1, LOW);
    digitalWrite(led_ctrl_2, LOW);
    digitalWrite(led_ctrl_3, LOW);
    digitalWrite(led_ctrl_4, LOW);

    // input signal
    digitalWrite(led_input, HIGH);
    delay(500);
    digitalWrite(led_input, LOW);
    delay(500);
}

```

*I know, the code could be more efficient.*

The blue LED is hooked up to I0 and blinks as it should. The problem comes when I try to change the control pin values. When I change it to, say 6...

```
// control signal
digitalWrite(led_ctrl_1, LOW);
digitalWrite(led_ctrl_2, HIGH);
digitalWrite(led_ctrl_3, HIGH);
digitalWrite(led_ctrl_4, LOW);

```

... and I move my LED to I6, I get no blink. I've tested all the pins and it doesn't seem like there is a signal coming from any of them. I assume that I am using the chip wrong, but I'm not sure how. Pictures of my setup follow... any help is greatly appreciated!

* Arduino pin 0 maps to chip pin 1 (through resistor) as input.
* Arduino pins 1-4 map to chip pins 10, 11, 14, and 13 in that order.
* I have a 5V going to chip pin 24.
* The LED is connected long leg to chip pin 9 in the images, the grounded.

# Answer
> 2 votes
Pin 15 on that MUX is the enable pin, you need to tie it to ground. Otherwise, it's just floating, and it only would have worked by accident.

Also, you state:

> I am also providing 5V to the Vcc pin on the MUX. I don't really know why I am doing this, but it seems to work.

The chip needs power to work. The Vcc pin is where you give it the +5V power. Without that, it might still work, but only by accident and depending on the inputs on the other pins.

---
Tags: arduino-uno
---


# Question
Title: Are these lcd and motor-shields stackable?
first of all, I'm kindly apologizing for asking such stupid questions, but as my electronic-knowledge is dramatically limited, you are my only hope to get my problem solved.

I'm pretty new to Arduino and my plans are to stack a lcd shield on a motor shield, which is stacked on the Arduino.

My setup would be the following:

My target is to enter specific values trough the LCD-shield (with its buttons) and to control a stepper-motor related to those.

Now to my question: Can I realize my project with the mentioned parts and are the two shields stackable (with head extentions on the motor-shield) without creating interferences?

Thank you very much for your time and answers in advance.

Best regards,

irie

# Answer
No, it doesn't look like it.

The LCD board uses digital pins 4-10 and analog 0

The motor board uses digital pins 3-12 if all motors are used.

If you need to stack boards look for boards that use I2C since they can share a single data bus.
> 4 votes

---
Tags: arduino-mega, shields, motor, lcd, arduino-motor-shield
---


# Question
Title: Efficient periodic wake up for sensor reads
I've been tasked to do an initial design for an Arduino setup that needs to run very infrequently.

Basically, I'd like the system to wake up *daily* to take some sensor readings and report them back to a central site (the mesh network for this will be my next stage).

Since these things are going to be run on battery, I need it to be as insanely efficient as possible, with minimal power drain when not reading the sensor.

What facilities does Arduino have to do this?

# Answer
Please refer to http://playground.arduino.cc/Learning/ArduinoSleepCode

it explains the details of a the sleep command and interrupts to re-a-wake. Where the power savings is from putting the resources individually into low power mode.

In your solution, you may want to put everything in low power, except power\_timer1\_disable(). Where timer1 would be configured to provide an overflow interrupt, say every 1 minute or longer and then go back to powering all off and return to sleep.

Note the article also mentions that the UNO's power supply is a linear regulator, which is very in-efficient. You may want to use your own. You can also get away with just running directly off of 2-3 AA's, if your other circuitry does not care. If this, then I would also suggest enabling the brown out detection, to ensure low battery does not get funny.
> 1 votes

---
Tags: power, interrupt, timers, battery, system-design
---


# Question
Title: SerialGSM for GSM shield without SoftwareSerial
SerialGSM is a library for simplifying GSM shields.

This is sample code for sending SMS:

```
#include <SerialGSM.h>
#include <SoftwareSerial.h>
SerialGSM cell(2,3);
void setup(){
 Serial.begin(9600);
 cell.begin(9600);
  cell.Verbose(true);
  cell.Boot();
  cell.FwdSMS2Serial();
  cell.Rcpt("+972123456789");
  cell.Message("hello world");
  cell.SendSMS();
}

void loop(){
  if (cell.ReceiveSMS()){
    Serial.println(cell.Message());
    cell.DeleteAllSMS();
  }

}

```

As you can see, he uses software serial.

I intend to use this for my school thesis, but I am using a shield, so I won't be using Software Serial.

What bothers me is this line

```
SerialGSM cell(2,3);

```

In my case, do I declare it like this?:

```
SerialGSM cell(0,1);

```

Or will there be conflicts with serial?

EDIT: In other words, how do I declare the SeralGSM object using hardware serial and not software serial?

# Answer
`SerialGSM` is designed to work with software serial, as you can see that from the class declaration in the `SerialGSM.h` header:

```
class SerialGSM : public SoftwareSerial {
...
};

```

Unfortunately, changing it to use hardware serial is more complicated than it looks. There are two potential ways you could go about it:

1. Derive from `HardwareSerial` instead of `SoftwareSerial`. This would give you flexibility, but you'd have to take care of passing all the right data to the `HardwareSerial` constructor, which is quite messy.
2. Don't derive from anything. Use the global `Serial` object, and manually replace all serial function calls with their `Serial.xxx()` equivalents. This is probably easier, but it restricts you to a specific serial port.

Both approaches involve quite a lot of coding, so they aren't trivial tasks. It's also important to note that `SerialGSM` currently uses the global `Serial` object to output debug information. You'd have to remove or modify that before converting to hardware serial, or else it could interfere.
> 5 votes

# Answer
Never mind, i went with the GSM SMS example from arduino 1.0.5 (Don't know the version of arduino IDE that included this) and works fine.

If you are considering using the SerialGSM library there is no need to!

CAUTION: In the Arduino's library, when you declare the phone number, you have to use international format

(Thanks bloomfield for the info you provided in the previous answer)
> 2 votes

---
Tags: gsm
---


title: Error compiling

text:
# Question
Title: Error compiling
I have this code:

```
#include <TinyGPS++.h>
#include <SoftwareSerial.h>

#include <Wire.h>
#include <Adafruit_MCP23017.h>
#include <Adafruit_RGBLCDShield.h>

#include <GSM.h>

#define PINNUMBER ""  // Opt from user
#define GPS_RX_PIN 2
#define GPS_TX_PIN 3
#define WHITE 0x7  //For LCD library

//Objects initialization
GSM gsmAccess;
GSM_SMS sms;

Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();

TinyGPSPlus gps;
SoftwareSerial ss(GPS_RX_PIN, GPS_TX_PIN);

// Chars and strings for gps values
char clat[10 + 20 + 1] = "Latitude/Longitude: ";
char clng[10 + 1];
String string1, string2, finalstr;

const int xpin = A0;                  // X-axis of the accelerometer
const int ypin = A1;                  // Y-axis
const int zpin = A2;                  // Z-axis (only on 3-axis models)

float convX = 0.0, convY = 0.0, convZ = 0.0;
int sampleDelay = 20;

char remoteNumber[20] = "306978666866"; // Opt from user

uint8_t i = 0;

void setup()
{
  Serial.begin(9600); //GSM
  ss.begin(4800);     //gps

  analogReference(EXTERNAL); // For external analog reference of ADXL335
  pinMode(xpin, INPUT);
  pinMode(ypin, INPUT);
  pinMode(zpin, INPUT);

  // Set up the LCD's number of columns and rows:
  lcd.begin(16, 2);
  lcd.setBacklight(WHITE);
  lcd.setCursor(0, 0);

  // GSM connection state
  boolean notConnected = true;

  while(notConnected)
  {
    if(gsmAccess.begin(PINNUMBER) == GSM_READY)
      notConnected = false;
    else
    {
      lcd.print("Not connected");
      delay(1000);
    }
  }
  lcd.print("GSM initialized");

  delay(2000);
  lcd.print("SELECT=Emergency");
}

void loop()
{
  bool uniFlag = false;
  int x = analogRead(xpin);
  delay(1); // Add a small delay between pin readings. I read that you should
            // do this but haven't tested the importance.

  int y = analogRead(ypin);
  delay(1);

  int z = analogRead(zpin);

  // zero_G is the reading we expect from the sensor when it detects
  // no acceleration. Subtract this value from the sensor reading to
  // get a shifted sensor reading.
  float zero_G = 502.0;

  // 'scale' is the number of units we expect the sensor reading to
  // change when the acceleration along an axis changes by 1G.
  // Divide the shifted sensor reading by scale to get acceleration in Gs.
  //   610 (1g) - 502 (0g) = 108
  float scale = 108;

  //value (g) = (measurement - 502)/ 108
  convX = ((float)x - zero_G)/scale;
  convY = ((float)y - zero_G)/scale;
  convZ = ((float)z - zero_G)/scale;

  delay(sampleDelay);

  if (convX > 2 || convX < -2 || convY > 2 || convY < -2)
    uniFlag = true;

  uint8_t buttons = lcd.readButtons();

  if (buttons) {
    if (buttons & BUTTON_SELECT) {
      uniFlag = true;}
  }

  if (uniFlag == true)
  {
    bool isGpsLocationValid = false;
    do
    {
      while (ss.available()>0)
      {
        char c = byte(ss.read());
        if (gps.encode(c))
        {
          if (gps.location.isValid())
          {
            dtostrf(gps.location.lat(), 10, 6, clat+20);
            dtostrf(gps.location.lng(), 10, 6, clng);
            isGpsLocationValid = true;
            string1 = String(clat);
            string2 = String(clng);
            finalstr = string1 + string2;
          }
        }
      }
    } while (isGpsLocationValid == false);
  }
  sendSMS(finalstr);
}

void sendSMS(String thisString)
{
  sms.beginSMS(remoteNumber);
  sms.print(thisString);
  sms.endSMS();
  lcd.setCursor(0, 0);
  lcd.print("Message sent!");
  delay(10000); //for multiple bumps
}

```

When I try to compile it I get these errors:

```
GSM\GSM3SoftSerial.cpp.o: In function `__vector_5':
C:\Program Files (x86)\Arduino\libraries\GSM/GSM3SoftSerial.cpp:525: multiple definition of `__vector_5'
SoftwareSerial\SoftwareSerial.cpp.o:C:\Program Files (x86)\Arduino\libraries\SoftwareSerial/SoftwareSerial.cpp:319: first defined here
GSM\GSM3SoftSerial.cpp.o: In function `__vector_4':
C:\Program Files (x86)\Arduino\libraries\GSM/GSM3SoftSerial.cpp:518: multiple definition of `__vector_4'
SoftwareSerial\SoftwareSerial.cpp.o:C:\Program Files (x86)\Arduino\libraries\SoftwareSerial/SoftwareSerial.cpp:312: first defined here
GSM\GSM3SoftSerial.cpp.o: In function `__vector_3':
C:\Program Files (x86)\Arduino\libraries\GSM/GSM3SoftSerial.cpp:511: multiple definition of `__vector_3'
SoftwareSerial\SoftwareSerial.cpp.o:C:\Program Files (x86)\Arduino\libraries\SoftwareSerial/SoftwareSerial.cpp:305: first defined here

```

What is going on? Is it that GSM.h declares SoftwareSerial inside? Are there any solutions?

This is the first time I get these kinds of compilation errors and have no idea what is going on or how to fix it.

# Answer
> 3 votes
Both `SoftwareSerial` and `GSM` are trying to declare the same interrupt vectors. You'll have to drop one of the libraries, find a replacement or change your code to omit one of the libraries. This is the disadvantage of using high level libraries.

Some Arduino's (Arduino Mega) have a microcontroller that supports more than one hardware serial channel, you may want to check that in the datasheet of the ATmega that is on the board.

# Answer
> 1 votes
I have not downloaded the libraries in question, but It would appear that there is a collision between "SoftSerial.h" and the "GSM/GSM3SoftSerial.h" built in to your GSM library.

There is a disscussion of this conflict here: https://github.com/mainehackerclub/open\_vehicle\_tracker/issues/28

It seems the answer is to use the "AltSoftSerial" library instead of the stock "SoftSerial" library. The "AltSoftSerial" library can be downloaded here http://www.pjrc.com/teensy/td\_libs\_AltSoftSerial.html

---
Tags: compile
---


# Question
Title: Reading button presses with the 74HC4067E multiplexer
My project is progressing quite well, but I am having some issues reading button presses through my MUX.

# The Goal

Cycle through twelve buttons and twelve LEDs. When a button is pressed, light up the corresponding LED. I have one MUX for the LEDs which is working great thanks to the stack exchange community. My button MUX is the issue.

# The Symptom

I have one button hooked up to the MUX. When it is not pressed, nothing lights up - that's right. But when it is pressed, every LED lights up as it is cycled through. It is as if pressing this button for one of the MUX pins is sending a HIGH signal to all of the MUX pins.

# The Pictures

^^ You can see the big honking button in the bottom right. It is connected to 5V and then the MUX pin.

^^ I have two multiplexers. The one on the left is for the LEDs and the one on the right is for the buttons (of which I currently \[ha!\] have only one).

# The Code

```
// set vars for all the pins
int led_input = 0;
int led_ctrl_1 = 1;
int led_ctrl_2 = 2;
int led_ctrl_3 = 3;
int led_ctrl_4 = 4;

int btn_input = 5;
int btn_ctrl_1 = 6;
int btn_ctrl_2 = 7;
int btn_ctrl_3 = 8;
int btn_ctrl_4 = 9;

// how many MUX pins?
int players = 12;

// function to take player number and convert to control pins
void ledWrite(int led, boolean val){

    if(!val){

        digitalWrite(led_input, LOW);

    }else{

        if((led - 8) >= 0){
            led = led - 8;
            digitalWrite(led_ctrl_4, HIGH);
        }else{
            digitalWrite(led_ctrl_4, LOW);
        }

        if((led - 4) >= 0){
            led = led - 4;
            digitalWrite(led_ctrl_3, HIGH);
        }else{
            digitalWrite(led_ctrl_3, LOW);
        }

        if((led - 2) >= 0){
            led = led - 2;
            digitalWrite(led_ctrl_2, HIGH);
        }else{
            digitalWrite(led_ctrl_2, LOW);
        }

        if((led - 1) >= 0){
            led = led - 1;
            digitalWrite(led_ctrl_1, HIGH);
        }else{
            digitalWrite(led_ctrl_1, LOW);
        }

        digitalWrite(led_input, HIGH);
    }
}

// function to take player number and convert to control pins
int btnRead(int btn){

    if((btn - 8) >= 0){
        btn = btn - 8;
        digitalWrite(btn_ctrl_4, HIGH);
    }else{
        digitalWrite(btn_ctrl_4, LOW);
    }

    if((btn - 4) >= 0){
        btn = btn - 4;
        digitalWrite(btn_ctrl_3, HIGH);
    }else{
        digitalWrite(btn_ctrl_3, LOW);
    }

    if((btn - 2) >= 0){
        btn = btn - 2;
        digitalWrite(btn_ctrl_2, HIGH);
    }else{
        digitalWrite(btn_ctrl_2, LOW);
    }

    if((btn - 1) >= 0){
        btn = btn - 1;
        digitalWrite(btn_ctrl_1, HIGH);
    }else{
        digitalWrite(btn_ctrl_1, LOW);
    }

    return digitalRead(btn_input);
}

void setup(){

    pinMode(led_input, OUTPUT);
    pinMode(led_ctrl_1, OUTPUT);
    pinMode(led_ctrl_2, OUTPUT);
    pinMode(led_ctrl_3, OUTPUT);
    pinMode(led_ctrl_4, OUTPUT);
    pinMode(btn_input, INPUT);
    pinMode(btn_ctrl_1, OUTPUT);
    pinMode(btn_ctrl_2, OUTPUT);
    pinMode(btn_ctrl_3, OUTPUT);
    pinMode(btn_ctrl_4, OUTPUT);
}

void loop(){

    for(int x = 1; x <= players; x++){

        if(btnRead(x) == HIGH){

            ledWrite(x, true);
            delay(100);
            ledWrite(x, false);
        }
    }
}

```

I know this is a lot to trudge through, and I honestly appreciate any help you are willing to offer. Thanks in advance!

# Answer
All your unused MUX input pins for the button MUX are floating. You will need to tie all of the unused inputs (those that do not have a physical button attached) to ground. Floating inputs are undefined and cause undefined output.

Also, when your attached button is *not* pressed, its input will also be floating. You can avoid this by connecting the input pin on the MUX to ground using a resistor. That way, when the button is not pressed the input will be low (through the resistor), and when the button is pressed it will be high (through the button connection).
> 3 votes

---
Tags: led, button
---


# Question
Title: Arduino Uno rev 3 toggling a 230 V submersible pump on intervals
I am software programmer and hobby farmer. While I was working on a hydroponic farming stuff, I had to use submersible pumps with timers. I don't want to buy timers that are actually a tedious scheduling process. so I am making one myself.

I want to toggle 230 V for turning a submersible pump(150-230 V and 18 W) ON/OFF. I read that Arduino may not able to supply enough input current that the relay requires. I am not sure about what transistor to use to amplify the input current. I came across a circuit diagram and a relay board. Do I still need to use a transistor and diode if I use this relay with an Arduino?

This is the two-channel relay I am about to use and the circuit is below.

Should I follow the circuit if I am using this relay? The relay has a tolerance of 250 V. What if the voltage fluctuates above 250 V? I am going to use a 9 V battery to power the Arduino. Feel free to explain anything that I may have to know.

**UPDATE**

Thanks marla for making it clear that I don't need diodes and transistors. Andy, as you said, I can't keep changing batteries often, and it will limit the system. Shall I use an adapter which reads output 5 V and 1 amperes? Will that drive the Arduino and be sufficient for both the relays?

# Answer
> 2 votes
The Arduino will easily drive this relay board, and it needs only a very small input current.

The board you linked to has a built-in optical isolation circuit, so there is no direct electrical connection between the Arduino-side of the circuit and the relay side. This *should* protect your Arduino if something goes wrong. For what it's worth, the product description specifies this board is suitable for "AC \[...\] appliances such as \[...\] motors". A pump is primarily a motor.

The voltage may fluctuate when the pump is started and stopped (Back-EMF). It's hard to say what this might do to the relay board if it goes way over specification. Perhaps you might be happier with a much more robust solid-state relay (SSR) that has a higher rating than the target load. Something like *SSR-25DA 25A Solid State Relay - White*. Since solid-state relays are non-mechanical, they will not wear-out from repeated switching either.

You may also want to build some fail-safe sensors into your project. For example, water level float switches for both high-water and low-water marks.

---
Tags: arduino-uno, relay
---


# Question
Title: Unexpected behavior of sprintf with i32/u32
I'm trying to build a string of characters from several elements given by the TinyGPS++ library with the use of sprintf().

This is my code making the string and printing it in the serial monitor.

```
char posmsg[100], lat[14+1], lon[14+1];

void sendString(){
  //- convert lat/lon
  dtostrf(gps.location.lat(), 10,6, lat);
  dtostrf(gps.location.lng(), 10,6, lon);

  //- sprintf the string
  sprintf(posmsg, "$%4d-%02d-%02d %02d:%02d:%02d,%s,%s,%i,%i,%i,%i,%i$",
          gps.date.year(),gps.date.month(),gps.date.day(),
          gps.time.hour(), gps.time.minute(), gps.time.second(),
          lat, lon,
          gps.speed.value(), gps.course.value(), gps.altitude.value(),
          gps.satellites.value(), gps.hdop.value()
        );

  Serial.println("--------------------");
  Serial.println(posmsg);
  Serial.println("--------------------");

  Serial.print("Speed:");
  Serial.println(gps.speed.value());
  Serial.print("Course:");Serial.println(gps.course.value());
  Serial.print("Height:");Serial.println(gps.altitude.value());
  Serial.print("Sats:");Serial.println(gps.satellites.value());
  Serial.print("HDOP:");Serial.println(gps.hdop.value());
  Serial.println("--------------------");
}

```

This is the result and what I expect... (spaces added for readability)

```
 Result:
 --------------------
 $2014-06-24 15:17:11,  51.xxxxxx,   5.xxxxxx, 2, 0, 4964, 0, 3660$
 --------------------
 Speed:2
 Course:4964
 Height:3660
 Sats:8
 HDOP:110
 --------------------

 Expected:
 --------------------
 $2014-06-24 15:17:11,  51.xxxxxx,   5.xxxxxx, 2, 4964, 3660, 8, 110$
 --------------------

```

So in the end of the string the numbers get displaced...

According to the documentation the type of the variables are all integers or unsigned integers, but the sprintf messes things up.

```
 gps.speed.value(); // Raw speed in 100ths of a knot (i32)
 gps.course.value(); // Raw course in 100ths of a degree (i32)
 gps.altitude.value(); // Raw altitude in centimeters (i32)
 gps.satellites.value(); // Number of satellites in use (u32)
 gps.hdop.value(); // Horizontal Dim. of Precision (100ths-i32)

```

What am I doing wrong?

# Answer
Ints and unsigned ints are 16 bits on AVR ATmegas. So while the argument passed is a 32-bit value, sprintf() is expecting a 16 bit value. The stack is packed with twice as much data as needed.

From the "2,0,4964" bit, it looks like it taking part of the previous/next parameter during processing, which makes me think this even more.

You need to use *long* types, e.g.: %ld or %li and %lu
> 2 votes

---
Tags: arduino-uno, programming, sketch, tinygps
---


title: How to update a text file dynamically

text:
# Question
Title: How to update a text file dynamically
I have Two Arduinos, One with the help of sensors it will dynamically updates in to my server database. Other Arduino, reads the stored contents from the server database and sends sms to phones.

Now, I have a text file in my server which updates dynamically for every 5 min - 10 min. I am trying to read that text file contents.

I want my server to be always connected, So It must be in `setup()` function. I want update only to my text file which dynamically changes, so it must be `loop()` function.

How to implement this ? Any Suggestion ?

# Answer
> 1 votes
It's difficult to answer without details of how your server works.

If your arduino is simply connected to the server, the server could open the arduino serial port (e.g.: COM5: or /dev/ttyUSB0) and simply read data. The arduino would only need to serialWrite() data for the server to parse and store.

If your arduino is not connected but has ethernet support you could do a HTTP request to your server, and pass the data as a parameters to the request, e.g.:

```
http://your.server.ip/send_data?param1=10.3&param2=5.6&param3=foo

```

When your server processes this HTTP request, it appends param1, param2, param3 to that text file.

The arduino could also beam data back to your server via IR, or bluetooth, etc.

There's lots of ways to do this.

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


# Question
Title: Pro Mini not communicating with computer
when I try to upload blink program to my Pro Mini, I get this error:

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

```

I've tried everything, changing the COM port, different USB cable and even another computer. Here is what I'm dealing with:

Arduino Pro Mini 328 5v 16M (Fake)

FT232RL USB to serial adapter

Nothing is connected to any pins on the Arduino, just trying to get LED to blink. I'm pretty sure the bootloader is installed, because when I hit the reset button, the LED blinks. I've tested the FTDI chip by connecting the TX and RX pins together, and it does echo in the serial monitor. Help appreciated!

# Answer
You did set the Serial Port and then tell the Arduino IDE that it's talking to a Pro Mini right?

This gets me every time I switch between my Nano & Uno.

On the main menu \[Tools\]-\>\[Board\]=\>"Arduino Pro or Pro Mini (5V, 16 MHz) w/ ATmega 328"

I've also had this problem trying to use a longer USB cable, it just wouldn't work. The stock cable (shorter) worked fine.
> 1 votes

---
Tags: uploading
---


# Question
Title: How do I manipulate a large number of moving platforms?
I am trying to build a device that will allow me to control at least a couple hundred raising platforms. The goal of this is to create a real time editor for board games (*Dungeons and Dragons*).

Ideally:

* All the platforms would move simultaneously
* The platforms would be transparent to allow us to place LEDs inside them to color the platform so we can make colors like blue for water and brown for dirt.

In our current setup, we use some acrylic prisms that are 1 inch x 1 inch x 6 inch (width, length, height). We wanted to use a CNC motor like system to move something around and move a platform. Obviously, this can only raise/lower one item at a time. We calculated (on paper) quite a long update time (calculated approximately 1 sec per platform) to raise/lower a platform. A CNC linear drive type system is the only solution we found that had a reasonable cost/quality (a CNC motor for every platform also raised the power consumption very high). After a few weeks of looking around, planning and throwing stupid ideas away, we found this.

Clearly, it's way better then our idea but I have no idea how they did this. They have 900 platforms and they all work simultaneously. We also don't need real time interaction. Loading from computer and staying static until we change it is good (though water movement would be really nice).

What would you guys recommend to raise simultaneously a thousand small platforms?

---

After looking at this document that the devs made, and doing a bit more research I found that the device they used to move the platforms cost approxomently $30; I don't think I need to say this, but I don't have $27,000.

Key difference between their implementation and our goal:

* No real-time interaction with the table. Controlled by an Arduino is fine.
* Size of the platforms will be closer to 1 inch^2
* All sides of the platform should be light up, but I believe this is mostly a question of choosing the right material

# Answer
> 1 votes
In terms of cost, perhaps it would be best to build a 4x4 prototype.

My first thought was to use inexpensive servos with a flexible rod inside a sheath, perhaps a wire, like a bicycle brake/gear. The amount of movement could then be governed by the size of the armature on an inexpensive servo.

Servos will position themselves after being given the command, so there's no need to wait and do them one-by-one. Fire off the command, then use some sort of multiplexed output like multiple 74HC595 shift registers to connect to the next one.

If the tiles were spring loaded, such that they returned to the topmost position by themselves, only a simple pull-string is needed to adjust the tile height. Even a very light filament (like fishing line) would be strong enough for the pull. This would allow the servos to be positioned even some metres away from the table.

---
Tags: system-design
---


title: Controlling Arduino through MATLAB?

text:
# Question
Title: Controlling Arduino through MATLAB?
I had a Roboteq motor controller, but it wasn't fast enough. I'm hoping Arduino will be faster.

Supposing that the transfer is fast enough for my purposes, how can I read angular velocity, given that I have an encoder? Honestly, I'm not totally sure how to hook it up to an Arduino board. I can't find a name for my encoder... This is the datasheet though.

Can anyone help me with how to hook it up, and what commands to use in MATLAB?

Thanks.

# Answer
Do all the processing on the Arduino, and supply the results to Matlab over serial.

I'm not 100% sure about your particular encoder, but generally encoders talk in "Grey Code". This is a series of bits which allow you to know the direction the encoder has turned.

There are a number of libraries and tutorials for Arduino dealing with encoders.

The one I use comes from here:

It would be best to use a library with interrupt routines on pins 2 & 3 (these support external hardware interrupts), so whenever the pin gets a signal from the encoder, the Arduino can act on it immediately. If you do not use these pins, and have time-consuming processing in the loop(), it's easy to miss 'ticks' from the encoder.

```
#include <Serial.h>

// Rotary Encoder (Interrupt Driven)
#define ENCODER_PIN_A       2 /* must be pin2 for interrupt */
#define ENCODER_PIN_B       3 /* must be pin3 for interrupt */
#define ENCODER_OPTIMIZE_INTERRUPTS
#include <Encoder.h>
Encoder encoder(ENCODER_PIN_A,ENCODER_PIN_B);

void setup()
{
    Serial.begin(115200);
    // Gentlemen, start your encoders
    pinMode(ENCODER_PIN_A,INPUT_PULLUP);
    pinMode(ENCODER_PIN_B,INPUT_PULLUP);
}

void loop()
{
    unsigned long start_time = millis();
    Serial.println("Dear Matlab...");

    while (1)
    {
        unsigned long now = millis();
        unsigned int encoder_value = encoder.read();

        // Do whatever angular velocity processing is needed here
        unsigned long ticks_per_ms = encoder_value / (now - start_time);

        // Send the result back to Matlab
        Serial.println(ticks_per_ms,DEC);
    }
}

```

I think for your encoder the "A" and "B" outputs are where the grey code will be coming from. These would be connected to Arduino pins 2 & 3.

Obviously the code above is not a complete solution, and needs to take care of edge-conditions like overflow of millis() after some time, etc. etc.
> 1 votes

---
Tags: arduino-uno, matlab
---


title: Use UTP Cable to transmit/receive data?

text:
# Question
Title: Use UTP Cable to transmit/receive data?
I was wondering if it was possible to use the utp port of a computer/laptop to transmit and receive data to an external device?

If you take a cat5 cable there are 8 wires, so lets say you have an Arduino would it be possible to use those wires for serial communication? If so how can I program the utp port? And is there a specification for this (for example use wire x for output and wire y for input..)

Thanks in advance, Regards

*Ps: I had no idea on which sub.stackexchange to ask it hopefully it suits here.*

# Answer
> 3 votes
By "UTP", I'm assuming you're referring to Unshielded Twisted Pair. The shielding and twisting aren't really relevant, because they're just physical characteristics of the cable itself. They don't have any bearing on the sender or receiver.

The salient point about UTP is that it uses differential transmission. That is, the data is sent down two wires at the same time, but one is inverted. The receiver uses the difference between the two signals to reconstruct the original data, eliminating any interference which may have been introduced en route.

Assuming the voltage level is safe (0-5v for most boards), you could connect each wire directly to an analog pin on the Arduino. If you read both continuously, and apply suitable thresholds/triggers in software to identify level changes, you could probably reconstruct the original signal.

It's definitely not ideal though, as ADCs are comparatively slow, and you would never be able to read both at exactly the same time. That means the transmission would have to be quite slow in order to work. The exact speed would depend on how quickly your program could poll the ADCs and process the result.

It would be much better to use some external circuitry to handle the differential signal. It could then produce a nice clean digital output which you could feed directly to any input on the Arduino. It should be able to run a lot faster, and leave your program free to do other things. Any good electronics vendor will stock a variety of ICs which would do the job, depending on your exact requirements.

Setting up your computer/laptop as a sender is a totally separate issue though. Many different ports use differential signals in some form, including ethernet, USB, and RS-232 (old DE-9 serial ports). Unfortunately, it would be very difficult to get direct control of their signal lines. You would almost certainly have to write your own device drivers, which is a pretty huge undertaking.

If you want to send serial data from your computer to an Arduino, the easiest way is just USB-to-TTL conversion. Most Arduino boards have this built-in, connected directly to the hardware serial lines on the microcontroller (which is how you upload programs/sketches). Alternatively, you can get external cables which do the conversion, and you can connect it manually to other pins, processing it using software serial.

---
Tags: serial
---


title: why there is 4 ground in l293d?

text:
# Question
Title: why there is 4 ground in l293d?
I am using L293d motor driver to drive 2 motors simutaniusly in several direction.

But I am not shure why there is 2 Vcc and 4 GND in this IC.

Can anyone tell explain it?

Thank You...

# Answer
> 5 votes
It's explain in the datasheet.

> A VCC1 terminal, separate from VCC2, is provided for the logic inputs to minimize device power dissipation. (pg. 2)

VCC1 is for the logic and VCC2 is for the motor supply.

The four grounds are all tied together internally and act as a heatsink for the chip. (pg. 11)

# Answer
> 2 votes
They are connected together and used for heatsinking,

VS - is voltage supply

VSS - is logic level definition, if your uC logic level is 5V then power this with 5V. This will define voltage levels for the signal to be considered 0 or 1

# Answer
> 2 votes
Apart from heatsinking the four pins in parallel reduce the impedance (resistance) to ground. The actual bond wires that run from the chip to the leadframe are pretty thin and as an effect the resistance is *relatively* high. By wiring these pins in parallel the impedance is reduced which is a good and important property when you are trying to drive high current loads.

Also the ground potential on the chip will be slightly lifted proportonal to the current in the ground connections. In practice this may cause strange effects like logic levels shifting up and down with load current.

Best to attach GND all to the ground plane, the impedance on the PCB will be low and and the large copper surface helps to keep temperature down.

Vcc1 is for logic and will often interface with your 5V microcontroller. Vcc2 is the supply rail that will actually power the load.

---
Tags: arduino-uno
---


# Question
Title: I cannot find the I2C device by scanning
I've been trying to get a LCD I bought from deal extreme to work for some time with my ATTiny85 chip. It should be capable. I've tried googling the device but there is no proper documentation, so I figured the best way to get the address is to scan for it. How ever, the code below does not work :( any pointers? Anyone else who has gotten this I2C LCD display to work with Arduino?

As I have no other output then the screen, the thought behind the code is to scan for devices and then when it finds one (the LCD is the *only* one connected to the bus) should then print the address :)

I only have a serial programmer and attiny85 chips, so I have no way to bring it to a full Arduino UNO or whatever for further debugging.

```
#include <TinyWireM.h>
#include <LiquidCrystal_I2C.h>

void setup()
{
  TinyWireM.begin();
}

void loop()
{
  byte error, address;

  for(address = 1; address < 127; address++ )
  {
    TinyWireM.beginTransmission(address);

    error = TinyWireM.endTransmission();

    if (error == 0) break;

    delay(5000);
  }

  LiquidCrystal_I2C lcd(address, 16, 2);

  lcd.init();
  lcd.backlight();
  lcd.clear();

  lcd.setCursor(0, 0);
  lcd.print("Hello World - " + address);
}

```

I2C LCD: http://www.dx.com/p/iic-i2c-2-5-blue-screen-lcd-display-module-for-arduino-green-black-266170#.U6f\_B\_l\_vIc

# Answer
> 1 votes
I'm not sure on your program, but I bought a LCD display from Deal Extreme. I use the following address to communicate with the display:

```
LiquidCrystal_I2C lcd(0x27,20,4);  // set the LCD address to 0x27

```

It seems as that is the correct address for the LCD.

---
Tags: i2c, lcd, attiny
---


# Question
Title: For which type of serial communication is Arduino Severino designed?
Arduino has become quite costly where I come from (2/3 of the price of Raspberry PI) so I have created an Arduino Severino clone.

I had used the device with the RS-232 Usb-Serial converter. But after a (long) while, the device stopped working. My friend came up with a point that RS-232 communication ranges between +6 to -6 V (with thresholds at +3 and -3 volts).

So I have tried FT232 which uses 0 to 5 volts instead. I have a little ~~Chinese~~ FTDI chip designed to do that:

However, after connecting it, it behaves unexpectedly. (it had crashed my PC, one of the communication LEDs is on all the time...) I realised that the Arduino board might get broken for a different reason (an accidental short-circuit is *very* likely).

So for which type of communication is this *"Arduino"* designed?

# Answer
Looking at the schematic of that board it uses a very crude signal inversion for the RS-232. This allows it to work of a standard RS-232 signal direct from a computer - *just*.

It's far from ideal and really should use a MAX232 (or similar) chip for the interface.

Your FT232 adaptor should bypass that chunk of the circuit and connect direct to pins 0 and 1 of the Arduino clone. The DTR pin of the FT232 should connect to the RESET pin of the Arduino clone via a 100nF capacitor to allow the IDE to reset the board to enter the bootloader. Oh, and of course, connect the ground to your Arduino clone too (something Arduino users often forget).

You can follow the serial breakout board portion of the Arduino breadboard tutorial and apply it to your board.
> 4 votes

# Answer
The arduino you linked to is designed for RS232-level serial signals, which can be guessed from the use of a DB09 connector.

The FT232 print you show is for 5V TTL (or maybe 3.3V 'TTL') signaling. Not compatible with your arduino. (BTW: that chip is not Chinese at all, it is made by www.ftdichip.com IMO they make the best usb-to-serial chip/driver products.)
> 3 votes

# Answer
The Arduino Severino (Single Sided Serial version 3 - S3V3rino) is designed to work with RS-232 serial interface, not with the TTL serial signal levels of your FT232 board.

So, to use your FT232 board to connect your Severino to a USB port, you'll need connections like those in the schematics below:

So, basically you need these connections:

```
  FTDI |  ATmega328           | Arduino Severino
----------------------------------------------------
  DTR  |  Pin 1 (thru cap C6) | RESET (thru cap C6)
  RXI  |  Pin 3               | TX (D1)
  TXO  |  Pin 2               | RX (D0)
  VCC  |  Not connected       | Not connected
  CTS  |  Not connected       | Not connected
  GND  |  Pin 8 & 22          | Ground

```

That's basically the same Majenko suggested (but with a picture added).

I'm not sure you can make these connections directly into the Severino without damaging the board or anything else. You'll probably need to cut the TX/RX traces that go from the ATmega328 to the DB9 female connector on the Severino and wire them to the FTDI header pins.

Best would be to modify the Severino EagleCAD schematics to remove all the RS-232 circuitry and replace it by TTL connector as shown in my schematics above and, with that, etch and assembly a new board. It's a lot of work, but can be done.

I hope this helps.
> 2 votes

# Answer
A typical 5V Arduino will use logic-level serial - that is 0 and 5V signalling.

RS232 has signal levels of plus or minus 3 to 15 volts. RS-232 drivers and receivers must be able to withstand indefinite short circuit to ground or to any voltage level up to ±25 volts

From Wikipedia

Many RS232 interfaces will receive 0-5V signals.

I believe the original serial Arduino had circuitry to tolerate RS232 signal levels on it's inputs.

Since most computers now have USB rather than RS232 ports, Most users of Arduinos use a USB to logic-level serial interface. Some of the most popular chips for this are from FTDI such as the FT232RL on your Chinese clone of a "FTDI Friend". In this case all the signals are logic-level 0-5V (or 3.3V if you change the jumper link).

So the following are probably OK

```
 PC DE-9 RS232    ----- Severino DE-9
 PC DB-25 RS232   ----- Severino DE-9
 PC USB port ---- "FTDI Friend" ---- Arduino 0(RX), 1(TX), Reset, GND and (optionally) VCC.

```
> 1 votes

---
Tags: serial
---


title: ATMega32u4 (Leonardo) Serial Baud Rate

text:
# Question
Title: ATMega32u4 (Leonardo) Serial Baud Rate
Does anyone know what the actual baud rate that the CDC Based virtual serial port on the Leonardo runs at is? Serial::being() for the CDC version is just empty, so it's not setting a baud rate anywhere.

Basically, I'm debating between using the 32u4 or the 328p with an FTDI chip and trying to figure out if the 32u4 will be slower... since it uses a virtual COM port I'm assuming it is, but I'd be happy if I was wrong :)

# Answer
I'm not sure if the concept of an "actual baud rate" is really meaningful in a pure USB connection.

In my experience, the 32u4 is faster than the 328p at serial-heavy tasks. There is no intermediate chip, and USB has much larger hardware buffers than the serial port does. I don't know how much processing you're planning to do on your data, but I would expect that a 32u4 can process serial data pretty much as fast as you can generate/process it.

On the host side, it seems to me that there is very little difference in whether the "virtual COM port" has an FTDI or a 32u4 on the other end, so I don't see why one should be faster than the other (though admittedly they go through different device drivers).
> 3 votes

---
Tags: serial
---


title: Understanding arduino shield schematics

text:
# Question
Title: Understanding arduino shield schematics
I am researching the schematic of the arduino GSM shield. Link is this: https://www.sparkfun.com/datasheets/DevTools/Arduino/cellular%20shield-v12.pdf

What i do not understand is the upper right part, wich says ARDUINO\_SHIELDNOHOLES.

What i want to do is understand which pins are used for Rx and which for Tx.

But there are four usable pins on the arduino side and six(?) pins on the other side which says jumper, where are six pins on seeminly two jumpers...

Can anyone understand what is going on here?

# Answer
"ARDUINO\_SHIELDNOHOLES" is a connector in the SparkFun EAGLE libraries which is basically, well, an Arduino shield. It provides the schematic symbol as well as the PCB landing pattern for such.

The pins on the top right of the schematic are two sets of 3, which should have jumpers connecting either 1 and 2, or 2 and 3. To use hardware serial to connect the Arduino to the SM5100B you connect 2 and 3 of the "top" one and 1 and 2 of the bottom one. This connects D0 (RX) and D1 (TX) of the Arduino to TXD0 and RXD0 of the SM5100B. If you want to use software serial instead, connect the other pairs. D2 will then be connected to TXD0 (and will become the software RX), and D3 will be connected to RXD0 (and will become the software TX).

As for "TXD0" and "RXD0" themselves, those are **net names**, and all wires with the same net name, such as those and the ones connected to pins 19 and 20 of the SM5100B, are considered to be the same wire even if they aren't connected in the schematic.
> 1 votes

# Answer
A lot of good shields will give you the option to use hardware or software serial, and that is what's happening here.

While you think you see four pins on the arduino side and six on the jumper side, what you're actually seeing is (yes) the four pins on the arduino, but those four pins go to four pins on the jumpers.

The other two pins on the jumpers (the ones in the middle) go to the TX and RX of the shield. The shield itself only has one TX (`TXD0` pin 2 on `JP4`) and one RX (`RXD0` pin 2 on `JP6`). So the jumpers form the connection between your arduino and the shield. This is why they are the middle pins, because you put the jumper on the first two, or the last two, depending on what it is you want to achieve.

You will note the net names of pin 2 of `JP4` and `JP6` relate directly to (and are connected to) pin 19 and 20 respectively of the chip on the shield.

The whole benefit of the jumpers is you connect `JP4` and `JP6` pins 1 and 2 to which closes the circuit and uses the inbuilt hardware serial (pin 1 of the jumper being arduino hardware and pin 2 being the `TXD0` source from the shield). Connecting pins 2 and 3 means you close the circuit between the shields TX and RX to the arduino GPIO pins `D2` and `D3` which you can assign when initialising your software serial.
> 1 votes

---
Tags: gsm
---


title: Arduino and XBee Series1

text:
# Question
Title: Arduino and XBee Series1
I have actually reap 3 numerical values (3 sensors) from a remote XBee module and then manipulate these 3 signal with an Arduino card attached to another XBee module. To do this, I chose to use the IO line passing because it proved the easiest. My problem is this: for the XBee transmitter, I set:

```
ATID 3001
ATDL 2
ATMY 1
ATIU 1 / / to activate the IO option
ATD0 3 / / where is plugged a pushbutton
ATD1 3 / / where is plugged another pushbutton
ATD2 3 / / where is plugged proximity sensor (presence)

```

For the XBee receiver (the one connected with the arduino board):

```
ATID 3001 ATDL 1 ATMY 2 ATIA 1
ATD0 4
ATD1 4
ATD2 4

```

Where I'm stuck is on the Arduino programming. Which command is used to determine the change of state of xbee remote? because I want to know if the states of the sensors on input are high or low.

# Answer
There are two ways this could be tackled:

1. physically through connections between the xbee and arduino and read the xbee pins directly (I've never done this, and it comes down to your shield supporting it). Each of the desired output pins of the receiving xbee would be tied to a GPIO pin of the arduino. Alternatively,
2. serially using `AT` commands via the serial connection.

I have never worked with series one, but essentially:

1. setup a serial connection to your arduino
2. send the desired `AT` command requesting the pins value
3. read the serial port response

Make sure to read the manual for the series 1 xbees for the right `AT` commands and in how to interpret the results. Register at digi and download the datasheet.

Also, just realise reading the xbee data is going to be different depending on how you have the xbee setup, ie `API` vs `AT` mode.

Here is someone who has done some work with series 1: http://www.johnhenryshammer.com/WOW2/pagesHowTo/xbeeSeries1.php#index

I'll leave the actual implementation to you since this sounds a little like a homework assignment. Give it a go using the second method above and see how you go. Then post back here (ie update the question) including source code and exact layout (schematic preferred) and we'll see where we can help you from there.

Hint: google such terms as: "read data pins xbee arduino" (without the quotes).
> 1 votes

---
Tags: xbee
---


title: Arduino standard libraries location

text:
# Question
Title: Arduino standard libraries location
I want to read the source code of an arduino library that comes with the IDE. Specifically the GSM.h

I dont know the location of the standard libraries that come with the IDE.

I only know the location of the user installed libraries.

So where is the source code of GSM.h?

# Answer
> 4 votes
Ok, i found out the location. In Win 7, it is C:\Program Files (x86)\Arduino\libraries

---
Tags: library, core-libraries
---


# Question
Title: Using more than one Ping Ultrasonic Range Finder
I have done various applications with the Ultrasonic example project but it is always using one pinger. I'd like to make a scanner resting on a servo sweep but to reduce sweep time use more than one censor.

the documentation is rather basic ping sonic that states the signal 40khz is used.

Down to the question now. Is there a means to tell one pinger to use 40Khz and another say 45Khz.

This would allow me to scan two areas (different directions) per cycle, reducing the time frame to complete area scan by half.

# Answer
There is no way to change the frequency, however there are other ways of doing what you want to accomplish. I think the best thing to do is stagger the timing of the pings so they don't happen at the same time.

Example code, modified by me:

```
#include <Servo.h>
Servo servo; // create servo object to control a servo

int pingPins[] = {7,8}; //The pins for the two sensors
char *pingString[] = {"Ping1", "Ping2"};

void setup()
{
  servo.attach(10); // attaches a servo to pin 10
  Serial.begin(9600);
}

void loop()
{
  unsigned long ultrasoundValue;
  for(int i = 0; i < ultraSoundSignalPins.length; i++)
  {
    ultrasoundValue = ping(i);
    Serial.print(pingString[i]);
    Serial.print(": ");
    Serial.print(ultrasoundValue);
    Serial.print("in, ");
    delay(50);
  }
  Serial.println();
  delay(50);
 }

//Ping function
unsigned long ping(int i)
{
  unsigned long echo;

  pinMode(pingPins[i], OUTPUT);         // Switch signalpin to output
  digitalWrite(pingPins[i], LOW);       // Send low pulse
  delayMicroseconds(2);                 // Wait for 2 microseconds
  digitalWrite(pingPins[i], HIGH);      // Send high pulse
  delayMicroseconds(5);                 // Wait for 5 microseconds
  digitalWrite(pingPins[i], LOW);       // Holdoff
  pinMode(pingPins[i], INPUT);          // Switch signalpin to input
  digitalWrite(pingPins[i], HIGH);      // Turn on pullup resistor
  echo = pulseIn(pingPins[i], HIGH);    //Listen for echo
  return (echo / 58.138) * .39;         //convert to CM then to inches
}

```

<sup> Sources: </sup>
> 4 votes

# Answer
The Ping))) sensor uses a crystal for timing. Some of the cheap knock-offs actually use a MAX3232 chip (which is an RS232 serial port/usart) to detect the return pulse, just for the carrier detection. If the parallax is similar, these have a fairly wide range of frequencies they work at, since you never know the baud rate to expect, from 9600 up to 1mhz, although they are deliberately not very fussy about accidentally picking up nearby frequencies. Since there's probably some other logic on the other chips, and everything is probably run off the one crystal, I'd recommend going to lower frequencies, otherwise you're overclocking. Also, make sure to send a longer trigger pulse because all the logic will be slower. From the picture, it looks like a 16MHz crystal, which must be divided down to the 40KHz. So solder in a 14MHz, and an 11MHz, lengthen the 5 uS trigger pulse accordingly, and you should be good to go.

As an aside, you might also consider scanning further apart. If it's taking you 30 seconds, you're probably checking every degree; maybe try every 15 or 30 degrees (just make sure to give the servo time to move)
> 1 votes

# Answer
I don't think it would be very easy to change the frequency unless Parallax decides to release the firmware for the Ping. It is possible to use two, as long as you use a different data pin for each, but the ultrasonic signals may interfere.
> 0 votes

---
Tags: sensors, robotics
---


# Question
Title: Binary serial transmission order of data
I'm implementing a filter for my IMU Sensor and thus I want close to real time data visualized on the computer. I use binary serial communication to facilitate the sending part for the arduino (as far as I know the serial.print is pretty slow). So I split my int16\_t in two bytes and send it, like:

```
Serial.write((uint8_t)(gx >> 8)); Serial.write((uint8_t)(gx & 0xFF));

```

After that i directly send the next number (3 in total by now, maybe up to 7 2byte numbers in the future). I read the thing in matlab with:

```
dt(k) = toc;
tic;
bindata([1:6],k) = fread(s,[6,1],'int8');
time = cumsum(dt(1:k));

```

Which reads 6 bytes (3 numbers) and then I recalculate the binary representation, concatenate them and get the original number (if someone can suggest an easier way.. I found matlab pretty unhandy here).

The problem is, that the numbers get mixed by the time. Somewhen one byte isn't read or anything, so the bytes get messed up and a nonsense number is produced.One full number (2byte) is skipped for one sample exactly. Instead of this number one number is there twice. The next sample the order is messed up (shifted, such that the first number is second). This process appears after maybe 30 sec, sometimes a few minutes. After the first time it keeps shifting and jumping around.

Can someone tell me, what to do here? Can I include some 'breakpoint'/line terminator, where the reader (matlab) knows, that we are at the start of the first number? Or how is this done actually?

I guess I have to add my main goal: I want to make the sending as fast for the arduino as possible. No extra calculations should be necessary (if possible). And: the reason for these shifts seems to be the some time delay (slowness). I suspect it to be a slow matlab reading, since I saw fluent processing scripts in HIL reading. The errors have stopped however, since I turned the baude rate down. Only wrong numbers are the problem still.

May there be a possibility to loop around the fread and read just store the values after an added 'header'? So let's say a wrong ordering occures. Then I discard everything until the next 'a' char/byte and use the following 6 bytes to produce my 3 values. Then I wait for an 'a' again. For that I would have to loop fread(s,\[1,1\],'int8'); and search for the header.

Full arduino code:

```
// Program to send the gyro/accel data via serialport
// corresponding matlab programs: sensing.m and sensing_binary.m
// 2 security loops to guarantee a constant sampling time

// #define DEBUG
#include "GY86.h"
#include "Wire.h"

GY86 gy86;
int16_t ax, ay, az;
int16_t gx, gy, gz;

uint32_t currenttime = 0;
uint32_t starttime = 0;
uint32_t starttime2 = 0;

// #define OUTPUT_ACCEL_COUNTS
#define OUTPUT_GYRO_COUNTS

// #define OUTPUT_ACCEL_BINARY
// #define OUTPUT_GYRO_BINARY

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

void loop () {
  currenttime = millis();
  if (currenttime-starttime > 9)
  {
    while (micros()-starttime2 < 9000) { }
    starttime2 = micros();

    // read raw accel/gyro measurements from device
    gy86.getSensorValues(&ax, &ay, &az, &gx, &gy, &gz);
    // testing constants
    // gx = -29;
    // gy = 245;
    // gz = 17;

#ifdef OUTPUT_GYRO_COUNTS
    Serial.print((int)gx); Serial.print(F("\t"));
    Serial.print((int)gy); Serial.print(F("\t"));
    Serial.print((int)gz); Serial.print(F("\t"));
#endif
#ifdef OUTPUT_ACCEL_COUNTS
    Serial.print(ax);   Serial.print(F("\t"));
    Serial.print(ay);   Serial.print(F("\t"));
    Serial.println(az); Serial.print(F("\t"));
#endif
#if defined(OUTPUT_ACCEL_COUNTS) || defined(OUTPUT_GYRO_COUNTS)
    Serial.print(F("\n"));
#endif

#ifdef OUTPUT_ACCEL_BINARY
    Serial.write((uint8_t)(ax >> 8)); Serial.write((uint8_t)(ax & 0xFF));
    Serial.write((uint8_t)(ay >> 8)); Serial.write((uint8_t)(ay & 0xFF));
    Serial.write((uint8_t)(az >> 8)); Serial.write((uint8_t)(az & 0xFF));
#endif
#ifdef OUTPUT_GYRO_BINARY
    Serial.write((uint8_t)(gx >> 8)); Serial.write((uint8_t)(gx & 0xFF));
    Serial.write((uint8_t)(gy >> 8)); Serial.write((uint8_t)(gy & 0xFF));
    Serial.write((uint8_t)(gz >> 8)); Serial.write((uint8_t)(gz & 0xFF));
#endif

    starttime = currenttime;
  }
}

```

# Answer
> 3 votes
**Edit:** It seems as the problem is overflow. That means that the USB connection isn't keeping up with the data trying to be sent. To fix this you need to do one of the following things (or both):

* **Higher baud rate.** The baud rate is the frequency that data is sent. From what I've heard, anything above `500,000` as a baud rate isn't helpful with the Arduino libraries.
    + The Arduino IDE only goes up so high. Try an application such as PuTTY to get higher baud rates on the serial monitor.
    + Doing very high rates like this are best suited on as short of a cable as you can manage. I'd say 4 feet **max**, although it depends on many factors, including cable quality. A shorter cable has less resistance (thus less errors).
    + The rest of the answer still applies. You might want to add a simple parity bit to make sure the data doesn't get corrupted while sent. Adding two or three characters greatly reduces the risk of corruption, but at the expense of cutting your sampling rate in half and it doesn't verify data integrity. I don't know your exact situation, so adding a bit might not be possible.
* **Lower sampling rate:** you're sending too much, so a simple solution is just to add `delay(250);` at the end of the loop so you don't overload the port.

---

**Original Answer:**

The only thing that comes to mind that is very efficient is a parity bit with another bit that's always the opposite of the parity bit. Why? Having an accidental thing where there the last two bits are opposite of each other and they all add up to a even number (ignoring the last bit) would be really odd.

A parity bit is an extra bit so all the bits added up with the parity bit equals an even number. If it isn't quite right, then you know there's a problem. It works only for odd numbers of bits changed, so it isn't foolproof. An example is you have the bits `10010110`. There are four `1`s, so it's an even number, thus the parity bit will be `0`. If it was an odd number, it would be `1` to make the total count an even number. If the computer calculates it doesn't add up right (excuse my lame pun) then it's corrupted and the computer can discard it.

To implement this you'd need to convert the number(s) and the parity bit to ASCII and then count the 0s and 1s. You can use a remainder function and divide by two so there will be a remainder of 1 if it's odd, thus it's corrupted. I'd personally take the latest bit and the x number before it, and just keep looping until you find a combination that satisfies the whole parity bit thing and is within a reasonable range that you've specified in the code.

A line-break would suffice, but it takes up more bits and discovers only missing data, not corrupt data.

Maybe you should be looking into *why* there's a problem. Could you reduce the length of the USB cable? Upgrade your cable/try a different one? Slightly reduce the baud rate?

# Answer
> 3 votes
You could add some kind of packet header/footer to the serial output. For example, if you sent the characters "ab" before the bytes for your number you could reject packets that only had 2 bytes in them. the serial would look like

"ab123ab123ab12ab123"

The matlab code could see another "ab" come in before the previous packet finished and ignore the packet that ended up as only "ab12", and then get itself back on track again. You should use 2 bytes for your header to avoid collisions with the actual data. Adding a checksum at the end of the packet would also allow you to detect bit swap errors. CRC or fletcher16 would work perfectly in this scenario, but in your case a checksum may be more than you need.

# Answer
> 0 votes
If what you want is high speed, the serial baud rate is your main concern. I assume that you are using an Arduino with a serial to USB converter chip, such as the Uno or Mega.

Transferring at 115200 baud, you send 11520 bytes/s at normal serial settings (1 start + 8 data + 1 stop bits = 10 bits to send 1 byte of data). With an Arduino running at 16 MHz clock, you can execute 16M / 11520 = 1389 instructions in the time it takes to transmit one byte. So you don't have to worry much about slow library routines, what you have to worry about is how many bytes you send. In that way you are right not to use Serial.print, as it will convert your int to ascii, making all number larger than 99 slower to transmit (for a uint16).

When you send data with Serial.write it is first stored in a ring buffer, then transmitted in the background by an Interrupt Service Routine. The ring buffer is typically 64 bytes. Once the the buffer is full, a call to Serial.write will block until a byte has been transmitted, so there is space in the buffer again. Therefore the timing in your main loop isn't really necessary, you can remove it and your sampling rate will adapt to your serial baud rate.

Once the data has reached the serial to USB converter chip, it will be transmitted on the USB bus at 12 Mbit/s. I don't know the exact data transfer rate since there's a lot more overhead on USB than on the serial, but you can rest assured that the bottleneck isn't here. I don't think you have to worry about USB cable lengths as there is built-in error detection and retransmit in the USB protocol, and the speed is so much faster than the serial link.

In the computer the data can be buffered in several places, it all depends on device drivers and serial libraries used. I'm not an expert here. With no flow control, the drivers/libraries probably have no choice but to drop data if it is receiving more than the end application or later layer can process. Maybe matlab or it's serial implementation or you computer is slow in some way (the data really isn't arriving very fast at all for a modern computer). So you could lower the baud rate or try to deal with lost packets.

I have a suggestion for dealing with lost packets: Reserve the upper x bits in each byte you transmit to hold the number of that byte in its sequence. You could f.ex. reserve 2 bits, allowing you to send up to 4 byte packets belonging together. Each byte-packet would have 6 data bits, enabling you to send numbers with 24 bits of precision. To send a uint16:

```
void send_int16(uint16_t data)
{
  Serial.write((0 << 6) | (data & 0b00111111));
  data >>= 6;
  Serial.write((1 << 6) | (data & 0b00111111));
  data >>= 6;
  Serial.write((2 << 6) | (data & 0b00111111));
}

```

Then in matlab you should wait for a sequence of packets numbered 0, 1, 2 in the two uppermost bits, remove the numbering and put the packets together with bitwise operators. If you get a malformed sequence, eg. 0, 2, can discard it and wait for the next byte starting with a zero.

I haven't really used matlab, so you are on your own.

---
Tags: serial, sensors, matlab
---


title: Arduino core for ATMega16u2

text:
# Question
Title: Arduino core for ATMega16u2
I've looked around a ton so it's probably not available but does anyone know if there is a usable core for the ATMega16u2 (the chip the Uno and Due uses for USB to Serial). I have a project I was going to use the 32u4 for but they aren't really available for several months and the 16u2 has all the functionality that I would really need.

# Answer
> 1 votes
As @IgnacioVazquez-Abrams said, a 16u4 is virtually identical with a 32u4, so you can use a Leonardo or Micro core with a tiny modification to boards.txt. A 16u2 is a rather different animal, with fewer timers, many fewer pins, and no A/D converter, so you’d have to do a fair amount of editing to obtain a usable Arduino core.

That said, if you’re reasonably fluent in C++, building your own Arduino core is not very difficult, and I found it an instructive exercise. If you care about getting your project up as quickly as possible and not get sidetracked, however, go with the 16u4.

---
Tags: core-libraries
---


# Question
Title: SoftwareSerial together with AltSoftSerial and HardwareSerial
The title says it all.

Angone with experience here on this subject?

I want to use all Hardware serial, SoftwareSerial and AltSoftSerial on Arduino Duemilanove with At328.

Is it possible?

# Answer
> 2 votes
in short - Yes. The following compiles and should work

Note the following links detail some subtle issues about HOW to use these various libraries. Some are more optimal depending upon your usage.

http://www.pjrc.com/teensy/td\_libs\_AltSoftSerial.html#speed

http://forum.arduino.cc/index.php?topic=152122.0;wap2

You might also want to consider just using either Alt or Soft. Note that NewSoftwareSerial is incorporated in the IDE 1.5.5+

```
/*
  Software serial multple serial test

 Receives from the hardware serial, sends to software serial.
 Receives from software serial, sends to hardware serial.

 The circuit:
 * RX is digital pin 10 (connect to TX of other device)
 * TX is digital pin 11 (connect to RX of other device)

 Note:
 Not all pins on the Mega and Mega 2560 support change interrupts,
 so only the following can be used for RX:
 10, 11, 12, 13, 50, 51, 52, 53, 62, 63, 64, 65, 66, 67, 68, 69

 Not all pins on the Leonardo support change interrupts,
 so only the following can be used for RX:
 8, 9, 10, 11, 14 (MISO), 15 (SCK), 16 (MOSI).

 created back in the mists of time
 modified 25 May 2012
 by Tom Igoe
 based on Mikal Hart's example

 This example code is in the public domain.

 */
#include <SoftwareSerial.h>
#include <AltSoftSerial.h>

SoftwareSerial mySerial(10, 11); // RX, TX

AltSoftSerial altSerial;
// AltSoftSerial always uses these pins:
// Board          Transmit  Receive   PWM Unusable
// -----          --------  -------   ------------
// Arduino Uno        9         8         10

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

  Serial.println("Goodnight moon!");

  // set the data rate for the SoftwareSerial port
  mySerial.begin(4800);
  mySerial.println("Hello, world?");
  altSerial.begin(9600);
  altSerial.println("Hello World");
}

void loop() // run over and over
{
  if (mySerial.available())
    Serial.write(mySerial.read());
  if (Serial.available())
    mySerial.write(Serial.read());

  char c;

  if (Serial.available()) {
    c = Serial.read();
    altSerial.print(c);
  }
  if (altSerial.available()) {
    c = altSerial.read();
    Serial.print(c);
  }
}

```

# Answer
> 1 votes
You should be aware that SoftwareSerial is blocking other interrupts when sending/receiving. I'm not sure exactly how AltSoftSerial behaves, but I believe it was written to deal with that issue. The issue arises if you use a slow baud rate on the SoftwareSerial in combination with a high baud rate on hardware serial. Then you can loose incoming data on the hardware serial. AltSoftSerial will probably be completely blocked during SoftwareSerial activity - hardwareserial can still send / receive one-two bytes in the hardware tx/rx registers. According to https://www.pjrc.com/teensy/td\_libs\_AltSoftSerial.html you can use AltSoftSerial together with SoftwareSerial, as long as the baud rate for SoftwareSerial is at least 10 times the baud rate of that used for AltSoftSerial.

If you never transmit/receive simultaneously on different interface, you don't really have to worry about any of the above mentioned issues.

When I write SoftwareSerial, I refer to NewSoftSerial, which has been called SoftwareSerial in Arduino for a while now (since 1.0 I believe).

---
Tags: serial, softwareserial
---


title: How can I send serial over RF?

text:
# Question
Title: How can I send serial over RF?
I've got the following:

```
#include <SoftwareSerial.h>

const int rx = -1;
const int tx = 4;

SoftwareSerial mySerial(rx, tx);

void setup()
{
  mySerial.begin(2400);
  pinMode(tx, OUTPUT);
}

void loop()
{
  if(mySerial.available())
  {
    String data = "Hello World";

    for(int k = 0; k < data.length(); k++ )
    {
      mySerial.write(0xAA);
      mySerial.write(data[k]);
    }

    mySerial.write(0xA9);
  }

  delay(1000);
}

```

Which I'm trying to send to to a RF transmitter module. It all compiles just fine, but am I forgetting something? And does pin 4 = physical pin 3?

# Answer
In your loop function you have:

```
if(mySerial.available())
{
  String data = "Hello World";

  for(int k = 0; k < data.length(); k++ )
  {
    mySerial.write(0xAA);
    mySerial.write(data[k]);
  }

  mySerial.write(0xA9);
}

```

The `available()` function returns the number of bytes available in the receive buffer. You say your module is a transmitter, so there will never be any data to receive (I can see the module doesn't even have a tx pin). Hence you will never transmit any data.

That said it's not a good idea to send data plain over wireless. It might work to some extent, but you'll likely get much more lost data. Look at the virtual wire library or google "manchester coding" if you wan't to roll your own.
> 1 votes

# Answer
First off, are you trying to send to the 433MHz transmitter? This will not work. If you mean you are using the 433MHz transmitter to send data to a receiver, the VirtualWire.h library work.

If you are using another transmitter please add more info on the transmitter used in this project.

HumanHarddrive on youtube got a tutorial on the DX transmitter and receiver. Tutorial
> 0 votes

---
Tags: attiny, softwareserial
---


# Question
Title: Buffering data from EthernetServer clients
I was trying to write a Telnet server that would be able to accept commands of sorts using the Arduino Ethernet library, and in order to access what the client was saying (to compare it to strings to check what command the client entered), I made a buffer string that would read until `\n`, which is part of the standard Telnet library. However, the string would never get printed to the serial connection (just for debugging purposes). Here's my code:

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

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xFE, 0xED };  // this client's MAC address

EthernetServer server(23);  // telnet is 23
boolean alreadyConnected = false;

void setup() {

  Ethernet.begin(mac);

  server.begin();  // open the socket

  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial to start, Leonardo only
  }

  Serial.print("Connect to ");
  Serial.print(Ethernet.localIP());
  Serial.println(":23.");

}

void loop() {

  EthernetClient c = server.available();

  if (c) {
    String messageBuffer = "";

    if (!alreadyConnected) {
      c.flush();
      Serial.println("New client");
      c.println("test post, please ignore");
      alreadyConnected = true;
    }
    if (c.available() > 0) {

      char thisChar = c.read();

      //server.write(thisChar);

      //buffer until the client sends a new line
      if (thisChar == '\n') {
        Serial.println(messageBuffer);
        messageBuffer = "";
      } else {
        messageBuffer += thisChar;
      }
    }
  }
}

```

Most of this code was copied from the Telnet chat server example, but I changed the `Serial.write(thisChar)` line, because I wanted to put it into a string first. When this is run, and a user `telnet`s to the IP, the Arduino prints `New client`, but when the user sends data, it doesn't print anything.

Any suggestions for what I'm doing wrong?

# Answer
Well, I asked on the #arduino IRC channel, and realized my stupid mistake. I was setting the buffer to `""` **inside** the loop.
> 0 votes

---
Tags: ethernet
---


# Question
Title: Cheap medium range wireless communication with a linux PC
I have a project that's currently using Arduino Uno with a cheap class-2 bluetooth serial adapter from ebay to send and receive data and control a LED light strip.

However, it struggles to establish connection at distances more than couple meters. I'd like to expand that range a bit - 15 meters with two load-bearing walls in the way. Bandwidth requirements are next to none - it should just move couple integers around.

Any suggestions how to do that on the cheap? From what I've seen, class-1 bluetooth adapters go for ~60$, two xbee modules + usb adapter end up costing even more, and wifi solutions seem to reside in the same price range. At that price point, it seems better to get a raspberry pi, wifi dongle and a couple beers for the software re-write. Am I overlooking some solution?

# Answer
> 2 votes
Since one end is a PC I would look into a Wifi shield for the arduino. That way you would not need any extra hardware on the PC side.

You can get a Wifi shield for less than 2 xbee modules. But using wifi will require changes to your code since it won't be using the serial port for communication.

Another wireless option that I have no personal experience with is NRF2401 modules -- you can get them dirt cheap on ebay (caveat emptor) but they use an SPI interface so you can't directly interface with them directly on the PC side.

Be aware that depending on the LED strip you may not be able to drive it directly from a raspberry pi. For example WS2811 driven LEDs (AKA adafruit NeoPixels) need precise timing that you can't get (or is tricky to get) with the raspberry pi.

# Answer
> 0 votes
"Smart home automation webserver on OpenWRT router WR703N interfaced to Arduino, compared to Raspberry Pi and Ubuntu" may lead you to some answers...

Just think of that solution as a kind of "homegrown Arduino YÙN"... just older and cheaper: "Nah, you don’t need an Ethernet module for your Arduino"

---
Tags: xbee, bluetooth, remote-control
---


# Question
Title: Using SoftwareSerial for the serial monitor
Most programs follow this route: They have a `Serial.begin()` for the serial connection between PC and Arduino (the serial monitor) and they use SoftwareSerial for a device.

Can you go the other way around? Can you use SoftwareSerial for the communication between PC and Arduino, and Serial for a device?

# Answer
Short answer: no.

Pins 0 and 1 an an Uno are directly wired to the PC communication chip. You could make a board that was wired differently and connected SoftwareSerial to the PC, but you would have to switch it back to pins 0 and 1 when uploading to the arduino somehow.

On an arduino leonardo "Serial" for communicating with PC over USB is different from "Serial1", which is connected to pins 0 and 1 on the board. You can use both simultaneously, so if you really need to use hardware serial and PC comms at the same time, I recommend you buy a leonardo.
> 3 votes

# Answer
Yes you can. If you use a USB FTDI type cable to connect your computer to the SoftwareSerial pins, you can use a terminal emulator program (HyperTerm, putty, etc) to communicate with the Arduino.
> 2 votes

---
Tags: serial, softwareserial
---


# Question
Title: What background do I need to have before starting Arduino?
Like: basics of electrical circuits, etc..

In order to go far in Arduino and electronics.

# Answer
I am a Electrical technician and bought the starter kit from the Arduino team for my 13 year old son. My plan was to try the kit to teach my son about electronics.

The end result is that he is the one showing me new stuff.

In my opinion, you do not need any special background before starting with Arduino. You should have a interest in learning something new, and in learning about electronics. To get started, buy a tutorial book and a starter kit. (Many starter-kits comes with a tutorial book) When you have gone through the book, you will have some basic knowledge and a base to continue learning from.

Good luck
> 7 votes

# Answer
You need a basic understanding of programming because you will need to program in C++. You need basic computer literacy, but I bet you've got that if you are on this website. You need some understanding of electronics, such as a High-School level textbook. You need to understand resistors, diodes, voltages, current etc. Otherwise you'll get very frustrated.
> 0 votes

# Answer
You need to learn some absolute basics about electronics so you don't fry your arduino. (Don't exceed the current limits on the i/o pins. How to use Ohm's Law to calculate current. How to tie inputs to ground with a resistor. How to tie inputs to +5 through a resistor. How to estimate the total current load of your entire circuit to make sure it doesn't overload the +5 regulated power from the Arduino. Basic precautions against static electricity.)

Beyond that, it makes a great learning tool, and you should be able to learn as you go. Build the sample projects that are on the Arduino website.

You might want to buy a book on logic circuits. I read "The CMOS Cookbook" years ago, and it gave me a good strong grounding.

You'll also want to learn programming, since you need to use C or C++. Again, though, you can use the Arduino as a learning tool. Looking at the sketches from the website and modifying them will help you learn.
> 0 votes

---
Tags: arduino-uno
---


title: Best Arduino board to play sound

text:
# Question
Title: Best Arduino board to play sound
I'm looking to purchase an Arduino for a little robot I'm going to make. The reason I've chosen Arduino is because it's much easier to use with servos and LEDs than a Raspberry Pi, but a nice little touch would be to have it play some sounds (voice recordings and mechanical SFX). I was just wondering (now I'm not after opinions here, but looking more at how each of the boards have been designed) what the *best* Arduino board for playing sound is, or if they are all pretty much the same in this regard.

(Note 'pins' was the best tag I could find for this post for lack of a 'sound' or 'speakers' one. If you want to edit it to something more appropriate please do)

# Answer
If all you need is to play back lo-fi audio then any with PWM will do, which means that any Arduino will do. If you want hi-fi sound then you'll need a DAC, which means either choosing the Due or using a discrete DAC via SPI. If you need decoding of complex audio formats such as MP3 or Vorbis then you'll need either the Due for its power, or a separate audio playback shield that supports the formats you're interested in.
> 4 votes

---
Tags: audio
---