body:
I want to extract longitude and latitude from GSM/GPS module and then upload it to thingspeak. I am using sim808 GSM/GPS module and AT+CGPSINF=0 to get GPS location information sentence (CGPSINF: 0,6.823375,80.001038,36.300000,20170705124133.000,0,10,0.037040,47.410000
). I want to extract longitude and latitude from it. Does anyone know how to do it? I am not an expert in programming. someone told me to use strtok. But I don't know how to do it. Does anyone have any Arduino code to do this?

I tried DFRobot SIM808 library to collect GPS data. it works like charm. But the problem was, my upload code didn't work when i was using the library to collect longitude and latitude in the same code.

This is my web upload code.

    #include <SoftwareSerial.h>
    #include <String.h>

    SoftwareSerial mySerial(10, 11);//(2,3)

    void setup()
    {
      mySerial.begin(2400);   // the GPRS baud rate 9600
      Serial.begin(2400);    // the GPRS baud rate 9600

      delay(1000);

      ShowSerialData();

    }

    void loop()
    {
          Send2Pachube();
      if (mySerial.available())
        Serial.write(mySerial.read());
    }
    void Send2Pachube()
    {
      mySerial.println("AT");//start with attention
      delay(1000);

      mySerial.println("AT+CPIN?");//check for the sim card
      delay(1000);

      mySerial.println("AT+CREG?");//check for registration and access technology of cell
      delay(1000);

      mySerial.println("AT+CGATT?");//check whether the device is attached to GPRS.0Detch,1Attch
      delay(1000);

      mySerial.println("AT+CIPSHUT");//shut packet data protocol context
      delay(1000);

      mySerial.println("AT+CIPSTATUS");// returns the current connection status
      delay(2000);

      mySerial.println("AT+CIPMUX=0"); //create multi-IP connection(0=single connection)
      delay(2000);

      ShowSerialData();

      mySerial.println("AT+CSTT=\"hutch3g\"");//start task and setting the APN,
      delay(1000);

      ShowSerialData();

      mySerial.println("AT+CIICR");//bring up wireless connection
      delay(3000);
      ShowSerialData();

      mySerial.println("AT+CIFSR");//get local IP adress
      delay(2000);
      ShowSerialData();

      mySerial.println("AT+CGPSINF=0");//get GPS
      delay(2000);
      ShowSerialData();

      mySerial.println("AT+CIPSPRT=0");//starts a TCP or UDP connection
      delay(3000);

      ShowSerialData();

      mySerial.println("AT+CIPSTART=\"TCP\",\"api.thingspeak.com\",\"80\"");//start up the connection
      delay(6000);

      ShowSerialData();

      mySerial.println("AT+CIPSEND");//begin send data to remote server
      delay(4000);
      ShowSerialData();

      String str="GET https://api.thingspeak.com/update?api_key=FF19NVWMPZEWX0XK&field1=100";
      mySerial.println(str);//begin send data to remote server
      delay(4000);
      ShowSerialData();

      mySerial.println((char)26);//sending
      delay(5000);//waitting for reply, important! the time is base on the condition of internet
      mySerial.println();

      ShowSerialData();

      mySerial.println("AT+CIPSHUT");//close the connection
      delay(100);
      ShowSerialData();
    }
    void ShowSerialData()
    {
      while(mySerial.available()!=0)
        Serial.write(mySerial.read());
    }

title: How to extract latitude and longitude from GPS

Answers: 1

body:
First rather than just dumping it to the screen store the data in a char array

    char dataBuffer[64];
    int dataCount=0;

    while ( (mySerial.available()!=0) && (dataCount<63) ) {
        dataBuffer[dataCount] = mySerial.read());
        dataCount++;
    }
    dataBuffer[dataCount] = 0;

then use strtok to split the string on the : and , characters

    char *output;
    output = strtok(dataBuffer,":");
    // output will now point to everything up to the first : so "CGPSINF" for gps
    int field = 0;
    while (output != null) {
      field++;
      output = strtok(null,",");
    // output will now point to each value in turn
    // for CGPSINF:0,6.823375,80.001038,36.300000,
    // when field == 1 output=="0"
    // when field == 2 output=="6.823375" etc...
    }


body:
I want to create a TCP server on the Wemos that serves the analogRead value of the connected potentiometer.

The code below is based on [this][1] example.
The Wemos connects to the Wi-Fi and i'm able to ping it,
but the problem is that I **can't connect to the server**.
Also I don't really understand why the length of the data has to be passed with the data (`        serverClients[i].write(sbuf, len);`). Why can't the library figure that out?

    #include <ESP8266WiFi.h>

    //how many clients should be able to telnet to this ESP8266
    #define MAX_SRV_CLIENTS 2
    const char* ssid = "myWifi";
    const char* password = "myPassword";

    WiFiServer server(23);
    WiFiClient serverClients[MAX_SRV_CLIENTS];

    unsigned long previousMillis = 0;
    const long interval = 200;
    void setup() {
      Serial.begin(115200);
      Serial.print("\nConnecting to "); Serial.println(ssid);

      WiFi.mode(WIFI_STA);
      WiFi.begin(ssid, password);
      uint8_t i = 0;
      while (WiFi.status() != WL_CONNECTED && i++ < 20) delay(500);
      if (i == 21) {
        Serial.print("Could not connect to"); Serial.println(ssid);
        while (1) delay(500);
      }
      server.setNoDelay(true);
      Serial.print(WiFi.localIP());
    }

    void loop() {
      unsigned long currentMillis = millis();
      uint8_t i;
      //check if there are any new clients
      if (server.hasClient()) {
        for (i = 0; i < MAX_SRV_CLIENTS; i++) {
          //find free/disconnected spot
          if (!serverClients[i] || !serverClients[i].connected()) {
            if (serverClients[i]) serverClients[i].stop();
            serverClients[i] = server.available();
            continue;
          }
        }
        //no free/disconnected spot so reject
        WiFiClient serverClient = server.available();
        serverClient.stop();
      }

      //do every 200ms
      if (currentMillis - previousMillis >= interval) {
        previousMillis = currentMillis;

        int isensorValue = analogRead(A0); //analog read
        String sSensorValue = String(isensorValue); //int to string
        size_t len = sSensorValue.length();
        uint8_t sbuf[len];
        sSensorValue.getBytes(sbuf, len);
        for (i = 0; i < MAX_SRV_CLIENTS; i++) {
          if (serverClients[i] && serverClients[i].connected()) {
            serverClients[i].write(sbuf, len);
            delay(1);
          }
        }

      }
    }

  [1]: https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266WiFi/examples/WiFiTelnetToSerial/WiFiTelnetToSerial.ino#L62

title: How to create a simple TCP server with the analogRead value on Wemos D1 mini?

Answers: 1

body:
So the problem was that I forgot the following line.
Thanks to @Johnny Mopp for pointing this out.

    server.begin()

**Correct code:**

    #include <ESP8266WiFi.h>

    //how many clients should be able to telnet to this ESP8266
    #define MAX_SRV_CLIENTS 2
    const char* ssid = "myWifi";
    const char* password = "myPassword";

    WiFiServer server(23);
    WiFiClient serverClients[MAX_SRV_CLIENTS];

    unsigned long previousMillis = 0;
    const long interval = 200;
    void setup() {
      WiFi.mode(WIFI_STA);
      WiFi.begin(ssid, password);
      uint8_t i = 0;
      while (WiFi.status() != WL_CONNECTED && i++ < 20) delay(500);
      if (i == 21) {
        Serial.print("Could not connect to"); Serial.println(ssid);
        while (1) delay(500);
      }
      server.begin();
      server.setNoDelay(true);
    }

    void loop() {
      unsigned long currentMillis = millis();
      uint8_t i;
      //check if there are any new clients
      if (server.hasClient()) {
        for (i = 0; i < MAX_SRV_CLIENTS; i++) {
          //find free/disconnected spot
          if (!serverClients[i] || !serverClients[i].connected()) {
            if (serverClients[i]) serverClients[i].stop();
            serverClients[i] = server.available();
            continue;
          }
        }
        //no free/disconnected spot so reject
        WiFiClient serverClient = server.available();
        serverClient.stop();
      }

      //do every 200ms
      if (currentMillis - previousMillis >= interval) {
        previousMillis = currentMillis;

        int isensorValue = analogRead(A0);
        String sSensorValue = String(isensorValue) + "\n\r";
        size_t len = sSensorValue.length();
        uint8_t sbuf[len];
        sSensorValue.getBytes(sbuf, len);
        for (i = 0; i < MAX_SRV_CLIENTS; i++) {
          if (serverClients[i] && serverClients[i].connected()) {
            serverClients[i].write(sbuf, len);
            delay(1);
          }
        }

      }
    }


body:
The code below is for turning RGB lights on/off. The connections are as indicated in pin numbers. I found the resulting value of the buttons of the remote but when I used them in code it is not showing ON/OFF.

I assume there may be some practical errors. How to avoid such errors?

    #include <IRremote.h>

 int RECV_PIN = 3;
 int red = 13;
 int blue = 12;
 int green = 11;

 IRrecv irrecv(RECV_PIN);

 decode_results results;

    void setup() {
      Serial.begin(9600);
      irrecv.enableIRIn(); // Start the receiver
      pinMode(red, OUTPUT);
      pinMode(blue, OUTPUT);
      pinMode(green, OUTPUT);
    }

    void loop() {
      if (irrecv.decode(&results)) {
        long int getting = results.value;
        Serial.println(getting);
      }
      switch (results.value) {
        case 16582903:
          digitalWrite(red, HIGH);
          digitalWrite(blue, LOW);
          digitalWrite(green, LOW);
          break;
        case 16615543:
          digitalWrite(red, LOW);
          digitalWrite(blue, HIGH);
          digitalWrite(green, LOW);
          break;
        case 16599223:
          digitalWrite(red, LOW);
          digitalWrite(blue, LOW);
          digitalWrite(green, HIGH);
          break;
        default:
          Serial.println("Enter ;");
      }
      irrecv.resume(); // Receive the next value
      delay(100);
    }

title: IR Remote code not activating ON/OFF states

Answers: 2

body:
Assuming you wiring is correct, the only mistake I could see is that your variable named "getting" used in switch is inside the if, and it should be at least in the same level of switch. Also, your resume needs to be inside the if.

    #include <IRremote.h>

 int RECV_PIN = 3;
 int green = 11;
 int blue = 12;
 int red = 13;

 #define code1  16582903 // Must match exactly the code generated by the IR button, would be something like 0xFF906F
 #define code2  16615543
 #define code3  16599223

 IRrecv irrecv(RECV_PIN);
 decode_results results;

 void setup() {
      Serial.begin(9600);
      irrecv.enableIRIn(); // Start the receiver
      pinMode(red, OUTPUT);
      pinMode(blue, OUTPUT);
      pinMode(green, OUTPUT);
 }

 void loop() {
      if(irrecv.decode(&results)) {
        //this checks to see if a code has been received
        Serial.println(results.value, HEX);
        unsigned int getting = results.value;
        Serial.println(getting);
        switch (getting) {
          case code1:
            digitalWrite(red, HIGH);
            digitalWrite(blue, LOW);
            digitalWrite(green, LOW);
            break;
          case code2:
            digitalWrite(red, LOW);
            digitalWrite(blue, HIGH);
            digitalWrite(green, LOW);
            break;
          case code3:
            digitalWrite(red, LOW);
            digitalWrite(blue, LOW);
            digitalWrite(green, HIGH);
            break;
          default:
            Serial.println("Enter ;");
        }
        irrecv.resume(); //receive the next value
      }
      delay(100);
 }

