text:
Confusion around LEDs on a breadboard
I am just starting out with an Arduino Diecimila and am playing around with LEDs, and am confused by why some circuits result in an LED not lighting up.
Successful Scenarios:

Yellow LED from pin13 to 16B on the breadboard, Green LED from 16A to GND. This works both LEDS light up.
Yellow LED from pin13 to 16A on the breadboard. Wire from 16E to 14E. Green LED from 14A to GND. This works and both LEDs light up.

Failed Scenarios:

Yellow LED from pin13 to 16A. Green LED from 16E to 14E. Yellow LED from 14A to GND. No LEDs light up. I would assume that all the LEDS are in series, and all 3 should light up, I assumed this would be exactly the same as my second successful scenario where the LED is acting the same as the wire.
Yellow LED from pin13 to 16A. Wire from 16E to 14E. Yellow LED from 15A to GND. Green LED from 16B to 14B. Here I have both Yellow LEDS lit, but the Green LED is not lit. I was expecting that the Green LED would have been in parallel and should have lit up.

In both failed scenarios I have swapped around the LEDs and proved that all the LEDs function.
There must be some basic concept that I am not understanding with the circuits, any ideas?

How do you expect us to figure out the problem if you don't supply a schematic you're using and your code?

Photograph of breadboard would also help.  Value and placement of resistors.  If you are not using resistors, I'm worried for the longevity of your LEDs and Arduino.

Read up on LEDs here. There is a lot to consider even for driving these simple devices. Namely, forward voltage and active-mode current are very important. Driving LEDs without a series (current limiting) resistor will surely end your experimentation sooner than later. Either you will burn out the LED or you will destroy one of your Arduino's output pins.

Of course we assume you know which way round you are connecting the LED's (Hint ... they are not light bulbs that don't care)

Scenario 1 fails because yellow and green LEDs have forward voltages of about 2V each, so when putting 3 in series, you need a forward voltage to light them that exceeds the 5V available.
Scenario 2 fails because the wire you have in parallel with the LED provides a path with a very low voltage drop (close to 0V), so the path through the LED with a ~2V voltage drop is not taken (and if you remove the wire, the same reasoning as in scenario 1 applies, so nothing would work).
BTW, you should never run LEDs without a series resistor, as your experiments will surely demonstrate to you soon ;-)

s/a series resistor/some form of current limiting, which may be but is not limited to a simple series resistor/

@IgnacioVazquez-Abrams, you forgot the opening  tag, but otherwise, you're, of course, right.


text:
Serial.write() prints a variable twice
I have this code:
#include <TinyGPS++.h>
#include <SoftwareSerial.h>

#define GPS_RX_PIN 2
#define GPS_TX_PIN 3

TinyGPSPlus gps;
SoftwareSerial ss(GPS_RX_PIN, GPS_TX_PIN);

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

char clat[11];
char clng[11];

void loop()
{

        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(), 11, 6, clat);
                        dtostrf(gps.location.lng(), 11, 6, clng);
                        isGpsLocationValid = true;
                    }
                }
             }
        } while (isGpsLocationValid == false);
        Serial.write(clat);
        Serial.println();
        Serial.write(clng);
}

Now when all is done, the clng value is printed twice in the serial monitor.
The value i get is in this format:
27.275869  15.151013
  15.151013

As you can see, clng is printed twice. Any ideas why is that?

I think your question may already be answered here: http://arduino.stackexchange.com/questions/1197/strange-behaviour-of-dtostrf

The width parameter to dtostrf() is the width of the resulting string NOT including the null terminator. So you are overflowing the array.
Change:
char clat[11];
char clng[11];

to
char clat[12];
char clng[12];

and it should work.

bear in mind, my number is this : 27.275869 . and i have declared 11 digits. i think they are more than enough. i will provide more feedback on this tomorrow

The width parameter is the minimum width not the maximum width.  See the docs.  If you have signed lat/long values you will need 11 characters plus the null terminator. Unsigned will only need 10 plus the null.

2 digits + 1 sign + 1 dot + 6 decimal digits + 1 NULL = 11. Why do i need to declare more?

Because dtostrf will pad the result string with spaces so that it is at least 11 characters long, so you need 12 chars in your variable. Instead of arguing, you should just do it and see that it works with 12.

I did with up to 14 digits and the results remain the same

you were right! I didnt pay too much attention to your answer and i misunderstood i should increase the dtostrf parameter instead of the array size!

source: Stack Exchange

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

sort: votes


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

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;

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


