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

body:
Assuming an Ethernet port on the PC, the Ethernet shield can be connected to it using an [Ethernet **crossover** cable][1]:

![enter image description here][2]
(*source: [Wikipedia][3]*)

Many recent PC network interfaces have automatic cross-over ([Auto MDI-X][4]), 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**.

  [1]: http://en.wikipedia.org/wiki/Ethernet_crossover_cable
  [2]: https://i.stack.imgur.com/xbJ3g.png
  [3]: http://en.wikipedia.org/wiki/File:Ethernet_MDI_crossover.svg
  [4]: http://en.wikipedia.org/wiki/Medium_Dependent_Interface#Auto_MDI-X


sender: user

message:
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][1] 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][2] I am about to use and the circuit is below.

![Circuit to use relay with Arduino][3]

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?

  [1]: http://en.wikipedia.org/wiki/Hydroponics
  [2]: http://www.ebay.in/itm/5V-2-Channel-Relay-Board-Module-10A-250AC-Opto-coupler-Arduino-Raspberry-Shield-/321432317541?pt=LH_DefaultDomain_203&hash=item4ad6dbee65
  [3]: https://i.stack.imgur.com/8Fvat.jpg

sender: assistant

body:
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][1]). 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][2] (SSR) that has a higher rating than the target load. Something
like *[SSR-25DA 25A Solid State Relay - White][3]*. 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.

  [1]: https://en.wikipedia.org/wiki/Counter-electromotive_force
  [2]: http://en.wikipedia.org/wiki/Solid-state_relay
  [3]: http://www.dx.com/p/ssr-25da-25a-solid-state-relay-white-134494


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