body:
I would change "unsigned int getting = results.value;" to "unsigned long getting = results.value;" in Andrew's sketch and use it. I don't know what "type" of Arduino you are using, but I know on the Uno and other ATMEGA based boards, unsigned ints yield a useful range of 0 to 65,535. Unsigned long will give you a range from 0 to 4,294,967,295.

If you press ANY button and hold it down for a while on some IR remotes, code 4294967295 will be sent. This is true for the "Car" remotes: https://www.amazon.ca/dp/B00SMI1GZA/ref=pe_386430_126088100_TE_item, Apple TV (2nd generation) remote, and LG 50" TV remote.

One minor issue I found with both sketches is I could not get them to compile. I had to remove the space between "#" and "include" and the spaces between "<" and ">" in "# include < IRremote.h >". I am using an older version of the IDE which may explain it. Arduino UNO. IDE Version 1.0.6.2, GCC 4.2.1 on OSX 10.6.8.


body:
I am trying to connect an OV7076 camera with a NodeMCU, but there are no pin diagram available for it. As NodeMCU has 4 MB storage and 128 KB  memory, is there any possibility to use it?

[AI thinker esp8266mod ](https://bennthomsen.files.wordpress.com/2015/12/nodemcu_pinout_700-2.png)

[Omnivision OV7076](http://i.ebayimg.com/00/s/NTAwWDUwMA==/z/fh0AAOxyUylTVi8n/$_3.JPG?set_id=2)

title: Connecting NodeMCU with OV7076 camera

Answers: 1

body:
You cannot connect an [OV7076][1] camera with NodeMCU because OV7076 got 4 analog pins (VGA) and on the other hand NodeMCU got only one analog pin.

  [1]: https://www.voti.nl/docs/OV7670.pdf


body:
I want to control (switch on/off) a solenoid valve via an RC power switch and an Adafruit M0 Feather Bluefruit LE. The RC power switch is [this one][1], and this is the [Adafruit Board Pinout][2].

My assumption was that I have to wire up the servo wire connector of the power switch with the Adafruit board like I would do with an ESC and control it via PWM (my guide tells me that possible pulse widths are between 870 and 2,220 µs). I am connecting the white cable (I assume it's the impulse wire) of the power-switches' servo-connector with a PWM-capable GPIO pin and the black cable (I assume it's the minus wire) with the GND pin of the Adafruit Board, like I did with an ESC, which is working fine with the servo library of Arduino.

My problem is that the solenoid valve is showing no reaction. Am I thinking the right way or am I completely wrong?

Thank you and many thanks.

  [1]: http://shop.pichler.de/Power-Switch-c74-86-7486
  [2]: https://learn.adafruit.com/adafruit-feather-m0-bluefruit-le/pinouts

title: How to control RC power switch with Arduino-/Adafruit-Board?

Answers: 1

body:
I fixed the problem by myself. If you want to arm an RC power switch, do it like arming an ESC with your sketch. The servo connector wires have to be connected as follows:

- (white) PWM-capable GPIO
- (red) positive wire of your battery
- (black) negative wire of your battery

The simple solution was that the power switches got less/no power.


body:
So I am creating a tachometer using black/white detector sensor. Here's the code.

    unsigned long WaktuOLD;
    unsigned long WaktuNOW;
    int Detection = HIGH;
    int Counter = HIGH;
    float HitungWaktu;
    float HitungRPM;

    void setup() {
      Serial.begin(9600);
      attachInterrupt(digitalPinToInterrupt(3), rpm, RISING);
      WaktuNOW = millis();
    }

    void rpm() {
      Detection = digitalRead(3);
      if (Detection == HIGH && Counter == LOW) {
        WaktuNOW = millis();
        HitungWaktu = WaktuNOW - WaktuOLD;
        HitungRPM = 60 / (HitungWaktu / 1000);
        Counter = HIGH;
      } else if (Detection == HIGH && Counter == HIGH) {
        Counter = LOW;
        WaktuOLD = millis();
      }
    }

    void loop() {
      Serial.println(HitungRPM);
      delay(5000);
    }

The code works well and it can read RPM correctly. And then from the same arduino, I am controlling a servo motor, in this case I am using GWS03N/STD/F, with this code :

    #include <Servo.h>

    Servo myservo;
    int pos = 0;

    void setup() {
      myservo.attach(9);
    }

    void loop() {
      myservo.write(90);
    }

And this code works well too.

But, when I am trying to combine both codes, only the servo code is working well. The tachometer reading is not correct (the reading must be around 1000-1500rpm, but now it reads 3000-30krpm). I am already trying to change my tachometer interrupt to pin 2 or 3, and servo to 3, 5, 6, and 9 but still the same.

So what is wrong in here. Thank you so much.

This is my code when combining both codes.

    #include <Servo.h>

    Servo myservo;
    int pos = 0;
    unsigned long WaktuOLD;
    unsigned long WaktuNOW;
    int Detection = HIGH;
    int Counter = HIGH;
    float HitungWaktu;
    float HitungRPM;

    void setup() {
      Serial.begin(9600);
      attachInterrupt(digitalPinToInterrupt(3), rpm, RISING);
      WaktuNOW = millis();
      myservo.attach(9);
    }

    void rpm() {
      Detection = digitalRead(3);
      if (Detection == HIGH && Counter == LOW) {
        WaktuNOW = millis();
        HitungWaktu = WaktuNOW - WaktuOLD;
        HitungRPM = 60 / (HitungWaktu / 1000);
        Counter = HIGH;
      } else if (Detection == HIGH && Counter == HIGH) {
        Counter = LOW;
        WaktuOLD = millis();
      }
    }

    void loop() {
      Serial.println(HitungRPM);
      myservo.write(90);
      delay(5000);
    }

title: Problem with tachometer using attachInterrupt and servo

Answers: 2

body:
All of those variables that are accessed inside the ISR need to be declared as volatile.

You are using a RISING interrupt, so there should be no need to test the pin in the ISR.  You can be confident that it went HIGH for the interrupt to be run.

body:
Your problem is probably that of interrupt conflicts.

The 8-bit Arduinos don't have any concept of interrupt priorities. When one interrupt routine is running it is impossible for any other interrupt routine to run until that first one has finished.

Interrupts have a "natural call priority" in that lower numbered pending interrupts will be called in preference to higher numbered ones, however that doesn't mean that they can interrupt each other.

The problem here is that the servo library uses a timer (and its associated interrupt) to generate the waveform.  That uses a lot of interrupt calls running all the time - and while they are running your external interrupt can't be called - at least not until the currently executing timer interrupt completes, at which point your external interrupt handler will be called since it is the highest priority.

So the results you get with all that delaying are pretty meaningless.

So what can you do?  Well, there's a number of options - all of which involve *not* using interrupts.

* You could not use the Servo.h library and instead reconfigure the hardware PWM to the right frequency and use that for the servo
* You could use one of the timers with an external clock source to count your tacho pulses (I think Timer 1 has that ability on the Uno)

Or even better: do both.  That would give you the most efficient system whereby the main CPU is only involved in getting the count from the timer periodically, and adjusting the PWM value for your servo. The rest is then done by hardware completely asynchronously.

Of course, for this you will want to study [the datasheet](http://ww1.microchip.com/downloads/en/devicedoc/atmel-42735-8-bit-avr-microcontroller-atmega328-328p_datasheet.pdf) so you know how to configure the various hardware modules.


body:
I use Visual Studio 2015 extensively for work, so it would seem like a logical choice for getting started with Arduino programming (though my C/C++ is rusty, that may take some time to get back). From what I understand the [Visual Micro Plugin][1] is popular. Is that sort of the de facto choice for those who come from VS? Does it tie into everything so that I can handle debugging, breakpoints, deployment etc from Visual Studio? Much obliged!

  [1]: http://www.visualmicro.com/

title: Visual Studio integration with Arduino

Answers: 2

body:
I think it is the *de facto* standard for VS (of course the default Arduino IDE is used most).

However, I think some advanced features (like breakpoint if I recall right) is only temporarily for free and you have to pay later for a subscription.

Note however, that debugging/breakpoints are not used often anyway since mostly it's more realtime controlled than PC applications.

If you need breakpoints etc. probably the easiest is to make stubs for some libraries and first develop the application not using Arduino and later use the Visual Micro plugin. [Update: it seems breakpoints are possible with vMirco, I never got them to work though].

body: Use Atmel's Atmel Studio 7. Uses the visual studio shell and is supported by Atmel. Also allows you to import your Arduino Sketches. Once I used it, I stopped using the Arduino IDE.


body:
I'm building a remote for my WiFi-RGB Lights. I have an ESP8266, which should send one TCP packet with 4 chars.

My code:

    #include <ESP8266WiFi.h>

    const char* ssid     = "Wifi";
    const char* password = "wifikey";

    void WiFiEvent(WiFiEvent_t event) {
      Serial.printf("[WiFi-event] event: %d\n", event);
    }

    void setup() {
      Serial.begin(115200);
      WiFi.disconnect(true);
      delay(1000);
      WiFi.onEvent(WiFiEvent);
      WiFi.begin(ssid, password);
    }

    void loop() {
      delay(1000);
      const uint16_t port = 5577;
      const char * host = "192.168.178.150";
      WiFiClient client;
      client.connect(host, port);
      client.print(char(0x71));
      client.print(char(0x24));
      client.print(char(0x0f));
      client.print(char(0xa4));
      client.flush();
      client.stop();
      delay(5000);
    }

The problem: I send 4 TCP packets, while I should send 1 TCP packet with all 4 chars.

Thanks for your help.

title: ESP8266 send TCP HEX packet with 4 chars

Answers: 1

body:
After searching and experimenting on this, I believe the short answer to the question is that you need to send the command string like a buffer of characters AND put your Hex Coded command for the LED controller as an escaped string of characters.

Here is my code (it toggles the LED Controller between Green and Blue every 5 seconds, but you can extend this for other commands and colors as described at http://jpelectron.com/sample/Electronics/WiFi LED control/):

    /*
    Send Commands to LED Controller via Wifi Network and Wemos D1 Board
    */
    #include <ESP8266WiFi.h>

    const char* ssid     = "***yourWifiSSID***"; //Change this value for your network
    const char* password = "***yourWifiPassword***"; //Change this value for your network
    boolean connected = false;
    boolean colorToggle = false;

    void WiFiEvent(WiFiEvent_t event) {
        //Serial.printf("[WiFi-event] event: %d\n", event);

        switch(event) {
        case 3:
            Serial.println("WiFi connected");
            Serial.println("IP address: ");
            Serial.println(WiFi.localIP());
            connected = true;
            break;
        case 6:
            Serial.println("WiFi lost connection");
            connected = false;
            break;
        }

        // 0 : WL_IDLE_STATUS when Wi-Fi is in process of changing between statuses
        // 1 : WL_NO_SSID_AVAILin case configured SSID cannot be reached
        // 3 : WL_CONNECTED after successful connection is established
        // 4 : WL_CONNECT_FAILED if password is incorrect
        // 6 : WL_DISCONNECTED if module is not configured in station mode

    }

    void setup() {
      pinMode(LED_BUILTIN, OUTPUT);     // Initialize the LED_BUILTIN pin as an output
        Serial.begin(115200);
        WiFi.disconnect(true);
        delay(1000);
        WiFi.onEvent(WiFiEvent);
        WiFi.begin(ssid, password);
        Serial.println("");

        // Wait for connection
        while (WiFi.status() != WL_CONNECTED) {
          delay(500);
          Serial.print(".");
        }
        Serial.println("");
        Serial.print("Connected to ");
        Serial.println(ssid);
        Serial.print("IP address: ");
        Serial.println(WiFi.localIP());

    }

    // the loop function runs over and over again forever
    void loop() {
        //if we are connected
        if(connected){
          digitalWrite(LED_BUILTIN, LOW); //Turn on LED on the Board
          turnLEDSOn();
        }
        else
        {
          digitalWrite(LED_BUILTIN, HIGH); //Turn off LED on the Board
          setup();
        }
    }

    void turnLEDSOn() {
        const uint16_t port = 5577;
        const char * host = "192.168.10.2";  //Change to whatever your LED Controller IP is

         WiFiClient client;

         if (client.connect(host, port)) //Try to connect to TCP Server
         {
            Serial.println("Connected to LED Controller... ");
            if (colorToggle)
            { //Green
              char command[] = "\x31\x00\xff\x00\x00\x00\xf0\x0f\x2f";
              client.write((uint8_t *)command, sizeof(command));
              colorToggle = false;
              delay(5000);
            }
            else
            { //Blue
              char command[] = "\x31\x00\x00\xff\x00\x00\xf0\x0f\x2f";
              client.write((uint8_t *)command, sizeof(command));
              colorToggle = true;
              delay(5000);
            }

            Serial.println("Command sent ... "); // command is the color or animation sent to the LED controller
         }
         else
         {
            Serial.println("connection failed ... ");
         }

          if (client.available())
          {
            //Read from LED Controller
            char c = client.read();
            Serial.print(c);
          }

          if (!client.connected())
          {
            Serial.println();
            Serial.println("disconnecting ... ");
            client.stop();
            for(;;);
          }
    }


body:
I know, it isn't my original code, but I'm using this for a larger project that I am currently working on. I keep getting this error message: "cannot declare 'client' to be of abstract type 'Client'".
here's the code:

    // RoboSapienServer.cpp
    // RobosapienServer - Web enable a RoboSapien
    // Kevin N. Haw
    // http://www.KevinHaw.com/RoboSapienServer.php

    // This project combines the default webserver example in the IDE distribution and Karl Castleton's(http://home.mesastate.edu/~kcastlet) RoboSapienIR (http://playground.arduino.cc/Main/RoboSapienIR).
    // Source code merged from those two sources.

    // Include files
    #include <Ethernet.h>
    #include <string.h>
    #include <WebServer.h>

    //////////////////////////////////////////////////////////////////
    // Begin Web Server specific variable deinitions
    //////////////////////////////////////////////////////////////////

    byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

    // KNH, 02/09/2010 - Change IP address to use local subnet at home
    //byte ip[] = { 10, 0, 0, 177 };
    byte ip[] = { 192, 168, 1, 177 };

    // Server for web requests
    EthernetServer server(80);

    // Define field name in the submitted form
    #define SUBMIT_BUTTON_FIELDNAME "RSCmd"

    // String for HTTP request variables
    char pcHttpReqRsCmd[20] = {'\0'};

    volatile int viRobsapienUrlCmd = -1;  // A robosapien command sent over the URL of a webpage HTTP request

    //////////////////////////////////////////////////////////////////
    // Begin Robosapien specific variable deinitions
    //////////////////////////////////////////////////////////////////

    // Some but not all RS commands are defined
    #define RSTurnRight       0x80
    #define RSRightArmUp      0x81
    #define RSRightArmOut     0x82
    #define RSTiltBodyRight   0x83
    #define RSRightArmDown    0x84
    #define RSRightArmIn      0x85
    #define RSWalkForward     0x86
    #define RSWalkBackward    0x87
    #define RSTurnLeft        0x88
    #define RSLeftArmUp       0x89
    #define RSLeftArmOut      0x8A
    #define RSTiltBodyLeft    0x8B
    #define RSLeftArmDown     0x8C
    #define RSLeftArmIn       0x8D
    #define RSStop            0x8E
    #define RSWakeUp          0xB1
    #define RSBurp            0xC2
    #define RSRightHandStrike 0xC0
    #define RSNoOp            0xEF

    // Subset of additional codes pulled from http://www.contrib.andrew.cmu.edu/~ebuehl/robosapien-lirc/ir_codes.htm
    #define RSRightHandSweep  0xC1
    #define RSRightHandStrike2 0xC3
    #define RSHigh5           0xC4
    #define RSFart            0xC7
    #define RSLeftHandStrike  0xC8
    #define RSLeftHandSweep  0xC9

    #define RSWhistle         0xCA
    #define RSRoar            0xCE

    int IRIn = 2;            // We will use an interrupt
    int IROut = 3;           // Where the echoed command will be sent from

    boolean RSEcho = true;    // Should Arduino Echo RS commands
    boolean RSUsed = true;    // Has the last command been used
    volatile int RSBit = 9;   // Total bits of data
    volatile int RSCommand;   // Single byte command from IR
    int bitTime = 516;        // Bit time (Theoretically 833 but 516)
    // works for transmission and is faster
    int last;                 // Previous command from IR

    //////////////////////////////////////////////////////////////////
    // Begin Robosapien specific code
    //////////////////////////////////////////////////////////////////

    // Receive a bit at a time.
    //  NOTE: Unused in the RoboServer aplication
    void RSReadCommand() {
      delayMicroseconds(833 + 208); // about 1 1/4 bit times
      int bit = digitalRead(IRIn);
      if (RSBit == 9) { // Must be start of new command
        RSCommand = 0;
        RSBit = 0;
        RSUsed = true;
      }
      if (RSBit < 8) {
        RSCommand <<= 1;
        RSCommand |= bit;
      }
      RSBit++;
      if (RSBit == 9) RSUsed = false;
    }

    // send the whole 8 bits
    void RSSendCommand(int command) {
      digitalWrite(IROut, LOW);
      delayMicroseconds(8 * bitTime);
      for (int i = 0; i < 8; i++) {
        digitalWrite(IROut, HIGH);
        delayMicroseconds(bitTime);
        if ((command & 128) != 0) delayMicroseconds(3 * bitTime);
        digitalWrite(IROut, LOW);
        delayMicroseconds(bitTime);
        command <<= 1;
      }
      digitalWrite(IROut, HIGH);
      delay(250); // Give a 1/4 sec before next
    }

    // Set up RoboSpapien functionality
    void RSSetup()
    {
      pinMode(IRIn, INPUT);
      pinMode(IROut, OUTPUT);
      pinMode(10, OUTPUT);
      digitalWrite(IROut, HIGH);

      attachInterrupt(0, RSReadCommand, RISING);

      last = RSNoOp;

      // Make robot burp to indicate setup is complete
      RSSendCommand(RSBurp);

    }

    // Loop for RoboSapien functionality
    // Write only functionality - send the command from the web page to the robot, ignoring any input from the remote
    void RSLoop()
    {
      // Has a new command come in from the server?
      if (viRobsapienUrlCmd != -1)
      {
        // New command - send it to robot
        Serial.print("Sending command to RoboSapien: ");
        Serial.println(viRobsapienUrlCmd, HEX);
        RSSendCommand(viRobsapienUrlCmd);

        // Now clear command
        viRobsapienUrlCmd = -1;
      }
    }

    //////////////////////////////////////////////////////////////////
    // Begin Webserver Specific Code
    //////////////////////////////////////////////////////////////////

    // Print ourt MIME and HTML header at top of webpage
    void HtmlHeader(Client client)
    {
      client.println("HTTP/1.1 200 OK");
      client.println("Content-Type: text/html");
      client.println();
      client.println("\n");
      client.println("  <TITLE>Kevin's Arduino Webserver</TITLE>");//
      //  client.println("  <META HTTP-EQUIV=\"refresh\" CONTENT=\"5\">");
      client.println("");
    }

    // Print the footer at the bottom of the webpage
    void HtmlFooter(Client client)
    {
      client.println("");
    }

    // Print a submit button with the indicated label wrapped in a form for the indicated hex command
    void SubmitButton(Client &client, char *pcLabel, int iCmd)
    {
      client.print("<form method=post action=\"/?");
      client.print(iCmd, HEX);
      client.print("\"><input type=submit value=\"");
      client.print(pcLabel);
      client.print("\" name=\"" SUBMIT_BUTTON_FIELDNAME "\">");
      client.println("</form>");
    }

    // Parse an HTTP request header one character at a time, seeking string variables
    void ParseHttpHeader(Client &client)
    {
      char c;

      // Skip through until we hit a question mark (first one)
      while ((c = client.read()) != '?' && client.available())
      {
        // Debug - print data
        Serial.print(c);
      }

      // Are we here for a question mark or did we run out of data?
      if (client.available() > 2)
      {
        char pcUrlNum[3], *pc;

        // We have enough data for a hex number - read it
        for (int i = 0; i < 2; i++)
        {
          // Read and dump data to debug port
          Serial.print(c = pcUrlNum[i] = client.read());
        }
        // Null terminate string
        pcUrlNum[2] = '\0';

        // Get hex number
        viRobsapienUrlCmd = strtol(pcUrlNum, &pc, 0x10);
      }

      // Skip through and discard all remaining data
      while (client.available())
      {
        // Debug - print data
        Serial.print(c = client.read());
      }
    }

    // Set up webserver functionality
    void WebServerSetup()
    {
      Ethernet.begin(mac, ip);
      server.begin();
    }

    // Web server loop
    void WebServerLoop()
    {
      Client client = server.available();
      boolean bPendingHttpResponse = false; // True when we've received a whole HTTP request and need to output the webpage
      char c;  // For reading in HTTP request one character at a time

      if (client) {
        // Loop as long as there's a connection
        while (client.connected()) {
          // Do we have pending data (an HTTP request)?
          if (client.available()) {

            // Indicate we need to respond to the HTTP request as soon as we're done processing it
            bPendingHttpResponse = true;

            ParseHttpHeader(client);
          }
          else
          {
            // There's no data waiting to be read in on the client socket.  Do we have a pending HTTP request?
            if (bPendingHttpResponse)
            {
              // Yes, we have a pending request.  Clear the flag and then send the webpage to the client
              bPendingHttpResponse = false;

              // send a standard http response header and HTML header
              HtmlHeader(client);

              // Put out a text header
              client.println("
Kevin's RoboSapien Webserver
");

              client.println("

");
              client.println("");

              // Create buttons
              SubmitButton(client, "WakeUp", RSWakeUp);
              SubmitButton(client, "Roar", RSRoar);
              SubmitButton(client, "Whistle", RSWhistle);
              SubmitButton(client, "High5", RSHigh5);
              client.println("
");

              client.println("	");

              SubmitButton(client, "LeftArmUp", RSLeftArmUp);
              SubmitButton(client, "LeftArmIn", RSLeftArmIn);
              SubmitButton(client, "LeftArmOut", RSLeftArmOut);
              SubmitButton(client, "LeftArmDown", RSLeftArmDown);
              SubmitButton(client, "LeftArmSweep", RSLeftHandSweep);
              client.println("
");

              client.println("	");

              SubmitButton(client, "RightArmUp", RSRightArmUp);
              SubmitButton(client, "RightArmIn", RSRightArmIn);
              SubmitButton(client, "RightArmOut", RSRightArmOut);
              SubmitButton(client, "RightArmDown", RSRightArmDown);
              SubmitButton(client, "RightArmSweep", RSRightHandSweep);
              client.println("
");

              client.println("

");

              client.print("

URL Hex no: ");
              client.print(viRobsapienUrlCmd, HEX);
              client.println("
");

              // send HTML footer
              HtmlFooter(client);

              // give the web browser time to receive the data
              delay(1);
              client.stop();
            }
          }
        }  // End while(connected)
      }
    }

    //////////////////////////////////////////////////////////////////
    // Begin arduino entry points
    //////////////////////////////////////////////////////////////////

    void setup()
    {
      // open the serial port at 9600 bps:
      Serial.begin(9600);

      // Print greeting
      Serial.println("Kevin's RobSapien Server");

      RSSetup();
      WebServerSetup();
    }

    void loop()
    {
      RSLoop();
      WebServerLoop();
    }

title: Compilation Error: "cannot declare 'client' to be of abstract type 'Client'"

Answers: 2

body:
You can't use Client directly like that.  It's just an abstract class.  You have to use one of the classes like EthernetClient or WiFiClient that implements it.

Client is like a shell of a class.  It says that there will be classes that act as clients and will have this basic form.  But it doesn't have any code, just the outline.  The base classes that implement that abstract class like EthernetClient or WiFiClient actually have the code to actually BE a client.

body:
I would guess the problem lies here:

    void HtmlFooter(Client client) {
        client.println("");
    }

(Also the HtmlHeader function)

When you call that function you make a new Client object and copy the contents of your existing object into it. Since Client is pure virtual you can't do that. Instead you should be working with a reference as in the other functions:

    void HtmlFooter(Client &client) {
        client.println("");
    }


body:
I was testing out my new Servo FS5106B. Here is the code I used:

    #include <Servo.h>

    Servo servo;
    void setup()
    {
        servo.attach(10);
    }

    void loop()
    {
        servo.write(0);
        delay(1000);
        servo.write(180);
        delay(1000);
    }

After I upload the sketch, the console says:
>Sketch uses 2872 bytes (1%) of your device memory. Total available 253952 bytes. Global variables use 161 bytes (1%) of the dynamic memory, leaving 8031 bytes for local variables. Maximum 8192

The delay between the rotations wasn't 1 second (as I was expecting), but 13 seconds (when I connect *only* a LED and use the delay function, everything works perfectly). Why is that happening?

P.S The power source for the servo is my Arduino-Mega 2560, wich outputs 5V. The model I use for wiring is: [![enter image description here][1]][1]

*Edit 1*:
I tried to execute the program that @ChrisStratton suggested, here an updated code

    #include <Servo.h>
    #define led 22

    Servo servo;

    void setup()
    {
        Serial.begin(9600);
        while(!Serial)
            delay(10);

        Serial.println("Start!");
        pinMode(led, OUTPUT);
        servo.attach(10);
    }

    void loop()
    {
        digitalWrite(led, HIGH);
        servo.write(0);
        delay(1000);
        digitalWrite(led, LOW);
        servo.write(180);
        delay(1000);
    }

When this program loads, servo does 2 rotations in 0.4 seconds and the LED goes high and low really fast, then anything changes for another 10 seconds, then again the LED goes high and low and the Servo does 2 rotations
  [1]: https://i.stack.imgur.com/nA2rp.jpg

title: Servo FS5106B does not work properly

Answers: 1

body:
In the official Arduino examples, a servo motor is powered by the 5V pin of the Arduino board. In real life, that is a bad idea.
Your FS5106B has specified about 1A stall current. The average current is less than that, but the start peak current could indeed be 1A.
Could you try to use a seperate power supply of 5V (or 6V) for the servo motor ?

To check if the Arduino resets, you could do a `Serial.begin(9600);` in setup, directly followed by `Serial.println("the sketch has started");`

Some servo motors require different timing. That would not explain the 13 seconds delay, so I assume that your servo motor has normal timing.

Do you use a breadboard ? Sending a current peak through a breadboard (with bad contacts) can cause a lot of voltage spikes.

(*To the other problem solvers: I'm ignoring the 13 seconds and assume that once in a while the servo motor is able to start, just a guess, I could be wrong*).

[ADDED]
@ChrisStratton is trying to tell you this:

    void setup()
    {
      pinMode( LED_BUILTIN, OUTPUT);
    }

    void loop()
    {
      digitalWrite( LED_BUILTIN, HIGH);
      delay(1000);
      digitalWrite( LED_BUILTIN, LOW);
      delay(1000);
    }

The next step would be:

    #include <Servo.h>

    Servo servo;

    void setup()
    {
      Serial.begin(9600);
      Serial.println("The sketch has started");
      pinMode( LED_BUILTIN, OUTPUT);
      servo.attach(10);
    }

    void loop()
    {
      servo.write(0);
      digitalWrite( LED_BUILTIN, HIGH);
      delay(1000);

      servo.write(180);
      digitalWrite( LED_BUILTIN, LOW);
      delay(1000);
    }

[ADDED2]
Or even more fun, with a counter (as @ChrisStratton wrote):

    #include <Servo.h>

    Servo servo;

    unsigned int counter;

    void setup()
    {
      Serial.begin(9600);
      Serial.println("The sketch has started");
      pinMode( LED_BUILTIN, OUTPUT);
      servo.attach(10);
    }

    void loop()
    {
      servo.write(0);
      digitalWrite( LED_BUILTIN, HIGH);
      delay(1000);

      servo.write(180);
      digitalWrite( LED_BUILTIN, LOW);
      delay(1000);

      Serial.print("Still alive after ");
      Serial.print(counter);
      Serial.println(" seconds");
      counter += 2;   // two seconds per loop iteration
    }


body:
I am working on a code including interrupts. They, however, refuse to work, even in this simple code that could be the most basic example of interrupts.

In this simplified extract I have a momentary push button attached to an Arduino Pro Mini's PIN 2, with the other side grounded. I have this code uploaded:

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

    #include <Encoder.h>   // is this library the cause??...

    #define PIN_1 4
    #define PIN_2 3 //interrupt pin    //using these for a rotary encoder, not in this extract
    #define PIN_B 2 //interrupt pin    // the rotary encoder also works as a push-button

    void setup() {
      pinMode(PIN_B, INPUT_PULLUP);
      Serial.begin(9600);
      attachInterrupt(PIN_B, ButtonPressISR, FALLING);
      attachInterrupt(PIN_B, ButtonReleaseISR, RISING);
    }

    void loop() {
      Serial.println("Don't interrupt me");
      delay(10);
    }

    void ButtonPressISR() {
      Serial.println("Yay, I'm pressed!");
      delay(1000);
    }

    void ButtonReleaseISR() {
      Serial.println("Yay, I'm released!");
      delay(1000);
    }

One would expect that without action, the Arduino floods the serial console with "Don't interrupt me". And that's correct.

When I press the button, however, nothing on Earth happens, neither of the interrupt service routines starts. No matter how hard I try, "Yay, I'm pressed" and "Yay, I'm released" never appears on the console output, and the 1 s delay never happens.

The circuit, shown below, is tested with a multimeter, and is error-free. Pin 2 does get pulled down, and back, upon button press/release.

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/8L7EY.png)

<!-- End schematic -->

title: Interrupt problem...?

Answers: 2

body: Neither delay or print should be used in an interrupt routine as they use interrupts themselves, instead set a flag (usually a volatile variable) and test for that in the loop. Also be aware that due to contact bounce the interrupt will trigger multiple times for each button press.

body:
> They, however, refuse to work,

more accurately, you are unable to make them work.

1. don't delay large amount of time;
2. be careful with calling routines that are also called outside of the isr;
3. one isr for one pin.


body:
I was about to design a small custom board using ATmega32U4, replicating the Arduino Micro. I know that T1 is used to block VUSB when VIN is connected.

But why T2? The gate is 5V, so it will be always OFF! Or does it act as a diode?

Schemtic https://www.arduino.cc/en/uploads/Main/arduino-micro-schematic.pdf

title: Why is the T2 transistor used in Arduino Micro?

Answers: 2

body:
It's known as a "zero drop-out diode". When the power is first applied the body diode of the MOSFET conducts and powers the system. That imposes a (roughly) 0.7V drop on the input voltage.

Once the power gets through the regulator and is regulated to 5V that is then fed back into the gate of the MOSFET, which turns it on (as long as -5V is above the source voltage less the diode drop, so -5.7V minimum [it's a P channel so thresholds etc are negative]). That then bypasses the internal body diode getting rid of the 0.7V drop.

If the input voltage is too low the 5V gate no longer turns the MOSFET on and the body diode blocks any reverse current.

body:
T1 and T2 implement a power supply ORing of the VUSB and VIN voltages. Read [this][1] for extended information.

The body diode of each MOSFET performs the basic ORing function. When the MOSFET is turned OFF it just behaves as a diode. But when the MOSFET is turned ON, the diode is shorted by the conduction channel, thus avoiding its voltage drop (and achieving a behaviour closer to an ideal diode).

So:

 1. When VUSB is present and VIN is not connected (but pulled down to ground by R9), T1 turns ON and the +5V rail is connected to VUSB. Also, T2 turns OFF and the regulator input is isolated from VIN and the regulator simply doesn't operate (thus, avoiding a potential conflict because its output +5V is being forced to VUSB).

 2. When VUSB is not connected and VIN is present, T1 turns OFF and VUSB is isolated from the +5V rail. Also T2 turns ON and VIN is connected to the regulator input, which then regulates the voltage down into the +5V rail.

 3. When both VUSB and VIN are connected, the behaviour is the same as in case 2 above. Because VIN is supposed to be >7V and VUSB approx 5V, T1 will isolate VUSB and avoid a conflict with the regulator output. Also, a VIN >7V will allow T2 to turn on hard enough to bypass the body diode and avoid its voltage drop.

  [1]: http://www.eetimes.com/document.asp?doc_id=1273175&page_number=3


body:
I have an Arduino Mega with a [Ethernet2 Shield][1] + [RS232 Shield][2]

SD Card works well with Ethernet2 Shield, but it get a conflict when I add the RS232 Shield.

Both hardware use the same PIN:

    #define RS232_DIR_PIN     4 // RS232 Shield
    #define AMS_SS_SD         4 // Ethernet Shield

     pinMode(RS232_DIR_PIN, OUTPUT);             //Set RS232 direction pin as output
        digitalWrite(RS232_DIR_PIN, LOW);           //Set RS232 chip as receiver

        //Set SPI to Read SD Card
        pinMode(AMS_SS_HARDWARE, OUTPUT);
        digitalWrite(AMS_SS_HARDWARE, HIGH);

I dont need both running at same time, but I dont know how to make only one work at a time.
  [1]: http://www.arduino.org/products/shields/arduino-ethernet-shield-2
  [2]: https://www.embarcados.com.br/arduino-rs-232-rs-485-hardware/

title: Arduino RS232 Shield with SD Card conflict

Answers: 0


body:
I'm using a CD4094 shift register to power my LEDs along with a ULN2003A darlington transistor array. I want to hook up the LEDs to an external power supply of 12V (common anode).

The cathodes of little groups of LEDs will be connected to the ULN2003A which is connected to the shift register which will get its data from the arduino (the digital pins which i assume work at 5V).

My question is, if I connect the Vdd pin of the shift register to the 12V external power supply, will it still function as intended through the Arduino?

title: Can I power my shift register with a 12V external power supply and connect only the data, strobe and clear pins to the Arduino digital pins?

Answers: 1

body:
No. CD4k devices reference their high and low voltages to a (mostly) fixed ratio of Vdd, so there will be no way for the Arduino to operate the device.

Consider using a TPIC6C595 instead, which combines the shift register and the high-voltage driver into a single device.


body:
I have created a GPS logger code using DFRobot SIM808 library. The tcp code and getGPS codes are working fine. but when integrating the both the code, it failed to upload GPS data to thingspeak. It gets the IP connect to the server, but the get command is not working; and also the GPS data shown as a string. Can anyone please tell me where the problem is?

    /*
    ### Connect TCP and send GET request.
    1. This example is used to test DFRobot_SIM808 GPS/GPRS/GSM Shield's connect TCP and send GET request.
    2. Open the SIM808_TCPConnection example or copy these code to your project
    3. Download and dial the function switch to Arduino
    4. Open serial helper
    5. Waiting for a few minutes, until serial has sent "Connect mbed.org success"
    6. Serial will send "Hello world!"

    create on 2016/09/23, version: 1.0
    by jason
    */
    #include <DFRobot_sim808.h>
    #include <SoftwareSerial.h>

    #define PIN_TX    10
    #define PIN_RX    11
    SoftwareSerial mySerial(PIN_TX,PIN_RX);
    DFRobot_SIM808 sim808(&mySerial);//Connect RX,TX,PWR,

    //make sure that the baud rate of SIM900 is 9600!
    //you can use the AT Command(AT+IPR=9600) to set it through SerialDebug

    //DFRobot_SIM808 sim808(&Serial);

    char buffer[512];

    void setup(){
      mySerial.begin(2400);
      Serial.begin(2400);

      //******** Initialize sim808 module *************
      while(!sim808.init()) {
          delay(1000);
          Serial.print("Sim808 init error\r\n");
      }
      delay(3000);

      //*********** Attempt DHCP *******************
      while(!sim808.join(F("hutch3g"))) {
          Serial.println("Sim808 join network error");
          delay(2000);
      }

      //************ Successful DHCP ****************
      Serial.print("IP Address is ");
      Serial.println(sim808.getIPAddress());

      //************* Turn on the GPS power************
      if( sim808.attachGPS())
          Serial.println("Open the GPS power success");
      else
          Serial.println("Open the GPS power failure");
      delay(2000);
    }

    void loop(){
    //  gps();
      delay(2000);
      tcp();
      delay(2000);
    }

    void tcp(){
        //*********** Establish a TCP connection ************
      if(!sim808.connect(TCP,"api.thingspeak.com", 80)) {
          Serial.println("Connect error");
      }else{
          Serial.println("Connect mbed.org success");
      }

      //*********** Send a GET request *****************
        float lati=sim808.GPSdata.lat;
        float longi=sim808.GPSdata.lon;

        char http_cmd[100];
        sprintf(http_cmd, "GET https://api.thingspeak.com/update?api_key=FF19NVWMPZEWX0XK&field2=%s&field3=%s HTTP/1.0\r\n\r\n\0", lati, longi);

        boolean retValue = true;
        sim808.send(http_cmd, strlen(http_cmd));
        int ret = sim808.recv(buffer, sizeof(buffer)-1);
        if (ret <= 0){
            Serial.println("error receiving");
            retValue = false;
        }
        buffer[ret] = '\0';
        Serial.print(buffer);

      //************* Close TCP or UDP connections **********
      sim808.close();

      //*** Disconnect wireless connection, Close Moving Scene *******
      sim808.disconnect();
    }

    //void gps() {
    //   //************** Get GPS data *******************
    //   if (sim808.getGPS()) {
    //    Serial.print(sim808.GPSdata.year);
    //    Serial.print("/");
    //    Serial.print(sim808.GPSdata.month);
    //    Serial.print("/");
    //    Serial.print(sim808.GPSdata.day);
    //    Serial.print(" ");
    //    Serial.print(sim808.GPSdata.hour);
    //    Serial.print(":");
    //    Serial.print(sim808.GPSdata.minute);
    //    Serial.print(":");
    //    Serial.print(sim808.GPSdata.second);
    //    Serial.print(":");
    //    Serial.println(sim808.GPSdata.centisecond);
    //    Serial.print("latitude :");
    //    Serial.println(sim808.GPSdata.lat, 6);
    //    Serial.print("longitude :");
    //    Serial.println(sim808.GPSdata.lon, 6);
    //    Serial.print("speed_kph :");
    //    Serial.println(sim808.GPSdata.speed_kph);
    //    Serial.print("heading :");
    //    Serial.println(sim808.GPSdata.heading);
    //    Serial.println();
    //
    //    //************* Turn off the GPS power ************
    //    sim808.detachGPS();
    //  }
    //}

title: GPS Logger Error

Answers: 1

body:
First, I would assume you need to call `sim808.getGPS()` to update the GPS data. Not sure why you commented that out.

Normally, when building a `GET` command, you don't include the url (unless going through a proxy).

Last, you need to use `%f` with `sprintf` to format a floating point value.

Something like this might work:

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

    void tcp()
    {
        // Update the GPS data
        float lati, longi;
        if (sim808.getGPS()) {
            lati = sim808.GPSdata.lat;
            longi = sim808.GPSdata.lon;
            sim808.detachGPS();
        }
        else {
            // No gps, abort
            return;
        }

        //*********** Establish a TCP connection ************

        if (!sim808.connect(TCP,"api.thingspeak.com", 80)) {
           Serial.println("Connect error");
           return;
        }
        else {
           Serial.println("Connect mbed.org success");
        }

       //*********** Send a GET request *****************

        char http_cmd[100];
        sprintf(http_cmd, "GET /update?api_key=FF19NVWMPZEWX0XK&field2=%f&field3=%f HTTP/1.0\r\n\r\n\0", lati, longi);
        sim808.send(http_cmd, strlen(http_cmd));
        int ret = sim808.recv(buffer, sizeof(buffer) - 1);
        if (ret <= 0){
            Serial.println("error receiving");
        }
        else {
            buffer[ret] = '\0';
            Serial.print(buffer);
        }

        //************* Close TCP or UDP connections **********
        sim808.close();

        //*** Disconnect wireless connection, Close Moving Scene *******
        sim808.disconnect();
    }


body:
I'm using Arduino Uno and Adafruit Wave Shield, with the WaveRP library.
I was able to run the example programs of the waveRP library, but I try to connect a mic to the shield, didn't go well, so I returned to one of the examples to verify if the shield was working well and now is showing me this error message. I damaged the shield?

    > Arduino:1.8.2 (Mac OS X), Tarjeta:"Arduino/Genuino Uno"
    >
    > Documents/Arduino/libraries/Adafruit_waverp/examples/dapRP/dapRP.pde:
    > In function 'void setup()': dapRP:31: error: 'class SdFat' has no
    > member named 'init'    if (!sd.init(SPI_FULL_SPEED))
    > sd.initErrorHalt();
    >
    >            ^ Documents/Arduino/libraries/Adafruit_waverp/examples/dapRP/dapRP.pde:
    > In function 'void play(SdBaseFile*)': dapRP:67: error: no matching
    > function for call to 'SdBaseFile::readDir(dir_t&)'    while
    > (dir->readDir(dirBuf) > 0) {    // Read every file in the directory
    > one at a time
    >
    >                              ^ Documents/Arduino/libraries/Adafruit_waverp/examples/dapRP/dapRP.pde:67:29:
    > note: candidate is: In file included from
    > Documents/Arduino/libraries/SdFat/SdFile.h:24:0,
    >                  from  Documents/Arduino/libraries/SdFat/SdFat.h:38,
    >                  from Documents/Arduino/libraries/Adafruit_waverp/WaveRP.h:22,
    >                  from Documents/Arduino/libraries/Adafruit_waverp/examples/dapRP/dapRP.pde:4:
    > Documents/Arduino/libraries/SdFat/SdBaseFile.h:325:10: note: int8_t
    > SdBaseFile::readDir(dir_t*)    int8_t readDir(dir_t* dir);
    >
    >           ^ Documents/Arduino/libraries/SdFat/SdBaseFile.h:325:10: note:   no known conversion for argument 1 from 'dir_t {aka
    > directoryEntry}' to 'dir_t* {aka directoryEntry*}' exit status 1
    > 'class SdFat' has no member named 'init'
    >

title: 'Class SdFat' error message with Adafruit wave shield

Answers: 0


body:
I am working on a project involving bluetooth and wifi communications. Both of them are wired up to the Arduino and communicate to it using two software serial port.
The scenario is the one in the picture attached.

What I am doing is:

 - retrieve the sensor value
 - send it from the BT slave module to the master one (wired up to Arduino)
 - take it and send it, using AT commands, through the WIFI channel (the WIFI module is a ESP8266-01) to a web server.

The problem is that if I start listening to the BT serial port (BTSerial.listen()) I am not able to properly send the sensor values through the WIFI connection. But if I comment out the lines related to the BT sotware serial, and try to send fixed value to the web server, the sending terminates succesfully.

In my opinion there are some problems with the BTSerial.listen() and WIFISerial.listen() calls, since they are not able to switch from one the the other correctly.

I saw the TwoSerialPort example provided into the Arduino IDE and I tried to apply it into my code but it still not works to me.

Does anyone have a idea which would be the problem? Does anyone already faced with this problem or a similar one?

Hoping to be as much clear as possible, thanks in advance to anyone would help me.

Filippo

**[EDIT] Added two code snippets**

    // This method prepares the AT commands will be send to the ESP8266-01 module in order to upload the values on the web server
    void send2server(String ip, int port, String file, int t, int h, int p) {

      String queryString = "temp=";
      queryString.concat(t);
      queryString.concat("&hum=");
      queryString.concat(h);
      queryString.concat("&press=");
      queryString.concat(p);
      Serial.println(queryString);

      // Prepare and exec the AT+CIPSTART command provideing the TCP connection init
      String CIPSTART_cmd = "AT+CIPSTART=\"TCP\",\"" + ip + "\"," + port + "";
      exec_cmd(CIPSTART_cmd, 1000);

      // Prepare the POST request
      String httpPOST_cmd = "POST /";
      httpPOST_cmd.concat(file);
      httpPOST_cmd.concat(" HTTP/1.1\r\n");
      httpPOST_cmd.concat("Host: ");
      httpPOST_cmd.concat(ip);
      httpPOST_cmd.concat("\r\n");
      //httpPOST_cmd.concat("Accept: */*\r\n");
      httpPOST_cmd.concat("Content-Length: ");
      httpPOST_cmd.concat(queryString.length());
      httpPOST_cmd.concat("\r\n\r\n");
      //httpPOST_cmd.concat("Content-Type: text/html\r\n\r\n");
      httpPOST_cmd.concat(queryString);

      // Calculate the POST request length
      unsigned int len = httpPOST_cmd.length();

      // Prepare and exec the AT+CIPSEND statement with the POST request length just calculated
      String CIPSEND_cmd = "AT+CIPSEND=";
      CIPSEND_cmd.concat(len);
      exec_cmd(CIPSEND_cmd, 1000);

      // Exec the HTTP POST request
      exec_cmd(httpPOST_cmd, 1000);

      // Close the connection
      exec_cmd("AT+CIPCLOSE", 1000);
    }

    // This method execute each AT command in the previuous method
    void exec_cmd(String cmd, int delayTime) {
       byte i = 0;

       while(1) {
          Serial.println("invio comando");
          WIFISerial.println(cmd);
          while(WIFISerial.available()) {
             if(WIFISerial.find("OK")) {
                i = 8;
             }
          }
          delay(delayTime);

          if(i > 5)
             break;

          i++;
       }

       if(i == 8) {
          Serial.println("OK");
          //return true;
       } else {
          Serial.println("ERRORE");
          //return false;
       }
    }
The problem is the code goes properly till the AT+CIPSEND command, then the POST request is sent but no good feedback arrives, ending with the "ERRORE" error message.
[![enter image description here][2]][2]

**[EDIT 2] Attached serial monitor output**
This is the serial monitor output when I execute the skecth. It seems to work properly but it does not upload any value.
[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/hGXl6.png
  [2]: https://i.stack.imgur.com/XNk0f.png

title: Arduino UNO two SoftwareSerial ports communication

Answers: 1

body:
[This answer](https://arduino.stackexchange.com/questions/34126#34130) provides full details on choosing "good" combinations of hardware and software serial ports.  To summarize:

*  Use the `HardwareSerial` port (i.e., `Serial`) for one of the devices.  You can still use it for debug prints, as long as the device has some kind of command "format".  For example, if commands start with "AT", just make sure that none of your debug prints start with "AT".  It is the absolute best choice.  You would have to disconnect RX pin 0 from the device in order to upload new sketches over USB.

*  Use `AltSoftSerial` for the other device.  It is the most efficient software serial port, and it can be used at the same time as `Serial`.  It only works on two specific pins.

*  `NeoSWSerial` is the next best choice, at limited baud rates.  It can be used with the above choices, but transmitting on `NeoSWSerial` prevents them from receiving.

*  `SoftwareSerial` is the worst choice.  Receiving **or** transmitting on `SoftwareSerial` prevents all of the above from receiving anything.  It disables interrupts for long periods of time.

<hr>
### UPDATE - Here is the most reliable configuration:
[![enter image description here][1]][1]

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

Your code will have something like this:

    #include <AltSoftSerial.h>
    AltSoftSerial BT; // 8 is RX, 9 is TX

    #define WIFI Serial  // 0 is RX, 1 is TX (disconnect 0 to upload new sketch)

    void setup()
    {
      WIFI.begin( 115200 );
      BT.begin( 9600 );
    }

    void loop()
    {
      if (BT.available) {
        char c = BT.read();
        // do something with the character
           ... save them until '\n' arrives?
             ... then parse some values?

        if (values all received) {
          Serial.print( F("Sending values") ); // this is the WIFI port, but
              //  the ESP8266 ignores this debug print because it doesn't
              //  start with "AT".

          WIFI.println( F("AT+ ...") ); // all the AT commands
              ...
          WIFI.print( btValue1 );    // and the BT values
              ...
        }
      }
    }


body:
I am using a vibration switch with a pin change interrupt on an ATTiny85 to wake the processor and run some code when the vibration switch grounds an input pin. The circuit is battery-powered, so sleep mode is important. I would now like to add another input switch (momentary pushbutton) between an internal pullup on the ATtiny and ground to use as a soft latching switch to accomplish on/mode/off (power-on/case-selection/power-off). I'd like the vibration-wake-sleep code to be one of the cases selectable by the pushbutton. The ATtiny85 has one hardware interrupt (pin2 aka INT0), and the rest are pin change interrupts available on the other I/O pins.
After reading around, my understanding is that the pin change interrupts *cannot* be separated to run pin-specific code, as they all trigger the same pin change interrupt effect. Is that correct?
To put it another way, do I need to put my pushbutton on the hardware interrupt pin, or can I put it on any old I/O pin and still be able to use the vibration switch on another I/O pin only when I select that mode, without it triggering the same effect as the pushbutton every time there's a vibration? Or is there a better way? I'm trying to minimize the number of components, as this is a space-constrained project. Thanks!

title: ATtiny85 soft-latching, and sensor-waking: Are multiple switches differentiable by pin change interrupt?

Answers: 2

body:
If you have one dedicated interrupt signal, and enable the shared pin change interupt *for only one* pin, then you have no ambiguity - the hardware ISR is caused by the dedicated pin, and the shared pin change ISR is caused by the only enabled pin change pin.

Where things get more complicated is if you enable more than one pin to trigger the pin-change interrupt.  In this case, either the ISR or whatever follows in cause from it will need to figure out which pin caused the interrupt.

Unless I'm overlooking it in the data sheet, the ATtiny pin change interrupts don't have a register which latches the causing condition, so you may have to look at the actual pin input register.   The catch is that things like contact bounce might make the causing signal no longer present at the exact instant you check it.  However, contact bounce is typically a more serious problem when *releasing* a contact than closing it.

Some things you can do:

- In the ISR, don't actually do anything, but set an "interrupt happened" flag.  Then in the main program, poll the inputs for a while until you see one actually asserted, and act on that.  You should only need to stay awake for a small fraction of a second before you catch the responsible contacts closed when you are looking.

- You could try to use a small capacitor to slow the rate at which the pullup resistor responds to the switch bouncing back open, in the hopes of  making sure that the causing condition is seen when the ISR itself looks.

In either case you will probably want to stay awake and keep the pin change interrupt *disabled* until the switch has been released, and for maybe a hundred milliseconds thereafter to let release bounces die out.  Then you can re-enable the interrupt and go back to sleep.

Do keep in mind that regardless if the MCU is awake or not, if someone wedges the product into packing material or something which holds the switch closed in opposition to the pullup resistor, then that pullup resistor itself may drain your battery over a few weeks/months.

body:
> Or is there a better way?

Read the data sheet to see if it has individual flags for those pins.

Short of that, read and keep track of the pin states in the use to see which pins may have changed.


body:
I am designing a driver for a Bipolar stepper motor using Arduino Mega 2560 and DRV8825 Stepper driver.

In my application, a stepper motor (Nema 24) will run for 5 minutes and stop for 2 minutes. I have doubts about is what is the maximum time an Arduino Mega can delay the process, or how much a maximum time `delay()` function will last, or work in programming?

title: Maximum Delay time

Answers: 1

body:
*Note: there's an existing question here this should be closed as a duplicate of, but that is proving hard to find.  So until someone does find it...*

The arduino `delay()` function creates a *blocking* delay of the provided number of milliseconds.   The argument is an `unsigned long` which on a 16-bit Arduino is a 32-bit unsigned integer type, having a maximum value of 4,294,967,295.  Since these are milliseconds, the maximum `delay()` would be 4,294,967.295 seconds, or about 49 days.

However, you can easily achieve longer delays by using counting variables to count up instances of shorter delays.  At an extreme, by using up available memory for keeping track of such counting, you can readily achieve theoretical delays exceeding the age of the universe.

Note that the Arduino `delay()` function is *blocking*, which is to say that nothing else (except interrupts and on-chip hardware peripherals) runs during it.  This is often undesirable.  A more useful solution might be to make a loop taking say 20 milliseconds to run, as the result of a `delay()` and a few housekeeping operations, and then run this over and over again while counting.  Or you could make a 1 second loop, or whatever you choose.


body: I have an Arduino Uno and I also have two Servo Motors. Say I have a room that is 15 feet wide, and I want to be able to place the Arduino in the center of the room and control two servo motors placed at each end of the room using a button on the Arduino. Is it possible to wirelessly communicate with these two servo motors using just one Arduino and bluetooth transmitters/receivers? Or will I have to use three Arduinos, one for the center with the button and one for each servo. If so, will I be able to substitute the two servo Arduinos with an ATtiny chip?

title: How to get Arduino to talk to two seperate motors wirelessly?

Answers: 2

body:
> Is it possible to wirelessly communicate with these two servo motors using just one Arduino and bluetooth transmitters/receivers?

Yes. The process goes like this:

1. Can you get your Arduino to talk?
2. Can you get your Arduino to talk to one servo via wires?
3. Can you get your Arduino to talk to one servo wirelessly?
R. Can you get your Arduino to talk to two servos wirelessly?

> Or will I have to use three Arduinos, one for the center with the button and one for each servo.

That's certainly one aporoach.

> If so, will I be able to substitute the two servo Arduinos with an ATtiny chip

It certainly can be done. Whether you can do it is unknown to anyone but you.

body:
You'll probably need 3 "controllers", of which the one in the middle of the room might need to be a full-featured Arduino. Depending on the the needed libraries of your bluetooth receivers at the remote servos, it seems likely that you could use ATTinys in place of more feature-filled Arduino, but you would still have to think of the ATTinys as Arduinos or at least the glue controller to translate commands from Bluetooth to servo signals (PWM).

You could provide us with more details, such what particular bluetooth modules or transceivers you plan to use; some might provide an asynchronous serial interface, others might present an I2C or SPI interface, and given the small flash and RAM size in the ATTiny line, you would need to evaluate the code and associated libraries needed to operate it on such a processor.

The answer to your question is, "Maybe", given the small amount of detail you have provided.


body:
I have a master and a slave (both are arduino UNO) connected through SPI connected. I want to transmit a character to the slave and receive true or false to the master. The transmission is working perfectly. If I send `'2'`, slave is receiving `'2'`. When I try to transmit an integer from slave to master, the master is always receiving some arbitrary number like 128 or 255.

Master Code:

    void setup() {
      Serial.begin(9600);
      Serial.println("Master");
      digitalWrite(SS,HIGH);
      SPI.begin();
      SPI.setClockDivider(SPI_CLOCK_DIV8);
    }
    void loop() {
      digitalWrite(SS,LOW);  //  Slave select to low
      received1 = SPI.transfer(test);  // test is a variable which is '2'. The data received by master is stored in received1 variable which is char.
      Serial.println(received1);
      digitalWrite(SS,HIGH);
    }

Slave code:

    void setup() {
      Serial.begin(9600);
      Serial.println("Slave");
      pinMode(MISO,OUTPUT);
      SPCR |= _BV(SPE);
      process = false;
      SPI.attachInterrupt();
    }
    ISR(SPI_STC_vect){
      received = SPDR;  // the data received by slave is slored in **received** variable(the variable is char type)
      Serial.println(received);
      process = true;
    }
    void loop() {
      if(process){
        SPDR = jj;  // Updating SPDR to send data from slave. jj is char type
        process = false;
      }
    }

title: SPI MOSI receive error

Answers: 1

body:
I have found a solution for this problem in a blog.

Link: http://www.gammon.com.au/forum/?id=10892

I modified my master code and got my desired result.

Master code:

    byte transferAndWait (const byte what)
    {
      byte a = SPI.transfer (what);
      delayMicroseconds (2000);
      return a;
    } // end of transferAndWait

    void loop() {
      digitalWrite(SS,LOW);
      transferAndWait (10);
      received1 = transferAndWait (11);
      digitalWrite(SS,HIGH);
      Serial.println(received1);
    }

The response will be "collected" next time through the loop. That's why we need to keep a dummy `transferAndWait()` function first and then the result of that transfer will be stored in `received1` variable.


body:
It keeps on giving me the error:

    Error compiling for board Arduino/Genuino Mega or Mega 2560.

Other sketches work fine, but this one will not compile, even though I have all the libraries.

Here is the link for the code:
https://drive.google.com/open?id=0B3R5NMiGZ3RPSk9WS0Y1amtEYms

The full error:

    Arduino: 1.8.3 (Windows 10), Board: "Arduino/Genuino Mega or Mega 2560, ATmega2560 (Mega 2560)"

    Tone.cpp.o (symbol from plugin): In function `timer0_pin_port':

    (.text+0x0): multiple definition of `__vector_13'

    libraries\IRLibRecv\IRLibRecv.cpp.o (symbol from plugin):(.text+0x0): first defined here

    d:/arduino/hardware/tools/avr/bin/../lib/gcc/avr/4.9.2/../../../../avr/bin/ld.exe: Disabling relaxation: it will not work with multiple definitions

    collect2.exe: error: ld returned 1 exit status

    exit status 1 Error compiling for board Arduino/Genuino Mega or Mega
    2560.

    This report would have more information with "Show verbose output during compilation" option enabled in File -> Preferences.

title: My Arduino code will not compile, when I can't see anything wrong with it

Answers: 4

body:
I can't see you code, but my guess is that you are passing an unsigned value into `round()`.

`millis()` returns an unsigned long, this means it can never be negative, so if you test `millis() >= 0` it will always be true.  That is your issue.

Write you own round function that doesn't check its greater than 0.

body:
There are a number of issues with your code besides the actual error:

* You are dividing an unsigned long by an integer which results in an unsigned long, then rounding it. Makes no sense.
* You are assigning (I assume - without seeing your code I can't be sure) long constants (eg `0xFFE01F`) to an integer - which overflows and whinges.

However your main problem is that you have two interrupt service routines (ISRs) for the same interrupt (vector 7). What that interrupt is I can't say, since it is different on different chips, and you don't seem able to make your mind up if you're using an Uno or a Mega (you tagged your question both for some reason). So you will have to change code and/or libraries to use different interrupts or combine the two together to use just one ISR.

body:
just some warnings about generally unsafe/unsound code pieces.

the major issue (potentially unresolvable) is the vector-7 error. you should look into the datasheet to see what interrupt vector it is referring to first. There are more than one of such ISRs declared in your code.

body: I searched but couldn't find an answer, then I suddenly released my Arduino external power caused this problem. When I shut down the external power I could install it in my device. I hope it works for your problem.


body:
Is it possible to control an Arduino using mBlock and Bluetooth?

Assuming yes, I tried various things, but was not able to come to a conclusion.

I am trying to get this combination working using a HC-05 Bluetooth module. I am not sure if my Bluetooh setup is the problem or is mBlock is not able to recognize the COM port provided by Bluetooth.

I can see the COM device (in fact two?) when I pair HC-05 with PC. I have the following questions based on whatever I have tried so far:

- When I connect HC-05, should I connect TX to TX OR reverse them?
- There are varying articles describing both ways of connection.
- How much baud rate do I need to set on the Bluetooth device?
- Do I need to use the voltage divider for RX? Again there are varying tutorials.
- Is mBlock default Arduino firmware sufficient for such setup?

title: How to control Arduino using mBlock and Bluetooth?

Answers: 2

body:
> - When I connect HC-05, should I connect Tx to Tx OR reverse them?
>     - There are varying articles describing both ways of connection.

Yes, swap them. TX on the HC-05 to RX on the Arduino. However you could struggle to use pins 0/1 since they are the USB connection. SoftwareSerial (which is nasty) is what most people use instead.

> -  How much baud rate do I need to set on the bluetooth device?

Whatever rate you want to communicate at. It's up to you. However all baud rates must match throughout the system - the baud rate on the Arduino, the baud rate of the HC-05, the baud rate of the SPP port on your PC, etc.

> - Do I need to use the voltage divider for Rx? Again there are varying tutorials.

Which RX? Arduino TX to HC-05 RX yes. HX-05 TX to Arduino RX no.

> - Is mblock default arduino firmware sufficient for such a setup?

What is *mblock*?

body:
I got it working. Following are steps.

- Set the Bluetooth baud rate to 115200. The mBlock firmware uses
  this baud rate for serial communication.
- Connect Bluetooth to Rx and Tx of Arduino.
- Upload default Arduino firmware (orion firmware) to
  Arduino using mBlock.
- Use mBlock to interact with Arduino using Bluetooth.
  - Please note that Bluetooth cannot be used to upload
    the sketches to Arduino for offline mode.

Connecting Bluetooth COM device to PC in AT mode to set baud rate.
==================================================================
- Upload empty (default) sketch to Arduino using USB cable.
- Connect 5V of BT shield to 3.3V of Arduino.
- Connect EN or BT to 5V.
- Connect Tx to Tx and Rx to Rx.
- Use USB cable to power on Arduino.
- Before turning the power ON, keep pressing the EN
  button on BT shield. The LED should blink with almost
  a second delay. That is the indication that it is AT mode.
- Start Arduino IDE, and connect to the COM port of Arduino
  and NOT that of the BT.
- Start serial monitor.
- Set the baud to 38400 and terminate character settings to
  "Both NL $ CR".
- In the command input field of Serial Monitor type `at` twice. First time response will be error, second time it should be ok.
- Now use the at commands to set baud rate using "at +uart=115200,0,0" e.g.
- Use "at +uart?" to see what is the baud rate set on the device.

Connect Bluetooth device to Rx and Tx of Arduino.
==================================================
   Arduino  <-> HC-05
   =======      =======
   5V            Vcc
   GND           GND
   Rx            Tx
   Tx            Rx (Via Voltage divider)

Some of the articles talk about connecting 3.3V of Arduino to the
Vcc of HC-05 and not using the voltage divider at all. However this
combination fails as once increases the baud rate.

Check out more details about voltage divider here. https://electronics.stackexchange.com/questions/280500/why-do-you-have-to-use-a-voltage-divider-with-hc-05-bluetooth-module-arduino

What is the story of two COM devices for Bluetooth?
===================================================
- https://electronics.stackexchange.com/questions/13741/bluetooth-module


body:
I'm working on a project for interfacing the Arduino with the Raspberry Pi. I need to be able to exchange serial data between the two using the USB port.

My question is, can I do that while having the Arduino powered, by using a 9 V battery connected to the DC pin and at the same time have serial data connection using the USB port?

title: Arduino USB and 9V

Answers: 1

body:
Yes, you can. Arduino can be connected to multiple power sources at the same time.

From this excelent page about [Arduino power][1], I cite:

>Arduino is provided with a comparison circuit that controls a type P MOSFET; if a tension is found on Vin (powering from the JACK or from the Vin socket), the MOSFET is interdicted and the possible presence of voltage coming from the USB port is ignored; in the opposite case, the MOSFET will connect the USB port’s 5 V to the 5 V socket, hence below the regulator, thus powering Arduino.

>Therefore it is clear that if you apply the voltage to the USB port and an external source to the JACK socket at the same time, it will be this last one to power the circuit, while the USB connection will keep working for the data exchange with the computer and no longer as a power source. We remind that in both cases the 5 V socket cannot be used as input, but only as output.

  [1]: http://www.open-electronics.org/the-power-of-arduino-this-unknown/


body:
I don't have much knowledge in Arduino and I'm about to start a new project which I believe can be done with it.

There will be 50 boxes with a led in top of each one. The user will type a number in a keyboard (1 to 5 for example), and then based on a table, the leds according to that number should light up.

It will have some overlaps, for example, Number 1 would light led 1, 2 and 3, while Number 2 would light leds 1, 2, 3 and 4.

Could I build such a project with arduino? Or are there too many inputs/outputs (keyboard, 50 leds)? I was thinking to buy an Arduino Uno to start learning, but first I'd like to know if it's feasible.

Thanks already

title: Feasibility of project with 50 leds working independently

Answers: 1

body:
depending on how you want to control your LED's there are several options.
firstly to be clear you could not feasibly connect that many LEDs to an arduino that could all be turned on at once (if that was needed) without damaging the arduino.

if all you need is on/off level of control then you could look at [shift registers][1] or if you have pre built arrays of LEDS in a grid type layout you could look at the [MAX7219/MAX7221][2]

if you also wanted to be able to control the brightness individually then you could look at the [TLC5940][3]

if we look at the pros and cons of each approach:
# 74HC595
pros:

 - cheap to buy
 - simple to use

cons:

 - each LED needs its own resistor
 - cannot vary brightness
 - if not using the hardware SPI pins can be slow for large numbers of outputs

# MAX7219/MAX7221
pros:

 - lower current draw than 74HC595
 - only needs one resistor per IC which can drive 64 LEDs

cons:

 - actually flashes LED's really fast to look like they are always on
 - costs more than 74HC595

# TLC5940
pros:

 - can vary brightness with a high number of steps (4096 steps from fully off to fully on)

cons:

 - uses more output pins than either of the above methods
 - requires resistor per LED
 - costs more for the IC than 74HC595

so to sum up, each method has its merits. if you are driving individual LEDs the the 74HC595 is probably the best/simplest route, if you are driving an array then the MAX7219/MAX7221 is best, and if you need variable brightness then the TLC5940 is probably best.

  [1]: https://www.arduino.cc/en/Tutorial/ShiftOut
  [2]: https://playground.arduino.cc/Main/MAX72XXHardware
  [3]: https://playground.arduino.cc/Learning/TLC5940


body:
So what exactly I am trying to do is control a motor and be able to turn it both ways without any extra parts.

So if the hmp was on (the plus pole) and the hmm (the minus pole) acted like ground the motor should start turning right.

But if the hmp acted in this case as ground and the hmm like the plus pole it should start turning the other way.

I know that it's probably not going to work. I'm just experimenting.

    int Hmp=12; // the plus pole
    int Hmm=11; // the minus pole

    while (HR=0 || Sr > Sl+300) {
      pinMode(Hmp, OUTPUT);
      digitalWrite(Hmp, HIGH);
      pinMode(Hmm, INPUT);
    }

    while (HR=1 || Sl > Sr+300) {
      pinMode(Hmp, INPUT);
      pinMode(Hmm, OUTPUT);
      digitalWrite(Hmm, HIGH);
    }

title: Is it possible to make normal pins act like ground pins?

Answers: 5

body:
No, it's not going to work - even worse, you risk frying your Arduino -, for the following reasons:

 1. The Arduino data pins can't source (neither sink) enough current for that to work.

 2. The inductive kickback of the motor could fry Arduino pins.

The right way to do what you want to do is **using an H-bridge controlled by your Arduino data pins**. There are lots of Motor Driver PCB modules for Arduino (most of them based on the inefficient L298 driver IC, which you should ignore and look instead on those based on the TB6612FNG driver IC or similar, because it would be a far better solution) that implement this function.

body:
You have to put both pin in OUTPUT mode. You digitalWrite() the "positive" pin HIGH and the "negative" pin LOW.

But, it's not a good idea in this case:

1. Motor's power requirement exceeds digital output pin current of 40 mA.
2. Back EMF. Every time you stop the motor, there is a brief current pulse back to your pins. Bad.

The proper ways to control a motor is this:

[![Arduino controlled motor][1]][1]

This will control only one direction. For changing directions, you need a H-Bridge. An H bridge is an electronic circuit that can drive the motor in both directions.

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

body:
> is it possible to make normal pins act like ground pins?

the answer is yes: i'm looking right now at a blinking led that straddles between two GPIOs with one of them permanently (via code) grounded so i can blink it via the other GPIO pin.

Obviously the usual limitations that apply to a GPIO pin apply here.

body:
I don't think that's going to work.

You'll be better off using a cheap module like the Pololu [Pololu DRV8838][1] which implements a MOSFET H-bridge.

(Note: I'm not related in any way with Pololu.)

  [1]: https://www.pololu.com/product/2990

body:
I just tried what you suggest, and it works fine, with only one (big)
caveat: you can only power this way very low power motors. I did this to
drive the linear motor that moves an HDD head assembly. This motor works
perfectly fine with less than 18 mA.

Note that I switch the Arduino pins between the `HIGH` and `LOW` states,
not going through `INPUT`. Setting the pin to `INPUT` would send the
motor's inductive kickback through the pin's protection diodes. On the
other hand, the inductance of this motor is presumably tiny...

For anything that can draw more than 40 mA, I would use an
H-bridge. For something between 20 and 40 mA, I may take the
risk of driving it directly _if_ it's for an experiment where I am not
too much concerned about the risk of loosing my Arduino.


body:
I am trying to read data from [RS232 Shield][1] with an Arduino Mega.

This is the [schematic pin][2], TX is 3 and RX is 2.

Wiring:
PC > USB-RS232 cable > Arduino RS232 Shield.
Software to send/receive data:
[Hercules Setup Utility][3]

From Arduino, I can transmit data to RS232, the TX led blink and I got the value at PC.
From PC, I send the data, the RX led blink but nothing is showed in Arduino Monitor.

    #include <SoftwareSerial.h>

    SoftwareSerial mySerial(2, 3); // RX, TX

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

      Serial.println("Goodnight moon!");

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

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

I also tried to move RX and TX to Pin 15 and 14 but worked as the same as before.

  [1]: https://www.embarcados.com.br/arduino-rs-232-rs-485-hardware/
  [2]: https://www.embarcados.com.br/wp-content/uploads/2015/02/pinos-conectores-headers.png
  [3]: http://www.hw-group.com/products/hercules/index_en.html

title: Arduino PC to RS232 not reading data

Answers: 1

body:
Found the problem, cant use PIN 2 as RX.

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


body:
I have 3 force resistors in a row, on top of which I have placed a board. I read values from the resistors through analogue ports. My goal is to be able to detect whether someone is pressing on the top, middle, or bottom of the board.

So far I can easily detect the left and right, like this: I first calibrate the 3 sensors for 2 seconds. Then I detect if pressure is applied on any of the calibrated sensors. If yes, I sum for all of them the values that they return on each round of the loop, until force has stopped being applied. I finally compare the 3 values against each other and I find which received higher pressure in total. This works perfectly fine for the left and right. However, when the board is pressed in the middle, pressure is applied on all 3, since the board is flat. Sorting the values does not help, because very often the left and right sensors have recorded a higher value than the middle.

I noticed that when the board is pressed on the left, the right sensor records very few values, and the same for the other way around. So, I get a high success rate in detecting middle presses like this:

    int threshold = 80;
    if (left_sum > threshold && middle_sum > 80 && right_sum >80)
        return middle_pressed;

However, when someone presses hard enough on the left or right, the if statement is satisfied.

Is there a more accurate way to detect where force is being applied?

*(Following is a quick schematic I made - I am not at all an expert so please excuse me for my mistakes, I just hope it illustrates more or less what it is supposed to)*

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/n1jev.png)

<!-- End schematic -->

Please ignore the double arrows right on top of the resistors.

title: Detect where pressure is being applied by using force resistors

Answers: 2

body:
Let's assume that you have only two FSR sensors. With those you can make three virtual buttons (above the left sensor, above the right sensor and in the middle).

To measure someone's weight, it is allowed to have a scale under each foot and add both weights. We can use that to calculate the total force pressing to the board, by just adding the two forces.

The FSR sensors have a curve to calculate the force in newtons. It is very inaccurate, but works more or less. That can be added later. For now let's assume that it is linear to the ADC value of the Arduino.

Are the FSR sensors connected to an analog input and GND ? Do you have a resistor between the analog input and 5V ? I assume you do. You need the resistors so that a nice pressing force to the board results somewhere in the middle of the ADC range.

Pseudo code:

    setup()

      Measure both ADC values (or a number of values and use the average)
      Store them as offsets in a global variable.

    loop()

      Measure both ADC values, substract the offset.

      Translate the ADC values into force.
      The more force the higher the number should get.
      Any range is okay for now.
      They can be translated into Newton later.

      The total force is by adding the two forces.

      The position in percentage is the force of the right sensor
      divided by total force times 100.
      Then the position will be 0 for left sensor, 50 for middle
      and 100 for right sensor.

      If the total force is above threshold, then check the position.

      for example position -50 to 20 for left virtual button.
      for example position 30 to 70 for middle virtual button.
      for example positition 80 to 150 for right virtual button.

You can start by printing the forces to the serial monitor. Press the board and check if the numbers increase when pressing more.

Don't get confused when you print the position. It will be very noisy when no force to the board is applied. It should be valid when the total force is above the threshold.

For the position I allow a large error of 50 percent left of the left sensor and right of the right sensor. It depends on the mechanical construction and the rest of the code if that makes sense.

Print the results to the serial monitor.
If that is working well, then you have to detect a single press.

Let's assume that as soon as the threshold is reached, a press to a virtual button is accepted. Let's not wait until the peak of the force is reached.
The [State Change Detection][1] example can be used to create a single event for pressing the virtual button.

Any jitter or noise (for example a single press to the board results into two events for the virtual button) can be solved by averaging or filtering in software. I think that it will be needed.

I'm not sure if all of this is okay. I hope that someone else will look into it as well.

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

body:
> Is there a more accurate way to detect where force is being applied?

normalize your measurements vs. the static values of those strain gauge readings obtained during calibration.


body:
Is the `.ino` file an alternative from a `main.cpp` file?

If yes, then could someone mind explaining the structure of the `.ino` file in `main.cpp` and its relationship?

title: What is the relationship of an Arduino .ino file to main.cpp?

Answers: 1

body:
The Arduino uses the gcc compiler. That compiler wants a normal `main` function of course. Arduino has put a layer on top of that with `setup` and `loop`.

The hidden `main` function for basic Arduino boards is in [main.cpp][1] (click on it to see it).
You see that `init` is called, and `setup` and `loop` and a few other things.

To learn how to use `setup` and `loop`, you can try a few examples. They are in the menu of the Arduino IDE and they are also online.

The .ino files are all combined together and presented to the compiler as a single .cpp file to compile. The Arduino libraries are compiled from source as well, and everything is linked into a binary.

When you know how to use `setup` and `loop`, try the [Blink Without Delay example][2]. It can be used to run different software timers and do all kind of tasks and keep everything running smooth.

  [1]: https://github.com/arduino/ArduinoCore-avr/blob/master/cores/arduino/main.cpp
  [2]: https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay


body:
I'm working with an Arduino UNO. I'm trying to use this Sensor to obtain the pressure in kPa. I'm using a `tl084cn` to amplifier the signal. But I don't know what values I'm getting and what to do with them.

Not applying  pressure prints `0`, if I apply air pressure it's goes up to `800-900` as max. What mean this values?

What is the maximum pressure that I should get? 10 kPa? I don't understand that very well. Because the data sheet says:
> Maximum Pressure (P1 > P2) PMAX 75 kPa

I can understand what is the differences between Max. Pressure and Max. Differential Pressure.

title: Pressure Sensor-MPX10DP with amplifier and Arduino UNO - output to kPa

Answers: 0


body:
What is the best **wired** way to communicate between multiple **NodeMCU ESP8266** boards for home automation.

Every room should get at least a light, temp, PIR and xx relay modules to switch things on and off.

To connect all these sensors the GPIOs from one NodeMCU are sometimes not enough.

To reach this goal I planned to install in every room one NodeMCU as gateway and multiple NodeMCU as nodes for my sensors. The gateway will receive and forward information from/to my **openHAB** center via **MQTT** messaging.

I thought to use an **RS-485** 2-Wire connection between my sensor nodes and the room gateway. The gateway from my room will be connected via wifi or wired cable to my network.

I2C seems more to be for communication directly on PCBs or only short wiring.

Do you have any suggestions for me, is my plan possible? Any better ideas?

title: Communicate between NodeMCU ESP8266 gateway and multiple sensor nodes

Answers: 1

body:
If you really wanted wired communication then yes, RS-485 is the way to go.

In any installation where you will be running cables in the vicinity of mains wiring you will have noise. I2C is very bad with noise and not a good choice for any off-board wiring. RS-485, however, owing to the balanced line nature of the signalling, is designed to reject common mode noise such as is induced by mains wiring.

I would ask, though, *why use ESP8266 as remote wired nodes?* It seems a real waste to use a WiFi module for wired communication - a smaller, simpler, lower powered board (Arduino Micro / Mini maybe [3.3V, 8MHz version for simplicity of interfacing]) would be far more suitable for such a role.


body:
I am trying to connect a stepper motor ( this model exactly https://create.arduino.cc/projecthub/trduunze/grove-starter-kit-for-arduino-stepper-motor-driver-66471d ) in an arduino 101 but it does not work for some reason. I have tried connecting everything ast they tell in the website with no results:

[![Pinout from motor controller to arduino 101 grove shield][1]][1]

And then I tried connecting directly to the board without using the shield, and still getting nothing.

The code I am using is this :

    #include <Stepper.h>
    int t =0;
    const int stepsPerRevolution = 200;  // change this to fit the number of steps per revolution for your motor
    // initialize the stepper library on pins 8 through 11:
    Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);

    int stepCount = 0;  // number of steps the motor has taken

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

    void loop() {
      // set the motor speed:
      int motorSpeed = 15;
      if (motorSpeed > 0) {
        myStepper.setSpeed(motorSpeed);
        // step 1/100 of a revolution:
        myStepper.step(stepsPerRevolution / 25);
      Serial.println(motorSpeed);//print how fast the motor is going in the serial monitor
      }
    }

Connecting the stepper motor and the driver, and launching the sketch in an arduino UNO board **works perfectly**, so I am really worried about that maybe the Stepper.h library might be different for the Arduino 101 but I couldn't find anything about that. I just have no idea why the project is not working in the 101 but working perfectly in the UNO. Any help or tips would be highly appreciated.

Cheers!

***EDIT***

After a lot of messing around, I have only been able to light up one led in the controller connecting one of the motor cables to GPIO5. None of the other GPIOS seem to work with the step motor controller.

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

title: Stepper motor not working in Arduino 101

Answers: 1

body:
After reading the Stepper library and searching for several, I saw that in an example using an EDISON ( [I want to thanks to Guimficus for posting his code here: ][1]https://communities.intel.com/thread/99133) they changed the pinMode of the GPIOS they were using in the setup function :

    pinMode(8, OUTPUT);
    pinMode(9, OUTPUT);
    pinMode(10, OUTPUT);
    pinMode(11, OUTPUT);

And after adding that seems to work like it is supposed to work.

Cheers!

  [1]: https://communities.intel.com/thread/99133 "merci mon ami"