text:
Bluetooth module(HC05) works with Arduino Uno but not with breadboard (ATmega328)
I am currently working on a project that requires communication between an android phone(galaxy s4) and an ATmega328 microprocessor. To connect these devices wirelessly I'm using an HC05 bluetooth module and to understand the connection I'm using pre-built arduino codes(turn LEDs on and off) and an android app called blueterm.
This connection is established and able to transmit data when connected to the Arduino uno, but as soon as this chip is removed and connected to a standalone breadboard the connection fails. The standalone breadboard works fine and has been tested with many other projects and I have attached the breadboard connection below. The HC05 when connected to the breadboard changes the blinking pattern to notify the user it is connected but the serial connection is never made. Any help would be greatly appreciated, if any other information is needed feel free to ask.

It looks like the HC05 should be moved one row to the left.

It might be a bad angle but the last pin is not needed on the HC05 unless editing its internal settings. The connection is not changed when moving back to the arduino just the pins that go to the atmega328 are moved from the breadoard to the arduino.

I guess your module has a different pinout that the one I found online. I also check, but the Uno doesn't have any pull-up resistors, so that's not it. Does your atmega run off 3.3V too?

Are you sure pin TX (on the Bluetooth side) is connected to pin 0 on the chip, and RX is connected to pin 1?

I would like to give some suggestions: If BT module connects to a phone (LED is solid, no blinks) and no data received, i would do some tests like: connect Rx-Tx and check does MCU echo typed letter. Connect Rx-Tx of BT module and check on android does it echo typed message.

i am also facing same problem did you ended up with any solution???

Some bypass capacitors on the ATMega and near the regulator wouldn't be a bad idea.  You have filter capacitors, but nothing physically close and compact enough to handle high frequency currents.  A bluethooth module is also a fairly high current device when it transmits, and yours is powered via a very surpentine route through the breadboard, past the ATmega.  Consider giving it its own connection directly to the regulator.

I too had the same issue. I used pullup 1k resistors for RX and TX. Then it works.

If the LED is blinking, the device is waiting to pair with another Bluetooth transceiver (your phone). Once paired, the LED will stay lit. The factory-set pairing code is usually 1234. I can't tell from the photograph how the HC-05 Rx & Tx are wired to your ATmega328, but note that it must be cross-connected; that is Rx -> Tx and Tx -> Rx.

I had same issue and solved by below mentioned layout.


text:
Arduino Ethernet Shield: May I connect it to a PC connected to the internet via wifi?
I have an Arduino Ethernet shield.
May I connect it to a machine that´s connected wirelessly to the internet in order to get the arduino into the internet?
Or do I need to connect it only to a router?

Assuming an Ethernet port on the PC, the Ethernet shield can be connected to it using an Ethernet crossover cable:

(source: Wikipedia)
Many recent PC network interfaces have automatic cross-over (Auto MDI-X), with which even a regular (straight) Ethernet patch cable will work.
This merely addresses the physical Ethernet connectivity.
For actually routing IP packets between the Arduino and the rest of the Internet, some software router or software bridge is required to run on the PC. Several open source routing products exist, especially for Linux and FreeBSD, but that is outside the scope of this StackExchange.
Finally, the Ethernet shield does not need a router, it an as well be hooked up to an Ethernet switch or hub.

Note: on Windows you can select both the WiFi adapter and the ethernet adapter and click "bridge connections."


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

The relay board you will be using already has opto-coupler and transistor driver on the board. You can directly drive the board from your Arduino. Check out this stack exchange page (similar product) : http://electronics.stackexchange.com/questions/18908/not-sure-how-to-wire-my-5vdc-to-120vac-arduino-relay-board

The relay coil will consume maybe 50 to 100 mA. This will reduce battery life dramatically.

@Andyaka could you please take a look at the update ?

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.

I am not using solar power now. but thinking about failsafe. i power arduino from wall wart dc supply. so incase of mains failure i want to supply from battery so my arduino wont restart and mess things.


