body:
Have you considered maybe using the Inhaos Buono Mega 2560 (see [a][1]), also called the [Inhaos Mega2560][2]?

As far as I can tell, it is pretty much identical hardware as the Arduino Mega 2560 -- including the ATmega2560 processor -- except it has a selector to run the ATmega2560 at 3.3 V, so its I/O pins can be directly connected to 3.3 V modules.

Like many websites, every page on the Inhaos website http://www.inhaos.com/ has a "Contact Us" link at the top of each page. Click that link to get a list of several ways to contact the company.

  [1]: http://www.inhaos.com/newsview.php?news_id=44
  [2]: http://www.inhaos.com/product_info.php?products_id=117


sender: user

message:
Need to power Arduino Mega 2560 with 3.3V

I found an LCD for my Arduino Mega 2560 that's parallel (I like that, I don't like SPI), but it works at 3.3V and isn't 5V tolerant. That's why I'd need to use level shifters, but that would use too much space and I'd like to power the microcontroller with 3.3V. But that would cause problems because the USART communication is set to be on 5V and that can't be changed.

Is there a way to power my Arduino at 3.3V? Is there an alternative Arduino for that?

Also, if there is, I'd need to have a 16MHz crystal on it. I know it's overclocking, but Gamebuino works at 16MHz on 3.3V and I would like to do the same.

sender: assistant

body:
Have you considered maybe using the [Iteaduino MEGA2560][1]?

The [Iteaduino MEGA2560][2]
uses the same ATmega2560 processor as the Arduino Mega 2560,
but is physically much smaller, the size of a Arduino UNO.
It has a switch to run the ATmega2560 at 3.3 V, so its I/O pins can be directly connected to 3.3 V modules.
It breaks out *all* the GPIO pins of the ATmega2560,
so it actually has more I/O on its connectors than the Arduino Mega 2560.

If I'm reading this right, the [Iteaduino schematics][3] and a [typical Iteaduino features list][4]
seems to say it already has a 16 MHz crystal.

  [1]: https://www.itead.cc/iteaduino-mega-2560.html
  [2]: http://wiki.iteadstudio.com/Iteaduino_MEGA_2560
  [3]: ftp://imall.iteadstudio.com/IM120410003_Iteaduino_MEGA_2560/Documents/SCH_IM120410003_Iteaduino_MEGA_2560.pdf
  [4]: http://www.epictinker.com/Iteaduino-MEGA-2560-p/dep024.htm


body:
Have you considered maybe using the [ElecFreaks Freaduino MEGA2560][1] ?

It has an identical I/O arrangement and dimensions as the Arduino Mega 2560 -- including the ATmega2560 processor. It has a selector to run the ATmega2560 at 3.3 V, so its I/O pins can be directly connected to 3.3 V modules.
The voltage regulators and reset switch position are better than the Arduino Mega 2560.

  [1]: http://www.elecfreaks.com/estore/freaduino-mega2560-white-color-mb-frdn011.html


message:
Problem in receieving message

I'm working on a project in which when I press reset button the arduino should send longitudes and latitudes to my phone. I'm a beginner and tried to join two codes, first code can send the message and the second code can get the lon and lat printed on the serial monitor.

First code--

    int timesTosend=1;
    int count=0;
    char phone_no[]="+917771914436";
    void setup()
    {
      Serial.begin(9600);
      delay(2000);
      Serial.println("AT+CMGF=1");
      delay(200);
    }
    void loop()
    {
      while (count<timesTosend)
      {
        delay(1500);
        Serial.print("AT+CMGS=\"");
        Serial.print(phone_no);
        Serial.println("\"");
        while(Serial.read()!='>');
        {
          Serial.print("Hii If this message is sent then its a huge sucess for me");
          delay(500);
          Serial.write(0x1A);
          Serial.write(0x0D);
          Serial.write(0x0A);
          delay(5000);
        }
        count++;
      }
    }

Second code--

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

    long lat,lon; // create variable for latitude and longitude object

    SoftwareSerial gpsSerial(4, 3); // create gps sensor connection
    TinyGPS gps; // create gps object

    void setup(){
      Serial.begin(9600); // connect serial
      gpsSerial.begin(9600); // connect gps sensor
    }

    void loop(){
      while(gpsSerial.available()){ // check for gps data
       if(gps.encode(gpsSerial.read())){ // encode gps data
        gps.get_position(&lat,&lon); // get latitude and longitude
        // display position
        Serial.print("Position: ");
        Serial.print("lat: ");Serial.print(lat);Serial.print(" ");// print latitude
        Serial.print("lon: ");Serial.println(lon); // print longitude
       }
      }
    }

My code which is not working--

    #include <SoftwareSerial.h>
    #include <TinyGPS.h>
    long lat,lon; // create variable for latitude and longitude object

    SoftwareSerial gpsSerial(4, 3); // create gps sensor connection
    TinyGPS gps; // create gps object

    void setup()
    {
      Serial.begin(9600); // connect serial
      gpsSerial.begin(9600); // connect gps sensor
        Serial.begin(9600);
      delay(2000);
      Serial.println("AT+CMGF=1");
      delay(200);
    }

    int timesTosend=1;
    int count=0;
    char phone_no[]="+917771914436";
    void loop()
    {
      while (count<timesTosend)
      {
        delay(1500);
        Serial.print("AT+CMGS=\"");
        Serial.print(phone_no);
        Serial.println("\"");
         while(Serial.read()!='>');
        {
          while(gpsSerial.available())
          {
            if(gps.encode(gpsSerial.read()))
            { // encode gps data
        gps.get_position(&lat,&lon); // get latitude and longitude
        Serial.print(lat,lon);
          delay(500);
          Serial.write(0x1A);
          Serial.write(0x0D);
          Serial.write(0x0A);
          delay(5000);
            }
          }
        }
        count++;
      }
    }

Please help me out by correcting my mistake in the code.

body:
    Serial.print(lat,lon);

That doesn't do what you think it does.  That is trying to print the latitude encoded in base "lon", which just isn't going to work.

Instead you need to send it as separate operations:

    Serial.print(lat);
    Serial.print(",");
    Serial.print(lon);

Also you should separate out the GPS and GSM routines.  Create a function that gets the latitude and longitude, and another function that sends the two values as a text message.  Then you can keep things as discrete obvious steps and not get confused with what is happening when.


message:
The Time are functions do not work correctly when the processor clock speed is set at 128K

How can I change The timers to work correctly when The processor clock is set to 128K instead of 16 M?
At present, using the delay function does not work correctly, The delay is far too long.

body:
A commonly-used approach is writing an intermediate or surrogate delay function that your application calls.  That delay routine needs a way to know if the clock is slow (128 KHz) or fast (16 MHz).  If the clock is slow, divide the delay counts by 125 (the ratio of 16 MHz and 128 KHz) before calling the built-in `delay()`.  [Or, adjust all your application calls to use numbers scaled down by a factor of 125, and in the surrogate scale them back up if the clock is fast.  This may give you better control than just rounding, truncating, or truncating up will do.]

For example, if you call the intermediate routine `vDelay()` and change your app calls from a `delay(x)` form to a `vDelay(x)` form, in the function `vDelay(unsigned long ms)` you will say something like `if (ClockIsSlow) delay((ms+124)/125); else delay(ms);`


body: Add a new entry in boards.txt with the new value for `f_cpu`. Note that the timing functions will become far less precise at so low a speed.


message:
Esp8266 V12 Wiring

I have tried a Google search and cannot find any place that tells me exactly how to wire the version 12 esp8266 ,

How should it be wired for normal operation and for flashing ?

I am designing a diy pcb and need to know the specifics,to wire a switch for flashing purposes etc.I am using just a esp8266 version 12 standalone without a typical arduino micro-controller attached and will be flashing it to take the arduino ide ,any help with this would be great as I'm sure someone has already come across this problem.

body:
You could find the [solution][1], on the first hit for googling "ESP8266 ESP-12".

> [![wiring][2]][2]
>
> You need to connect a few GPIO pins on the ESP-12 to 3.3V or Ground,
> to set it in the right mode for communicating with it. Here are the
> connections you need to make :
>
> VCC ----> 3.3V Power supply (Vout of LM1117)
>
> GND ----> Ground of power supply
>
> CH_PD ----> HIGH (3.3V)
>
> GPIO2 ----> HIGH (3.3V)
>
> GPIO15 ----> LOW (GND)
>
> GPIO0 ----> HIGH or Floating for AT Mode (3.3V) [ * if you want to
> flash completely different firmware then you must connect it to ground
> ]

You need to connect `GPIO0` to `GND` for flashing and to `VCC` for normal operation.

  [1]: http://www.instructables.com/id/Getting-Started-with-the-ESP8266-ESP-12/?ALLSTEPS#step3
  [2]: https://i.stack.imgur.com/r9Zj3.jpg


message:
Switch MPU6050 to send SCL data through A4 and SDA through A5

I have [this MPU6050][1], and like most of the other MPU6050s, it is set up for SCL to be attached to A4 and SDA to be attached to A5. I have [this shield][2] on my Arduino Uno, which is configured for Sainsmart's (the company who made the shield) MPU6050, so the special MPU6050 pins are set up V, G, A5, A4, and my current setup needs V, G, A4, A5. I am using the built-in Wire library, [I2CDev library][3], and [the MPU6050 library][4]. So I am wondering whether there is something in these libraries that define which pins it looks for my MPU6050 on, and if so how do I change it.

  [1]: http://www.dfrobot.com/index.php?route=product/product&product_id=880
  [2]: http://www.amazon.co.uk/SainSmart-InstaBots-SS-SBR-1-0-Sensor-Shield/dp/B00N1YANH2
  [3]: https://github.com/jrowberg/i2cdevlib/tree/master/Arduino/I2Cdev
  [4]: https://github.com/jrowberg/i2cdevlib/tree/master/Arduino/MPU6050

body: The pin definition is in hardware. There is nothing you can do to change it. However you could try to reprogram it to use a software i2c library instead of the hardware wire library.


body:
Why not build a small board that converts the pins from V, G, A5, A4 to V, G, A4, A5? Or modify the PCB e.g. cut and rewire the signals in the order you want. It is only two pins!

Cheers!


message:
Choosing Right Power Supply for Arduino - ESP8266 - HC-SR04

If I make connections like you see in picture below, will it work? Will I damage ESP or HC-SR04?

As I know;

HC-SR04 (VCC) -> 5V

ESP8266 (VCC) -> 3.6V

ESP8266 (RX/TX) -> has 5V tolerance ?

I have not taken into account the currents that will each pin draw. So, is everything OK?

I'm not good at this stuff, so I'll appreciate it if you guys give me advice