<!-- language-all: lang-cpp -->

    /*
    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 movement&ea=door open&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);
      }
    }

body:
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()][1]
 - [Ethernet Library][2]

  [1]: https://www.arduino.cc/en/Reference/EthernetClient
  [2]: https://www.arduino.cc/en/Reference/Ethernet


message:
Concatenation of non constant character array with a string

I have an Arduino Duemilanove.

I read [this page][1] 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?

  [1]: http://arduino.cc/en/Tutorial/StringAdditionOperator

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


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


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

body:
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](http://en.wikipedia.org/wiki/Voltage_divider). [Even more on voltage dividers](https://learn.sparkfun.com/tutorials/voltage-dividers/all?print=1).

To build one:

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

  [1]: https://i.stack.imgur.com/teuuJ.png


message:
appending string to char and vice versa

Some days ago i started a thread.
https://arduino.stackexchange.com/questions/3023/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

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

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


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


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

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


message:
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](http://arduino.cc/en/Tutorial/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](https://www.sparkfun.com/products/11121) --> BB line 30 --> BB Ground --> Arduino Ground

Please check out this picture for confirmation:

Thanks in advance for any help that you can provide!

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


message:
Controlling an LED with the 74HC4067E multiplexer

I am testing a [74HC4067E MUX](http://www.ti.com/lit/ds/schs209c/schs209c.pdf) 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](http://arduino.cc/en/Tutorial/Blink). 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.

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


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

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


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

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

****
**Original Answer:**

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

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

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

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

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


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


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

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


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

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

    class SerialGSM : public SoftwareSerial {
    ...
    };

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

 1. Derive from `HardwareSerial` instead of `SoftwareSerial`. This would give you flexibility, but you'd have to take care of passing all the right data to the `HardwareSerial` constructor, which is quite messy.

 2. Don't derive from anything. Use the global `Serial` object, and manually replace all serial function calls with their `Serial.xxx()` equivalents. This is probably easier, but it restricts you to a specific serial port.

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


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


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

body:
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][1]/[MasterWriter][2] 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");
        }
      }
    }

  [1]: http://arduino.cc/en/Tutorial/MasterReader
  [2]: http://arduino.cc/en/Tutorial/MasterWriter


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

1. Don't do Serial prints in an ISR (interrupt service routine)
2. Don't do beginTransmission / endTransmission in a receive event.
3. Don't do any writes
4. 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](http://www.gammon.com.au/i2c)


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

https://arduino.stackexchange.com/questions/16292/sending-and-receiving-different-types-of-data-via-i2c-in-arduino


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

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


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

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


body:
Even if [compiling C++ on the openwrt of the yun is possible][1] with the [last release of the yun-openwrt][2] 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][3] see the `Disabling the Bridge Script` chapter) and manually handle the serial communication.

Hope it helps!

  [1]: https://github.com/arduino/openwrt-packages-yun/pull/7
  [2]: http://forum.arduino.cc/index.php?topic=268347.0
  [3]: http://cylonjs.com/documentation/platforms/yun/


message:
Unexpected behavior of sprintf with i32/u32

I'm trying to build a string of characters from several elements given by the [TinyGPS++ library][1] 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, "$M-d-d d:d:d,%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][1] 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?

  [1]: http://arduiniana.org/libraries/tinygpsplus/

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


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

1. How do I put the string input parameter in sendSMS?
2. 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()?

body:
 1. Just change

        void sendSMS()

    to

        void sendSMS(const String& thisIsAString)

    You can then access the parameter inside the function with `thisIsAString`.

 2. No, you do not need a prototype.


body:
You can change

`void sendSMS()`

to

`void sendSMS(String myinputstring)`

you can use
myinputstring in your code.


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


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

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


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


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

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


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

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


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

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


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


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

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


message:
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][1], 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][2] 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][3] that do this already, but where's the fun in that?

  [1]: http://www.digikey.com/product-detail/en/EE-SY310/OR525-ND/68127
  [2]: http://smile.amazon.com/Trifield-100XE-EMF-Meter/dp/B00050WQ1G/ref=sr_1_3?ie=UTF8&qid=1403667890&sr=8-3&keywords=magnetic field detector
  [3]: http://smile.amazon.com/Wattvision-WV2-A-Energy-Sensor-Gateway/dp/B005BI9K0C/ref=sr_1_3?ie=UTF8&qid=1403668106&sr=8-3&keywords=wattvision

body:
A low cost option is the [TCRT5000][1] 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:

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

![TCRT5000][2]

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

  [1]: http://www.vishay.com/docs/83760/tcrt5000.pdf
  [2]: https://i.stack.imgur.com/O0tS1.jpg


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


message:
How to retrieve the data type of a variable?

I am using Arduino and I would like to know if there is a function that returns the data type of a variable. That is, I would like to run something as like the following:

    // Note: 'typeof' is a sample function that should return the data type.
    Serial.println(typeof(myVar));

body:
In a typical C++ program, you would use the `typeid` operator, like this:

<!-- language-all: lang-cpp -->

    std::cout << typeid(myVar).name();

***However,*** that requires a compiler feature called Runtime Type Information (RTTI). It's disabled in the Arduino IDE, presumably because it tends to increase the runtime memory requirements of the program.

You can get more information about the resource cost here: https://stackoverflow.com/questions/579887/how-expensive-is-rtti

Any fully-featured C++ compiler will definitely support RTTI though. If you want to try using a 3rd party IDE (such as Eclipse with the Arduino plugin) then you could easily enable it. It's probably not worth the hassle just for that though.

---

**Alternative**
A higher-performing (but less flexible) solution would be to use a traits class approach. This involves some funky template meta-programming:

    // Generic catch-all implementation.
    template <typename T_ty> struct TypeInfo { static const char * name; };
    template <typename T_ty> const char * TypeInfo<T_ty>::name = "unknown";

    // Handy macro to make querying stuff easier.
    #define TYPE_NAME(var) TypeInfo< typeof(var) >::name

    // Handy macro to make defining stuff easier.
    #define MAKE_TYPE_INFO(type)  template <> const char * TypeInfo<type>::name = #type;

    // Type-specific implementations.
    MAKE_TYPE_INFO( int )
    MAKE_TYPE_INFO( float )
    MAKE_TYPE_INFO( short )

You can add `MAKE_TYPE_INFO(..)` lines for any type you want, including the names of custom classes. You could then use it like this:

    int myVar = 17;
    Serial.println( TYPE_NAME(myVar) );

Anything you don't define using `MAKE_TYPE_INFO(..)` will show up as `"unknown"`.

That's some fairly advanced stuff in there, so I won't try to explain how it all works here. There are various tutorials on the web though about C++ template programming if you're interested.

EDIT: It's worth noting that the `typeof` operator isn't standard C++, but is supported by a few compilers, such as GCC. It's basically an older equivalent of `decltype`, which appears in the C++11 standard.


body:
I use a simple stupid approach...

```lang-C
// serial print variable type
void types(String a) { Serial.println("it's a String"); }
void types(int a) { Serial.println("it's an int"); }
void types(char *a) { Serial.println("it's a char*"); }
void types(float a) { Serial.println("it's a float"); }
void types(bool a) { Serial.println("it's a bool"); }
```

This is the concept of **function overloading** where **multiple functions** with different parameter types are created but with the **same function name**. During run time, the function matching the right number of arguments and argument type(s) will get called. Hope this explanation helps.


body:
Building on @snakeNET's answer (which I regard as function **overload** rather than **polymorphism**)...

A more generic way would be to pass in a pointer to Print, allowing any Print related class to be used (not just Serial); also pass objects by reference e.g.
```
void types(Print* p, const String&) { p->print("it's a String"); } // for each type
...
Serial.print("Type is "); types(&Serial, myStr); Serial.println();
```
Note that I has changed 'println' to 'print'; again, making it more generic.


body:
I tested the template form, the long-hand form, and the `__PRETTY_FUNCTION__` macro and got different results. See the last two rows of the table for the differences.

# Template Form 1

Attribution: [Peter Bloomfield][1]

```cpp
MAKE_TYPE_INFO( bool )
MAKE_TYPE_INFO( bool* )
MAKE_TYPE_INFO( char )
MAKE_TYPE_INFO( char* )
MAKE_TYPE_INFO( double )
MAKE_TYPE_INFO( double* )
MAKE_TYPE_INFO( float )
MAKE_TYPE_INFO( float* )
MAKE_TYPE_INFO( int )
MAKE_TYPE_INFO( int* )
MAKE_TYPE_INFO( short )
MAKE_TYPE_INFO( short* )
MAKE_TYPE_INFO( String )
MAKE_TYPE_INFO( String* )
MAKE_TYPE_INFO( char[5] )
MAKE_TYPE_INFO( char(*)[5] )
```

# Long-Hand Form

Attribution:
1. [SnakeNET][2]
2. [brewmanz][3]
3. Tweaked by me to be more generic.

```cpp
const char* TypeOf(const bool&)   { static const char type[] = "bool";    return type; }
const char* TypeOf(const bool*)   { static const char type[] = "bool*";   return type; }
const char* TypeOf(const char&)   { static const char type[] = "char";    return type; }
const char* TypeOf(const char*)   { static const char type[] = "char*";   return type; }
const char* TypeOf(const double&) { static const char type[] = "double";  return type; }
const char* TypeOf(const double*) { static const char type[] = "double*"; return type; }
const char* TypeOf(const float&)  { static const char type[] = "float";   return type; }
const char* TypeOf(const float*)  { static const char type[] = "float*";  return type; }
const char* TypeOf(const int&)    { static const char type[] = "int";     return type; }
const char* TypeOf(const int*)    { static const char type[] = "int*";    return type; }
const char* TypeOf(const String&) { static const char type[] = "String";  return type; }
const char* TypeOf(const String*) { static const char type[] = "String*"; return type; }
//const char* const TypeOf(const char[5])    { static const char* type = "char[5]";    return type; }  // Decays to char* so generates compiler redefinition warning.
const char* const TypeOf(const char(*)[5]) { static const char* type = "char(*)[5]"; return type; }
```

# Template Form 2: `__PRETTY_FUNCTION__` Macro

Attribution:
1. Original `String` version by [Vladimir Talybin][4]
2. Tweaked `char` array version by me.

## Using `String`

```cpp
template <class T>
String type_name(const T&)
{
    String s = __PRETTY_FUNCTION__;
    int start = s.indexOf("[with T = ") + 10;
    int stop = s.lastIndexOf(']');
    return s.substring(start, stop);
}
```

## Using `char` array

This variation has lower memory requirements.

```cpp
template <typename T>
char* type_name(const T&)
{
    char* pf = __PRETTY_FUNCTION__;
    char* begin = strstr(pf, "[with T = ") + 10;
    char* end = strrchr(pf, ']');
    *end = 0;
    return begin;
}
```

# Test Code

```cpp
bool b = false;
char c = 'a';
double d = 1.2;
float f = 3.4;
int i = 5;
String s = "6789";
char chars[] = "1234";

Serial.println(F("TypeOf() Test"));
Serial.println(TypeOf(b));
Serial.println(TypeOf(&b));
Serial.println(TypeOf(c));
Serial.println(TypeOf(&c));
Serial.println(TypeOf(d));
Serial.println(TypeOf(&d));
Serial.println(TypeOf(f));
Serial.println(TypeOf(&f));
Serial.println(TypeOf(i));
Serial.println(TypeOf(&i));
Serial.println(TypeOf(s));
Serial.println(TypeOf(&s));
Serial.println(TypeOf(chars));
Serial.println(TypeOf(&chars));

Serial.println(F("TYPE_NAME() Test"));
Serial.println(TYPE_NAME(b));
Serial.println(TYPE_NAME(&b));
Serial.println(TYPE_NAME(c));
Serial.println(TYPE_NAME(&c));
Serial.println(TYPE_NAME(d));
Serial.println(TYPE_NAME(&d));
Serial.println(TYPE_NAME(f));
Serial.println(TYPE_NAME(&f));
Serial.println(TYPE_NAME(i));
Serial.println(TYPE_NAME(&i));
Serial.println(TYPE_NAME(s));
Serial.println(TYPE_NAME(&s));
Serial.println(TYPE_NAME(chars));
Serial.println(TYPE_NAME(&chars));

Serial.println(F("type_name() Test"));
Serial.println(type_name(b));
Serial.println(type_name(&b));
Serial.println(type_name(c));
Serial.println(type_name(&c));
Serial.println(type_name(d));
Serial.println(type_name(&d));
Serial.println(type_name(f));
Serial.println(type_name(&f));
Serial.println(type_name(i));
Serial.println(type_name(&i));
Serial.println(type_name(s));
Serial.println(type_name(&s));
Serial.println(type_name(chars));
Serial.println(type_name(&chars));
```

# Results

| TypeOf()   | TYPE_NAME() | type_name() |
| :---:      | :---:       | :---:       |
| bool       | bool        | bool        |
| bool*      | bool*       | bool*       |
| char       | char        | char        |
| char*      | char*       | char*       |
| double     | double      | double      |
| double*    | double*     | double*     |
| float      | float       | float       |
| float*     | float*      | float*      |
| int        | int         | int         |
| int*       | int*        | int*        |
| String     | String      | String      |
| String*    | String*     | String*     |
| char*      | char[5]     | char [5]    |
| char(*)[5] | char(*)[5]  | char (*)[5] |

# Some Conclusions

1. `TypeOf()` has an issue with a decaying pointer.
2. `TypeOf()` and `TYPE_NAME()` have to have individual definitions with long-hand form or `MAKE_TYPE_INFO`.
3. `type_name()` uses the `__PRETTY_FUNCTION__` macro to automatically get the type name within the template function, therefore there is no need to individually define the different types.
4. Template Form 1 has the lowest memory requirements.

# Questions

1. Since Template Form 2 has higher memory requirements than Template Form 1, how could it be converted from Form 2 to Form 1?
2. How would a `static const char *` be initialised from a substring of a `char` array obtained from the `__PRETTY_FUNCTION__` macro and passed as a template argument at compile-time?

Something like this pseudo code?

```pseudo
static const char * name = substr(__PRETTY_FUNCTION__, begin, end);
```

Perhaps this constant expression which can be assigned to a template struct member at compile-time? (I used a `for` loop because `strstr` and `strrchr` are not `constexpr`.)

```cpp
template <typename T>
constexpr char* type_name(const T&)
{
    char* pf = __PRETTY_FUNCTION__;
    char* begin;
    char* end;
    begin = end = pf;
    bool found_open_square_bracket = false;
    for (; *pf != 0; pf++)
    {
      if (!found_open_square_bracket && *pf == '[')
      {
        begin = pf + 10;
        found_open_square_bracket = true;
      }
      if (*pf == ']')
      {
        end = pf;
      }
    }
    *end = 0;
    return begin;
}
```

  [1]: https://arduino.stackexchange.com/a/3080/68310
  [2]: https://arduino.stackexchange.com/a/39013/68310
  [3]: https://arduino.stackexchange.com/a/85315/68310
  [4]: https://arduino.stackexchange.com/a/85398/68310


body:
There also a trick using compiler predefined macro. The advantage is it can print any type.

```lang-cpp
template <class T>
String type_name(const T&)
{
    String s = __PRETTY_FUNCTION__;

    int start = s.indexOf("[with T = ") + 10;
    int stop = s.lastIndexOf(']');

    return s.substring(start, stop);
}
```

Use it like this

```lang-cpp
double pi = 3.14;
const char* str = "test";

Serial.println(type_name(pi));
Serial.println(type_name(str));
```

EDIT:
-----

Some improvements based on tim's analyze.

First I have a comment on variation that has lower memory requirements. `__PRETTY_FUNCTION__` is a literal string (a constant) that should not be changed. So my const version that do not use heap is following.

```lang-cpp
template <size_t N>
const char* extract_type(const char (&signature)[N])
{
    const char* beg = signature;
    while (*beg++ != '=');
    ++beg;

    const char* end = signature + N;
    for (; *end != ']'; --end);

    static char buf[N];
    char* it = buf;

    for (; beg != end; ++beg, ++it)
        *it = *beg;
    *it = 0;

    return buf;
}

template <class T>
const char* type_name(const T&)
{
    return extract_type(__PRETTY_FUNCTION__);
}
```

A less safe but more efficient version using the fact that offset to type we want extract is a constant (always the same). If function signature changes (like put it in a namespace) the offset will change too. But come on, set it once, write a comment and it will work forever :).

```lang-cpp
template <size_t N>
const char* extract_type(const char (&signature)[N])
{
    const char* beg = signature + 42;
    const char* end = signature + N - 2;

    static char buf[N - 43];
    char* it = buf;

    for (; beg != end; ++beg, ++it)
        *it = *beg;
    *it = 0;

    return buf;
}

template <class T>
const char* type_name(const T&)
{
    return extract_type(__PRETTY_FUNCTION__);
}
```

While above is ok ofcourse it can be improved further. Here is a my version of constexpr function mentioned by @tim. It uses constant offset as above to keep it short. This code generates only extracted string of type, the proof is [here](https://godbolt.org/z/4o1aev6n4).

```lang-cpp
#include <utility>

template <class T, std::size_t... I>
const char* type_name(std::index_sequence<I...>)
{
    static constexpr char name[] = { __PRETTY_FUNCTION__[I + 60]..., 0 };
    return name;
}

template <class T>
const char* type_name(const T&)
{
    return type_name<T>(
        std::make_index_sequence<sizeof(__PRETTY_FUNCTION__) - 44>());
}
```
The minimum requirement for this is C++14 because of sequence traits. These can be re-implemented (see definition [here](https://en.cppreference.com/w/cpp/utility/integer_sequence)) to adapt it to C++11.


message:
Controlling Arduino through MATLAB?

I had a Roboteq motor controller, but it wasn't fast enough. I'm hoping Arduino will be faster.

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

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

Thanks.

  [1]: http://www.mathworks.com/matlabcentral/fileexchange/32374-matlab-support-package-for-arduino-aka-arduinoio-package
  [2]: http://www.mathworks.com/hardware-support/arduino-matlab.html
  [3]: http://www.superdroidrobots.com/images/encoder-datasheet.jpg

body:
Do all the processing on the Arduino, and supply the results to Matlab over serial.

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

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

 - http://playground.arduino.cc/Main/RotaryEncoders

 - http://www.hobbytronics.co.uk/arduino-tutorial6-rotary-encoder

The one I use comes from here:

 - http://www.pjrc.com/teensy/td_libs_Encoder.html

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

    #include <Serial.h>

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

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

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

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

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

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

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

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


message:
Use UTP Cable to transmit/receive data?

I was wondering if it was possible to use the utp port of a computer/laptop to transmit and receive data to an external device?

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

Thanks in advance,
Regards

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

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

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

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

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

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

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

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


message:
Using SoftwareSerial for the serial monitor

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

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

body:
Short answer: no.

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

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


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


message:
why there is 4 ground in l293d?

I am using L293d motor driver to drive 2 motors simutaniusly in several direction.

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

Can anyone tell explain it?

Thank You...

body:
They are connected together and used for heatsinking,

VS - is voltage supply

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


body:
It's explain in the [datasheet][1].

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

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

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

  [1]: http://www.ti.com/lit/ds/symlink/l293d.pdf


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

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

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

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


message:
Auto acknowledge failed with nRF 24L01+ and Arduino

My transceivers are running fine. I've written a few code and got them running. Then I decided to check the auto acknowledgement feature wherein we can return data back to the sender WITHOUT manually changing the radio modes on both units. But I find that the serial monitor always shows "failed to transmit". Why is this happening, because otherwise they work fine?

I am using maniacbug's RF24master library.

The Tx code is:

    #include<SPI.h>
    #include<nRF24L01.h>
    #include<RF24.h>

    int msg[1] = {1};
    int rec[1] = {0};
    bool stat = true;
    RF24 radio(9,10);
    const uint64_t pipe[1] = {0xF0F0F0F0E1LL};

    void setup()
    {
      Serial.begin(57600);
      radio.begin();
      delay(1000);
      radio.setAutoAck(true);
      radio.enableAckPayload();
      radio.openWritingPipe(pipe[0]);
      radio.setRetries(15,15);
     }
    void loop()
    {
      if(stat)
      {
        radio.stopListening();
        bool ok = radio.write(msg,sizeof(msg));
        delay(100);
        if(ok)
        {Serial.println("transmitted successfully !!");}
        else
        {Serial.println("faileed to transmit");}
        msg[1]++;
        if(msg[1]>=200)
        {msg[1]=1;}
        stat = false;
        //delay(20);
      }
      if(!stat)
      {
        if(radio.isAckPayloadAvailable())
        {
          radio.read(rec,sizeof(rec));
          Serial.print("received ack payload is : ");
          Serial.println(rec[1]);
          stat = true;
        }
      }

    }

and the Rx part is:

    #include<SPI.h>
    #include<nRF24L01.h>
    #include<RF24.h>
    const uint64_t pipe = 0xF0F0F0F0E1LL;
    RF24 radio(9,10);
    int rec[1] = {0};
    int ack[1] = {1};
    void setup()
    {
      Serial.begin(57600);
      radio.begin();
      delay(100);
      radio.setAutoAck(true);
      radio.enableAckPayload();
      radio.openReadingPipe(1,pipe);
      radio.startListening();
      radio.setRetries(15,15);
    }
    void loop()
    {
      if(radio.available())
      {
        Serial.println("payload available....");
        bool ok = radio.read(rec,sizeof(rec));
        if(ok)
        {
            Serial.println("message received !!");
            Serial.print("integer got is : ");
            Serial.println(rec[1]);
            radio.writeAckPayload(1,ack,sizeof(ack));
        }
        else
        {Serial.println("failed to receive the message");}
      }
    }

body:
To achieve that you have to do the following -

    if ( radio.available() ) { // make sure the read will succeed
    radio.writeAckPayload( 1, buf, len ); // prep the ack payload
    radio.read( &got_time, sizeof(unsigned long) ); // also shunts out ack payload
    }
So your program finally becomes -

    #include<SPI.h>
    #include<nRF24L01.h>
    #include<RF24.h>
    int msg[1] = {1};
    int rec[1] = {5};
    bool stat = true;
    RF24 radio(9,10);
    const uint64_t pipe[1] = {0xF0F0F0F0E1LL};

    void setup()
    {
      Serial.begin(57600);
      radio.begin();
      delay(100);
      radio.setAutoAck(true);
      radio.enableAckPayload();
      radio.enableDynamicPayloads();
      radio.stopListening();
      radio.openWritingPipe(pipe[0]);
      radio.setRetries(15,15);
     }
    void loop()
    {
    if(stat)
    {
        if(radio.write(msg,sizeof(msg)))
        {
          Serial.print( msg[0] );
          Serial.println("...tx success");
          if(radio.isAckPayloadAvailable())
          {
            radio.read(rec,sizeof(int));
            Serial.print("received ack payload is : ");
            Serial.println(rec[0]);
          }
          else
          {
            stat = false; //doing this completely shuts down the transmitter if an ack payload is not received !!
            Serial.println("status has become false so stop here....");
          }
          msg[0]+=3;;
        if(msg[0]>=100)
        {msg[0]=1;}
        }
     }
    }
And the RX part becomes -

    #include<SPI.h>
    #include<nRF24L01.h>
    #include<RF24.h>
    const uint64_t pipe[1]= {0xF0F0F0F0E1LL};
    RF24 radio(9,10);
    int rec[1] = {2};
    int red;
    void setup()
    {
      Serial.begin(57600);
      radio.begin();
      delay(100);
      radio.setAutoAck(true);
      radio.enableAckPayload();
      radio.enableDynamicPayloads();
      radio.openReadingPipe(1,pipe[0]);
      radio.startListening();
      radio.setRetries(15,15);
    }
    void loop()
    {
      if ( radio.available() ) {
        radio.writeAckPayload( 1, rec, sizeof(int) );
        radio.read( &red,sizeof(red) );rec[0]+=2;
        Serial.print("integer got is : ");
        Serial.println(red);
    }
    }
Know more about it at the following pages -
https://shantamraj.wordpress.com/2014/07/19/exploring-the-auto-ack-feature-of-the-transceiver/
https://shantamraj.wordpress.com/2014/11/30/auto-ack-completely-fixed/


message:
HC-0# Bluetooth module questions

I've been playing with the HC-06 BT module lately, but now I want to do more with it and I'm not sure how to. I was wondering if it's possible to get signal strength from the module, or would I have to purchase another HC-0# module to do so? Also the HC-05, can initiate connection if I'm understanding documentation right, and return available devices in the area?

body:
> I was wondering if it's possible to get signal strength from the module

No, it doesn't appear so from the data sheet / AT command list.

> Also the HC-05, can initiate connection if I'm understanding documentation right, and return available devices in the area?

Yes, and it can get the signal strengths.  You should be able to get an HC-05 module on a breakout board from Ebay for less than $10 delivered.  There's also a method to update the HC-06 firmware to be an HC-05 but it's probably easier for you to buy one.