text:
Arduino Laser Trip Wire with Analytics
I've done this laser trip wire:
http://www.instructables.com/id/Another-Arduino-Laser-Tripwire/
Got it working, and now I'd like to send info to analytics - to measure how many times I enter the kitchen...
I tried to take bits of code and add it to my code from:
http://bigsnarf.wordpress.com/2013/12/24/arduino-sensor-python-and-google-analytics/
and one more which I can't post due to permissions....
but neither will work and adding this code breaks my basic functionality (I know as I measure it via the buzzer, it stops responding once I add this new code...
Is there anyone able to help?

Here is my basic working code for the laser trip wire that makes buzzer noise if someone walks through it:
/*
Jonathan Robson Feb 09.
Laser tripwire activates a buzzer. adapted from
http://www.instructables.com/id/Arduino_Laser_Tripwire/
*/

int buzzPin = 11; // buzzer connected to digital pin 11

void setup() {
  pinMode(buzzPin, OUTPUT); // sets the digital pin as output
}

void loop(){
  if(analogRead(0) < 850){ // this number depends on calibration of the photocell
    digitalWrite(buzzPin, HIGH); // turns buzzer on
    delay(1000); // waits for 1 second
    digitalWrite(buzzPin, LOW); // turns buzzer off
  } else{
    digitalWrite(buzzPin, LOW);
  }
}

Here is the code with analytics additions I’ve added:
/*
Jonathan Robson Feb 09.
Laser tripwire activates a buzzer. adapted from
http://www.instructables.com/id/Arduino_Laser_Tripwire/
*/
#include <SPI.h>
#include <Ethernet.h>

byte mac[]     = {  0x0C, 0xD2, 0x92, 0xAC, 0x75, 0x0B };

// To skip the DNS
IPAddress server(173,194,40,97); // www.google-analytics.com => 173.194.40.97
EthernetClient client;

int buzzPin = 11; // buzzer connected to digital pin 11

// Global switch (debug mode without API call)
boolean netword_enabled = true;

int sendEventToGA() {
  int responseCode      = 0;

  if (!netword_enabled) {
    return responseCode;
  }

  // open the connection
  if (client.connect(server, 80)) {
    int responseSize      = 0;
    int responseSizeMax   = 1024;
    char response[1024];
    String eventData = "v=1&tid=UA-51525058-1&cid=123&t=event&ec=home%20movement&ea=door%20open&el=bedroom"; // Refer to the Google documentation

    Serial.println("Connection opened!");

    // Write the HTTP request to the Client
    client.println("POST /collect HTTP/1.1");
    client.println("Host: www.google-analytics.com");
    client.print("Content-Length: ");
    client.println(eventData.length());
    client.println("Content-Type:application/x-www-form-urlencoded");
    client.println();
    client.println(eventData);

    Serial.println("Request sent.");

    // Wait a little bit
    delay(1000);

    // Read the response, looking for the Response Code.
    while (client.available() && client.connected() && responseCode < 100 && responseSize < responseSizeMax) {

      response[responseSize] = client.read();
      responseSize++;
      response[responseSize] = '\0'; // Set manualy the end of string char

      // Here is the magic!
      sscanf (response, "HTTP/1.%*d %d", &responseCode);

      Serial.print("HTTP code ");
      Serial.print(responseCode);
      Serial.print(" founded in ");
      Serial.println(response);
    }
  }

  Serial.println("End of communications.");

  client.stop();
  return responseCode;
}

void setup() {
  pinMode(buzzPin, OUTPUT); // sets the digital pin as output
  Serial.begin(9600);

  // start the Ethernet connection
  if (netword_enabled && Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");

    // no point in carrying on, so do nothing forevermore:
    for(;;)
      ;
  }

  // give the Ethernet shield a second to initialize:
  delay(1000);
}

void loop(){
  int responseCode;
  if(analogRead(0) < 850){ // this number depends on calibration of the photocell
    digitalWrite(buzzPin, HIGH); // turns buzzer on
    responseCode = sendEventToGA();
    delay(1000); // waits for 1 second
    digitalWrite(buzzPin, LOW); // turns buzzer off
  } else{
    digitalWrite(buzzPin, LOW);
  }
}

Welcome to Arduino SE! Can you please add your code? If you "can't post it because of permissions," you probably can't even use it. Also, it's generally okay if you cite your source (although it's your call). Either way, it's impossible to tell you how to fix your code without seeing it. If you can narrow it down to a small section and post that, it'd be fine to do so (along with any dependencies/extra functions it calls). Until then, we can't really help you. The only advice I can give you is this: does the code sending it to the serial port block the checking function? Is there a delay()?

I'm trying but my code is over 2k characters and there's a limit here to 600 characters per response.....

I also started reading an arduino book and it mentions Ethernet shield - so I ordered that... Here is a link to my code hosted on Google docs (I couldn't figure out how to use github) https://docs.google.com/document/d/19zs9w6boCrlycgCAMj2P_llAl-arpekeR1IbDxO4J70/edit?usp=sharing

Do you get no buzzer? Or does the buzzer start, but not stop?

in my current code - everything works fine. in the version with updated analytics - the buzzer doesn't stop when hovered by laser. But again - as above, I don't even have the ethernet shield addon  - so maybe when I have that it will work? Maybe that's why there's a conflict.

@KrystianS Did you ever end up trying this with the Ethernet shield? Did it make a difference?

I'm voting to close this question as off-topic because it has been abandoned for 3 years without information to make it answerable ever being provided.

As with any piece of code that doesn't work, it is very easy to troubleshoot using the Serial.println() statement.
The big clue here is that the buzzer turns on but never turns off. Go ahead and add unique Serial.println() statements between each statement in the loop() function.
My guess is that the digitalWrite(buzzPin, HIGH) executes but it never exits the sendEventToGA() function.
If this is the case, then go ahead and add unique Serial.println() statements in between each line of the sendEventToGA() code.
Again, my guess is that the code goes into the while() statement and never comes out. This while statement is waiting for a response from the server. If you never get a response it won't exit.
Perhaps add a timeout or determine why Google Analytics isn't returning a response.
Help on the topic can be found at the Arduino Libraries reference pages:

EthernetClient()
Ethernet Library


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

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.

totally worked! But i have an extra question. Imagine i have two values a latitude and longitude. So char clat[11],clon[11]; And dtostrf(gps.location.lat(), 10, 6, clat); dtostrf(gps.location.lon(), 10, 6, clat); And i want a final string that is "Latitude/Longitude: 30.111111 20.111111". How do i do that? I tried char final[20 + 30m + 1] = "Latitude/Longitude: "; dtostrf(gps.location.lat(), 10, 6, clat+10); dtostrf(gps.location.lng(), 10, 6, clng+32); and other permutations of the numbers but none of these work. I get "Latitude/L 30.000000" Message is cut and 2nd value doesnt appera at all!

For "Latitude/Longitude: 30.111111 20.111111" literally, you would need char cfinal[39+1] = "Latitude/Longitude: "; dtostrf(gps.location.lat(), 11, 6, cfinal+20); dtostrf(gps.location.lat(), 11, 6, cfinal+30);. I'd probably make the array a little longer and make the dtostrf() fields a little wider. Lat/longs could go to -180.0.... If you plan for it now, your maintenance at a later time will easier.

I just read your other question on this topic. See my edited answer above - should help you with both questions.

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:

http://arduino.cc/en/Reference/StringObject: main documentation for the string datatype
http://arduino.cc/en/Tutorial/StringAdditionOperator how to append data to a string


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

See http://arduino.stackexchange.com/posts/418/edit - you need a logic-level voltage converter (e.g.), unidirectional in this case.

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.


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

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?

Avoid using String at all costs! This is very bad for embedded programs. Take a lookk at my answer http://arduino.stackexchange.com/questions/1013/how-do-i-split-an-incoming-string/1033#1033 to see why

(See my updated answer to your other question.

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!

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.

In C/C++, char clat[31] allocates 31 characters, not 32. The resulting elements are indexed 0 to 30 inclusive (i.e. there is no element 31).

@Peter Fixed that mistake..

I think it was I who started expressing array lengths as sums in an earlier thread w/ this OP. It isn't necessary to do but it documents why I made the array that long. The final sum is all the compiler cares about but '30+1' reminds me that I've allowed for the NUL terminator in my count. Likewise, '10 + 10 + 1' says I'm counting two strings and the terminator. It just serves to remind me how I arrived at the size.


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

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.


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

How is the Arduino powered?

Powered by USB.

If the Arduino is powered, then the LED should either always be lit since it is always between 5V and GND, or never if it was mounted reverse (that is not visible in the picture you posted). It won't ever blink if you wire it this way!

The long leg of the LED is on the positive side - the left. Your first comment made me go back to the Uno spec and I read: "The board can operate on an external supply of 6 to 20 volts. If supplied with less than 7V, however, the 5V pin may supply less than five volts and the board may be unstable." So maybe that is my issue since USB is only 5V.

No, USB is fine for Arduino. The problem is that you did not connect your LED to a digital output of Arduino. Please take a careful look at the circuit in the blink tutorial you referred to.

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!

How couldn't I figure that one first? I have been bitten by the same stupid mistake on a few occasions already :-) That's why I have put staples to connect halves of power lines of all my breadboards now! Staples work great for that.

Don't feel bad, we've all made this mistake more than once. I like the staples idea!

What I usually do is just place jumpers to connect the two sides of the power/ground rails. This way they're connected by default and if I need to separate them, I can just remove that wire.


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

Pins 1 & 2 are connected to the breadboard but NOT connected to the IC, as you forgot to put a wire from E to F on the breadboard for these pins, they are thus not connected to your IC.

Good eye! I will give it a run tonight. This is the second time you have solved one of my questions. I wish you would post these as answers so that I can give you credit!

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.

I've heard a few things about floating pins and grounding them for stability's sake. Any suggested reading to help me fully understand the subject?

@Nate It's not just stability, but the enable pin 15 is an input to the logic in the chip. The output depends on the state of all inputs as defined by the truth table in the data sheet. The enable input is pretty important and its state is undefined if you don't connect an input wire to it. If the enable input is undefined, then it follows that the output is undefined.

@Nate The exception is inputs that are marked with an X in the truth table (which indicate a "don't care" input).

It worked! It worked sporadically after I actually connected pins 10 and 11 as jfpoilpret suggested, but it works consistently with the enable pin grounded. In fact, this fixes another issue I was having - I had been needing to disconnect the 5V supply line from the arduino board in order to upload code to it. Now, that is not needed. Thanks!


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

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 1s, 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?

The cabling is maybe 2m long. Baude Rate is 115200... what would be the benefit of a lower baude rate? And how do I know how much I need?

Since I thought the error is in my matlab code, I already opend a SE question for that, since this is now more concerning the delay, rathen than the swaps in bits, let's continue there.
Your suggestion works! 1/3s sample time gives valid/current time values! Pls help me to fully understand where this could have come from:
http://stackoverflow.com/questions/24368670/matlab-plot-serial-data-continously

@mike it's not a problem of the Matlab code, it's the Arduino then. You're sending more data than the serial chip can handle at the baud rate you specified. I know I said lower it (I thought info was getting corrupted), but you need to raise the baud rate and lower the sample rate.

25 Hz is possible. That's as high, as possible. However I wanted to debug a quadcopter filtering,... which doesn't quite make that much sense if I run 1/2 or even 1/4 of the planned sampling rate. (I try to get my 100Hz, or at least 50).
Also if I add more numbers this phenomenon gets occurs more often I guess? Because it's overflow, right? I'll try to get a shorter cabling, thanks for the advice!

@mike Glad I could help! Edited my question and I cleaned up the comments here.

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.

So I need to add Serial.write('ab') and then write the number bits. And in matlab fread 2+number-bits and check if the first 2 are ab. If not, re-read.
Is this the thing you suggest? What do you mean by collision with my data.. If I just read 1+num-bits, and they shift, I would still get an error if not all bits are there, or the first one is not "a"?

By collision I mean that if your data happened to be the characters 'ab' it would mess up a reading. Your correct about the arduino side, just send "ab" before the data. The matlab code should detect that the sequence "ab" happened and then look for the data bits next, but if another "ab" happens before the data bits are done dump what has already come in and start over. That way it will realign with the data if a byte is dropped.

Collision you mean the probability, that in my actual values one of the bytes contains the header by incidence? So a longer header would reduce the possibility of having real data = termination string. Correct?

Exactly. With two bytes there is a 1 in 2^16 probability of random data generating the header. A longer header than 2 bytes that might result in less data making it across since your packets are so small; Sending an extra character per packet would probably cost more time than losing one in 65536 packets.

Ok fine. I would implement this as Serial.write(219); Serial.write(128); Since what is sent is binary (thus the same as some char), and for matlab it is easier to directly read (&compare) the uint with 8 bit.
I mark this as solution, since I can remove the shifts. The whole thing is useless however, since there is some strange time delay that adds up. See:
http://stackoverflow.com/questions/24368670/matlab-plot-serial-data-continously

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.


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

Arduino MEGA2560
LCD-Shield http://www.sainsmart.com/arduino/arduino-shields/lcd-shields/sainsmart-1602-lcd-keypad-shield-for-arduino-duemilanove-uno-mega2560-mega1280.html
Motor-Shield http://www.sainsmart.com/arduino/arduino-shields/motor-shields/sainsmart-l293d-motor-drive-shield-for-arduino-duemilanove-mega-uno-r3-avr-atmel.html

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

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.


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

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:

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

Thanks a lot! Ok, if that is the case, i can use it in Software Serial mode. Now, i have a gps unit that i want to use as well. That means, plug in the shield and use the SerailGSM library, and also plug in the gps on ports 0 (and 1 if i want the gps to receive data), and use Serial.begin(4800); to start the serial receiving stuff?

That should work, although bear in mind that SerialGSM outputs debug info to hardware serial. That means if you connect the hardware TX to your GPS, then it will probably go wrong.

OK, another approach then would be to use arduinos ready example of sending sms. the thing is i have this shield https://www.sparkfun.com/products/9607,  with the SM5100B chipset. Do you know if the arduinos example of SMS sending will work with this shield?

I've never used that shield, so I'm afraid I don't know. It looks SparkFun have their own sample code for it though: https://github.com/sparkfun/SM5100B_Cellular_Shield/blob/master/Firmware/Cellular_Shield_Passthrough_b/Cellular_Shield_Passthrough/Cellular_Shield_Passthrough.pde

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)


text:
I2C 2 way communication between Arduino Uno and Arduino Mega
If I remove the transmission code from slave this works properly but I need to transmit from slave.
Here is my master code
#include <Wire.h>
void setup() {
  Wire.begin(3);
  Wire.onReceive(receiveEvent);
}
byte x = 0;

void loop() {
  Wire.beginTransmission(9);
  Wire.write("s");
  Wire.write(x);
  Wire.endTransmission();
  x++;
  delay(500);
}

void receiveEvent(int howMany) {
  if(Wire.available()){
    int x = Wire.read();
    Serial.println(x);
  }
}

Here is my slave code:
#include <Wire.h>
void setup() {
  Wire.begin(9);                // join i2c bus with address #9
  Wire.onReceive(receiveEvent); // register event
  Serial.begin(9600);           // start serial for output
}

void loop() {
  delay(100);
}

void receiveEvent(int howMany) {
  if(Wire.available()){
    char c = Wire.read();
    Serial.print(c);
    if(c == 's'){
      int x = Wire.read();
      Serial.println(x);
      //transmit to master
      Wire.beginTransmission(3);
      Wire.write(1);
      Wire.endTransmission();
    } else {
      Wire.read();
    }
  }
}

Is it possible not to use Wire.onRequest(requestCallback); to send data to master? Kindly help.

When a sketch calls Wire.begin() and passes a number, it has nominated itself as a slave on the bus.  So you appear to have two slaves.  Normally one would have one master and one slave.

What you seem to want is a combination of the Arduino Wire Tutorial http://arduino.cc/en/Tutorial/MasterReader and http://arduino.cc/en/Tutorial/MasterWriter do you agree?

i had a look but not able to implement it properly any suggestion ? if i give 2 wire.write the master is not reading it properly

I don't know what you mean, sorry.

the Wire.requestFrom has only one wire.write i need multiple wire.write which is not supported so is there any workarounds ?

To join the bus as a master you cannot supply a 7-Bit slave address so your code has two slaves.
Below you will find 2 sketches that successfully sends data to a slave. I would suggest you start looking at the I2C protocol and understand there are 4 Modes:

Master->Transmitter
Master->Receiver
Slave->Transmitter
Slave->Receiver

All communications regardless of how the data is transferred requires a master. It's the master that controls the clock pulses, thats why its always the master that initiates the communcation.
The MasterReader/MasterWriter tutorials on the arduino forum should now possibly start to make a little more sense when understanding those modes.
This code shows how a master sends data to a slave, and then how it requests data from the slave. If we look at this code from the master point-of-view, you can see it essentially says, send this byte to the client (m->t & s->r), then request data from the slave (m->r,s->t)
Master Code
#include <Wire.h>

#define SLAVE_ADDRESS 0x60

void setup()
{
  Wire.begin();
  randomSeed(analogRead(3));
  Serial.begin(9600);
}

byte x = 0;

void loop()
{
  x = random(0,255);
  Serial.print("Sent: ");
  Serial.print(x, HEX);
  Serial.print("\n");
  Wire.beginTransmission(0x60);
  Wire.write(x);
  Wire.endTransmission();
  delay(500);
  Serial.println("Requesting Data");
  Wire.requestFrom(SLAVE_ADDRESS, 1);

  int bytes = Wire.available();
  Serial.print("Slave sent ");
  Serial.print(bytes);
  Serial.print(" of information\n");
  for(int i = 0; i< bytes; i++)
  {
    x = Wire.read();
    Serial.print("Slave Sent: ");
    Serial.print(x, HEX);
    Serial.print("\n");
  }
  delay(500);
}

Slave Code
#include <Wire.h>

#define SLAVE_ADDRESS 0x60
byte x = 0x00;
void setup()
{
  Wire.begin(SLAVE_ADDRESS);
  Wire.onReceive(receiveEvent);
  Wire.onRequest(requestEvent);
  Serial.begin(9600);
}

void loop()
{
  delay(100);
}

void requestEvent()
{
  Serial.print("Request from Master. Sending: ");
  Serial.print(x, HEX);
  Serial.print("\n");

  Wire.write(x);
}

void receiveEvent(int bytes)
{
  if(Wire.available() != 0)
  {
    for(int i = 0; i< bytes; i++)
    {
      x = Wire.read();
      Serial.print("Received: ");
      Serial.print(x, HEX);
      Serial.print("\n");
    }
  }
}

On master you could scan the address range for connected device. This would be a proper approach.

In both of your event handlers: Don't do serial prints inside an ISR. It may work until the serial buffer fills up, then it will hang.

You don't need to test if(Wire.available() != 0) because the bytes variable has the number of bytes you received. If anything, test if bytes > 0 however I presume that a receive event would have at least one byte.

I went through this problem recently. Your slave needs two functions: one for sending and the other for receiving data.
// function: what to do when asked for data
void requestEvent() {
Wire.write(t);
}

// what to do when receiving data from master
void receiveEvent(int howMany)
{Val = Wire.read();}

Here is a code that works both ways of i2c communication in a single code
Sending and receiving different types of data via I2C in Arduino

You had:
 void receiveEvent(int howMany)
 {
   {
         if(Wire.available()){
           char c = Wire.read();
           Serial.print(c);
           if(c == 's'){
             int x = Wire.read();
             Serial.println(x);

             //transmit to master
             Wire.beginTransmission(3);
             Wire.write(1);
             Wire.endTransmission();

           }else{
             Wire.read();
           }
         }

       }

There are a number of problems with your slave code.

Don't do Serial prints in an ISR (interrupt service routine)
Don't do beginTransmission / endTransmission in a receive event.
Don't do any writes
To send data back use a requestEvent not a receiveEvent.

Better would be:
// add in setup()
Wire.onRequest (requestEvent);  // interrupt handler for when data is wanted

...

volatile byte what;

void receiveEvent(int howMany)
{
  if (howMany < 2)
    return;

  char c = Wire.read ();
  if (c != 's')
    return;

  what = Wire.read ();  // remember what we got
}  // end of receiveEvent

void requestEvent()
{
  Wire.write (1);  // return a response
}  // end of requestEvent

the Wire.requestFrom has only one Wire.write. I need multiple Wire.write which is not supported so are there any workarounds?

Batch up the response and do one write:
void requestEvent ()
  {
  byte buf [4] = { 1, 2, 3, 4 };
  Wire.write (buf, sizeof buf);   // send response
  }  // end of requestEvent

Reference
There are a lot of examples at I2C - Two-Wire Peripheral Interface - for Arduino


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

Also relevant: http://arduino.stackexchange.com/questions/1096/extend-battery-life-with-a-power-controlling-microcontroller

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.


text:
Arduino Yun C++ environment? Bridge + Cross-Compiler
I'm creating an XMPP chatbot for the Arduino Yun. However, I'm not too confident in the Python performance on such a low performance device and I'm much more comfortable with C++. Is there a C++ crosscompile environment available, and is there a port of the Bridge library to C++? Alternatively, documentation on how to interface with the ATMega using raw serial communication?

The Linux side of the Yun is just an OpenWRT installation. It has hardly been modified at all.
To cross-compile you will first need a Linux computer, or a Linux virtual machine.  Then you need to download the OpenWRT source code and configure it for the Yun (I think it defaults to the right settings).  Then you can build the whole OpenWRT image.  One side-effect of that is it compiles and configures a full cross-compiling environment for you.
You can then use that cross-compiling environment to compile your own code.

Even if compiling C++ on the openwrt of the yun is possible with the last release of the yun-openwrt you should make a yun build-chain. That makes you compile on you computer for the processor architecture of the embedded machine on the yun.
I have never done but you can find some informations about it in those links:
- https://github.com/arduino/openwrt-yun
- http://fibasile.github.io/arduino-yun-custom-buildroot.html
- http://fibasile.github.io/compiling-nodejs-for-arduino-yun.html
- https://github.com/arduino/openwrt-yun/issues/20
For the other question.. for sure you can read/write serial directly from the openwrt. You need to disable the Bridge library (there are a lot of post around the internet. one is this one see the Disabling the Bridge Script chapter) and manually handle the serial communication.
Hope it helps!


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

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


text:
Functions with string parameters
Inside my main loop there is this string:
String string1;

I have a function that will take string1 as parameter, and use it to send this string as SMS.
sendSMS(string1);

This is the sendSMS() function (without parameters):
void sendSMS()
{ sms.beginSMS(remoteNumber);
  sms.print(finalstr);
  sms.endSMS();
  lcd.setCursor(0, 0);
  lcd.print("Message sent!");
  delay(10000);
}

My questions are:

How do I put the string input parameter in sendSMS?
Do I also need to use a function prototype for sendSMS()? (so that it appears three times, 1 in the prototype, 1 in the declaration and one in the call). Or I don't need to use function prototype before the main loop()?

Just change
void sendSMS()

to
void sendSMS(const String& thisIsAString)

You can then access the parameter inside the function with thisIsAString.
No, you do not need a prototype.

I would rather advise to pass the String by reference, to avoid additional code to be executed for nothing (copy-constructor, destructor): void sendSMS(String& thisIsAString) or even better, a const reference, if the string argument is not to be modified by the function: void sendSMS(const String& thisIsAString)

I'd say to never use String again. When code gets bigger and memory usage will be critical you'll hit a dead-end. I know it's more convenient, but give char arrays a shot. Something like:
bool sendSMS(int remoteNumber, char *finalstr){
  bool isFinished = 0;
  sms.beginSMS(remoteNumber);
  for (int i=0;i<sizeof(finalstr);i++){
      sms.print(finalstr);
  }
  sms.endSMS();
  lcd.setCursor(0, 0);
  lcd.print("Message sent!");
  delay(10000);
  isFinished = 1;
  return isFinished;
}

I changed the function to bool. It means that you can use it inside an if statement, where you would want it completed before continuing with your code.
You will need to allocate memory yourself for the array; declare it like this:
char stringArray[33] = {'\0'};

Here, I allocate 32 bytes for data and one additional byte for the character that means "end of string" (it's that \0).

You can change
void sendSMS()
to
void sendSMS(String myinputstring)
you can use
myinputstring in your code.

That's just a repeat of the other answer.

Not a repetition of the other answer. This one is by copy, not by reference. Prefer the other answer to avoid copying of the object.

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


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

Welcome to Arduino SE! Is it that GSM.h declares SoftwareSerial inside? You could've tried that before posting. It seems as that's the problem. I'm closing this as a duplicate of the question listed, in the time being as the errors are near identical, but if it's not, feel free to ping me with @ and my username or to flag this. Thanks!

No problem! Glad you got it solved.

the code utilizes interrupt 3/4/5 (check your datasheet to see what they are) that are already being utilized by other parts of your code.

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.

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


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

Did you install the driver? What OS are you on?

Yes, the driver has been installed. I'm currently running Windows 7, although I have an IMac if needed.

Just curious, what happens when you use your iMac? I'm trying to figure out if it's your computer or Arduino.

I will try tomorrow and get back to you soon.

I've tried with my iMac and I get this error
avrdude: stk500_recv(): programmer is not responding

You'll get a similar message if there is no bootloader on the atmega328. Maybe the fake pro-mini is just blank. You can flash the bootloader using a working arduino as ISP.

I don't have another Arduino. I an also pretty sure there is a bootloader because when I press the reset button, The LED comes on for about a second, and then turns off. It will also occasionally blink.

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.


text:
Can the Adafruit PN532 NFC/RFID be used to read Gen-2 EPC class RFID Tags?
I used Mifare Classic cards on a previous project and it worked brilliantly with the RIFD/NFC shield and Arduino Uno. I came across a Gen 2 EPC Class 1 RFID tags. This tags are long range ones. They use an IC chip called Alien Higgs3. I know that the shield itself is not capable of reading from a long range. I would just like to know if the shield is just able to read this type of tag even in close contact.
Is there a UHF RFID Reader that I can use to connect it with the Arduino and read these tags?
Any advice or suggestions are welcome. Thank alot.
RFID Tag Specifications:
Protocol- EPC Class 1 Gen2
Frequency- 860-960 MHz
IC Type (chip)- Alien Higgs3

It can not. The frequencies are different: 13.56MHz vs.868–956 MHz.


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

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

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


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

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

Also, floating inputs will generally increase current consumption of CMOS chips.

Ah ha! The Digital Read Serial and Input Pullup Serial tutorials make more sense now. If only there was an INPUT_PULLDOWN! I should never assume that a lack of a definite signal means LOW.


text:
What sensor would detect the black stripe on an analog electricity meter?
I have an analog electricity meter (AEM) and I would like to track my usage of electricity.
I've attempted to use the EE-SY310 photo sensor, but that's not sensitive enough it seems. I suspect the black stripe on the dial is too thin to be picked up. The other concern on using any photo sensor is its dependance on light (obviously) hence no reading would be picked up during the night.
Other: I've also found that AEMs work by using magnetic fields to move the dial. The magnetic field detector I used did not show much fluctuation when turning appliances on/off. The dial was pegged at the max. Therefore, I'm not so confident that a sensor to measure magnetic fields would work here, but I'm open to suggestions.
So, would anyone know what sensor would be good to detect the black stripe on AEMs?
Preferably to also work without light.
I know there are off-the-shelve products that do this already, but where's the fun in that?

Why not a reflectivity sensor?

I didnt think of that. Worth checking.

A low cost option is the TCRT5000 infrared proximity sensor. While this is designed to sense objects coming close to the sensor, by reflection of the infrared light emitted by the integrated IR LED, it also does very well in detecting black versus reflective surfaces placed near it.
There are two parts to making this work:

Reduce the drive current for the IR LED of the TCRT5000 to the bare minimum which causes detection of the non-black portion of the electricity meter disc. While the datasheet specifies a forward current of up to 60 mA absolute maximum, a quick experiment I conducted shows appreciable detected signal at as little as 4 mA forward current, for a metallic target surface 2 mm away. Tune the forward current to work with the actual distance and reflectivity of your particular electricity meter wheel.
Place a black piece of card or plastic in front of the detector part of the TCRT5000, with a thin slit cut in it to align with the black strip on the electricity meter wheel. I am getting good results using a 1.2 mm plastic sheet with a 0.3 x 1.5 mm slit cut in it.
Note that the two hemispherical plastic parts of the TCRT5000 look more or less the same, so you will have to identify which one is the detector, and ensure that you do not obstruct the emitter by mistake. The side with the angled vertical edges (right side of image below) is the emitter and must not be obstructed.

With this arrangement, the collector current through detector will dip significantly each time the black stripe passes in front of the detector.

On ALL mechanical watt-hour meters (those with a rotating disk), the disk will have either one or two holes, typically in the mid section or outer edge of the aluminum disk. Utilities used these holes to pass a light beam through (from the top of the meter to the bottom of the meter) to detect and count disk rotations. A simple light source and photo-transistor can be used to detect the presence of the disk hole to sense disk rotations.