message:
SIM808 module GSM working fine, GPS not working (No GPS ready message on power on)

I powered on my SIM808 module. It showed me following output:

    RDY
    +CFUN: 1
    +CPIN: READY
    Call Ready
    SMS Ready

It supposed to show `GPS ready` also.

I sent AT command and return ok.
However `AT+CGPSPWR=?` returns error. All GPS command showed error.

I think GPS is not initialized at all as i didn't see GPS message when module powered on.

Why is the GPS not working?

body: You have a version2 module. Use AT+CGNSxxx instead of AT+CGPSxxx


sender: user

sender: assistant

body:
Use `AT+CGNSxxx` instead of `AT+CGPSxxx` commands

`ATGNSPWR=1` and `ATCGNSINF` to get location.

if you get following output

`1,0,19800106001337.000,,,,0.00,0.0,0,,,,,,0,0,,,,, `

It means your GPS is not set.

Try to put GPS antenna outside your room, on open space for 10-15 minutes.
GPS bulb will start blinking to confirm it is now ready for use.

Then use `AT+CGNSINF`.

Good luck.


body:
Had the same problem with a Simcom868: AT+CGNSPWR=1 (for the GLONASS) and the most common AT+CGPSPWR=1 didn't work giving me back an ERROR. The Simcom808 needs 2A peak current so check if your power supply unit can reach that power and in case replace it;
then try the AT+CGNSPWR=1 or AT+CGPSPWR=1 again.


message:
Arduino uno unexpected void loop stop

I have a trouble with following, few lines code.
For some reason after few seconds Arduino uno stops responding into void loop section of code.
I tried to remove serial communication, all print and println without any success. Is the problem comming from MMA_7455.h?

    #include <MMA_7455.h>
    #include <Servo.h>

    int servoPin = 9;
    int servoAngle = 0;

    Servo servo;

    MMA_7455 accel = MMA_7455();
    char yVal;
    char yVal_bkp;

    void setup() {
        servo.attach(servoPin);
        accel.initSensitivity(2);
        accel.calibrateOffset(1.0, 26.0, -69.0);
    }

    void loop() {
        yVal = accel.readAxis('y'); //Read out the 'y' Axis

        if(yVal_bkp != yVal + 2 || yVal_bkp != yVal -2)
        {
            servo.write(90 + yVal);
            yVal_bkp = yVal;
        }
    }

P.S. Servo is normal G90

body:
Have you checked that MMA_7455 can handle this many reads?
I had sensors that stop working because I asked to often for feedback.
As the servo needs a 20ms to adjust its location I would add a delay(20) to the loop.


message:
Servo Speed Changer with Buttons