[Image](http://postimg.org/image/mik7ms3fv/#codes)

[![Circuit Diagram][1]][1]

Most of you suggest to use voltage regulator instead of external AA batteries. However, I have already ordered one but it takes too much time (nearly week) to get, due to delivery-shipping issues. So, I want to work on the coding part of my project.

  [1]: https://i.stack.imgur.com/ua0lc.jpg

body:
 1. GND seems dangling.
 2. If you are going to use multiple power sources, make sure that all the minus/GND are connected together.
 3. Whether the ESP8266 can use 5V or not should be checked against the actual unit you have. There are many variants and some might be more tolerant than others.
 4. You do not show the power source for 5V - what is it?
 5. By just typing on google HC-SR04 5V, you get a link to the manual, which has a section "4.0 PRODUCT SPECIFICATION AND LIMITATIONS": Min:4.5V Typ:5V Max:5.5V. You should at least give it a try and report your findings, asking for clarifications, if you need any, rather than just ask here for something that google can provide.


body: When you get the wiring sorted out, remove the batteries and plug in the USB, that should power it up and allow you to start writing your code.


message:
Can one supply an Arduino Zero's VIN pin with 5v?

The title pretty much says it all. I know that most Arduinos can do this, but I couldn't find very much information for the Zero. Any help would be very much appreciated.

body:
Yes you can. If you look at the schematics on the Arduino website you can see that the 3.3 volt regulator is connected to the 5 volt regulator. That means that if you feed 5 volts straight into the 5 volt pin it will go through the 3.3 volt regulator to supply the main chip.
Note that this is going into the 5 volt pin not the VIN pin which goes into the 5 volt regulator and would thus require a higher voltage than 5 volts.


message:
What wrong with that code?

Hi i have made this code
its so simple its should receive data from the computer and send it back via the serial but the problem is he do not what it is suppose to do
when its run its keep sending -1 to the computer
and if i send something to the arduini  like  55   i receive and answer 53
i have no idea were is the problem in this code

    long number = 0;

    void setup() {
      Serial.begin(9600);
    }
       void loop() {
       number = Serial.read();
       delay(1000);
       Serial.println(number);
    }

body:
You need to include `DEC` as the second argument to the `Serial.println()` call to get the correct numbers out.  Read up on this here: [Arduino Serial Print](https://www.arduino.cc/en/Serial/Print).

In other words, make change below:

    Serial.println(number, DEC); // DEC is needed to get the correct values


body:
`Serial.read()` returns one character from the input. `Serial.println` will try to convert a variable into ASCII characters, and print that. Your variable, `number` gets the ASCII code of the first typed character in its first byte. The `Serial.println` call will interpret that and the next 3 bytes (whatever they happen to be...?) as a value to be printed.

Your problem is in not understanding the conversion of digit strings into values and vice-versa, and of how the Serial.xxx functions work.

You'll need to collect the terminal input character-by-character into an array, then convert it to a numeric value (assuming you're eventually going to do more with it than print it back out). Then you could `Serial.println()` that (or another) value out to the terminal.


message:
Read sensor and convert reading to const char*

I'm working on a home automation project using Arduino and MQTT.

I've found a problem and my limited programming knowledge find a way to solve it.

I can send text trough MQTT normally, using

    client.Publish("some/topic","Some text here");

But when I try to send a variable (int, char, etc), the compiler says "invalid conversion from 'char' to 'const char*' [-fpermissive]"

How can I store DHT11 sensor reading in const char* to send it?

BTW, I've found [this][1] code where

    char *tempC;
    tempC = dtostrf(((((analogRead(tempPinIn) * 5.0) / 1024) - 0.5) * 100), 5, 2, message_buffer);
    client.publish("arduino/temperature",tempC);

is used. But the extra sensor calibration makes it even harder for me to understand whats going on.
  [1]: http://e.verything.co/post/61576413925/publishing-arduino-sensor-data-through-mqtt-over

body:
The function `dtostrf()` is prototyped as:

    char *dtostrf (double          val,
                   signed char     width,
                   unsigned char   prec,
                   char           *sout);

    Where:
       val      Your float variable;
       width    Length of the string that will be created INCLUDING decimal point;
       prec     Number of digits after the deimal point to print;
       sout     Destination of output buffer;

An example of usage is as follows:

    /* OPTION ONE */

        char msgBuffer[20];           // make sure this is big enough to hold your string
        char *pointer_to_created_string;

        float testFloat = 123.45;

        pointer_to_created_string = dtostrf(testFloat, 6, 2, msgBuffer);
        client.Publish("...topic...", pointer_to_created_string);

    /* OPTION TWO */

        char msgBuffer[20];           // make sure this is big enough to hold your string

        float testFloat = 123.45;

        client.Publish("...topic...", dtostrf(testFloat, 6, 2, msgBuffer));

Don't be put off by the code in the link you included in your question. The first argument sent to `dtostrf` (everything before the first comma) is nothing more than a some calculations bundled into one single line.


message:
Advanced Line Follower robot

I know about line follower mainly the grid solving robots i know the basics actually. Actually they have to trace the path of the grid in an arena and then reach back to starting point in a shortest distance. Here my doubt is regarding the line follower in this link I have attached.[Advanced Line Follower Robot for maze solving][1]

My doubt is what are the procedures to do it? They have mapped the path and used Dijkstra algorithm to solve the path. But how do they transfer the code(i.e) where it has to turn which direction it has to turn. how are they generating the what function should be passed? Please explain i need the procedure alone. am going to try it with python.

  [1]: https://www.youtube.com/watch?v=5At_u5rnh2U

body:
Any language will do, as long as it is supported by your HW platform.
If you want to use python, you need a board that can run python.
That could be an Arduino Yun, for example. Or an Intel Quark. Or an Intel Edison with an Arduino shield.
But these will be expensive.

You could, alternatively, use C/C++ and an Ardino UNO (or micro, nano, mini pro), which is far cheaper.

Googling for something as simple as "Arduino line following kit" gives as first answer [this][1], which seems to be exactly what you are looking for.

  [1]: http://www.instructables.com/id/Line-following-Robot-with-Arduino/?ALLSTEPS


message:
Is it possible to specify a pin upon which the data sent over i2c can act?

A master will send fan speed values to the slave. The slave will then read the fan speed values and change the speed value for the relevant pwm pin. However I am not sure how I can tell the slave which pin the data is for.  Should I send two packets of data in quick sucsession and then have a loop system wherby the first peice of data out of two is always for specifying the pin? Any help in tackling this would be greatly appreciated.

body:
In a way, yes.  You are making the assumption that many beginners do, that I2C is only able to send one byte.  That's not the case. You can send many bytes as one single packet with I2C.

Send a single packet consisting of two bytes - the first is the pin number and the second the speed.


body:
You can use a struct to send multiple things, like this:

<!-- language-all: lang-C++ -->

    #include <Wire.h>

    const byte SLAVE_ADDRESS = 42;

    struct t_message
    {
      byte pin;
      byte speed;
    } message;

    void setup ()
    {
      Wire.begin ();   // initialize master
    }  // end of setup

    void loop ()
    {
      // set desired parameters
      message.pin = 10;
      message.speed = 50;

      // send the message
      Wire.beginTransmission (SLAVE_ADDRESS);
      Wire.write ((byte *) &message, sizeof message);
      Wire.endTransmission ();
    }  // end of loop

---

More information about [I2C - Two-Wire Peripheral Interface - for Arduino](http://www.gammon.com.au/i2c)

---

On that page is mentioned how to [Send and receive any data type](http://www.gammon.com.au/forum/?id=10896&reply=8#reply8). This includes structs. Using the code there you could send a struct, and receive a struct.


message:
Difference in bootloader of ATmega with 16MHz external crystal and 8MHz external crystal

I have used your bootloader for ATmega2560-16AU with 16MHz external crystal and it works like a wonder.

In my new project I have a 3V power supply. Therefore, I am planning to use a low frequency external crystal in order to operate the ATmega at a low frequency so that the voltage will be able to go as low as possible.

However, I have a number of issues/questions:

 1. I uploaded the bootloader using an 8MHz external crystal and it went successfully but I am not able to upload a sketch.

 2. Can I run an ATmega2560-16AU with an 8MHz crystal and will it work at 3V, without any risk?

 3. As I do not have an ATmega2560-8AU right now, I am not able to test this. Will your bootloader work with Atmega2560-8AU and an external 8MHz crystal or, before burning bootloader, do I need to make any changes?

Sorry to ask you such a long query, but I have really spent lots of time looking at this and finally today I made a post everywhere.

body:
Yes, the ATmega328 will run fine at 8MHz, at 3 volts.

The formulas for clock speed vs. volts are:

* Below 1.8V - cannot operate
* Below 4 MHz - use at least 1.8V
* Between 4 MHz and 10 MHz you require: Volts = 1.8 + ((M - 4) * 0.15)
(Where M is Megahertz)
* Between 10 MHz and 20 MHz you require: Volts = 2.7 + ((M - 10) * 0.18)
(Where M is Megahertz)
* You can supply an absolute maximum of 5.5V

Plugging 8MHz into this formula: volts = 1.8+((8-4)*0.15) = 2.4 volts minimum (5.5 volts maximum). Note that, as batteries are used, their voltage goes down gradually, so the 0.6 volts difference will mean that your project will run a little longer.

Since your supply is > 2.7V, we can reverse the second formula: 3V=2.7+(M-10)*0.18); 0.3=(M-10)*0.18; 0.66=M-10, so you can run it at 10.66MHz at 3V (but it is likely to stop as soon as the battery starts to drain).

Your second question, I think, is the most relevant one - the bootloader is written for 16MHz, and some things will not work at other speeds - serial communications used for programming for example. The same, for that matter, applies to the program - if you put in a `delay()` instruction in your code, it will `delay()` for twice as long as it should.

You can get around the programming side by ditching the bootloader altogether - once your code is ready, select file->upload using programmer. This will still affect the speed your sketch runs at (anything time-related - serial communications, `delay()`, etc). To change this, you will need to add a custom entry to the `boards.txt` file. See [\[HOWTO:\] Anatomy of the boards.txt file for custom boards][1].

  [1]: http://forum.arduino.cc/index.php?topic=158701.0


message:
Problem activating HC-05 AT command mode with Arduino Uno Bluetooth shield

Please be gentle with me. I am attempting to modify the configurations of my HC-05 bluetooth module by using the AT command set. The method by which I'm trying to do this is by implementing the following connection:

HC-05 GND --> Arduino GND;
HC-05 3.3v --> Arduino 3.3V;
HC-05 TX --> Arduino Pin 10;
HC-05 RX --> Arduino Pin 11;
HC-05 KEY --> Arduino Pin 9

[![enter image description here][1]][1]

This is the code which I uploaded to my Arduino (btw my arduino uno is an SMD clone): (code's from http://www.instructables.com/id/Modify-The-HC-05-Bluetooth-Module-Defaults-Using-A/step2/The-Arduino-Code-for-HC-05-Command-Mode/)

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

    #include <SoftwareSerial.h>

    SoftwareSerial BTSerial(10, 11); // RX | TX

    void setup() {
      pinMode(9, OUTPUT);  // this pin will pull the HC-05 pin 34 (key pin) HIGH to switch module to AT mode
      digitalWrite(9, HIGH);
      Serial.begin(9600);
      Serial.println("Enter AT commands:");
      BTSerial.begin(38400);  // HC-05 default speed in AT command more

     }

    void loop() {
      // Keep reading from HC-05 and send to Arduino Serial Monitor
      if (BTSerial.available())
        Serial.write(BTSerial.read());

      // Keep reading from Arduino Serial Monitor and send to HC-05
      if (Serial.available())
        BTSerial.write(Serial.read());

    }

The problem is I can't seem to activate the AT mode. I don't get any response from the Serial Monitor whatever AT command I try. I double-checked the wiring and it's all good. I can't figure out what the problem is.

body: After 3 hours I magically solved my pretty simple problem myself. If you wired the HC-05 and arduino correctly, the module should indicate that it's in AT Mode by blinking the LED in an interval of 2 seconds. You should get response in the Serial Monitor by typing the AT commands by switching from "No line ending" to "Both NL and CR". That's about it.


message:
Problems connecting reliably using HC-05 (as bluetooth master)

I currently try to connect an Arduino Micro/Leonardo/32u4 to an ELM327 Bluetooth dongle using a HC-05 Bluetooth shield from iTeadStudio. I also have similar problems trying to connect to a bluetooth dongle (with added serial connection) on my PC.

The basic AT-command communication works, but I haven't found out yet why AT+PAIR or AT+LINK are failing and what should be done to avoid this (I've done dozens of Serial Monitor command iterations). Until now I haven't found a command sequence that reliably connects. What I've tried so far (from different documentation and example codes):

Check general AT command set:

    AT
    > OK
Reset to default values:

    AT+ORGL
    > OK
Set master mode and check it:

    AT+ROLE=1
    > OK
    AT+ROLE?
    > +ROLE:1
    > OK
Connect only to the specified bluetooth address:

    AT+CMODE=0
    > OK

Reset and initialize:

    AT+RESET
    > OK
    AT+INIT
    > OK
Configure inquiring mode:

    AT+INQM=1,9,48
    > OK
Inquire:

    AT+INQ
    > +INQ:12:34:567890:1F1F,7FFF
    > OK
    AT+STATE?
    > +STATE:INQUIRING

Try to stop inquiring:

    AT+INQC
    > OK
    AT+STATE?
    > +STATE:INQUIRING
    > OK
Reset and initialize again (otherwise we can't leave the inquiring state):

    AT+RESET
    > OK
    AT+INIT
    > OK
    AT+STATE?
    > +STATE:INITIALIZED
    > OK
Try to pair with the found device (my PC asks for the 1234-password and creates a serial port):

    AT+PAIR=12,34,567890,20
    > OK
    AT+STATE?
    > +STATE:PAIRED
Try to connect

    AT+BIND=12,34,567890
    > OK
    AT+LINK=12,34,567890
    > FAIL
    ...

Does someone have some hints for finding the right sequence?

body:
I am using a "BIND" between the PAIR and LINK:

    AT+PAIR=98D3,31,FC2D54,5
    AT+BIND=98D3,31,FC2D54
    AT+LINK=98D3,31,FC2D54

That seems to work for me.

See the docs here:

ftp://imall.iteadstudio.com/Modules/IM120723009/DS_IM120723009.pdf


body:
It looks like I now have a slight understanding of what happens and how to get the HC-05 working.

Be sure to have the CMD-DAT-switch set to CMD before turning on the HC-05.

**Command mode (configuration)**

Check general AT command set:

    AT
    > OK
Reset to default values (sets, among others, ROLE=0 and CMODE=1):

    AT+ORGL
    > OK
Set master mode and check it:

    AT+ROLE=1
    > OK
    AT+ROLE?
    > +ROLE:1
    > OK
Reset and initialize (reset aborts, e.g. the inquiring state - quickly flashing LED; without initializing you would get ERROR(16)):

    AT+RESET
    > OK
    AT+INIT
    > OK
Now the LED should slowly flash.
Optionally: set password of the target device:

    AT+PSWD=1234
    > OK
Show count of all authenticated devices in pair list:

    AT+ADCN?
    > +ADCN:7
    > OK
If the value is larger than 0, delete all authenticated devices in pair list:

    AT+RMAAD
    > OK
Now pair with the desired device (the last 20 mean 20s):

    AT+PAIR=12,34,567890,20
    > OK
The LED starts flashing one time with a longer pause.
Set the desired device:

    AT+BIND=12,34,567890
    > OK
Now link (e.g. when connecting to the ELM327; the PC will create another new port after having requested the password from the user):

    AT+LINK=12,34,567890
    > OK
The LED starts flashing two times with a longer pause. After linking, it might be that either the HC-05 switches to data-mode or continues in command-mode (haven't found out when it does one or the other).

**Command mode (auto connect)**

Now switch off the HC-05 and keep the CMD-DAT-switch to CMD. Switch it on again. It should automatically connect to the previously connected device. To switch to the data mode, first disconnect...

    AT+DISC
    > +DISC:SUCCESS
    > OK
... and reconnect.

    AT+LINK=12,34,567890
    > OK
Now the connection seems to have switched to data mode.

**Data Mode**

Now switch off the HC-05 and move the CMD-DAT-switch to DAT. Turn on the HC-05. It automatically will try to connect to the previously connected device - the LED should flash two times with longer pause - and you don't have to mess with HC-05-AT commands any more.


message:
How to use serial.read a sentences and serial.print after that enter to new line

This is my code but it doesn't work. I don't no why . I hope someone can explain the problem. Tks

    unsigned char InTransfer;
    char buffer;
    void setup()
        {
      Serial.begin(9600);
    }

    void loop()
    {
      /* when get the sentences and print it*/
       while ( Serial.available())
      {
        buffer=Serial.read();
        Serial.write(buffer);
        InTransfer=1;    // detect
      }
      /* After done enter one time */
      if (Serial.available()==0)
        if(InTransfer==1){
          Serial.println("");
          InTransfer=0;
      }
    }

body:
Your code works perfectly, I don't see a problem with it. It's doing *exactly* what you're telling it to.

The problem lies in a fundamental lack of understanding about how serial communications work on your part, so you are telling it to do the wrong thing.  Until you fix that aspect no program you try and write in this way will be a success.

You should start by learning how serial communication actually works.  A good starting point is an article I wrote ages ago: http://hacking.majenko.co.uk/reading-serial-on-the-arduino


message:
How can I enable the security bit of a teensy board?

I want to prevent someone from connecting an arduino device to a computer and downloading the code (yes, the hex-dump code) because I want to embed a wifi password inside a device that should be kept secret

With that said, I stumbled upon [this answer][1] that mentions a security bit

I would like to ask for more details regarding it - i.e. how can I use it, enable it, what are it's limitations, etc. (Preferably for a Teensy v3.2 board, but if it's standard/generic, I would accept such an answer as well).

  [1]: https://arduino.stackexchange.com/a/180/10606

body:
It is possible for the AtMega processors - like the Teensy 2.0 (see https://www.pjrc.com/teensy/ ).

Steps:

1. Work out your exact code. It will be a pain to update it once this is done, so thing carefully.

2. Upload the code using ICSP (file->upload using programmer). TEST IT HERE!

3. Work out the fuse you need to set. The important one is "RSTDISBL" - this disables the reset pin (makes it behave just like a regular pin).  Use the page at http://www.engbedded.com/fusecalc/ to calculate your fuse settings.

4. DOUBLE CHECK IT!

5. Use an ICSP to set the fuse. You will need to work out the 6 pins to connect the ICSP to, since there is no standard ICSP header.

If you did everything right, and the reset pin no longer works - this will protect the code from download!

If anything went wrong (e.g. you set the wrong fuse values - I've been there), or if you want to change the code, you will run into problems. In theory, you can use a high-voltage programmer - like http://www.societyofrobots.com/member_tutorials/node/239 - to reset everything to factory, but that takes 20 volts, and there's a high chance one of the other components on the Teensy board will be damaged.

Note that, if you do use the High-voltage programmer, the chip's memory will be wiped, so this can't be used to recover your code.


body:
While this does not answer your question, I believe it may help you with an alternative approach, which won't hide it completely, but will make it a lot harder to figure out.

Rather than keeping the password in plain text (which will be easy to spot in a hex dump), you can hide it somewhat. For example, exclusive-or each byte of the password with a randomly chosen number, put the result in your code; then, when you want to log in to the wifi, exlusive-or it with the same numbers (which must also be on your code).

Note that all the information required MUST be on the Teensy, so it is not impossible to reverse engineer; however, it will be hidden from casual inspection.

Note that, although more complex obfustication is possible (using any off-the-shelf encryption), since both the code and any keys will be available to an attacker, it is a token gesture only.

The Teensy v3 has JTAG, which means a running Teensy can be inspected, single-stepped, all memory and pin states can be viewed & modified. Once someone has your device, it's pretty much a lost cause against a determined attacker.


body:
The Teensy 3.2 board is based on MK20DX256. The processor core is an ARM and not AVR. The best way to learn about security on the MK20DX256 is to read the [documentation][1].

> Chapter 8 Security
8.1 Introduction
This device implements security based on the mode selected from the flash module. The following sections provide an overview of flash security and details the effects of security on non-flash modules.

> 8.2 Flash Security
The flash module provides security information to the MCU based on the state held by the FSEC[SEC] bits. The MCU, in turn, confirms the security request and limits access to flash resources. During reset, the flash module initializes the FSEC register using data read from the security byte of the flash configuration field.

> NOTE The security features apply only to external accesses: debug and
EzPort. CPU accesses to the flash are not affected by the status
of FSEC. In the unsecured state all flash commands are available to the programming interfaces (JTAG and EzPort), as well as user code execution of Flash Controller commands. When the flash is secured (FSEC[SEC] = 00, 01, or 11), programmer interfaces are only allowed to launch mass erase operations and have no access to memory locations.

> Further information regarding the flash security options and enabling/disabling flash security is available in the Flash Memory Module.

The next step is to search for an open-source project that uses the FSEC setting. And by chance the mbed does. Here is [link][2] to how it is done in the mbed CMSIS Cortex-M4 Core Device Startup File for the MK20DX256. There should be the same setting in the Teensy Arduino core. Locating that is left to the reader.

Cheers!

  [1]: https://www.pjrc.com/teensy/K20P64M72SF1RM.pdf
  [2]: https://github.com/mbedmicro/mbed/blob/master/libraries/mbed/targets/cmsis/TARGET_Freescale/TARGET_K20XX/TARGET_TEENSY3_1/TOOLCHAIN_ARM_STD/startup_MK20DX256.S#L287


message:
Communicating Arduino with Intel Galileo

I'm doing a project where I have few sensors on Arduino Uno. Now I am trying to send some data to the internet where i figured using my GSM shield with the Galileo board I have is the best solution.

The problem I am facing is that software serial is not working on Galileo so I have to use the Serial1 of Galileo board (Pin 0 and Pin 1) and I am out of serial ports. I was thinking of using serial communication between Arduino and Galileo but Galileo seems to have only pin0 and pin1 as serial and they are occupied by the GSM shield.

Is there any part I am getting wrong or any suggestions?

(other than using the sensors on Galileo and getting rid of the Arduino Uno :) )

body:
You could use SPI/I2C as interface between Arduino and Galileo.
They are better than plain serial.


message:
Relay module and internal pull-up resistors

I'm currently assembling a prototype of the lightning infrastructure (*based on several MEGAs interconnected via RS485, as described [in this other post][1]*)

The prototype consists of three MEGAs, a couple of [wall-push-button][2] and the two relay modules here below:

 - [250V 2A 8 Channel OMRON SSR G3MB-202P Solid State Relay Module For Arduino][3]
 - [5V 4 CH OMRON SSR G3MB-202P Solid Relay Module with Resistive Fuse For Arduino][4]

Obviously I've:

 - connected one endpoint of each push-buttons to Arduino INPUT-PIN; the other endpoint to ground;
 - connected the relay-module control-pins to Arduino OUTPUT-PIN (and ensuring a properly connected ground).
 - connected lamps to relay-modules power connectors.

My question relates to "**pull-up resistor**": I've read in **lots** of places that when involving push-buttons, "pull-up resistors" are needed in order to prevent shorts between ground and input-pin. As such, there are **lots** of tutorial/videos on the web, showing a nice resistor added in the push-button circuit.

Further investigating, I've also learnt from the official documentation that "[*...There are 20K pullup resistors built into the Atmega chip that can be accessed from software....*][5]", by setting the `pinMode()` as `INPUT_PULLUP` or setting it to `INPUT` and the forcing a `digitalWrite(<PIN>,HIGH)`.

So, I ended:

 - directly connecting the two relay-modules to MEGAs INPUT-PINs and...
 - ...activating the internal pull-up, with `digitalWrite(<INPUT_PIN>,HIGH)`;

Nothing more.

This is the second evening I'm "testing" my Arduino-luggage-prototype and... lamps are turning on/off like a charm, without any noticeable problem.

The question is: am I doing something nasty toward my MEGAs? Is the approach depicted above, a commonly-safe (as for the Arduino's health) approach?

---

P.S.: should you wonder about how the prototype looks like, here is a photo (actually, taken right after the first power-up ;-)

[![enter image description here][6]][6]

  [1]: https://arduino.stackexchange.com/questions/15834/how-to-interconnect-multiple-arduinos-with-a-rpi-to-control-home-lights-switches
  [2]: http://www.vimar.com/en/int/catalog/product/index/code/14008
  [3]: http://www.aliexpress.com/item/NEW-250V-2A-8-Channel-OMRON-SSR-G3MB-202P-Solid-State-Relay-Module-For-Arduino/32393847675.html
  [4]: http://www.aliexpress.com/item/5V-4-CH-OMRON-SSR-G3MB-202P-Solid-Relay-Module-with-Resistive-Fuse-For-Arduino/32419548955.html
  [5]: https://www.arduino.cc/en/Tutorial/DigitalPins
  [6]: https://i.stack.imgur.com/IWbOC.png

body:
Connecting one side of a switch to ground and the other side to an input pin (with its pinmode set to INPUT_PULLUP) is a standard way of connecting control switches to an Arduino installation, and is not a problem.

Note, claims that built-in pull-ups are 20KΩ oversimplifies the situation.  See, for example, Table 28.2, DC Characteristics, in the ATmega48PA/88PA/168PA/328P specs, which shows a min value of 20KΩ for   I/O Pin Pull-up Resistors and a max value of 50KΩ.  I've measured resistances of about 40KΩ, IIRC, whenever I've measured the pull-up values.

Note, built-in pull-ups typically are of too much resistance to work as pull-ups for TWI/SPI/I2C communications.

Note, when you say in the question that you connected the relay-modules to input pins and they worked ok, I suppose that could be the case, but in general it is better to put i/o pins into output mode when you want to drive an output.  When you send LOW to an input pin, its built-in pull-up is turned off, the input impedance becomes high, and then the pin can float to any value between ground and Vcc. It might fail to turn off an attached device if that device also has high impedance.


body:
I am making the assumption the push buttons are wired directly to the mega.  This may work but for me it is not acceptable.  Why?  All of those wires act as an antenna array tuned to a lot of different frequencies.  My favorite trick is to use a 74C14 Schmidt trigger chip.  The reason is several fold. First it isolates the antennas from the processor.  The family I use will tolerate about 25volts input, giving a lot of head room.  Second it makes the software a bit easier, all switches come in positive true. Third I use a low pass network in front so if one of the mains hits it it will probably survive.  What I do is Pull up with a resistor that will cause about 1.5 ma to flow through the switch.  This value is dependent on your voltage, I typically use 12 or  24 VDC.  This input then goes through a 100K resistor to the input of the gate where I also put a .01 uF cap.

I am also working on a similar project, I made the same decision on a hardwired network about 15 years ago.  All the switching is on several output boards (5V) located in a PC AT. I also chose the mega for several reasons, first I needed full duplex with my network, the MAX485 will do that you just have to leave the receive enabled and cycle the transmit when you want to send something.  I also added a low pass on the (A line I Think) to another pin so I could determine if the network was busy,  I currently have about 150 outputs with very few inputs.  Code is all in ASM86.

I hope this helps, I will see if I can add to your reference question.

Thanks,
Gil


message:
Help with arduino car project

So in computer engineering I've got to make a arduino based car, I've added a whole bunch of features such as IR tracking, obstacle avoidance(proximity sensor), optical tracking(follow a black line), and remote control through an android based phone.

Since I'm a total newbie to technology I'm having trouble. I would appreciate it if You guys can point me towards resources and arduino libraries(for coding) that will work for me. Right now for coding I've only got basic pseudo-code setup since I do not know what libraries to use. I have searched up many sketches online and looked at them but didn't really understand any of the code.

Here's the basic pseudo-code I got setup on the things that I've got to work on:

***DC Motor** (4 of em for the wheels) (I also plan to add a stepper motor for turning right and left so if you could direct me on that as well)*

//Import necessary library
//Setup the motors and pins

//If signal for forward received
//Code for moving forward
//Set speed

//Else If signal for backward received
//Code for moving backward
//Set speed

//Else If signal for right received (keep turning right till stop signal received)
//Code for moving right
//Set speed

//Else If signal for left received (keep turning left till stop signal received)
//Code for moving left
//Set speed

//Else If signal for stop is received (Should we slow down to a stop or just stop?)
//Code for stop
//Set speed

***IR** (I've got transmitting and recording diodes)*

//Import Library

//Declare Pin for the IR Sensor

//While loop: Move Right
//If IR signal is received
//move forward
//Else
//Jump back to top of loop

***Proximity Sensor** (obstacle avoidance mode) (I might either use the one from Lego kit or buy a separate one )*

//Import Library

//Declare Pin for proximity sensor

//While Loop: Send out sonar(echolocation or whatever) every second
//Is there any obstacle?
  //Yes, turn right so many degrees, and go back to while loop
  //No, move on forward at set speed

//If you’re surrounded and cannot exit send out a message through flashing LED's
________________________________________________________________________________________________________

I'm not asking for the code or for any of you to do all my stuff for me, I'm just asking for direction and resources.

Thank You

body:
1) start simple - adding extra features will not help you, especially if you have a deadline

2) implement and test code for each low level function separately - however, in case you use libraries and or snippets, make sure that if a library/snippet requires exclusive use of a certain feature (ex: a timer), others do not need it.

3) test the overall logic elsewhere, where it easier to debug (ex: on a PC), by replacing the actual function calls to low level actuators/sensors with mockup functions that do I/O through either a file or a console.

Said this, what do you mean that you didn't understand the examples you found? To understand most of them, you need at least to read the API/interface of the libraries they use. And also reading the reference manual of the ATMega328P for the HW blocks referred by each library will help getting an overall feeling of what the library does.

About the basic physical model: once you have 4 DC motors (but 2 plus a caster would be enough), why do you want to add a stepper? Youc could do all of it with just 2 stepper motors , which will give you a simpler way to control precisely the orientation of the robot.

I'd suggest you to get the basic movement sorted out, before worrying about the rest. Just make sure that it doesn't make exclusive use of the microcontroller.


message:
Raspberry Pi, Teensy and Arduino's on i2c

I just got into an interesting mess.

I have 3 Arduino's (Pro Mini's) and 2x Teensy's (3.1's) connected via I2C to a Raspberry Pi Master. The 2x Teensy's I2C data lines are connected via OctoBoards but that doesn't really matter since the OctoBoard maps the I2C Pin's of the Teensy to itself. I have 4k7 pullup resistors for SDA/SLC close to the master (also tried on the end - with no effect).

The Arduino's alone are super solid - no issues other than the occasionally I2C lockup when writing data.

[![Arduino][1]][1]

The I2C interface has been running for over 3h with no problems.

Now as soon I add a Teensy to it, the bus locks-up and I need to completely shut down everything. Only thing I got to work was direct connection from RPI -> Teensy and even then there were sporadic detection issues.

I tried the Wire lib as well the IC2_T3 lib with no difference. Also tried with 4 different Teensy's with no difference.

Are the Teensy's not compatible with RPI?

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

body:
I do not have experience with your exact setup, but I once had a similar problem. I had a pi as I2C master, a battery module that used I2C to communicate battery status and two servo controllers attached. The servo controllers alone worked and the battery module alone worked, but all three attached to the pi didn't work and there was no collision in I2C addresses (have you checked that btw?). It turns out, that both servomodules and the battery module had I2C pullup resistors attached, so the end result was 3x4k7 in parallel, which is around 1566 ohm. The solution was to remove the pullup resistors from the servo controllers.

So the question is, have you by any chance enabled pullup resistors on any of the arduinos/teensys/pi in addition to your own resistors, resulting in wrong pullup resistor value?


message:
A whole basic game project Arduino

Firstly, I know that I have already posted this. I do not think anyone here is stupid so:
The game is: a power source connected to 6 buttons connected to 6 LEDs. you press them all in the randomly generated order, and they blink in the order pressed after completion, then randomize and reset.

I have an array shuffler code  1)Does the array shuffler work 2)How do I configure ports and attach them to values in the array, 3) How do I use an if-then statement to say if all buttons pressed in order, then LEDs blink 3 times?  I have a picture but not the actual Arduino, so, upon request, I can post the picture. Thank you. code:

    void setup() {
        // put your setup code here, to run once:
    }

    void loop() {
        // put your main code here, to run repeatedly:
        int questionNumberArray[] = {0,1,2,3,4,5,6};//the array itself
        const size_t n = sizeof(questionNumberArray) / //the array used
        sizeof(questionNumberArray[0]);//the base of the array

        for (size_t i = 0; i < n - 1; i++) //the loop itself
        {
            size_t j = random(1, n - i);
            int t = questionNumberArray[i]; //integer output for increase
            questionNumberArray[i] = questionNumberArray[j];//the value definition
            questionNumberArray[j] = t;
        }

    }