ok so yesterday i was in trouble with the buttons, with help from you i got over it and everything worked fine with the 1st speed of the servo, then i added the other 2 speeds and it looks like it all messed up... the buttons don`t respond as they should and the servo moves very weirdly.
Here is the code:

    const int button1Pin = 2;
    const int button2Pin = 3;
    const int ledPin1 = 13;
    const int ledPin2 = 12;
    const int ledPin3 = 11;
    #include <Servo.h>
    Servo servo1;

    int x = 0;
    int button1State = 0;
    int lastButton1State = 0;
    int button2State = 0;
    int lastButton2State = 0;

    void setup() {
      servo1.attach(9);
      pinMode(button1Pin, INPUT);
      pinMode(button2Pin, INPUT);
      pinMode(ledPin1, OUTPUT);
      pinMode(ledPin2, OUTPUT);
      pinMode(ledPin3, OUTPUT);
      Serial.begin(9600);
    }

    void loop() {
      // put your main code here, to run repeatedly:
        int position;
        button1State = digitalRead(button1Pin);
        button2State = digitalRead(button2Pin);

          if (button1State != lastButton1State)
         {
            if (button1State == HIGH)
              {
                x++;
                Serial.println("on1");
                Serial.print("number of button Pushes:  ");
                Serial.println(x);
              }
            else
              {
                Serial.println("off1");
              }
         }

        if (button2State != lastButton2State)
          {
            if (button2State == HIGH)
              {
                x--;
                Serial.println("on2");
                Serial.print("number of button Pushes:  ");
                Serial.println(x);
              }
            else
              {
                Serial.println("off2");
              }
           }
              delay(1000);

    lastButton1State = button1State;
    lastButton2State = button2State;

      if(x == 1)
        {
          digitalWrite(ledPin1, HIGH);
          digitalWrite(ledPin2, LOW);
          digitalWrite(ledPin3, LOW);
            for(position = 0; position < 360; position += 2)
              {
                servo1.write(position);
                delay(20);
              }
        }
       else if (x == 2)
        {
          digitalWrite(ledPin1, LOW);
          digitalWrite(ledPin2, HIGH);
          digitalWrite(ledPin3, LOW);
            for(position = 0; position <360; position += 5)
              {
                servo1.write(position);
                delay(20);
              }
        }
       else
        {
          digitalWrite(ledPin1, LOW);
          digitalWrite(ledPin2, LOW);
          digitalWrite(ledPin3, HIGH);
            for(position = 0; position < 360; position += 10)
              {
                servo1.write(position);
                delay(20);
              }
        }
    }

body:
There may be better ways to mitigate button bounce. Check [this link][1] for a discussion on button bounce and example code to work around this problem. In your code, it appears you can not press your buttons faster than once a second.

Determine if the servos you are using are capable of the range you are demanding.  Some servos only travel from 0 degrees to 180 degrees.  Your code is asking the servo to travel from 0 degrees to 360 degrees.  Also, it is unlikely that any normal servo can travel this far.  Most servos use a potentiometer as a feed back sensor.  And most potentiometers can only be turned to something less than 1 full revolution.

It is likely you have not given the servos enough time to move to the zero degree position at the start of each of your 3 loops.  Understand that normal servos can not make complete revolutions.  They need to stay within their designed limit of rotation.  If you want to start over at 0 degrees you need to allow the servos time to rotate back in reverse to the 0 degree position.

Consider your last loop.  You are asking the servo to move from 0 degrees to 360 degrees in 10 degree steps.  You are allowing 20ms per step.  That means the servo will be demanded to move almost a complete revolution in (((360 / 10) * 0.020 = 0.72 seconds) less than a second.  Some but not all servos can move that fast.

  [1]: https://www.arduino.cc/en/Tutorial/Debounce


message:
How to convert char[] to int with fail\success control?

this is more like C question, but i failed to google this.

i expect a command parameter in char[], but there may be no argument passed at all, so i need to try to parse this char[] to int and if there is garbage instead of a number, notify user.

i also need to be able to parse negative (with -sign char) numbers from char[].

how can i do this? thanks.

body:
It isn't doable, reliably, with the given specs. If the array has garbage in it, it won't necessarily fail to parse as an int. That said, you can try to parse as an int with atoi() or sscanf(), as suggested in the comments, and report that it *did or did not parse*, but not necessarily whether it is valid in some respect.

If you're in control of the array, zero its first element. Then if you get back a non-empty string, at least you'll know some command parameter had been placed in it.


message:
What does 16u and 128u mean?

The below is a snippet of a code for operating SI4455 Rf module with Arduino. I have some doubts which I'd like to seek some help in clearing.

    byte numOfBytes = *pSetPropCmd++;

  if (numOfBytes > 16u) // What does this 16u mean?
  {
   /* Initial configuration of Si4x55 */
   if (SI4455_CMD_ID_WRITE_TX_FIFO == *pSetPropCmd)
   {
    if (numOfBytes > 128u) // What does this 128u mean?
    {
     /* Number of command bytes exceeds maximal allowable length */
     return SI4455_COMMAND_ERROR;
    }

    /* Load array to the device */
    pSetPropCmd++;
    WriteEZConfigArray(numOfBytes - 1, pSetPropCmd);

    /* Point to the next command */
    pSetPropCmd += numOfBytes - 1;

    /* Continue command interpreter */
    continue;
   }

In the above snippet, what does 16u and 128u mean?. I think its meaning u for unsigned, but still not clear as what does 16u and 128u mean.

Rgds
VD

body:
It means that it is a unsigned value. Because the compiler checks for signed and unsigned in the same operation this is used (amongst others) to avoid warnings.

This is explained on stackoverflow here https://stackoverflow.com/questions/14844119/define-foo-1u-2u-4u-what-does-1u-and-2u-mean


message:
Sending data via SoftwareSerial results in garbled reception

My overall goal is to have an Arduino Uno with an Ethernet Shield send a short (5-character) string via a SoftwareSerial connection and a UDP packet when I press a button.

The device which is receiving the serial message is fixed at 9600 baud, no parity, one stop bit.

For the purposes of debugging my serial problem I have removed the Ethernet Shield. I mention it above only so that potential responders understand my intended final hardware configuration.

I am using a USB/serial adaptor and Kermit to check the serial output.

    C-Kermit>show communications

    Communications Parameters:
     Line: /dev/ttyUSB0, speed: 9600, mode: local, modem: none
     Parity: none, stop-bits: 1 (8N1)
     Duplex: full, flow: none, handshake: none
     Carrier-watch: off, close-on-disconnect: off
     Lockfile: /var/lock/LCK..ttyUSB0
     Terminal bytesize: 8, escape character: 28 (^\)

My first job on receiving garbled characters was to test my test rig. I connected the predecessor device and was able to receive the expected characters. (It cannot send the UDP packet, which is why it is being replaced.)

One button on the original device sends "X0401", exactly as expected:

    $ od -b oldserial⋅
    0000000 000 130 060 064 060 061
    0000006

Another button on the original device sends "X0402" (which I expected) and also a whole bunch of nuls, which I didn't expect:

    $ od -b oldserial⋅
    0000000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000
    0000020 000 000 000 000 000 130 060 064 060 062
    0000032

In any event, it seems that the terminal is actually receiving 8N1 data at 9600, so I can trust what it shows me.

I was going kind of nuts trying to figure out what was the problem, because nothing I sent from the Arduino came through properly. Then I stumbled on a suggestion that 'U' made a good test character because an ASCII 'U' is 0123 or 01010101. Indeed, I am able to send sequences of arbitrary length and so long as they contain only the 'U' caracter, they come through correctly.

(I've got three buttons and three different sets of messages, so my tests tend to run in sets of three attempts.)

Next step is to reintroduce a little bit of variety and see what comes through:

Here I send "UUUUU", "UUEUU", and then "UUQUU". 'E' and 'Q' were chosen because they are each just one bit different from 'U'.

What I saw when I sent the first message was:

    UUUUU

Then sent the second:

    UUUUUUU]UU

Then the third:

    UUUUUUU]UUUUWUU

Kermit was also storing the session to a log file, which looked like this:

    $ od -b serialUsequesnce⋅
    0000000 125 125 125 125 125
    0000005
    $ od -b serialUsequesnce⋅
    0000000 125 125 125 125 125 125 125 135 125 125
    0000012
    $ od -b serialUsequesnce⋅
    0000000 125 125 125 125 125 125 125 135 125 125 125 125 127 125 125
    0000017

Somehow, 'E' (0105) turned into 0135 and 'Q' (0121) turned into 0127. In each case, a sequence of three 0 bits were turned into 011, while no 1 bits were changed.

Sending:

    UUAUU

Got me:

    $ od -b serialUsequesnce2⋅
    0000000 000 125 125 137 125 125
    0000006

The five consecutive 0 bits in 01000001 were turned into 01111 to give me 01011111 or 0137

Longer strings get weirder.⋅

Test strings of:

    UU0123456789UU
    UUABCDEFGUU

Got me:

    $ od -b serialUsequesnce3
    0000000 125 125 326 266 226 166 126 066 026 366 215 125 125 000
    0000016
    $ od -b serialUsequesnce4
    0000000 125 125 137 257 335 325 315 305 125 125 001
    0000013

Now I'm seeing not just bits being replaced, but I'm getting fewer characters than I'm sending.

Since I wasn't getting good data from my SoftwareSerial port, I thought I would listen in on the USB traffic, which is also set to 9600 baud.

This text from the Arduino monitor:

    UUAUU
    Start button pressed
    UU0123456789UU
    Stop button pressed
    UUABCDEFGUU
    Light button pressed

Came through as this:

    $ od -b serialUSB
    0000000 125 125 137 125 125 171 275 165 324 332 027 277 073 025 027 027
    0000020 041 043 277 037 031 031 065 067 345 353 000
    0000033
    $ od -b serialUSB2
    0000000 125 125 326 266 226 166 126 066 026 366 215 125 125 345 353 131
    0000020 027 041 037 277 073 025 027 027 041 043 277 037 031 031 065 067
    0000040 345 353 000
    0000043
    $ od -b serialUSB3
    0000000 125 125 137 257 335 325 315 305 125 125 225 353 147 055 061 057
    0000020 027 277 073 025 027 027 041 043 277 037 031 031 065 067 345 353
    0000040 000
    0000041

I'm guessing that I'm doing something wrong with the hardware, but my serial connector simply has pin 5 connected to ground and pin 2 connected to digital 6 (or 2 when watching USB traffic).

I'm powering the Arduino Uno via its USB connection. When I checked the voltage at Vin and the adjacent ground, I got 4.51 volts.

    /*
    Listens on three buttons:
     - Start
     - Stop
     - Lights

    Sends serial messages to a Color Kinetics iPlayer 2
    9600 baud, 8 data bits, no parity, 1 stop bit
    Commands are
     - X0100 Lights Off
     - X0288 Lights at half
     - X02FF Lights at full
     - X0401 Set Show #1

    Created 2016-07-13
    by David H. Silber
    (Cribbing extensively from the Arduino examples.)
    */

    #include <SPI.h>         // needed for Arduino versions later than 0018

    #include <SoftwareSerial.h>
    SoftwareSerial softSerial( 5, 6 ); // RX, TX

    const int noButton = 100;
    const int startButton = 2;
    const int stopButton = 3;
    const int lightButton = 4;
    bool startTriggered = false;
    bool stopTriggered = false;
    bool lightTriggered = false;
    int lastTriggered = noButton;
    unsigned long lastButtonTime = 0;

    const char startSerial[] = "UUUUU";
    const char stopSerial[]  = "UUEUU";
    const char lightSerial[] = "UUQUU";

    void setup() {
      // initialize the pushbutton pin as an input:
      pinMode(startButton, INPUT);
      pinMode(stopButton, INPUT);
      pinMode(lightButton, INPUT);

      Serial.begin(9600);           // set up Serial library at 9600 bps
      Serial.println("Starting");  // prints hello with ending line break⋅

      // set the data rate for the SoftwareSerial port
      softSerial.begin(9600);
      delay( 1000 );
    }

    void loop() {
      // read the state of the pushbutton value:
      startTriggered = ( HIGH == digitalRead(startButton) );
      stopTriggered = ( HIGH == digitalRead(stopButton) );
      lightTriggered = ( HIGH == digitalRead(lightButton) );

      if ( startTriggered && (startButton != lastTriggered) ) {
        action( "Start button pressed", startSerial );

        lastTriggered = startButton;
        startTriggered = false;
      }

      if ( stopTriggered && (stopButton != lastTriggered) ) {
        action( "Stop button pressed", stopSerial );

        lastTriggered = stopButton;
        stopTriggered = false;
        }

      if ( lightTriggered && (lightButton != lastTriggered) ) {
        action( "Light button pressed", lightSerial );

        lastTriggered = lightButton;
        lightTriggered = false;
      }

      buttonTimeout();
    }

    void action( const char usbMessage[], const char serialMessage[] ) {
        Serial.println( serialMessage);⋅
        Serial.println( usbMessage);⋅

        softSerial.write( serialMessage );

        lastButtonTime = millis();
    }

    void buttonTimeout() {
      if ( millis() - lastButtonTime > 2000 ) {
        lastTriggered = noButton;
      }
    }

body:
A friend came and visited me with his oscilloscope and we determined that the 'serial' output from the Arduino was not actually RS-232. It was only an accident that any data came through at all.

I think my answer will be to add [https://www.arduino.cc/en/Main/ArduinoBoardSerial][1] or something like it.

One of our realizations was that we needed to level shift the output, searching on "arduino serial level shifter" led me to [http://forum.arduino.cc/index.php?topic=18689.0][2] which in turn led us to the MAX232 chip and boards that provide it.

It would be a good thing if there were some mention in the Arduino documentation that the 'serial' connection one would get from it was not actually RS-232.

  [1]: https://www.arduino.cc/en/Main/ArduinoBoardSerial
  [2]: http://forum.arduino.cc/index.php?topic=18689.0


message:
Best way to read CSV from SD card and store values by date

I am starting a project in Arduino and I need to read data from an CSV stored in an SD card. The data is stored as the following:

id, value, date

What I want to do is read the file, filter by date and then store the values by id. Each id will correspond to different values from that same date.

Is it possible to do something like this?

Thank you very much for your advice.

body:
I highly suggest checking out this YouTube video ([https://www.youtube.com/watch?v=5v5A3j7Rrco][1]), especially around 21:30. It goes over in detail to do exactly what you are asking for, mainly the headings with IDs for each data point. At the end of the day you are going to need something that looks similar to this:

    float id = 0; //used to provide a numbered ID to each data point

    void setup(){
    //initialize all your once-run variables and such
    }

    void loop(){
      //Write Log File Header
      File logFile = SD.open("NAME.csv", FILE_WRITE);

      if (logFile){
        logFile.println(", , , ,"); //Just a leading blank line, incase there was previous data

        String header = "ID, Time, Light, Temp"; //These will be the headers for your excel file, CHANGE "" to whatevr headers you would like to use
        logFile.println(header);
        logFile.close();
        Serial.println(header);
      }

      else {
        Serial.println("Couldn't open log file");
      }
    }
    }

This is all code that I currently use to do the exact same thing as you, and its a small edit from what Jeremy Blum does in the YouTube video I just linked you too. This is how the header files will look on an excel sheet, I took a screenshot of an actual file I have created using this method:

[![Sample File with Headers][2]][2]

  [1]: https://www.youtube.com/watch?v=5v5A3j7Rrco
  [2]: https://i.stack.imgur.com/xF2uC.png


message:
calling a timer when a button is pushed

I'm trying to call a function to keep an LED on for a certain amount of time. The function is called when the button is pushed but the LED stays on. I used the same code in the void loop before moving it into a function and it worked.

    const int ledPin2 = 2;
    const int buttonPin7 = 7;
    const unsigned long onTime = 1000;
    unsigned long previousMillis = 0;

    //
    void timer(){
     unsigned long currentMillis = millis();
     digitalWrite(ledPin2, HIGH);

     if (currentMillis - previousMillis >= onTime){
      digitalWrite(ledPin2, LOW);
      previousMillis = millis();
     }
    }

    void setup(){
     Serial.begin(9600);
     pinMode(ledPin2, OUTPUT);
     pinMode(buttonPin7, INPUT);
    }

    void loop(){
     int buttonState = digitalRead(buttonPin7);
     if (buttonState == HIGH) timer();
    }

body:
Your code says

    if (buttonState == HIGH) timer();

So... what will it do if `buttonstate` is `LOW`? Sorry, but the answer is "nothing". You don't have any code to tell it what to do when the button is in the opposite state.

What you should do is check the button, and if it's pressed (whether that's `HIGH` or `LOW` depends on your circuit), then light the LED and start the timer (assign to `previousMillis`).

Then, _regardless of the state of the button_, check to see if `currentMillis - previousMillis >= onTime`. If it is, then turn off the LED.


body:
When your code:

    if (currentMillis - previousMillis >= onTime){
        digitalWrite(ledPin2, LOW);
        previousMillis = millis();
    }
was in the loop, it was executed multiple times, so when `if (currentMillis - previousMillis >= onTime)` eventually became true, it would set ledPin2 LOW again.
Now that you moved it to the `timer` funtion, it only gets executed once (and `if (currentMillis - previousMillis >= onTime)` never gets a chance to become true).

You need to introduce a loop in the `timer` function. It also looks like you have your `currentMillis` / `previousMillis` messed up. I think you are looking for something like this:

    void timer(){

        unsigned long previousMillis = millis();
        unsigned long currentMillis = millis();
        digitalWrite(ledPin2, HIGH);

        while((currentMillis - previousMillis) < onTime) {
            // wait for a bit
            sleep(10);
            // update currentMillis
            currentMillis = millis();
        }

        digitalWrite(ledPin2, LOW);
    }


message:
Manually Declare Global Variable

Is it possible to manually declare a global variable that is inside of a function. The only current way I know how to do so is to declare that variable within the `setup()` function or simply outside of any function, but I was hoping there was a way to manually declare a variable as global so that I may call one variable from within one function in another function.

body:
You need to research 'Scope'.

Your variable has to be at the same level as all functions that will use it.  So at a simple level the answer has to be no.

    int variableOne = 0;
    void setup ()
    {
      variableOne = 1;
    }
    void loop ()
    {
      variableOne = 2;
    }
The above code will work, but if you move `int variableOne = 0;` inside either function then it won't work, because the variable will not be in scope in the other function.

You can use parameters to functions.

    void AFunction (const int& variable);

Will let you pass a single integer value to the function from the parent.  You can't change that value, because of the `const` qualifier.  If you remove the const then the `&` means pass the parameter by reference, which means you are passing in a reference (pointer) to the variable in the parent function and you can change it.  A better way to change the parent's value is to return a value from the call.

    int AFunction (const int& variable);

So you could use this like this:

    int AFunction (const int& variable)
    {
      return (++variable);
    }
    void loop (void)
    {
      int value = 0;
      value = AFunction(value);
      // value now == 1.
    }

You could use a Singleton class, but this is hardcore and I'm not sure you would see any real benefit on an Arduino.  A class is a grouping of related function and variables that you see in libraries and a Singleton class means there will only ever be one during the lifetime of the program.  In this way you can declare an instance of the class (i.e. `CSingleInstanceClass onlyOne;`) and then retrieve/set data from the setup and loop function, i.e.

    void setup ()
    {
      CSingleInstanceClass onlyOne;  // Single instance class
      onlyOne.SetVariableOne (1);
    }
    void loop ()
    {
      CSingleInstanceClass onlyOne;  // Single instance class
      Serial.println(onlyOne.GetVariableOne());// Prints 1
    }

Hope that helps.


body:
> even though I understand this takes up a bit of dynamic memory

There is no way around that. They have to go somewhere and that place is RAM (exception: constants could be stored in flash).

Another variation (which goes beyond your question) is that a parent function could declare and build a collection of data in a local array or struct and pass a pointer to it to any sub-functions. It still takes RAM, but it will be on the parent function's stack, so only for the duration of parent function's execution(s); it will be released when the parent function exits.


body:
Please note that 'Scope' of a variable is limited inside the block ( _a block starts at **{** and ends at **}**_ ), and that variable cant be accessed outside the block.

consider **life time** of a variable as well. using the keyword **static** may can help you some times. refer this [link.][1]

  [1]: https://stackoverflow.com/questions/5033627/static-variable-inside-of-a-function-in-c


message:
Read and write on the same node (central) using an RF24 network on Arduino

I want to send and receive on the same node using the RF24Network library, but I'm unable to do so even when I use `radio.StopListening()`.

Here is the code:

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

    RF24 radio(9,10);
    RF24Network network(radio);
    struct payload_t{unsigned long int code; unsigned long int message;};

    void setup(void) {
      Serial.begin(9600);
      SPI.begin();
      radio.begin();
      radio.setPALevel(RF24_PA_MAX);
      radio.setDataRate(RF24_250KBPS);
      radio.setAutoAck(false);
      network.begin(108, 0);
    }

    void loop(){
      network.update();
      RF24NetworkHeader header;
      payload_t payload;
      if(network.available()) {
        network.read(header, &payload, sizeof(payload));
        Serial.println(payload.message);
        // I WANT HERE TO SEND BACK TO THE TRANSMITTER but I'm unable to do that
        radio.stopListening();
        payload_t payload = { 2000, 15444452 };
        RF24NetworkHeader header(2);
        network.write(header, &payload, sizeof(payload));
      }
    }

Second Node:

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

    RF24 radio(9,10);
    RF24Network network(radio);
    struct payload_t{unsigned long int code; unsigned long int message;};
    firstExec = 1;

    void setup(void) {
      Serial.begin(9600);
      SPI.begin();
      radio.begin();
      radio.setPALevel(RF24_PA_MAX);
      radio.setDataRate(RF24_250KBPS);
      radio.setAutoAck(false);
      network.begin(108, 2);
    }

    void loop() {
      network.update();
      if(firstExec) {
        radio.stopListening();
        payload_t payload = { 2000, 5555555 };
        RF24NetworkHeader header(0);
        network.write(header, &payload, sizeof(payload));
        radio.startListening();
        firstExec = 0;
      }
      RF24NetworkHeader header;
      payload_t payload;
      if(network.available()) {
        network.read(header, &payload, sizeof(payload));
        Serial.println(payload.message);
      }
    }

body: The library says you must include `network.update()` in `loop()` for the nodes to be in sync. Place that call at the top of `loop()` in both nodes.


message:
Can I make so when I press a button on my Arduino Uno board, it will press a key on my computer?

I looked up the question before, but they only gave answers for boards that are not the Uno. Is there any way to make it so when I press a button on my board, it registers as a key press on my computer? I'm trying to make a flight controller for PC sims.

Thanks!

body:
Not without extra software on your computer side.

However if you use Arduino Micro, you can emulate keyboard and/or mouse directly.


body:
You'll need something on the Arduino that sends an event to your PC whenever the button is pressed. The easiest version of this would be the Serial channel over USB.

Second, you'll need a program running on your PC that receives that Serial message and generates your desired keyboard and mouse events.

In Windows, you can generate system wide keyboard and mouse events fairly easily using the Windows API. This would allow you to click a mouse, or keyboard button when inside of most programs written in Windows. https://msdn.microsoft.com/en-us/library/ms171548(v=vs.110).aspx

That said, you can have problems sending spoofed events to video games that don't use standard Windows forms. You might find this answer helpful from StackOverflow - https://stackoverflow.com/questions/7320424/c-win32-simulate-keypress-with-directinput


body:
EDIT: check @JohnBurger 's comment. THIS is NOT good for the UNO.

You can connect your Arduino as a keyboard to the computer. There is a Keyboard Arduino library you can use. Here is a reference:
[KeyboardWrite][1]

For example this line of code will react just like you pressed A on your keyboard:

    Keyboard.write(65);

  [1]: https://www.arduino.cc/en/Reference/KeyboardWrite


body:
You can do USB HID device on any AVR or Arduino chip without USB hardware interface by bitbanging on any 2 DIO:

[https://www.obdev.at/products/vusb/index.html][1]

Supports 4 endpoints (like 2 mouse and 2 keyboard, if makes sense :). Sure no additional software or driver is needed on OS side (default drivers shall be ok if correct VID/PID specified).

EDIT:

Seems 2 endpoints are required for USB HID keyboard. If remaining 2 is enough for USB HID joystick, it could be useful for flight sim.

  [1]: https://www.obdev.at/products/vusb/index.html


message:
Wifly Library that works with RN171

Does anyone know of a library that works with the WiFly-RN171?
I've tried all that I could find (WiFly, WiFlyHQ and WiFlySerial) but none of them work.

WiFly and WiFlySerial both hang on WiFly.begin().

WiFlyHQ fails to enter command mode and hence proceeds no further.

I'm using the WiFly-RN171 with an Arduino Uno and Communication Shield (XBee, Bluetooth, RFID) - XBee Shield as seen below.

Has anybody gotten this configuration to work?

[![arduino setup][1]][1]

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

body:
I have the same configuration and it works (Arduino UNO rev3)
I used WiFlyHQ library. Just be carefull with the serial.

    Serial.begin(9600);
    ...
    if (!wifly.begin(&Serial, NULL)) {
       ...

Upload with serial select then put it on USB and then open the monitor.


message:
Constantly read analog in in SWITCH/CASE setup

I'm writing a program with three different cases. Case one an LED is off, in another it is on and in the last case the brightness is controlled by a potentiometer. Each case works as I press the button. The issue I am having is with the third case. The potentiometer is read only once and the LED is set accordingly. I would like the LED to be adjusted continuously until the button is pushed again and the case is switched to off. I used the Serial.print to see the valves read from the potentiometer. I verified its only read once on each cycle through the different cases. I also changed from a SWITCH/CASE to If statements and it only reads the potentiometer once.

*CODE HAS BEEN UPDATED*

    //-------------------------------------------------------
    // BUTTON AND POT - TEST
    // KNOWN ISSUE - POT ONLY TAKES ON READING
    // vonderasche
    // 7/28/2016
    //-------------------------------------------------------

    const int BUTTON_PIN = 9;
    const int LED_PIN = 3;
    const unsigned long DEBOUNCE_TIME = 50;

    int val = 0;
    int pot = 0;

    int state = 0;

    void setup()
    {
     pinMode(BUTTON_PIN, INPUT_PULLUP);
     pinMode(LED_PIN, OUTPUT);
     Serial.begin(9600);
    }

    bool button_press()
    {
     static bool last_state;
     static unsigned long last_state_change;
     unsigned long now = millis();

     if (now - last_state_change < DEBOUNCE_TIME)
      return false;

     bool state = digitalRead(BUTTON_PIN);
     if (state != last_state) last_state_change = now;
     bool press = last_state && !state;
     last_state = state;
     return press;
    }

    void loop()
    {

     unsigned long now = millis();
        static enum { OFF, ON, POT } state;

     if (button_press()) switch (state) {
     case OFF:
      analogWrite(LED_PIN, 255);
      state = ON;
      Serial.println(state);
      break;
     case ON:
      analogWrite(LED_PIN, 0);
      state = POT;
      Serial.println(state);
      break;
     case POT:
      Serial.println(state);
      int Mode = button_press();
      while (val < 1023) {
       val = (analogRead(pot) / 4);
       analogWrite(LED_PIN, val);
       Serial.println(val);
       state = OFF;
       break;
      }
     }
    }

body:
The problem is that it will only go through the POT case once, if you want it to repeatedly read the potentiometer, and then change the LED brightness, you would have to put the case in a loop.

So, you might do something like this:

    case POT:
    int Mode = digitalRead(BUTTONPIN);
    while(Mode == LOW) {
        val = (analogRead(pot) / 4);
            analogWrite(LED_PIN, val);
            Serial.println(val);
            state = OFF;
            break;
            Mode = digitalRead(BUTTONPIN);
        }
    }

If you want to use the debounce, do something like this:

    static enum { OFF, ON, POT } state;
    unsigned long now = millis();
    int x = 0;

    while (x == 0) {
        switch (state) {
        case OFF:
            analogWrite(LED_PIN, 255);
            if (button_press()) {
            state = ON;
            }
            break;
        case ON:
            analogWrite(LED_PIN, 0);
            if (button_press()) {
            state = POT;
            }
            break;
        case POT:
            val = (analogRead(pot) / 4);
            analogWrite(LED_PIN, val);
            Serial.println(val);
            if (button_press()) {
            state = OFF;
            }
            break;
        }
    }

This should work. What it's doing is basically just going through this while loop over and over and over again, and whenever the button is pressed, THEN it will switch state, but otherwise, it'l just do the same state again and again. This way the potentiometer will work AND the debounce.


message:
Limited to 1MP still captures with OV5642 ArduCam Mini + Arduino Uno

I have an Arducam-Mini-5MP with Arduino UNO R3. I am running the unaltered example [ArduCAM_Mini_OV5642_Video_Streaming][1] to the arduino and am running ArduCAM_host_v1.0.exe on my PC with huge successes.

In this state, I can reliably take photos at low resolution (up to 1280x720) in all tested settings. However, when I go to higher resolutions (2592x1944, 2048x1563, and 1920x1080), certain situations result in consistently corrupt images all with the exact size of 524288 bytes.

The images are corrupted whenever I point the camera outside my window, and images are fine when taking photos inside my house. At 1280x720, a typical photo inside my house is 80kb and a typical photo out the window is 190kb (more than double in size). I suppose some content of the photo is impacting the jpg compression?

Unfortunately, images are corrupt 100% of the time for the actual subject I want to take; but the camera works perfectly when I'm testing it indoors. In my scenario I can only capture 0.8MP before images become corrupt.

The frame buffer limit for Arducam is 512kb, so am I just running up against the constraints of the hardware? I feel a bit fooled because I bought a 5MP camera and can only take 0.8MP photos with it.

Is my understanding of this failure correct -- is this the frame buffer size being hit by conditions impacting jpg compression? Are there Arducam shields available with higher frame buffers? Can I avoid this situation somehow?

  [1]: https://github.com/ArduCAM/Arduino/blob/master/ArduCAM/examples/mini/ArduCAM_Mini_OV5642_Video_Streaming/ArduCAM_Mini_OV5642_Video_Streaming.ino

body:
The Arducam Mini Shield is limited to 512kb frame buffer, so photos of larger resolution easily overflow the buffer. You can fit higher resolution photos onto the frame buffer by increasing the compression or adjusting other settings on the camera that reduce the file size of the resulting image (reduce saturation, windowing, etc).

To change the compression, adjust register 0x4407. The higher the number the more compression there is. The camera's default is 0x0C and the Arducam sample code sets it to 0x04.  `myCAM.wrSensorReg16_8(0x4407,0x09);`

To adjust other settings on the camera (including the ones listed above) check out the detailed list of camera registers at http://www.dragonwake.com/download/camera/ov5642/OV5642-DS.pdf

Also, Arducam is releasing the Arducam Mini Plus which has an 8 MByte frame buffer and is available on advanced order for $35 USD by contacting Arducam directly.


message:
How to connect ESP8266 12e directly to Arduino Uno (without shields)

I have an ESP8266 12E module and I'm trying to connect it to arduino, without any shields or whatsoever. I've looked everywhere but all I can find is about ESP-01 or with a NodeMCU. I'd like to do the bridge manually, but I don't know which pins I should ground and which pins I should power.

This is my current setup:
[![enter image description here][1]][1]

And the following sketch:

    #include <SoftwareSerial.h>

    //RX pin 2, TX pin 3
    SoftwareSerial esp8266(2, 3);

    #define DEBUG true

    void setup() {
      Serial.begin(9600);
      esp8266.begin(115200);
      sendData("AT\r\n", 2000, DEBUG);
      delay(1000);
      Serial.println("Firmware version:");
      delay(3000);
      sendData("AT+GMR\r\n", 2000, DEBUG);
      Serial.println("** End **");
    }

    void loop() {}

    String sendData(String command, const int timeout, boolean debug) {
      String response = "";
      esp8266.print(command);
      long int time = millis();
      while ( (time + timeout) > millis())
      {
        while (esp8266.available())
        {
          // The esp has data so display its output to the serial window
          char c = esp8266.read(); // read the next character.
          response += c;
        }
      }
      if (debug)
      {
        Serial.print(response);
      }
      return response;
    }

When run, I get the following output:

    Firmware version:
    ** End **

On the module, the led flashes when I power it up, but after that it remains off. I've already tested the voltage regulator with [ReadAnalogVoltage](https://www.arduino.cc/en/Tutorial/ReadAnalogVoltage), and the output was 3.33v, so it is working.

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

body:
Make sure to specify as SoftwareSerial's Rx pin, the pin# connected to the ESP's Tx pin. They have to be crossed. (I just fumbled that myself, a couple of hours ago ):

It is the ESP's Rx pin that needs the voltage divider.

Also pullup the ESP's reset pin.

Update:

ESP-01 and ESP-12 modules use the same ESP8266 chip. The differences are in the number of pins brought out from the chip and made available on the board. Other differences include the firmware interpreters installed on them before shipment: "NodeMCU" is one. ESP-01 is usually shipped with the AT+ command interpreter unless it specified otherwise; I would expect the same for the others. Bottom line is they are connected pretty much alike. Interacting with them serially from an Arduino (or other device) then depends on the installed firmware, including whether you've installed your own. So far, I've used all of mine as WiFi modules using the AT+ interpreter they came with.

> How can I pullup the reset pin? Also do I need to pullup it just for
> initial setup (changing baud rate and such) or should it be pulled up
> at all times?

I use a 10K-Ohm resistor to +3.3v as a pullup. You need it pulled up anytime you are not trying to force a hardware reset; grounding it resets the chip. I have never used a reset button on my ESPs. I just leave them pulled up. If you want one, it should short the reset pin to ground.

Update 2 (wiring):

You've powered the ESP with 3v but your pullups are taken to the Arduino's 3.3v supply. Most chips have a slim tolerance for signal levels above their supply voltage. I'd suggest driving the entire ESP from your 3v battery - power & both pullups.

I don't know the ESP-12E's pinouts to check them; I'm sure you have, and you might want to label the diagram so someone else can look over it too.

Then there's whatever "chicken dance" is needed on the reset and the GPIO line that needs to get toggled to start an upload. I don't know that sequence, but I think you need a grounding buttons on on each one to be able to sequence them.


body:
Oh boy, lot of things can be the problem here.

First of all: a voltage divider using 10k-10k has an output of 2.5V when the source is 5V. The ESPs run on 3.3V, so this effectively could mean the commands are completely scrambled when they arrive at the ESP.

The other way around and you're putting 3.3V comms into a 5V device. This isn't a problem per say, but it could definitely lead to problems. I suggest you use a bi-directional logic level converter which will transform a 5V command to the 3.3V ESP level, and back.

Your wiring between the Arduino and the ESP seems al right, but make sure TX~RX and RX~TX are connected, not TX~TX and RX~RX, but as I said above: use a bi-directional logic level converter.


body: From your code, I understand that you're setting the baud rate of the software serial pins as 115200. Software serial doesn't support speeds this high. You could set the baud rate of ESP8266 down to 9600 by using a USB to TTL converter and the AT command interface. Then you should try repeating this process using a baud rate of 9600 for the software serial. Or if you happen to have an Arduino Mega which comes with 4 serial ports, you can use the hardware serial pins which supports high speeds.


message:
Telit GPRS Module never returning and never timing out for command AT#FTPOPEN

Howdie!  I trying to run a GPRS modem on an Arduino. My full stack is [Nimbelink's NL-SW-GPRS Modem][1] (containing Telit GE910-QUAD GPRS module) with the [Nimbelink Arduino Development Shield][2] on an Arduino UNO R3.

My goal is to connect to an FTP server and upload a file. I am following this [guide from Nimbelink][3] and [section 3.3 from Telit's user guide][4].

I am stuck because the AT#FTPOPEN command doesn't seem to ever timeout nor does it return any result (ERROR or OKAY).

Here is the AT commands I am running:

    AT
    > OK

    AT+CGREG?
    > +CGREG: 0,1
    > OK

    AT#SIMDET=1
    > OK

    AT+CGDCONT=1,"IP","internet.com","0.0.0.0",0,0
    > OK

    AT#SCFG=1,1,300,90,600,200
    > OK

    AT#SGACTAUTH=0
    > OK

    AT#SGACT=1,1
    > <My IP Address>
    > OK

    AT#FTPTO=100
    > OK

    AT#FTPOPEN="209.86.62.76","anonymous","anonymous",0

Where 209.86.62.76 is the IP address of ftp.earthlink.net which I am just using for testing purposes, but I have tried several others. I have tried with FTP mode 0 (active) and 1 (passive) with no change in behavior.

The AT#FTPOPEN just never returns anything (no ERROR and no OK). I've waited up to 5 minutes. The command does returns "ERROR" if I deliberately mess up the syntax of the command (eg. AT#FTPOPEN="") but for any valid format it just seems to hang.

Is this a known problem or something I can easy work around? Am I doing something crazy with my timeout values? Is there an easy way to test the context that I activated with the SGACT?

This is more of a question for an M2M forum, but I'm on an Arduino and it seems like there are many people using GSM modules on Arduino - so I thought I'd post here because I am a bit desperate. Thanks :)

  [1]: http://nimbelink.com/skywire-gsmgprs/
  [2]: http://nimbelink.com/skywire-arduino-cellular-shield/
  [3]: http://nimbelink.com/wp-content/uploads/2015/11/Skywire-FTP-Application-note.pdf
  [4]: http://www.telit.com/fileadmin/user_upload/products/Downloads/3G/Telit_IP_Easy_User_Guide_r19.pdf

body:
The issues were:

 1. Pin 9 MSM_nRESET should be explicitly set to HIGH.
 2. Pin 10 (DTR) and pin 11 (RTS) should be explicitly set to LOW.
 3. The Nimbelink device requires 5V external power. With USB power, the modem can intermittently reset during period of high activity. If the modem resets, then the command can appear to run forever when nothing is actually running.
 4. Must use FTPOPEN with connection type 1 (passive).


message:
How to use Aiduino module to connect to computer network?

I have 4 usb Hard Drives and I just want to connect them to computer network directly without a traditional computer. Is there an any module with 4 usb ports and one RJ45 port. The module should able to connect drives to network as NAS (Network Area Storage) or other mounting possibility.

body:
An Arduino is completely incapable of doing such a difficult task. It's literally impossible because the processor isn't strong enough, it has no built in network capabilities that support NAS, it has no USB software built in, and so on and so on.

But you *can* use a Raspberry Pi. They are cheap for their capabilities, they do require quite some programming to get it to work but there's a huge community that has guides for everything. Best of luck :)


message:
Follow up question to Calling a timer when a button is pushed

I have changed the code with some help here. There are two buttons each one is set to turn on a LED. When the LED turns on it is timed and when the time is up it turns off. The problem I am having is that only one LED can be on at a time even though I am not using the delay() and I am using millis() to keep track of time. So if I press button one the first LED will turn on. Even if I press button two at this time the second LED wont turn on until the first one turns off.

    const int ledPin2 = 2;
    const int ledPin3 = 3;
    const int buttonPin6 = 6;
    const int buttonPin7 = 7;

    const unsigned long onTime = 10000;
    unsigned long previousMillis = 0;

    void timer() {

 unsigned long previousMillis = millis();
 unsigned long currentMillis = millis();
 digitalWrite(ledPin2, HIGH);

 while ((currentMillis - previousMillis) < onTime) {

  currentMillis = millis();
 }

 digitalWrite(ledPin2, LOW);
    }

    void timer2() {

 unsigned long previousMillis = millis();
 unsigned long currentMillis = millis();
 digitalWrite(ledPin3, HIGH);

 while ((currentMillis - previousMillis) < onTime) {

  currentMillis = millis();
 }

 digitalWrite(ledPin3, LOW);
    }

    void setup() {
 Serial.begin(9600);
 pinMode(ledPin2, OUTPUT);
 pinMode(ledPin3, OUTPUT);
 pinMode(buttonPin6, INPUT);
 pinMode(buttonPin7, INPUT);

    }

    void loop() {

 int buttonState2 = digitalRead(buttonPin6);
 if (buttonState2 == HIGH) timer2();

 int buttonState = digitalRead(buttonPin7);
 if (buttonState == HIGH) timer();

    }

body: Yes, it is because in timer() and timer2() you busy-loop with while until the condition is not met. Hence, when buttonState2 is HIGH, your code will execute timer2() until the condition of the while loop is not met. You are effectively doing a delay.


body:
As jogco says, you are (effectively) using a delay in your timer function, by doing this:

    while ((currentMillis - previousMillis) < onTime) {

        currentMillis = millis();
    }

What you want is to remember the time each LED was switched on, and each every time through the loop check if the required time has passed. Something like this:

    const int ledPin2 = 2;
    const int ledPin3 = 3;
    const int buttonPin6 = 6;
    const int buttonPin7 = 7;

    const unsigned long onTime = 10000;
    unsigned long led1_start = 0;
    unsigned long led2_start = 0;
    boolean led1_on = false;
    boolean led2_on = false;

    void timerOn(int led) {

        switch(led) {
            case 1:
                led1_start = millis();
                digitalWrite(ledPin2, HIGH);
                led1_on = true;
                break;
            case 2:
                led2_start = millis();
                digitalWrite(ledPin3, HIGH);
                led2_on = true;
                break;
        }
    }

    void timerOff(int led) {

        switch(led) {
            case 1:
                digitalWrite(ledPin2, LOW);
                led1_on = false;
                break;
            case 2:
                digitalWrite(ledPin3, LOW);
                led2_on = false;
                break;
        }
    }

    boolean checkTime(unsigned long startTime) {
          return ((startTime + onTime) >= millis());
    }

    void setup() {
        Serial.begin(9600);
        pinMode(ledPin2, OUTPUT);
        pinMode(ledPin3, OUTPUT);
        pinMode(buttonPin6, INPUT);
        pinMode(buttonPin7, INPUT);
    }

    void loop() {

        int buttonState2 = digitalRead(buttonPin6);
        if (buttonState2 == HIGH) timerOn(2);

        int buttonState = digitalRead(buttonPin7);
        if (buttonState == HIGH) timerOn(1);

        if (led1_on) {
            if (checkTime(led1_start)) timerOff(1);
        }

        if (led2_on) {
            if (checkTime(led2_start)) timerOff(2);
        }

    }

In fact I would look at arrays for the pin numbers and status/time variables, to make it more reusable...

    int ledPins[2] = {2, 3};
    int ledStart[2] = {0, 0};
    int buttonPins[2] = {6, 7};

... and the like


message:
Arduino-like ethernet only board?

I don't think USB chip is more expensive than Ethernet chip. So, I expect there should exist a board like Arduino, but where USB is removed in favour of Ethernet.

Are there such boards?

body: Yes, there's the Arduino Ethernet. Available from [Sparkfun](https://www.sparkfun.com/products/11229) for example


body:
It is highly unlikely you will ever find an "Ethernet only" board. There are plenty of boards that have both Ethernet and USB, but one without USB? I doubt it.

To make an Ethernet only board you would first need to create a bootloader with built-in support for the Ethernet port as well as a way of configuring that port to suit your network. Than kind of program would be rather large and take up a fair proportion of the flash memory, leaving you with much less room for your own program.

And as you have rightly noticed, USB chips (especially the dreaded CH340G, the bane of my life) are so cheap now, so why *wouldn't* you include one on your board?

So you get boards with both USB *and* Ethernet, and you install the software (generally) through USB which doesn't need any special configuration or complex software to get it to work.

Some boards provide "OTA" (Over The Air) updates, such as the ESP8266, but these generally require the OTA software first installing via the USB (or UART) connection to allow it to communicate on your network and accept OTA firmware. Others, such as the Arduino Yun, use multiple MCUs to provide remote programming. In the case of the Yun you get a "host" microcontroller which is considerably more powerful than the AVR microcontroller that it is programming, which always strikes me as a little pointless.

So no, I doubt that anyone would ever want to make an Ethernet only board.


message:
OTA Update Esp8266 without IDE

I was wondering if its possible to program the esp8266 to receive firmware updates without the use of an IDE to program.

Use Case:
This device should be setup to the WiFi network scan an IP for a firmware update and update itself if needed.

Any help is greatly appreciated. Thank you

body:
The firmware host will need a loader application that can talk to the bootloader in the ESP. You'll probably need to build a bit of hardware on the client to sequence grounding of the appropriate GPIO & Reset pins.

The application on the ESP would probably need to do something like:

 - Discover the availability of an update;
 - Tell the host to start its loader application;
 - Begin the local I/O-pin sequencer to start the local bootloader.

The final step should cause the chip to reset and the bootloader to take control. Both the loader on the host and the bootloader will nned to be somewhat tolerant of the potential network delays.


body:
This: https://github.com/arendst/Sonoff-MQTT-OTA-Arduino is a Arduino based firmware with support for OTA. It's written for Sonoff, but that is just a ESP8266 with a relay attached, you can easily adapt it to any ESP8266.

It uses a 'hard coded' address of a web server where it downloads the firmware, and updates are triggered by MQTT messages, but all of that should not be too hard to change to something else.


message:
SIM808 module: GSM location command (AT+CIPGSMLOC=1,1) giving wrong value after execution of sending message command (AT+CMGS=+91xxxxxxxx)

I wrote the code that if an interrupt is generated, get GSM location and send a  message.

The first time the interrupt is generated, I got the correct GSM location using `AT+CIPGSMLOC=1,1` and successfully sent a message using the `AT+CMGS=+91xxxxxxxx`command.

But the next time an interrupt was generated, `AT+CIPGSMLOC=1,1` gave a wrong location. When I commented out the code to send a message, on every interrupt generated I am getting the correct GSM location. So it seems like the problem is occurring after sending a message. But I have no clue what exactly is going wrong. Following is my code.

Note: on restarting the module, I'm again getting the correct location the first time, before sending a message.

    void setup() {
      mySerial.begin(9600);
      Serial.begin(9600);
      while (!Serial) {
      }
      // initialize the pushbutton pin as an input:
      pinMode(sensorPin, INPUT);
      // Attach an interrupt to the ISR vector
      attachInterrupt(0, pin_ISR, FALLING);
    }

    /////////***GSM RESPONSE***///////////
    String DisplayGSMResponse() {
      if(mySerial.available()) {
        String gsm_input="";
        while(mySerial.available()) {
          gsm_input+= (char)mySerial.read();
        }
        gsm_input.trim();
        delay(1000);
        Serial.println(gsm_input);
        return gsm_input;
      }
    }

    void SendMessage(String mobNum,String Location) {
      Serial.println("Sending message..");
      mySerial.println("AT+CMGF=1");
      //Sets the GSM Module in Text Mode
      delay(2000);
      // Delay of 1000 milli seconds or 1 second
      DisplayGSMResponse();
      mySerial.println("AT+CMGS=\""+mobNum+"\"\r");
      // mobile Number
      delay(4000);
      DisplayGSMResponse();
      cleanBuffer();
      mySerial.print("test");
      // The SMS text you want to send
      delay(100);
      mySerial.println((char)26);
      // ASCII code of CTRL+Z
      delay(8000);
      DisplayGSMResponse();
    }

    void gprsInit() {
      if (isGPRSInit) {
        return;
      }
      Serial.println("GPRS INITIALIZING");
      mySerial.println("AT+SAPBR=3,1,\"CONTYPE\",\"GPRS\"");
      delay(2000);
      DisplayGSMResponse();
      mySerial.println("AT+SAPBR=3,1,\"APN\",\"INTERNET\"");
      delay(2000);
      DisplayGSMResponse();
      mySerial.println("AT+SAPBR=1,1");
      delay(8000);
      DisplayGSMResponse();
      mySerial.println("AT+SAPBR=2,1");
      delay(2000);
      DisplayGSMResponse();
      isGPRSInit = true;
    }

    void gprsterm() {
      mySerial.println("AT+SAPBR=0,1");
      delay(1000);
      DisplayGSMResponse();
      isGPRSInit = false;
    }

    String getGPS() {
      Serial.println("GETTING GPS LOCATION");
      String loc = "";
      String location = "";
      mySerial.println("AT+CIPGSMLOC=1,1");
      delay(3000);
      loc = DisplayGSMResponse();
      return location;
    }

    void loop() {
      if (buttonState == 1) {
        detachInterrupt(0);
        gprsInit();
        location = getGPS();
        SendMessage(mobileNumber, location);
        gprsterm();
        Serial.println("location = " + location);
        buttonState = 0;
        location = "";
        attachInterrupt(0, pin_ISR, FALLING );
      }
    }

    void pin_ISR() {
      buttonState = 1;
      Serial.println("interrupt");
    }

EDIT: added gprsterm function.

Note: I removed the interrupt and called the code inside the loop function twice. The first time I got a correct result. The second time a wrong result. So it seems like the interrupt is not be causing the problem.

EDIT2:
One interesting thing I found is that at my home it is showing correct results every time, but in the office it is showing a wrong location on second location call i.e after the SMS was sent and we get the GSM location using `AT+CIPGSMLOC=1,1`.

body: It might be due to the command giving the nearest cell tower location. And for sending SMS it might be shifting to a different cell tower depending on your network. This could maybe be easily checked using a different cell provider or as you said its working at your home so I believe I am correct in assuming this is the answer


message:
Reading digital port with pullup via Firmata

I've got a weird issue, probably something I'm missing but have no clue what.

Got some simple float sensors connected to D2 - D5 on a Nano. Need internal pull-up to eliminate a floating value. Wrote this little sketch to test things:

    pinMode(2, INPUT_PULLUP);
    int sensorVal = digitalRead(2);
    Serial.println(sensorVal);

    pinMode(3, INPUT_PULLUP);
    int sensorVal = digitalRead(3);
    Serial.println(sensorVal);

There's one sensor connected reading HIGH and one reading LOW. This works as expected (displays 1010101010...).

Now I've got this connected to my Raspberry Pi via Bluetooth (BT shield connected to RX/TX) and using Firmata to communicate with the Nano. Code (C#):

    _arduino.pinMode(2, PinMode.PULLUP);
    PinState result2 = _arduino.digitalRead(2);

    _arduino.pinMode(3, PinMode.PULLUP);
    PinState result3 = _arduino.digitalRead(3);

    Debug.WriteLine($"Result pin 2: {result2} and pin 3: {result3}");

This always gives me two pinstates of LOW, even though I'm absolutely sure it should be reading HIGH as my test sketch is outputting the correct value. This driving me nuts. The Firmata sketch I've got loaded on the Arduino is this one: https://github.com/jsiegmund/submerged/blob/master/src/Arduino Sketches/SubmergedCabinetModule/SubmergedCabinetModule.ino. Also tried the latest available version from the firmata repo, doesn't solve the issue. As I've got the BlueTooth shield connected to RX/TX (and wasn't able to change that) I cannot use the serial monitor to provide more debug info. Should anyone know how to change that, would also be appreciated.

Btw for other things, Firmata is working just fine. So the communication itself shouldn't be the issue I think.

body: Never mind, I found out what the problem is. The Firmata SDK (Remote Wiring) for Windows just completely ignores the PULLUP pin mode. There are PR (https://github.com/ms-iot/remote-wiring/pull/102) which fixes this, now it's working just fine.


message:
ir sender detecting receiver and display

I am in a pickle and want to know if you can help me. I have an IR sensor and receiver and want a program that makes a light bulb flash or detect whenever the IR receiver is in range.
So whenever the IR sender detects the receiver, it should print "detect". This will be done using the Arduino program. And it is an Arduino Nano I am using.

These are the things I use:

http://www.dx.com/p/keyestudio-digital-ir-receiver-module-for-arduino-black-429206#.V5gcpzYko-U

http://www.dx.com/p/38khz-ir-infrared-transmitter-module-for-arduino-135040#.V5gcpjYko-U

How should this program look like? Anyone have the code for this?

Never mind the LED blinking, I just want the program to know whenever the receiver is detected and probably display it somehow. My plan is to send the number of times the transmitter detects the receiver to an Android app in the end.

body:
You can't.

IR is a one-way protocol. The transmitter has no way of knowing whether a receiver is in range; it's literally just an LED that emits infrared instead of visible light.


body:
Assuming you got receiver and transmitter mixed up, then its simple. Otherwise, its not as simple. As @duskwuff points out, simple IR is one-way. The Transmitter here is just an IR Led. That's it. The Receiver is a Remote Control type IR Receiver, looks for a 38khz modulated IR signal, and removes the 38khz carrier wave, passing on the data to be read by the other end.

For a IR beacon type setup, in either simple or two way mode, you'd need two micro controllers.

Simple:

- Microcontroller A is the Transmitter. All it does is repeatedly send out an IR modulated code. The Arduino IRLib library can do this.

- Microcontroller B is the Receiver. It looks for that specific code, and if found, does X, which could be print to serial, or send over bluetooth to a phone.

Complex, both receive and send:

- **Microcontroller A is the main part**. It sends a code then switches to receive mode for X seconds. If it receives a confirmation or its own code back, it tells the phone/pc it has been found or flashes a different LED.

- Microcontroller B is **a beacon/repeater**. It waits to receive the code above, then switches to transmit mode, and sends the same code or a different code back. That's all it does. A Basic IR Remote Control Repeater.

[This tutorial at Adafruit][1] explains it all, with code examples.

  [1]: https://learn.adafruit.com/using-an-infrared-library?view=all


message:
Please explain this adafruit image for connecting a DS1307 RTC

https://learn.adafruit.com/assets/3813

I understand that `analog 4` and `5` are `SDA/SLC`, isn't the picture also showing `5v` and `GND` being plugged into two analog pins? Does that work?

I have it wired up to the actual `5v` and `GND`, but it would be convieniet to be able to stack the RTC like they show in the picture

body:
It's written in [the tutorial](https://learn.adafruit.com/ds1307-real-time-clock-breakout-board-kit/wiring-it-up)

> If you set analog pin 3 (digital 17) to an OUTPUT and HIGH and analog pin 2 (digital 16) to an OUTPUT and LOW you can power the RTC directly from the pins!


message:
Arduino and A4988

I am new in the Arduino area.
What is necessary to control motors through Arduinos.

1. What is the difference between [A4988](http://www.allegromicro.com/en/Products/Motor-Driver-And-Interface-ICs/Bipolar-Stepper-Motor-Drivers/A4988.aspx) and the Arduino motor shield?
2. Is one A4988 needed for each stepper motor?
3. Or is one A4988 enough for all motors?

body:
An A4988 can control a single motor and supply up to 35V at 1.5A.
An Arduino motor shield can drive 2 DC Motors or 1 stepper motor at up to 12V and 4A/2A.

An A4988 needs mounting.
A motor shield drops straight in.

There are other options, including getting the ICs and doing it your self.  I have a motor shield which drives 4 DC motors or 2 Stepper motors that I got off eBay.


body:
The A4988 is a bipolar stepper driver. It is designed specifically to drive a single bipolar (4-wire) stepper motor. It consists of a pair of H-bridges and some extra drive logic to provide a simple GPIO interface.

The motor shield, in contrast, uses the L298D motor driver chip. This provides, as well, two H-bridges like the A4988. However it just gives you direct control of those H-bridges without a simple stepper-oriented interface.  So it is up to you to provide the correct control signals to effectively emulate the A4988's outputs.

Both chips can interface with exactly one bipolar stepper motor. The A4988 can *only* interface with a stepper motor. The L298D can *also* be used with other types of motor (though of course not at the same time as a bipolar stepper).


message:
Arduino sketch unexpected behaviour

I am currently in a arduino project to read some parameters from another microcontroller serially and the arduino is supposed to transmit these serially to dweet.io cloud. I use SIM900 modem for this. But my problem is that if i put some data to the variables, then the post to the cloud becomes unsuccessfull. Without any data in all parameters, the code runs fine.

Please find the code

    char code[4] = {'\0'}, voltage[4] = {'\0'}, current[4] = {'\0'}, mcurrent[4] = {'\0'}, acurrent[4] = {'\0'}, power[4] = {'\0'}, pf[4] = {'\0'}, freq[4] = {'\0'}, temp[4] = {'\0'};
    const char APN[18] = "bsnlnet";
    byte dtype = 0;

    #include <avr/pgmspace.h>

    void read_comp() {
     byte flag = 0, index = 0, l = 0;
     char c;
     char readings[8] = {'\0'};
     dtype = 0;

     do {
      while (Serial.available() && l == 0) {
       c = Serial.read();
       delay(20);

       if (c == '\n') {
        l = 1;
        break;
       } else {
        readings[index] = c;
        index++;
       }
      }

      readings[index] = '\0';
      index = 0;
      l = 0;

      if (readings[0] == 'v' || readings[0] == 'V') {             //check if received reading is voltage
       dtype = 1;
       flag = 1;

       if (readings[1] == 'o') {
        flag = 100;
       }
      } else if (readings[0] == 'c' || readings[0] == 'C') {  //check if received reading is current
       dtype = 2;
       flag = 1;

       if (readings[1] == 'u') {
        flag = 100;
       }
      } else if (flag == 1 && readings[1] == 'o') {
       dtype = 9;
       flag = 100;
      } else if (readings[0] == 'm' || readings[0] == 'M') {
       dtype = 3;
       flag = 1;

       if (readings[1] == 'c' && flag == 1) {
        flag = 100;
       }
      } else if (readings[0] == 'a' || readings[0] == 'A') {
       dtype = 4;
       flag = 1;

       if (readings[1] == 'c') {
        flag = 100;
       }
      } else if (readings[0] == 'p' || readings[0] == 'P') {
       flag = 1;

       if (readings[1] == 'o') {
        flag = 100;
        dtype = 5;
       } else if (readings[1] == 'f' || readings[1] == 'F') {
        flag = 100;
        dtype = 6;
       }
      } else if (readings[0] == 'f' || readings[0] == 'F') {
       dtype = 7;
       flag = 1;

       if (readings[1] == 'r') {
        flag = 100;
       }
      } else if (readings[0] == 't' || readings[0] == 'T') {
       dtype = 8;
       flag = 1;

       if (readings[1] == 'e') {
        flag = 100;
       }
      }

      if (flag == 100) {
       switch (dtype) {
        case 1:
         voltage[0] = readings[3];
         voltage[1] = readings[4];
         voltage[2] = readings[5];
         voltage[3] = readings[6];
         voltage[4] = '\0';
         flag = 0;
         break;

        case 2:
         current[0] = readings[3];
         current[1] = readings[4];
         current[2] = readings[5];
         current[3] = readings[6];
         current[4] = '\0';
         flag = 0;
         break;

        case 3:
         mcurrent[0] = readings[3];
         mcurrent[1] = readings[4];
         mcurrent[2] = readings[5];
         mcurrent[3] = readings[3];
         mcurrent[4] = '\0';
         flag = 0;
         break;

        case 4:
         acurrent[0] = readings[3];
         acurrent[1] = readings[4];
         acurrent[2] = readings[5];
         acurrent[3] = readings[6];
         acurrent[4] = '\0';
         flag = 0;
         break;

        case 5:
         power[0] = readings[3];
         power[1] = readings[4];
         power[2] = readings[5];
         power[3] = readings[6];
         power[4] = '\0';
         flag = 0;
         break;

        case 6:
         pf[0] = readings[3];
         pf[1] = readings[4];
         pf[2] = readings[5];
         pf[3] = readings[6];
         pf[4] = '\0';
         flag = 0;
         break;

        case 7:
         freq[0] = readings[3];
         freq[1] = readings[4];
         freq[2] = readings[5];
         freq[3] = readings[6];
         freq[4] = '\0';
         flag = 0;
         break;

        case 8:
         temp[0] = readings[3];
         temp[1] = readings[4];
         temp[2] = readings[5];
         temp[3] = readings[6];
         temp[4] = '\0';
         flag = 0;
         break;

        case 9:
         code[0] = readings[3];
         code[1] = readings[4];
         code[2] = readings[5];
         code[3] = readings[6];
         code[4] = '\0';
         dtype = 10;
         flag = 0;
         break;
       }
      }
     } while (dtype != 10);
    }

    void modem_initialization(void) {
     char rec_data, r;
     byte network_status = 0 ;//network_status initialized as zero
     byte status_check = 0 ;//status_check initialized as zero
     byte Serial3_cnt = 0;//Serial3_cnt initialized as zero
     byte ok_flag = 0; //ok_flag initialized as zero
     byte count = 0; //count initialized as zero
     clear_rx_buffer();

     while (Serial3_cnt < 4) { // repeat entire loop until Serial3_cnt less than 5
      switch (Serial3_cnt) {
       case 0:
        clear_rx_buffer();//clearing receiving buffer
        Serial3.println(F("AT"));// Attention command to wake up Serial3 modem
        delay(1000);
        break;

       case 1:
        clear_rx_buffer();//clearing receiving buffer
        Serial3.println(F("ATE0"));//Command for disable echo
        delay(1000);
        break;

       /*case 2: clear_rx_buffer();//clearing receiving buffer
              // Serial3.println("ATV0");// Command for numeric response after this '0'(zero) will be recieved instead of "OK"
               delay(1000);
               break;*/
       case 2:
        clear_rx_buffer();//clearing receiving buffer
        Serial3.println(F("AT&W"));// Command TO SAVE SETTINGS
        delay(1000);
        break;

       case 3:
        Serial3_cnt = 4;// exit from the loop
        break;

       default :
        break;
      }

      while (Serial3.available() > 0) {
       rec_data = Serial3.read();

       if (rec_data == 'O') { // 'o' is recieved
        ok_flag = 1;
       } else if (ok_flag == 1 && rec_data == 'K') { // 'K' is recieved
        Serial3_cnt ++;
        ok_flag = 0;
       } else if (rec_data == '0') { // '0'(zero) is recieved (numeric response)
        Serial3_cnt ++;
        ok_flag = 0;
       } else if (rec_data == '+') { // '+' is recieved message
        clear_rx_buffer();

        if (Serial3_cnt > 0) {
         Serial3_cnt --;
        }
       }
      }
     }

     Serial3_cnt = 0;
     ok_flag = 0;

     while (network_status == 0) { //wait for PIN READY
      if (status_check == 0) {
       delay(1000);
       status_check = 1 ;
       clear_rx_buffer();
       Serial3.println(F("AT+CPIN?")); //checkin PIN return ready(+CPIN: READY) with a valid simcard otherwise error
      }

      while (Serial3.available() > 0) {
       rec_data = Serial3.read();

       if (rec_data == '+' && status_check == 1) { // '+' is recieved
        status_check = 2 ;
       } else if (rec_data == 'C' && status_check == 2) { // 'C' is recieved
        status_check = 3 ;
       } else if (rec_data == 'P' && status_check == 3) { // 'P' is recieved
        status_check = 4 ;
       } else if (rec_data == 'I' && status_check == 4) { // 'I' is recieved
        status_check = 5 ;
       } else if (rec_data == 'N' && status_check == 5) { // 'N' is recieved
        status_check = 6 ;
       } else if (rec_data == ':' && status_check == 6) { // ':' is recieved
        status_check = 7 ;
       } else if (rec_data == ' ' && status_check == 7) { // ' ' is recieved
        status_check = 8 ;
       } else if (rec_data == 'R' && status_check == 8) { // 'R' is recieved
        status_check = 9 ;
       } else if (rec_data == 'E' && status_check == 9) { // 'E' is recieved
        status_check = 10 ;
       } else if (rec_data == 'A' && status_check == 10) { // 'A' is recieved
        status_check = 11 ;
       } else if (rec_data == 'D' && status_check == 11) { // 'D' is recieved
        status_check = 12 ;
       } else if (rec_data == 'Y' && status_check == 12) { // 'Y' is recieved
        status_check = 13 ;
       } else if (rec_data == 0X0D && status_check == 13) { //Carriage return
        status_check = 14 ;
       } else if (rec_data == 0X0A && status_check == 14) { //Line Feed
        status_check = 15 ;
       } else if (rec_data == 'O' && status_check == 15) { // '0' is recieved
        status_check = 16;
       } else if (rec_data == 'K' && status_check == 16) {
        clear_rx_buffer();
        status_check = 0 ;
        network_status = 1; //goto next step
       } else if (rec_data != 'R' && status_check == 8) { //+CPIN: NOT READY
        clear_rx_buffer();
        status_check = 0 ;
        network_status = 0; //repeat current step
       } else if (rec_data == 'M' && status_check == 3) { // in case of any message
        clear_rx_buffer();
        status_check = 0 ;
        network_status = 0; //repeat current step
       }
      }
     }

     while (network_status == 1) { //wait for SIM network registration
      if (status_check == 0) {
       delay(1000);
       status_check = 1 ;
       clear_rx_buffer();
       Serial3.println(F("AT+CREG?")); //checking for SIM card registration ,if registerd "+CREG: 0,1" will receive
      }

      while (Serial3.available() > 0) {
       rec_data = Serial3.read();

       if (rec_data == '+' && status_check == 1) { // '+' is recieved
        status_check = 2 ;
       } else if (rec_data == 'C' && status_check == 2) { // 'C' is recieved
        status_check = 3 ;
       } else if (rec_data == 'R' && status_check == 3) { // 'R' is recieved
        status_check = 4 ;
       } else if (rec_data == 'E' && status_check == 4) { // 'E' is recieved
        status_check = 5 ;
       } else if (rec_data == 'G' && status_check == 5) { // 'G' is recieved
        status_check = 6 ;
       } else if (rec_data == ':' && status_check == 6) { // ':' is recieved
        status_check = 7 ;
       } else if (rec_data == ' ' && status_check == 7) { // ' ' is recieved
        status_check = 8 ;
       } else if (rec_data == '0' && status_check == 8) { // '0' is recieved
        status_check = 9 ;
       } else if (rec_data == ',' && status_check == 9) { // ',' is recieved
        status_check = 10 ;
       } else if (rec_data == '1' && status_check == 10) { // '1' is recieved
        status_check = 11 ;
       } else if (rec_data == 0X0D && status_check == 11) { //Carriage return
        status_check = 12 ;
       } else if (rec_data == 0X0A && status_check == 12) { //Line Feed
        status_check = 12 ;
       } else if (rec_data == 'O' && status_check == 12) { // '0' is recieved
        status_check = 13;
       } else if (rec_data == 'K' && status_check == 13) {
        clear_rx_buffer();
        status_check = 0 ;
        network_status = 2; //goto next step
       } else if (rec_data != '1' && status_check == 10) { // +CREG: 0,2 not registered
        clear_rx_buffer();
        status_check = 0 ;
        network_status = 1; //repeat current step
       } else if (rec_data == 'M' && status_check == 3) { // in case of any message
        clear_rx_buffer();
        status_check = 0 ;
        network_status = 1; //repeat current step
       }
      }
     }

     Serial3_cnt = 0;

     while (Serial3_cnt < 4) { // repeat entire loop until Serial3_cnt less than 4
      switch (Serial3_cnt) {
       case 0:
        clear_rx_buffer();//clearing receiving buffer
        Serial3.println(F("AT+CMGF=1"));// Attention command to wake up Serial3 modem
        delay(1000);
        break;

       case 1:
        clear_rx_buffer();//clearing receiving buffer
        Serial3.println(F("AT+CNMI=2,1,0,0,0"));//Command to configure new message indication
        delay(1000);
        break;

       case 2:
        clear_rx_buffer();//clearing receiving buffer
        Serial3.println(F("AT+CMGD=1,4"));// Command to delete all received messages
        delay(1000);
        break;

       case 3:
        Serial3_cnt = 4;// exit from the loop
        break;

       default :
        break;
      }

      while (Serial3.available() > 0) {
       rec_data = Serial3.read();

       if (rec_data == 'O') { // '0'(zero) is recieved (numeric response)
        rec_data = Serial3.read();

        if (rec_data == 'K') {
         Serial3_cnt ++;
        }
       } else if (rec_data == '+') { // '+' recieved ,before "AT+CIICR" command,may be any message
        clear_rx_buffer();

        if (Serial3_cnt > 0) {
         Serial3_cnt --;
        }
       } else if (rec_data == 'E' && Serial3_cnt > 2) { // '4' recieved (error),in gprs initialisation commands
        clear_rx_buffer();
        Serial3_cnt = 4;
       }
      }
     }

     Serial3_cnt = 0;
    }

    void clear_rx_buffer(void) {
     Serial3.flush();
    }

    void gprs_init() {
     byte st = 1, i = 0, response = 0;
     char r[10];

     while (st <= 9) {
      delay(1000);
      clear_rx_buffer();

      switch (st) {
       case 1:
        Serial3.println(F("AT+CGATT?"));
        break;

       case 2:
        Serial3.println(F("AT+CIPSHUT"));
        break;

       case 3:
        Serial3.println(F("AT+CIPMUX=0"));
        break;

       case 4:
        response = cmd1_check(1);
        break;

       case 5:
        Serial3.println(F("AT+CIICR"));
        delay(1000);
        break;

       case 6:
        Serial3.println(F("AT+CIFSR"));
        break;

       case 7:
        response = cmd1_check(2);
        delay(2200);
        clear_rx_buffer();
        break;

       case 8:
        Serial3.println(F("AT+CIPSEND"));
        break;

       case 9:
        Serial3_send();
        ++st;
        break;
      }

      if (st == 10) {
       clear_rx_buffer();
      }

      delay(1000);

      while (Serial3.available() && st < 9 && st != 7 && st != 4) {
       r[i] = Serial3.read();
       i++;
      }

      i = 0;

      if (strstr(r, "ALREADY") != NULL) {
       Serial3.println("AT+CIPSHUT");
       delay(50);
       clear_rx_buffer();
       st = 2;
       r[0] = '\0';
      }

      if (strstr(r, "OK") != NULL || strstr(r, "+CGATT") != NULL || (strstr(r, ".") != NULL && st == 6) || strstr(r, ">") != NULL) {
       st++;
      } else if (strstr(r, "ERR") != NULL) {
       break;
      } else if (response == 1 && (st == 7 || st == 4)) {
       st++;
       response = 0;
      }
     }
    }

    char cmd1_check(short int o) {
     byte timout1 = 10500, m1, p1 = 0, resp1 = 0;
     char response1[25] = {'\0'};
     m1 = millis();
     clear_rx_buffer();

     if (o == 1) {
      Serial3.print(F("AT+CSTT="));
      Serial3.print('"');
      Serial3.print(APN);
      Serial3.print('"');
      Serial3.print(',');
      Serial3.print('"');
      Serial3.print('"');
      Serial3.print(',');
      Serial3.print('"');
      Serial3.println('"');
      delay(3000);
     } else if (o == 2) {
      Serial3.print(F("AT+CIPSTART="));
      Serial3.print('"');
      Serial3.print(F("TCP"));
      Serial3.print('"');
      Serial3.print(',');
      Serial3.print('"');
      Serial3.print(F("dweet.io"));
      Serial3.print('"');
      Serial3.print(',');
      Serial3.println(80);
      delay(2000);
     }

     do {
      p1 = 0;

      while (Serial3.available()) {
       response1[p1] = Serial3.read();
       p1++;
       delay(20);
      }

      if (strstr(response1, "OK") != NULL && o == 1) {
       resp1 = 1;
      } else if (strstr(response1, "ERR") != NULL) {
       resp1 = 2;
      } else if (strstr(response1, "CONNECT OK") != NULL && o == 2) {
       resp1 = 1;
      }
     } while ((millis() - m1) <= timout1 && resp1 == 0);

     return (resp1);
    }

    void Serial3_send() {
     Serial3.print("POST /dweet/for/");
     Serial3.print("mythingname");
     Serial3.print("?vo=");
     Serial3.print(voltage);
     Serial3.print("&cu=");
     Serial3.print(current);
     Serial3.print("&Mc=");
     Serial3.print(mcurrent);
     Serial3.print("&Ac=");
     Serial3.print(acurrent);
     Serial3.print("&Po=");
     Serial3.print(power);
     Serial3.print("&PF=");
     Serial3.print(pf);
     Serial3.print("&fr=");
     Serial3.print(freq);
     Serial3.print("&Te=");
     Serial3.print(temp);
     Serial3.println(" HTTP/1.1");
     Serial3.println("connection: keep-alive");
     Serial3.println();
     Serial3.println();
     Serial3.write(26);
     Serial3.println();
     delay(10000);
     Serial3.println("AT+CIPSHUT");
     delay(50);
    }

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

    void loop() {
     dtype = 0;
     read_comp();
     gprs_init();
    }

body:
This __looks like__ you are constructing the data to be sent as __GET__ parameters (i.e as part of the querystring), whereas I believe dweet.io expects them as part of the __POST__ body - [as seen here][1].

There seem to be many people [struggling to successfully send HTTP POSTs with a SIM900][2], but I think [this answer outlines the correct sequence to make it work][3].

  [1]: https://dweet.io/play/#!/dweets/postDweet_post_0
  [2]: http://google.com/?q=sim900 post data
  [3]: https://arduino.stackexchange.com/questions/21688/send-json-via-post-on-sim900-shield-with-at-commands


message:
Solar Power Inside a Car

I plan on making an Arduino project for reminding a parent to take a child from a car. In order to power the project I though on using a solar panel. Since I can't rely on having solar power all the time I'll need to use rechargeable batteries and charge them with the solar panel.

The problem is that from reading about the subject it is clear that it can be dangerous as far as battery go up in flame in some cases, especially due to high heat.

My car can get into very high temperature when parked outside so this scenario is very likely to happen.

Can someone please direct me to reading materials about using solar power in a very safe way?

body:
Firstly, solar panels inside a car is pretty pointless. Solar panels need to be in direct sunlight to be effective. Having them inside a car means they're not going to be in direct sunlight, so they're not going to be able to generate anywhere near enough power - unless they are massive, in which case where is the child going to sit? Yes, you could put them on the roof, but that would be silly.

The whole concept of solar panels for this project is completely wrong.

The car has a big battery and an in-built generator. Use them. There is absolutely no reason for you to have your own batteries as well. Yes, you could charge your own batteries from the car's battery, but that just introduces extra losses and wastefulness.

The only possible benefit of having your own batteries is it will safeguard the car's battery when the engine isn't running. It would then be impossible for your project to flatten the car's battery. But if you design your project properly that wouldn't be a problem anyway.

Some things you seem to be missing with your project:

1. The car has power you can use. It's throughout the car. No need to provide your own external power source.
2. The car has an "accessory" signal that is only turned on when the ignition is on. It's used by things like the radio etc so that when you turn the car's ignition off the radio turns off. No need for vibration sensors or anything to know if the car is running, it can tell you directly.
3. Cars generally have "seat occupied" sensors in them that couple with the seatbelts to know if a passenger hasn't got their seatbelt on and warn the driver (in most jurisdictions it's the responsibility of the driver to ensure all passengers have their seatbelts on).

If you really must charge batteries there are certain safety aspects you really must take into account. Your charge circuit must be able to manage the battery charging 100% safely. You have mentioned heat, and that is a very very important thing to manage. A decent battery manager chip will include an input for a thermistor. That is used as one of the multiple methods of charge termination (there's dv/dt (change in voltage over time), dT/dt (change in temperature over time), etc). It also serves as an over-heat safety cutout. Ensure that the charge circuit you use not only provides a thermistor input but also has the ability to cut off charging in the case of an overheat situation.

You also need to consider over-voltage. A car's 12V supply isn't 12V. It can get as high as 16V sometimes, and noise from the ignition can cause regular spikes as high as 70V or more. Automotive electronics have to be able to withstand those spikes, and that means your charge circuit has to be able to withstand those spikes.  Buffering the 12V through a proper 5V (cigarette lighter USB charger) regulator will remove that noise and make your circuit easier to work with.

So you need to think more carefully about just what it is you want to achieve and how that is going to fit into an automotive situation.


message:
On UNO, when serial.print to UART pin 11, nothing comes out of pin 11

The problem: Message prints only to the Arduino IDE's **Tools > Serial Monitor**, not coming out of TX pin 11.
Question, please how to get Arduino Uno or Mega to send data out of pin 11?

    #include <SoftwareSerial.h>
    SoftwareSerial mySerial(12, 13); // RX, TX pins on Arduino
    void setup() {
      Serial.begin(9600);
    }
    void loop() {
      Serial.print("This is a test\n\n");
      delay(1000);
    }

body:
Of course it's only coming out on the serial monitor - you are printing it to the hardware UART which comes out on the serial monitor.

You have created a SoftwareSerial object which you are then completely ignoring and then using the HardwareSerial UART object instead, which is on pins 0/1.

If you want to use a SoftwareSerial object you should actually *use* the SoftwareSerial object.

Replace all the references to `Serial` with `mySerial` instead.


message:
Blocking Serial Data

I am driving two stepper motor using serial data from Raspberry Pi to Arduino. Motors work fine when i am passing serial data but once i stop sending serial data, it doesn't accept serial data again unless I burn the program again in arduino. Here is code for that:

     #include <Driver.h>

    //////////////////////////////////////////////////////////////////////////////////////////
    /*
       Hardware pins defined in this section as connected from arduino to Pan DRV8834
       controller and tilt DRV8834 controller.M0 and M1 pins are common for both controllers
       ,hence declared only once(This is done to save number of pins, connecting it to
       additional pins , provide no special advantage since both both motors should be set
       to same level of microstepping).SLP pin is not currently used.

    */
    //////////////////////////////////////////////////////////////////////////////////////////

    #define PAN_DIRECTION_PIN 8
    #define TILT_DIRECTION_PIN 7

    #define PAN_STEP_PIN 10
    #define TILT_STEP_PIN 9

    #define M0 6
    #define M1 5

    #define MOTOR_SPEED 200

    #define SLP 0
    ///////////////////////////////////////////////////////////////////////////////////////////

    #define BAUD_RATE 230400      //Baud Rate for serial communication

    ///////////////////////////////////////////////////////////////////////////////////////////

    /*
       field data for receiving buffer on arduino side , important for serial communication
    */
    #define NUMBER_OF_FIELDS 2 // how many comma separated fields we expect
    int fieldIndex = 0;           // the current field being received
    int values[NUMBER_OF_FIELDS];  // array holding angles for both motors

    const char startChar = '<'; //beginning character of a valid command
    const char endchar   = '>'; //this will be ending character to ensure a valid command has ended
    boolean storeString = false; //This will be our flag to put the data in our buffer

    #define zeroCharacter 'z'

    bool zeroCommand = false;

    #define DATABUFFERSIZE 50
    char dataBuffer[DATABUFFERSIZE + 1]; //Add 1 for NULL terminator
    int dataBufferIndex = 0;

    int procBufCounter;         //iterate through whole string to obtain the commands

    float panAngle, tiltAngle;

    int sign = 1;

        Driver stepper_pan(M0, M1, PAN_STEP_PIN, SLP, PAN_DIRECTION_PIN);
        Driver stepper_tilt(M0, M1, TILT_STEP_PIN, SLP, TILT_DIRECTION_PIN);

        void processCommand(char *buffer) {

            procBufCounter = 0;
            bool startprocessing = false;
            bool endprocessing = false;

            values[0] = 0;
            values[1] = 0;

            while ((procBufCounter < DATABUFFERSIZE) && (!endprocessing)) {

                char ch = buffer[procBufCounter];           //read the character while simulatneously increasing the buffer cursor

                if (ch == '<') {
                    startprocessing = true;
                }
                else if (ch == '>') {
                    values[fieldIndex] = values[fieldIndex] * sign ;
                    fieldIndex = 0;
                    endprocessing = true;
                }

                if (startprocessing)
                {
                    if (ch == ',') {
                        values[fieldIndex] = values[fieldIndex] * sign ; // set value to the accumulated value
                        sign = 1;
                        fieldIndex++;
                    }
                    else if ('0' <= ch && ch <= '9' ) {
                        values[fieldIndex] = (values[fieldIndex] * 10) + (ch - '0');
                    }
                    else if (ch == '-') {
                        sign = -1;
                    }
                    else if(ch == 'z'){
                      zeroCommand = true;
                    }
                }
                procBufCounter++;
            }
            panAngle = ((float)(values[0]))/100;
            tiltAngle = ((float)(values[1]))/100;

           bool panMoved = true, tiltMoved = true;
            stepper_pan.moveTo(panAngle);
            stepper_tilt.moveTo(tiltAngle);
          while (panMoved || tiltMoved) {
            panMoved = stepper_pan.run();
            tiltMoved = stepper_tilt.run();
          }

          if(zeroCommand){
            stepper_pan.reset_positions();
            stepper_tilt.reset_positions();
            zeroCommand = false;
          }

        }

        //////////////////////////////////////////////////////////////////////////////////////

        void setup() {
          stepper_pan.setStepMode(STEP_THIRTYTWO);
          stepper_pan.setSpeed(MOTOR_SPEED);
          stepper_tilt.setStepMode(STEP_THIRTYTWO);
          stepper_tilt.setSpeed(MOTOR_SPEED);
          Serial.begin (BAUD_RATE);
          Serial.flush();
        }

        void loop() {
          if (processString) {
            processCommand(dataBuffer);
            processString = false;
        //     dataBuffer = "";

          }
        }

        void serialEvent() {
          static int dataBufferIndex = 0;
          while (Serial.available() > 0) {
            char incomingbyte = Serial.read();
            if (incomingbyte == startChar) {
              dataBufferIndex = 0;  //Initialize our dataBufferIndex variable
              storeString = true;
            }
            if (storeString) {
              //Let's check our index here, and abort if we're outside our buffer size
              //We use our define here so our buffer size can be easily modified
              if (dataBufferIndex == DATABUFFERSIZE) {
                //Oops, our index is pointing to an array element outside our buffer.
                dataBufferIndex = 0;
                break;
              }
              if (incomingbyte == endchar) {
                dataBuffer[dataBufferIndex] = endchar; //null terminate the C string
                dataBuffer[dataBufferIndex + 1] = '\0';
                //Our data string is complete.  return true
                storeString = false;
                processString = true;
                dataBufferIndex = 0;
              }
              else {
                dataBuffer[dataBufferIndex++] = incomingbyte;
                dataBuffer[dataBufferIndex] = 0; //null terminate the C string
              }
            }

          }

        }

body: I finally figured it out. It is due to reset whenever I open a port for serial communication. Attaching a 10uF capacitor between ground and reset fixed everything.