The six buttons are connected to digital pins (1, 2, 9, 11, 12, 13)

body:
So you leds are connected to "pins" not "ports." Since each of the buttons will turn on only 1 led we need to keep track of which button pairs with which led. To do this we can use a `struct` like this one:

    struct ButtonLed{
            int buttonPin;
            int ledPin;
    };

You declare a `ButtonLed` like this: `ButtonLed button1 = {1, 0}` where the first parameter is the button's pin and the second is the led's pin. **(All of the led pins are set to 0 since I don't know which pins you have them connected to.)**

And the array will hold the button/led pin pair like this:

`ButtonLed questionNumberArray[] = {button1, button2, button3, button4, button5, button6}; `

Since there are 6 leds you know that your array is size 6 so use this declaration instead

`const int n = 6;`

I fixed you range for the random number generation. Look at the documentation for `random()` here https://www.arduino.cc/en/Reference/Random. We can use this function for shuffling the array.

    void shuffleArray (ButtonLed arr [], const int size){
        for (int i = 0; i < size - 1; i++){ // iterates through array except last element
            int j = random(0, size); // generates a random index from (0 to n-1) inclusive

            // swap current index with random index
            ButtonLed t = arr[i];
            arr[i] = arr[j];
            arr[j] = t;
        }
    }

We will use this function to wait until the user enters a sequence of button presses:

    ButtonLed getButtonPress (ButtonLed arr [], const int size){
        bool pressed = false;
        ButtonLed  pressedButton;
        while (!pressed){ // loops until a button was pressed
            for (int i = 0; i < size && !pressed; i++){ // !pressed allows early out
                if (digitalRead(arr[i].buttonPin)){ // one of the six buttons was pressed
                    pressed = true; // exit both loops
                    pressedButton = arr[i]; // stores which button was pressed
                }
            }
        }
        return pressedButton; // return the pressed button
    }
Essentially it gets stuck in a loop and reads each of the 6 buttons until one of them is pressed and then records which one was pressed.

Try using the code below and read the comments the only thing you need to do is change all the zeros in the `ButtonLed` declarations to whatever pin the leds are connected to. Also the `struct` above needs to go into it's only file called "ButtonLed.h" It **must** be called that.

    #include "ButtonLed.h"

    // These are ButtonLeds our newly created data type
    // they hold both an led's pin and the pin for the button
    // that turns it on
    ButtonLed button1 = {1, 10};
    ButtonLed button2 = {2,  8};
    ButtonLed button3 = {9,  7};
    ButtonLed button4 = {11, 6};
    ButtonLed button5 = {12, 5};
    ButtonLed button6 = {13, 4};

    // This function will randomly shuffle an array of ButtonLeds
    void shuffleArray (ButtonLed arr [], const int size){
        for (int i = 0; i < size - 1; i++){ // iterates through array except last element
            int j = random(0, size); // generates a random index from (0 to size-1) inclusive

            // swap current index with random index
            ButtonLed t = arr[i];
            arr[i] = arr[j];
            arr[j] = t;
        }
    }

    ButtonLed getButtonPress (ButtonLed arr [], const int size){
        bool pressed = false;
        ButtonLed  pressedButton;
        while (!pressed){ // loops until a button was pressed
            for (int i = 0; i < size && !pressed; i++){ // !pressed allows early out
                if (digitalRead(arr[i].buttonPin)){ // one of the six buttons was pressed
                    digitalWrite(digitalRead(arr[i].ledPin, HIGH); // turns on the led the user chose
                    delay(200);
                    digitalWrite(digitalRead(arr[i].ledPin, LOW); // turns it back off
                    pressed = true; // exit both loops
                    pressedButton = arr[i]; // stores which button was pressed
                }
            }
        }
        return pressedButton; // return the pressed button
    }

    void setup() {
        randomSeed(analogRead(A0));
        // This is how you set up the leds for output
        pinMode(button1.ledPin, OUTPUT);
        pinMode(button2.ledPin, OUTPUT);
        pinMode(button3.ledPin, OUTPUT);
        pinMode(button4.ledPin, OUTPUT);
        pinMode(button5.ledPin, OUTPUT);
        pinMode(button6.ledPin, OUTPUT);

        // This is how you set up the buttons for input
        pinMode(button1.buttonPin, INPUT);
        pinMode(button2.buttonPin, INPUT);
        pinMode(button3.buttonPin, INPUT);
        pinMode(button4.buttonPin, INPUT);
        pinMode(button5.buttonPin, INPUT);
        pinMode(button6.buttonPin, INPUT);
    }

    void loop() {

        // This array is of type ButtonLed our newly created data type
        ButtonLed questionNumberArray[] = {button1, button2, button3,
                                           button4, button5, button6};
        const size_t n = 6; // array's size

        shuffleArray(questionNumberArray, n);

        numLeds = 1;
        bool guessCorrectly = false;

        // this while loop allows the user to keep trying until they get it right
        while (!guessCorrectly){

            // This loop displays the correct sequence to the user
            for (int i = 0; i < numLeds; i++){
                digitalWrite(questionNumberArray[i].ledPin, HIGH); // turn on the led

                delay(500); // decrease this number to flash faster; increase to flash slower

                digitalWrite(questionNumberArray[i].ledPin, LOW); // turn off the led
            }

            bool correctButton = true; // the user has pressed the correct button
            ButtonLed userSequence [6];      // stores the sequence the user entered
            // lets the user push 6 buttons
            for (int i = 0; i < numLeds; i++){
                userSequence[i] = getButtonPress(questionNumberArray, numLeds);
                delay(500); // delay between button presses
            }

            // check if the user entered the correct sequence
            for (int i = 0; i < numLeds && correctButton; i++){
                if (userSequence[i].buttonPin != questionNumberArray[i].buttonPin)
                    correctButton = false;
            }

            if (correctButton){ // user entered the correct sequence
                guessCorrectly = true;
                // This will turn on the leds in the correct sequence
                for (int i = 0; i < numLeds; i++){
                    digitalWrite(questionNumberArray[i].ledPin, HIGH); // turn on the led
                    delay(500); // delay half a second
                    digitalWrite(questionNumberArray[i].ledPin, LOW); // turn off the led
                }
                numLeds++;
                if (numLeds > 6)
                    --numLeds;
            }
        }
    }

After you are finished typing the code above it `ctrl+shift+n` and open a new tab called "ButtonLed.h" and add this to it:

    #ifndef BUTTONLED_H
    #define BUTTONLED_H
    #include <Arduino.h>

    // We create new data type called ButtonLed which stores the button's pin
        // and the led's pin; this allows us to keep both an led and it's
        // corresponding button together without have to manage 2 arrays
        struct ButtonLed{
            int buttonPin;
            int ledPin;
        };

    #endif

Make sure you open a new tab and not a new project. Also as others have said you should really learn how to program. Be aware this code compiles however, I haven't tested it. I will update the code when you tell me what pins the leds are connected to.

**Edit 1**

I added a while loop that allows the user to keep trying until they guess correctly.

**Edit 2**

I also updated the code for which pins the leds are connected to. Remember they're connected to "pins" **Not** "ports.

[![Schematic for your project.][1]][1]

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


message:
How to program an offbrand arduino uno?

So I recently bought this off brand arduino uno from betemcu.cn.
it says its r3 compatible.

Can I program this thing with the arduino coder or do I need to use something else? whenever I try uploading the code it says "problem uploading to board"

what settings or program should I use to code this?
[![enter image description here][1]][1]

[![enter image description here][2]][2]

  [1]: https://i.stack.imgur.com/DMzKg.jpg
  [2]: https://i.stack.imgur.com/WUIJx.jpg

body:
**The issue is probably that you need a driver for the onboard CH340G USB-to-serial bridge.**

The Baite Electronics Arduino clones are generally of good quality and work well.
There are some differences between them and Arduino-brand Arduinos. Two notable ones are a different voltage regulator and (probably the issue here) a different USB-to-serial bridge IC.  The Arduino brand products use an FTDI IC and Baite uses, in this case, the CH340 USB bridge IC.

The product is described [**on this webpage**](http://www.aliexpress.com/store/product/10pcs-lot-high-quality-UNO-R3-MEGA328P-CH340G-for-Arduino-Compatible-Improved-version-expert-version-NO/812021_1933705621.html) and you will see that they say

> UNO MEGA328P **CH340G** for Arduino Compatible

The CH340G relates to the USB interface IC.
Until about a year ago the USB driver in windows worked with most common USB ICs as well as with FTDI ICs.  However, FTDI changed their system so that the Windows driver will now only work with FTDI brand ICs. So it is now necessary to load a driver into the PC (whether Windows, Linux or other O/S) to suit the CH340.

If you email them Baite will provide a link to the CH340 driver, but they do not usually provide it on their website (reason unknown to me.)

Or, you can obtain a driver from numerous websites.
[**A web search on eg:  driver ch340 baite arduino**](https://www.google.co.nz/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=ch340 baite arduino driver)
turns up many pages.   How good or how safe any of these is is TBD.

[**This page**](http://www.arduined.eu/ch340g-converter-windows-7-driver-download/) claims to provide a Windows 7 CH340G driver and install instructions

[This YouTube video](https://www.youtube.com/watch?v=Ix4t-_RZ7NI) describes how to install a driver and provides a link to [this page](http://www.wch.cn/download/CH341SER_EXE.html) which lists a number of drivers.

[**This page discusses the issue**](http://doityourselfchristmas.com/forums/showthread.php?14690-CH340-USB-RS232-Driver)


body: Just install your driver. Some might install automatically. Then try to upload the sketch using arduino IDE.


message:
How to Store the Value of A Sr04 Ultrasonic distance sensor (ping)?

I am using a Sr04 Ultrasonic distance sensor with Uno clone for making a Alarm. The basic idea behind this project is that In Setup, Read the distance And store it in a varibale as Threshold. And in Loop, Check the distance readings regularly and if the Reading anytime is not equal to The threshold (that means someone interrupted in front of ultrasonic sensor), then a led flashes. I Know that is system is not enough good because the real world is a bit noisy. My problem is I am storing the theshold distance in "int" variable. The compiling error is "Cant convert Long Unsigned char to Int" something like this. Please tell me how can I store the reading of my sr04 sensor in a variable. I am using NewPing Library.

body:
 1. First you must verify that storing the value as int is even possible: long int can represent much larger values than int. Are you 100% sure that the maximum reading you will ever get can be represented as int?
 2. In case the answer to the previous question is "yes", then you can just cast it on the fly:
`int int_val = (int)function_returning_longint();`
 3. In case the answer is "no", you can either give up the idea of using int and stick with long, which is not necessarily bad, or you can scale down the value, at the price of loosing some resolution:
`int int_val = function_returning_longint() >> 8;` This assumes that long is 16 bit and int is 8 bit, but it would be preferable to use explicit types, like `int8_t` and `int16_t`. And in your case you might have to shift by a different value than 8.

Either way, do not make casts of from big type to small type without being 100% sure that the max value you will ever deal with can fit in the small type.


message:
Change UART pin

I am developing GPRS HTTP send request code using a GSM/GPRS module. I found the following code via google:
<!-- language: cpp -->

    /*************************************************************************
    * SIM800 GPRS/HTTP Library
    * Distributed under GPL v2.0
    * Written by Stanley Huang <stanleyhuangyc@gmail.com>
    * For more information, please visit http://arduinodev.com
    *************************************************************************/

    #include <Arduino.h>

    // change this to the pin connect with SIM800 reset pin
    #define SIM800_RESET_PIN 7

    // change this to the serial UART which SIM800 is attached to
    #define SIM_SERIAL Serial

    // define DEBUG to one serial UART to enable debug information output
    //#define DEBUG Serial

    typedef enum {
        HTTP_DISABLED = 0,
        HTTP_READY,
        HTTP_CONNECTING,
        HTTP_READING,
        HTTP_ERROR,
    } HTTP_STATES;

    typedef struct {
      float lat;
      float lon;
      uint8_t year; /* year past 2000, e.g. 15 for 2015 */
      uint8_t month;
      uint8_t day;
      uint8_t hour;
      uint8_t minute;
      uint8_t second;
    } GSM_LOCATION;

    class CGPRS_SIM800 {
    public:
        CGPRS_SIM800():httpState(HTTP_DISABLED) {}
        // initialize the module
        bool init();
        // setup network
        byte setup(const char* apn);
        // get network operator name
        bool getOperatorName();
        // check for incoming SMS
        bool checkSMS();
        // get signal quality level (in dB)
        int getSignalQuality();
        // get GSM location and network time
        bool getLocation(GSM_LOCATION* loc);
        // initialize HTTP connection
        bool httpInit();
        // terminate HTTP connection
        void httpUninit();
        // connect to HTTP server
        bool httpConnect(const char* url, const char* args = 0);
        // check if HTTP connection is established
        // return 0 for in progress, 1 for success, 2 for error
        byte httpIsConnected();
        // read data from HTTP connection
        void httpRead();
        // check if HTTP connection is established
        // return 0 for in progress, -1 for error, bytes of http payload on success
        int httpIsRead();
        // send AT command and check for expected response
        byte sendCommand(const char* cmd, unsigned int timeout = 2000, const char* expected = 0);
        // send AT command and check for two possible responses
        byte sendCommand(const char* cmd, const char* expected1, const char* expected2, unsigned int timeout = 2000);
        // toggle low-power mode
        bool sleep(bool enabled)
        {
          return sendCommand(enabled ? "AT+CFUN=0" : "AT+CFUN=1");
        }
        // check if there is available serial data
        bool available()
        {
          return SIM_SERIAL.available();
        }
        char buffer[256];
        byte httpState;
    private:
        byte checkbuffer(const char* expected1, const char* expected2 = 0, unsigned int timeout = 2000);
        void purgeSerial();
        byte m_bytesRecv;
        uint32_t m_checkTimer;
    };

The problem is I have no idea how to change or define Rx and Tx Pin. If I define SIM_SERIAL serial1 it's showing me error. I want to change it to pins 10 and 11.

Here is other code whenever I try to compile it shows me error on "serial1" online. above code is sim800.h file

here is program code of send data through http

    "SIM800.h"

    #define APN "connect"
    #define con Serial
    static const char* url = "http://arduinodev.com/datetime.php";

    CGPRS_SIM800 gprs;
    uint32_t count = 0;
    uint32_t errors = 0;

    void setup()
    {
      con.begin(9600);
      while (!con);

      con.println("SIM800 TEST");

      for (;;) {
        con.print("Resetting...");
        while (!gprs.init()) {
          con.write('.');
        }
        con.println("OK");

        con.print("Setting up network...");
        byte ret = gprs.setup(APN);
        if (ret == 0)
          break;
        con.print("Error code:");
        con.println(ret);
        con.println(gprs.buffer);
      }
      con.println("OK");
      delay(3000);

      if (gprs.getOperatorName()) {
        con.print("Operator:");
        con.println(gprs.buffer);
      }
      int ret = gprs.getSignalQuality();
      if (ret) {
         con.print("Signal:");
         con.print(ret);
         con.println("dB");
      }
      for (;;) {
        if (gprs.httpInit()) break;
        con.println(gprs.buffer);
        gprs.httpUninit();
        delay(1000);
      }
      delay(3000);
    }

    void loop()
    {

      char mydata[16];
      sprintf(mydata, "t=%lu", millis());
      con.print("Requesting ");
      con.print(url);
      con.print('?');
      con.println(mydata);
      gprs.httpConnect(url, mydata);
      count++;
      while (gprs.httpIsConnected() == 0) {
        // can do something here while waiting
        con.write('.');
        for (byte n = 0; n < 25 && !gprs.available(); n++) {
          delay(10);
        }
      }
      if (gprs.httpState == HTTP_ERROR) {
        con.println("Connect error");
        errors++;
        delay(3000);
        return;
      }
      con.println();
      gprs.httpRead();
      int ret;
      while ((ret = gprs.httpIsRead()) == 0) {
        // can do something here while waiting
      }
      if (gprs.httpState == HTTP_ERROR) {
        con.println("Read error");
        errors++;
        delay(3000);
        return;
      }

      // now we have received payload
      con.print("[Payload]");
      con.println(gprs.buffer);

      // show position
      GSM_LOCATION loc;
      if (gprs.getLocation(&loc)) {
        con.print("LAT:");
        con.print(loc.lat, 6);
        con.print(" LON:");
        con.print(loc.lon, 6);
        con.print(" TIME:");
        con.print(loc.hour);
        con.print(':');
        con.print(loc.minute);
        con.print(':');
        con.println(loc.second);
      }

      // show stats
      con.print("Total Requests:");
      con.print(count);
      if (errors) {
        con.print(" Errors:");
        con.print(errors);
      }
      con.println();
    }

i already know how to send data through http using AT command and software serial library here is  my code

    #include <SoftwareSerial.h>

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

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

      Serial.println("Goodnight moon!");

      // set the data rate for the SoftwareSerial port
      mySerial.begin(9600);
      mySerial.write("AT\n");
      delay(1000);
      mySerial.write("AT+CSQ\n");
      delay(1000);
      mySerial.write("AT+SAPBR=3,1,\"APN\",\"internet\"\n");
      delay(2000);
      mySerial.write("\nAT+SAPBR=1,1\n");
      delay(1000);
      mySerial.write("AT+HTTPINIT\n");
      delay(1000);

    }

    void loop() { // run over and over
      if (mySerial.available()) {
        Serial.write(mySerial.read());
        delay(1000)
        serial.print(enter key)
      }
      if (Serial.available()) {
        delay(2000);
         mySerial.write("AT+HTTPPARA=\"URL\",\"http://www.mydomain.in/index.php?dt=testdata\"\n");
         delay(2000);
         mySerial.write("AT+HTTPACTION=0\n");
          delay(2000);
          mySerial.write("\n");
        mySerial.write(Serial.read());
      }

In this code I define Rx Tx (UART)pin. Can you please suggest me any idea how can i define RX Tx pin in sim800.h file. because serial1 give me error on compiling time

body:
>     SoftwareSerial mySerial(10, 11); // RX, TX

Well there you are.

    #define SIM_SERIAL mySerial


body:
I think Serial1 has to do with the Hardware serial Port(tx1,rx1) on Arduino mega . But since you are not using Serial.print i suggest you try "Serial/Serial0" if you are using UNO.
If you want (10,11) like you said then i think you should use Softwareserial

 #include SoftwareSerial.h //check spelling online not sure
SoftwareSerial allex(10,11);

 #define SIM_SERIAL  allex

 try it and see if it works.


message:
What's the difference between pow and sqrt in this code?

I'm not the best at Arduino so I'm sorry for my "noobiness".

I'm extending some code that I found online to work on the gyroscope that I'm building.

I'm wondering what the difference is between `pow` and `sqrt` in this code.

I'm also wondering what the `180/pi` is used for. I haven't gotten my mind around this part yet.

    arx = (180/3.141592) * atan(ax / pow((ay, 2) + pow(az, 2));

What's the difference here?

    ary = (180/3.141592) * atan(ay / sqrt(square(ax, 2) + square(az, 2)));

body:
Converting Gerben's comment into an answer:

---

pow(x, 2) is the second power, in other words:

[![x squared][1]][1]

<!-- $$x^2$$ or $$x \times x$$ -->

---

sqrt(x) is the square root of x, that is:

[![Square root of x][2]][2]

<!-- $$\sqrt x$$ -->

---

  A whole circle is 360 degrees or 2π when measuring in radians. So this ratio of `180 / 3.141592` is used to convert an angle in radians to an angle in degrees.

[![radians to degrees][3]][3]

<!-- $$degrees = \frac{180}{\pi} \times radians$$  -->

<!-- Note: maths symbols manually done from TeX markup shown -->

  [1]: https://i.stack.imgur.com/FxSj7.png
  [2]: https://i.stack.imgur.com/LrrbS.png
  [3]: https://i.stack.imgur.com/q7Zfk.png


message:
USB detect on Arduino DUE

I want to know when something is connected to USB port by blinking an LED.

I suppose have to check PB10 UOTGVBOF, but how to do this ?

body: What I'm going to say is probably not the most efficient way to do it, but it should work: if your DUE is used as gadget and you wnat to detect the presence of a master, connect a GPIO to the +Vcc line of the usb port and either poll or program an edge triggered interrupt to detect when the line goes high.


message:
Help choosing servo motor for Arduino crane

I'm building an automated Arduino crane where the base material is PVC pipes. The arm consists of the picking mechanism and other sensors, so the total arm might come to about 2-3 Kg (I haven't built it yet).

Can you please suggest to me an appropriate make/model of servo motor which I can purchase (preferably from India only)?

body:
It really depends on where you are placing the servo, how much peak load & at what kind if distance from the servo.

[These Corona servos][1] are capable of lifting 2-3Kg at a distance of 2cm from the servo centre. (look at the torque entry on the specification sheet)

  [1]: http://www.hobbyking.com/hobbyking/store/__10347__Corona_538MG_Digital_Metal_Gear_Servo_7_0kg_53g_0_13sec.html


message:
Arduino IDE says fcould not convert 'pinMode(buttons[((inti)], 0u)' from 'void' to 'bool'. How do I fix

Alright, so this code is for a game that is a power source connected to 6 buttons at ports 1, 2, 9, 11, 12, and 13. These are consequently supposed to light up 6 LEDs, each connected to 1. If you press the buttons in the right order, all the LEDs blink at once. Does it work?

    #define DEBOUNCE 10  // button debouncer, how many ms to debounce, 5+ ms is usually plenty

    // here is where we define the buttons that we'll use. button "1" is the first, button "6" is the 6th, etc
    byte buttons[] = {1, 2, 9, 11, 12, 13}; // the analog 0-5 pins are also known as 14-19
    // This handy macro lets us determine how big the array up above is, by checking the size
    #define NUMBUTTONS sizeof(buttons)
    // we will track if a button is just pressed, just released, or 'currently pressed'
    volatile byte pressed[NUMBUTTONS], justpressed[NUMBUTTONS], justreleased[NUMBUTTONS];

    void setup() {
    byte i;

    // set up serial port
    Serial.begin(9600);
    Serial.print("Button checker with ");
    Serial.print(NUMBUTTONS, DEC);
    Serial.println(" buttons");

    // pin1 LED
    pinMode(1, OUTPUT);

     // Make input & enable pull-up resistors on switch pins
     for (i=0; ipinMode(buttons[i], INPUT);
     digitalWrite(buttons[i], HIGH);
      }

     // Run timer2 interrupt every 15 ms
     TCCR2A = 0;
     TCCR2B = 1<<CS22 | 1<<CS21 | 1<<CS20;

     //Timer2 Overflow Interrupt Enable
      TIMSK2 |= 1<<TOIE2;

     }

    SIGNAL(TIMER2_OVF_vect) {
    check_switches();
    }

    void check_switches()
    {
      static byte previousstate[NUMBUTTONS];
    static byte currentstate[NUMBUTTONS];
     static long lasttime;
     byte index;

      if (millis() // we wrapped around, lets just try again
         lasttime = millis();
      }

      if ((lasttime + DEBOUNCE) > millis()) {
        // not enough time has passed to debounce
    return;
      }
      // ok we have waited DEBOUNCE milliseconds, lets reset the timer
      lasttime = millis();

      for (index = 0; index digitalRead(buttons[index]);   // read the button

        /*
        Serial.print(index, DEC);
        Serial.print(": cstate=");
        Serial.print(currentstate[index], DEC);
        Serial.print(", pstate=");
        Serial.print(previousstate[index], DEC);
        Serial.print(", press=");
        */

        if (currentstate[index] == previousstate[index]) {
          if ((pressed[index] == LOW) && (currentstate[index] == LOW)) {
              // just pressed
              justpressed[index] = 1;
          }
          else if ((pressed[index] == HIGH) && (currentstate[index] == HIGH))        {
              // just released
              justreleased[index] = 1;
          }
          pressed[index] = !currentstate[index];  // remember, digital HIGH     means NOT pressed
        }
        //Serial.println(pressed[index], DEC);
        previousstate[index] = currentstate[index];   // keep a running tally  of the buttons
      }
    }

    void loop() {
      for (byte i = 0; i if (justpressed[i]) {
          justpressed[i] = 0;
          Serial.print(i, DEC);
          Serial.println(" Just pressed");
          // remember, check_switches() will CLEAR the 'just pressed' flag
        }
        if (justreleased[i]) {
          justreleased[i] = 0;
          Serial.print(i, DEC);
          Serial.println(" Just released");
          // remember, check_switches() will CLEAR the 'just pressed' flag
        }
        if (pressed[i]) {
          Serial.print(i, DEC);
          Serial.println(" pressed");
          // is the button pressed down at this moment
        }
      }
    }

    int questionNumberArray[] = {1, 2, 9, 11, 12, 13};//the array itself
    const size_t n = sizeof(questionNumberArray) / //the array used
    sizeof(questionNumberArray[0]);//the base of the array

    for (size_t i = 0; i < n - 1; i++) //the loop itself
    {
    size_t j = random(1, n - i);
    int t = questionNumberArray[i]; //integer output for increase
    questionNumberArray[i] = questionNumberArray[j];//the value definition
    questionNumberArray[j] = t;
    pinMode(questionNumberArray, INPUT);
    if (digitalRead(questionNumberArray) == HIGH) {
      then(digitalRead(1, 2, 9, 11, 12, 13 == High(3))
      break;
    }
    }
Also, how do I make it so that people have infinite times to try

body:
There is very little about the code you are producing at the moment that could be classified as "right".

You are like a child who has been playing with LEGO® being let loose on the workings of a nuclear reactor.  You're sticking things together without a) knowing what they do and b) knowing how they are supposed to work, and it's all going to end in tears.

I suggest that, for the time being, you forget this game project of yours and go back to the basics.  Start by learning how to make an LED light up when you press a button.  That will teach you both how to read the state of a button and how to control an LED.  Then move on to doing it with multiple LEDs and multiple buttons.

As it stands you are just going to end up getting frustrated and annoyed.  You're asking questions without either knowing just what it is you are asking or how to understand the answers when you are given them.  And that is going to end up reflecting badly on the rating of your various users (hint: if you ask reasonable questions you get reasonable answers, and that means upvotes and reputation, which then means you can ask more questions so you don't have to keep creating new users to ask more questions where you don't actually understand what you're asking).


message:
Issue with leOS2 for one-time tasks

I'm trying to use the last version of **leOS2 scheduler from Leonardo Miliani** ( https://github.com/leomil72/leOS2 ) but I have a strange behavior with a very simplistic ONETIME task.

Platform : Arduino Uno clone, so Atmel Atmega 328P CPU.

My code is very straightforward :

    #include "leOS2.h"
    leOS2 myOS; //create a new istance of the class leOS

    bool test = true;

    void setup()
    {
     myOS.begin(); //initialize the scheduler
    }
    void loop()
    {
        // Do some stuff ...

        if(test)
        {
           DoAndUndo(3000);
           test = false;
        }
    }

    void DoAndUndo(unsigned long duration)
    {
     doSomething();

        myOS.addTask(cancelTheThing, myOS.convertMs(duration), ONETIME);
    }

    void doSomething()
    {
     Serial.println("thing on");
    }

    void cancelTheThing()
    {
     Serial.println("thing is off");
    }

In case it can be some kind of conflict, my code also relies on the following :

    #include <Wire.h>
    #include <LiquidCrystal_I2C.h>
    #include <IRremote.h>

The problem is :
        myOS.addTask(cancelTheThing, myOS.convertMs(duration), ONETIME);
is supposed to call asynchronously the "cancelTheThing" method 3 seconds later, and for only one time, and then forget it.
But for an unknown reason, it's called after the expected delay, **but it loops infinitely on this method** ! In the example case above, my serial stream is filled with a lot of "thing is off" messages, and the µc is unresponsive to anything apart a reset.

The call to DoAndUndo() will produce a such like output :

     thing on
And 3s later, in a very fast infinite loop :

     thing is off
     thing is off
     thing is off
     thing is off

If I remove the "ONETIME" flag, the task is called every three seconds (exactly as it's suppose to do, so the scheduler works, but it's not what I want in my use case).

note : As a try of workaround, I've tried some tricks like calling haltScheduler() inside my cancelTheThing() and reenable it with restartScheduler() in DoAndUndo(), and also tried to call removeTask once it has ran, but it didn't help.

Thank you for your help

body:
There appears to be a fault with the library whereby if the only registered task is a one-shot task it doesn't get cancelled when it has executed.

Adding another periodic task in `setup()` (say to blink an LED every 500ms) so there are now 2 tasks instead of one works around the problem.

The way the system is written it will always try an execute task number 0 even when there are 0 tasks registered because they erroneously used a "do {...} while" construct instead of a "while { ...}" construct.

----

I  have filed a bug report, corrected the error, and raised a pull request with the fix in it.  Until it gets accepted you can obtain the fixed version here: https://github.com/majenkotech/leOS2


message:
Error while compiling

I made a code which can send the message to the entered phone number while it receieves a specific message or when the push button is pressed.
but it is showing the error that 'smsReceivingFunction' was not declared in this scope.
I'm a beginner and don't know what i'm doing wrong.

to know the working of functions of library--
http://1sheeld.com/docs/sms/#example

here is the code--

    #include <OneSheeld.h>
    float lat ;
    float lon ;
    char charlat [30];
    char charlon [30];
    char readings [150];
    int buttonPin=11;
    int ledPin=12;

    void setup() {
      // put your setup code here, to run once:
      OneSheeld.begin();
        /* Set the button pin as input. */
      pinMode(buttonPin,INPUT);
      /* Set the LED pin as output. */
      pinMode(ledPin,OUTPUT);
      SMS.setOnSmsReceive(&smsReceivingFunction);
    }

    void loop()

    {
        charlat[0] = 0;
      charlon[0] = 0;
      readings [0] = 0;
    if(digitalRead(buttonPin) == HIGH)
      {
        /* Turn on the LED. */
        digitalWrite(ledPin,HIGH);
        delay( 1000);
        digitalWrite(ledPin,HIGH);
        delay( 500);

          lat = GPS.getLatitude();
          lon = GPS.getLongitude();
          dtostrf(lat, 3, 7, charlat);
          dtostrf(lon, 3, 7, charlon);
          strcat(readings, "please call me I i do not pick up the call please reach to my location:\n");
          strcat(readings, "http://maps.google.com/maps?q=");
          strcat (readings, charlat);
          strcat(readings, ",");
          strcat (readings, charlon);
          SMS.send("+917771914436", readings);

          void smsReceivingFunction(const char * number,const char * text);

           if(!strcmp(number,"+7771914436"))               /* phone number from which you will send the sms "PUT YOURS IN PLACE OF +1234567890" */
          {
            if(!strcmp(text,"?"))
            lat = GPS.getLatitude();
          lon = GPS.getLongitude();
          dtostrf(lat, 3, 7, charlat);
          dtostrf(lon, 3, 7, charlon);
          strcat(readings, "please call me I i do not pick up the call please reach to my location:\n");
          strcat(readings, "http://maps.google.com/maps?q=");
          strcat (readings, charlat);
          strcat(readings, ",");
          strcat (readings, charlon);
          SMS.send("+917771914436", readings);
          }
      }

      }
    }

body:
Basically the formatting and layout of your program is completely wrong.  You haven't actually defined this `smsReceivingFunction` anywhere.  You have created a *prototype* to it part way through your `loop()` function, but not created the actual function.

You should learn to strictly indent your program properly.  It is important, since by doing so you can follow the flow and structure of your program much easier.

For instance, if I pass your program through [Artistic Style](http://astyle.sourceforge.net/) to attempt to automatically correct your indenting it results in this:

    #include <OneSheeld.h>
    float lat ;
    float lon ;
    char charlat [30];
    char charlon [30];
    char readings [150];
    int buttonPin = 11;
    int ledPin = 12;

    void setup() {
        // put your setup code here, to run once:
        OneSheeld.begin();
        /* Set the button pin as input. */
        pinMode(buttonPin, INPUT);
        /* Set the LED pin as output. */
        pinMode(ledPin, OUTPUT);
        SMS.setOnSmsReceive(&smsReceivingFunction);
    }

    void loop()
    {
        charlat[0] = 0;
        charlon[0] = 0;
        readings [0] = 0;
        if (digitalRead(buttonPin) == HIGH) {
            /* Turn on the LED. */
            digitalWrite(ledPin, HIGH);
            delay( 1000);
            digitalWrite(ledPin, HIGH);
            delay( 500);
            lat = GPS.getLatitude();
            lon = GPS.getLongitude();
            dtostrf(lat, 3, 7, charlat);
            dtostrf(lon, 3, 7, charlon);
            strcat(readings, "please call me I i do not pick up the call please reach to my location:\n");
            strcat(readings, "http://maps.google.com/maps?q=");
            strcat (readings, charlat);
            strcat(readings, ",");
            strcat (readings, charlon);
            SMS.send("+917771914436", readings);
            void smsReceivingFunction(const char * number, const char * text);

            if (!strcmp(number, "+7771914436")) {           /* phone number from which you will send the sms "PUT YOURS IN PLACE OF +1234567890" */
                if (!strcmp(text, "?")) {
                    lat = GPS.getLatitude();
                }

                lon = GPS.getLongitude();
                dtostrf(lat, 3, 7, charlat);
                dtostrf(lon, 3, 7, charlon);
                strcat(readings, "please call me I i do not pick up the call please reach to my location:\n");
                strcat(readings, "http://maps.google.com/maps?q=");
                strcat (readings, charlat);
                strcat(readings, ",");
                strcat (readings, charlon);
                SMS.send("+917771914436", readings);
            }
        }
    }
    }

As you can now see you have an extra `}` at the end of your sketch, so your brackets are not balanced. That in itself is a syntax error.  Also you can see your function prototype slap bang in the middle of your loop() function:

    ...
            SMS.send("+917771914436", readings);
            void smsReceivingFunction(const char * number, const char * text);

            if (!strcmp(number, "+7771914436")) {           /* phone number
    ...

I think, though of course I can't actually test this since I don't have your hardware, that you really meant to start a new function at that point in your program, and of course that would mean finishing the previous function first: you *cannot* nest functions inside each other.  So I would guess your program *should* have looked something more like this:

    #include <OneSheeld.h>
    float lat ;
    float lon ;
    char charlat [30];
    char charlon [30];
    char readings [150];
    int buttonPin = 11;
    int ledPin = 12;

    void setup() {
        // put your setup code here, to run once:
        OneSheeld.begin();
        /* Set the button pin as input. */
        pinMode(buttonPin, INPUT);
        /* Set the LED pin as output. */
        pinMode(ledPin, OUTPUT);
        SMS.setOnSmsReceive(&smsReceivingFunction);
    }

    void loop()
    {
        charlat[0] = 0;
        charlon[0] = 0;
        readings [0] = 0;
        if (digitalRead(buttonPin) == HIGH) {
            /* Turn on the LED. */
            digitalWrite(ledPin, HIGH);
            delay( 1000);
            digitalWrite(ledPin, HIGH);
            delay( 500);
            lat = GPS.getLatitude();
            lon = GPS.getLongitude();
            dtostrf(lat, 3, 7, charlat);
            dtostrf(lon, 3, 7, charlon);
            strcat(readings, "please call me I i do not pick up the call please reach to my location:\n");
            strcat(readings, "http://maps.google.com/maps?q=");
            strcat (readings, charlat);
            strcat(readings, ",");
            strcat (readings, charlon);
            SMS.send("+917771914436", readings);
        }
    }

    void smsReceivingFunction(const char * number, const char * text) {
        if (!strcmp(number, "+7771914436")) {           /* phone number from which you will send the sms "PUT YOURS IN PLACE OF +1234567890" */
            if (!strcmp(text, "?")) {
                lat = GPS.getLatitude();
            }
            lon = GPS.getLongitude();
            dtostrf(lat, 3, 7, charlat);
            dtostrf(lon, 3, 7, charlon);
            strcat(readings, "please call me I i do not pick up the call please reach to my location:\n");
            strcat(readings, "http://maps.google.com/maps?q=");
            strcat (readings, charlat);
            strcat(readings, ",");
            strcat (readings, charlon);
            SMS.send("+917771914436", readings);
        }
    }


message:
Using random() in a header file

#ifndef FOO_H
    #define FOO_H

    struct Foo{
      int randInt = random(0, 101);
    };

    #endif

I have a header file with a `struct` like above but when I compile I get this error:

`'random' was not declared in this scope`

How can I use random() in a header file?

body:
The struct is a declaration of a type. You cannot mix it with the initialization. This is how it could be:

In foo.h:

    #ifndef FOO_H
    #define FOO_H

    struct Foo{
      int randInt;
    };

    extern struct Foo foo;
    struct Foo *initFoo(struct Foo *foo_ptr);
    #endif

In foo.c:

    #include "foo.h"

    struct Foo foo;
    struct Foo *initFoo(struct Foo *foo_ptr) {
      if (!foo_ptr)
        return NULL;
      foo_ptr->randInt = random(0, 101);
      return foo_ptr;
    }

random() is a function and therefore its return value cannot be used as static initializer.
Unless -std=c++11 or -std=gnu++11 are enabled.


body:
Add `#include <Arduino.h>` like this

    #ifndef FOO_H
    #define FOO_H

    #include <Arduino.h>

    struct Foo{
      int randInt = random(0, 101);
    };

    #endif


message:
Unable to tell if error is from receiving or transmitting end

so I am having trouble sending data using software serial's write function.

TX Code:

    #include <SoftwareSerial.h>

    SoftwareSerial TX(2,3);

    void setup() {
      // put your setup code here, to run once:
      TX.begin(1200);
    }

    void loop() {
        TX.write(60);
    }

**Is the delay necessary?**

RX Code:

    #include <SoftwareSerial.h>
    SoftwareSerial RX(2,3); //(rx pin, tx pin)
    const unsigned int bufferSize = 100;

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

    }

    void printBuffer(const uint8_t *serialBuffer)
    {
      //print contents of buffer
      for (int i = 0; i<100; i++)
        Serial.println(serialBuffer[i], BIN);
    }

    void processBytes(const uint8_t value)
    {
      static uint8_t serialBuffer[bufferSize]; //buffer to hold values
      static unsigned int startPosition=0;

      if(startPosition < bufferSize)
        serialBuffer[startPosition++] = value;

      else
      {
        printBuffer(serialBuffer);
        startPosition = 0;
      }

    }//end of processBytes
    void loop() {

      //check if data is available in serial buffer
      while(RX.available())
      {
        //process data
        processBytes(RX.read());
      }
    }

If i transmit the number 60, it prints 226 constantly for 2-3 seconds, then prints 60 for a short while, then goes back to printing 226. Am I doing something wrong with my code?

**FIRST QUESTION:** In the case when startPosition (in the process function) equals 100, it will call print. Print will then print 100 integers. Now, when doing that, there could still be data being transmitted from the transmitter. But the read function won't be executed until printBuffer returns, process returns, and the while loop iterates again. So during that time, couldn't some transmitted values potentially not be read?

**SECOND QUESTION** How come Software serial doesn't synchronize incorrectly more often? How is it being so accurate if the start bit is just a single bit and it's a 0. So for instance, if payload has some 0s, how come one of those 0s aren't being assumed to be the startbit? How does this get resolved? I looked at the software serial library, but I am not able to find out why. Any guidance here?

**THIRD QUESTION** Other than getting the startbit syncing right, are there other ways to sync the data? I was reading of NRZ encoding, manchester encoding, etc. Can any of these be implemented here? Also, would it be wise to alter the softwareSerial library to have more than one startbit?

Any guidance would be very appreciated! Thank you so much!
This is all being done with wireless RF modules.

body:
<!-- language-all: lang-C++ -->

    void loop() {
      Serial.println("NEW-------------");
      int x;
      int y[100];
      for(int i = 0; i<100; i++){
        x=RX.read();
        y[i] = x;
      }
    ...
    }

You are reading data without checking if there is any data there. That's like watching the TV without checking if it is turned on. Of course you get weird data.

---

    SoftwareSerial RX(0,1); //(rx pin, tx pin)

Pins 0 and 1 are used by HardwareSerial. Why are you using them for SoftwareSerial?

---

    SoftwareSerial RX(0,1); //(rx pin, tx pin)
    ...

      Serial.begin(9600);
      RX.begin(1200);

So you initialized HardwareSerial, which now controls pins 0 and 1.

Then you try to initialize SoftwareSerial on those **same** pins! Would you mind explaining why?

Whatever your explanation is, it won't work.

---

> I've added in the changes you mentioned, but the data still seems to be skewed.

You've changed things, for sure:

     for(int i = 0; i<100; i++){
        if(RX.available())
          x=RX.read();

        y[i] = x;
        }

Let's see. In a loop of 100 iterations you see if anything is available (and if so, put it into `x`).

Then, regardless of **whether or not you got anything** you now assign `x` to `y[i]`. So, most of the time, `y[i]` will have garbage in it.

>  the data still seems to be skewed

Not surprised. Do it differently. Only write to the array if you have data. In fact you may want a complete rework. Read this:

[How to read serial without blocking](http://www.gammon.com.au/serial)

---

>  I have posted the amended code. Change: Only add to the array is data is being read from buffer.

      int y[100];
      for(int i = 0; i<100; i++){
        if(RX.available())
        {
          x=RX.read();
          y[i] = x;
        }
      }

     for (int j = 1; j<=64; j++){
        Serial.println(y[j]);
      }

You still have not fixed it. Let me talk you through what it is doing now.

You are making 100 attempts to read some data. One or two may succeed, and they will be put into the buffer `y` (funny name for a buffer, right?).

So imagine `.` is garbage and `X` is good data, after doing that loop of 100 the buffer will look like this:

    ........X...........X...........X...X......................X.............................................

So your buffer is still 80% unchanged garbage. Then you print the first 64 elements (why 64 and not 100?) and you get a lot of garbage out. Exactly as expected.

---

You need to think about what you are doing. Draw it out on a bit of paper, perhaps.

Here is some example code from the page I linked for you, more than once. Please compare:

    // how much serial data we expect before a newline
    const unsigned int MAX_INPUT = 50;

    void setup ()
      {
      Serial.begin (115200);
      } // end of setup

    // here to process incoming serial data after a terminator received
    void process_data (const char * data)
      {
      // for now just display it
      // (but you could compare it to some value, convert to an integer, etc.)
      Serial.println (data);
      }  // end of process_data

    void processIncomingByte (const byte inByte)
      {
      static char input_line [MAX_INPUT];
      static unsigned int input_pos = 0;

      switch (inByte)
        {

        case '\n':   // end of text
          input_line [input_pos] = 0;  // terminating null byte

          // terminator reached! process input_line here ...
          process_data (input_line);

          // reset buffer for next time
          input_pos = 0;
          break;

        case '\r':   // discard carriage return
          break;

        default:
          // keep adding if not full ... allow for terminating null byte
          if (input_pos < (MAX_INPUT - 1))
            input_line [input_pos++] = inByte;
          break;

        }  // end of switch

      } // end of processIncomingByte

    void loop()
      {
      // if serial data available, process it
      while (Serial.available () > 0)
        processIncomingByte (Serial.read ());

      // do other stuff here like testing digital input (button presses) ...

      }  // end of loop


message:
Reasons why it is not OK to connect a relay directly from an Arduino digital pin

After looking into various schematics on controlling a relay via an Arduino, I have noticed that, most of the time, transistors are used to switch the separate supply into the relay coil rather than directly supplying the relay with the 5-Volt output from the I/O pin of the Arduino. For example, I have a 5-volt DPDT relay and also a small dc motor. I want to drive both directly from my Arduino UNO (SMD clone) with an Atmel328 processor? Would it be advisable to proceed?

If not (most likely):

1. Can someone give a detailed explanation and might as well important cautions on current limits and stuff?

2. How can one control such components without risking the Arduino? What are some common means to accomplish this?

3. What other devices can generally harm an Arduino board (or any microcontroller unit) in a similar manner?

I'm just a beginner who wants to be extremely cautious. Thanks.

body:
The recommended output (source or sink) from an I/O pin is 20 mA. The absolute maximum is 40 mA. Your relay coil is likely to consume more than that, particularly when it initially energizes. This will damage your output pin. Then it will eventually fail.

> Nothing seems to be amiss by far.

No, not yet. :)

> How can one control such components without risking the Arduino? What are some common means to accomplish this?

Use transistors or MOSFETs.

> What other devices can generally harm an Arduino board (or any microcontroller unit) in a similar manner?

Anything that exceeds the maximum voltage or current limits as documented in the datasheet. Coils (eg. in relays and motors) in particular are likely to have a high reverse voltage when they are turned off, which is why you need a [snubber diode](https://en.wikipedia.org/wiki/Snubber).

> Would it be advisable to proceed?

It would be advisable to take heed of what I wrote above, and to read the many, many articles on the Web about how to drive motors and relays from an Arduino. You are not the first person to attempt this.