body:
The client always reply with *"ThisCodeTurnsTheUnoOnn"* or *ThisCodeTurnsTheUnoOff"* based on some conditions.

This piece of code is inside arduino uno's *void loop()*.

**Expected behavior:**

The arduino read the reply and turn the digital pin 13 to HIGH if the onCount is 22 after matching every character one by one with the client's reply which was "ThisCodeTurnsTheUnoOnn" and the other way around:

The arduino read the reply and turn the digital pin 13 to LOW if the offCount is 22 after matching every character one by one with the client's reply which was "ThisCodeTurnsTheUnoOff".

and the digital pin 13 should always remain in the previous state if the new client's reply was the same as previous reply. (e.g. if
client's reply was "ThisCodeTurnsTheUnoOff" and the arduino turn the digital pin 13 to LOW, then in next loop the client's reply was same "ThisCodeTurnsTheUnoOff" and the arduino should keep the digital pin 13 in LOW state).

**Actual behavior:**

CASE :
client's reply was "ThisCodeTurnsTheUnoOff" and the arduino turn the digital pin 13 to LOW, then in next loop the client's reply was same "ThisCodeTurnsTheUnoOff" and the arduino should keep the digital pin 13 in LOW state but the arduino turns the digital pin 13 HIGH when entering the next loop(void loop()) then turns back to LOW after entered the loop(void loop()).

      // available() will return the number of characters
      // currently in the receive buffer.

      const int solenoidValve = 13;

      char onCode[23] = "ThisCodeTurnsTheUnoOnn";
      char offCode[23] = "ThisCodeTurnsTheUnoOff";

      int onCount = 0;
      int offCount = 0;

      while (client.available())
      {
        char c = client.read();

        if(c == onCode[onCount])
        {
          onCount++;

          if(onCount == 22)
          {
            digitalWrite(solenoidValve, HIGH);
            break;
          }
        }
        else
        {
          onCount = 0;
        }

        if(c == offCode[offCount])
        {
              offCount++;

              if(offCount == 22)
              {
                digitalWrite(solenoidValve, LOW);
                break;
              }
        }
        else
        {
          offCount = 0;
        }
        Serial.write(c);
      }

**The complete code, in case the logical errors is not within the above piece of code:**

    #include <SoftwareSerial.h>
    #include <SparkFunESP8266WiFi.h>

    //////////////////////////////
    // WiFi Network Definitions //
    //////////////////////////////
    // Replace these two character strings with the name and
    // password of your WiFi network.
    const char mySSID[] = "SSID";
    const char myPSK[] = "PASSWORD";
    const int solenoidValve = 13;
    char onCode[23] = "ThisCodeTurnsTheUnoOnn";
    char offCode[23] = "ThisCodeTurnsTheUnoOff";

    //water flow calculation variables
    volatile int flow_frequency; // Measures flow sensor pulses
    unsigned int l_hour; // Calculated litres/hour
    unsigned char flowsensor = 2; // Sensor Input
    unsigned long currentTime;
    unsigned long cloopTime;

    //////////////////
    // HTTP Strings //
    //////////////////
    const char destServer[] = "192.168.0.101"; //private ip //[Kugan] 07/8/16 try4 : changed Global IP to Local IP for testing Code ID:1132
    const uint16_t port = 8080; // Code ID: 1126 [Kugan] added variable port
    const String httpRequest = "GET /aquosdb/getStatus.php HTTP/1.1\n"
                               "Host: 192.168.0.101\n" //private ip [note for myself: dont forget to change IP]
                               "Connection: close\n\n"; //[Kugan] 07/8/16 try4 : changed Global IP to Local IP for testing Code ID:1132

    // All functions called from setup() are defined below the
    // loop() function. They modularized to make it easier to
    // copy/paste into sketches of your own.
    void setup()
    {
       pinMode(flowsensor, INPUT);
       digitalWrite(flowsensor, HIGH); // Optional Internal Pull-Up
       Serial.begin(9600);
       attachInterrupt(0, flow, RISING); // Setup Interrupt
       sei(); // Enable interrupts
       currentTime = millis();
       cloopTime = currentTime;

      // Serial Monitor is used to control the demo and view
      // debug information.
      Serial.begin(9600);
      //serialTrigger(F("Press any key to begin.")); //[Kugan] 28/7/16 try3 : disabled serial trigger for self automation Code ID:1130

      // initializeESP8266() verifies communication with the WiFi
      // shield, and sets it up.
      initializeESP8266();

      // connectESP8266() connects to the defined WiFi network.
      connectESP8266();

      // displayConnectInfo prints the Shield's local IP
      // and the network it's connected to.
      displayConnectInfo();

      //serialTrigger(F("Press any key to connect client."));  //[Kugan] 28/7/16 try3 : disabled serial trigger for self automation Code ID:1130
      //valveControl();
    }

    void loop()
    {
      setFlow();
      //delay(500); // [Kugan] 29/7/16 try3 : added delay to debug connection bug Code ID:1131
      valveControl();
    }

    void initializeESP8266()
    {
      // esp8266.begin() verifies that the ESP8266 is operational
      // and sets it up for the rest of the sketch.
      // It returns either true or false -- indicating whether
      // communication was successul or not.
      // true
      int test = esp8266.begin();
      if (test != true)
      {
        Serial.println(F("Error talking to ESP8266."));
        errorLoop(test);
      }
      Serial.println(F("ESP8266 Shield Present"));
    }

    void connectESP8266()
    {
      esp8266.disconnect(); // Code ID:1125 [Kugan] To disconnect from previously connected wifi AP
      delay(100);           // esp8266 has auto-reconnect function to connect previously connected AP

      // The ESP8266 can be set to one of three modes:
      //  1 - ESP8266_MODE_STA - Station only
      //  2 - ESP8266_MODE_AP - Access point only
      //  3 - ESP8266_MODE_STAAP - Station/AP combo
      // Use esp8266.getMode() to check which mode it's in:
      int retVal = esp8266.getMode();
      if (retVal != ESP8266_MODE_STA)
      { // If it's not in station mode.
        // Use esp8266.setMode([mode]) to set it to a specified
        // mode.
        retVal = esp8266.setMode(ESP8266_MODE_STA);
        if (retVal < 0)
        {
          Serial.println(F("Error setting mode."));
          errorLoop(retVal);
        }
      }
      Serial.println(F("Mode set to station"));

      // esp8266.status() indicates the ESP8266's WiFi connect
      // status.
      // A return value of 1 indicates the device is already
      // connected. 0 indicates disconnected. (Negative values
      // equate to communication errors.)
      retVal = esp8266.status();
      if (retVal <= 0)
      {
        Serial.print(F("Connecting to "));
        Serial.println(mySSID);
        // esp8266.connect([ssid], [psk]) connects the ESP8266
        // to a network.
        // On success the connect function returns a value >0
        // On fail, the function will either return:
        //  -1: TIMEOUT - The library has a set 30s timeout
        //  -3: FAIL - Couldn't connect to network.
        retVal = esp8266.connect(mySSID, myPSK);
        delay(60);
        if (retVal < 0)
        {
          Serial.println(F("Error connecting"));
          errorLoop(retVal);
        }
      }
    }

    void displayConnectInfo()
    {
      char connectedSSID[20];
      memset(connectedSSID, 0, 20);
      // esp8266.getAP() can be used to check which AP the
      // ESP8266 is connected to. It returns an error code.
      // The connected AP is returned by reference as a parameter.
      int retVal = esp8266.getAP(connectedSSID);
      if (retVal > 0)
      {
        Serial.print(F("Connected to: "));
        Serial.println(connectedSSID);
      }

      // esp8266.localIP returns an IPAddress variable with the
      // ESP8266's current local IP address.
      IPAddress myIP = esp8266.localIP();
      Serial.print(F("My IP: ")); Serial.println(myIP);
    }

    void flow() // Interrupt function
    {
       flow_frequency++;
    }

    void setFlow()
    {
       // To use the ESP8266 as a TCP client, use the
      // ESP8266Client class. First, create an object:
      ESP8266Client client1;
      client1.stop(); //[Kugan] 28/7/16 try2 : added Code ID:1127

      // ESP8266Client connect([server], [port]) is used to
      // connect to a server (const char * or IPAddress) on
      // a specified port.
      // Returns: 1 on success, 2 on already connected,
      // negative on fail (-1=TIMEOUT, -3=FAIL).
      int retVal = client1.connect(destServer, port); //Code ID:1126 [Kugan] created variable port
      if (retVal <= 0)
      {
        Serial.println(retVal);  //[Kugan] 28/7/16 try2 : added Code ID:1130 for debugging
        Serial.println("flow");
        Serial.println(F("Failed to connect to server."));

        initializeESP8266(); // [Kugan] 28/7/16 try2 : added Code ID:1129 reinitialize, connect, and display connection info
        connectESP8266();
        displayConnectInfo();

        return;
      }

       currentTime = millis();
       // Every second, calculate and print litres/hour
       if(currentTime >= (cloopTime + 1000))
       {
          cloopTime = currentTime; // Updates cloopTime
          // Pulse frequency (Hz) = 7.5Q, Q is flow rate in L/min.
          l_hour = (flow_frequency * 60 / 7.5); // (Pulse frequency x 60 min) / 7.5Q = flowrate in L/hour
          flow_frequency = 0; // Reset Counter
       }

      // print and write can be used to send data to a connected
      // client connection.
      String httpPostRequest = "GET /aquosdb/setFlow.php?data=" + String(l_hour) + " HTTP/1.1\n" //sets the water flow value
                               "Host: 192.168.0.101\n" //private ip
                               "Connection: close\n\n"; //[Kugan] 07/8/16 try4 : changed Global IP to Local IP for testing Code ID:1132
      client1.print(httpPostRequest);

      while (client1.available()) // [Kugan] 28/7/16 Code ID: 1128  to clear the buffer
        Serial.write(client1.read()); // read() gets the FIFO char

      if (client1.connected())
        client1.stop(); // stop() closes a TCP connection.
    }

    void valveControl()
    {
      // To use the ESP8266 as a TCP client, use the
      // ESP8266Client class. First, create an object:
      ESP8266Client client;
      client.stop(); //[Kugan] 28/7/16 try2 : added Code ID:1127 stop any existing connections

      // ESP8266Client connect([server], [port]) is used to
      // connect to a server (const char * or IPAddress) on
      // a specified port.
      // Returns: 1 on success, 2 on already connected,
      // negative on fail (-1=TIMEOUT, -3=FAIL).
      int retVal = client.connect(destServer, port); // Code ID:1126 [Kugan] created variable port
      if (retVal <= 0)
      {
        Serial.println(retVal);  // [Kugan] 28/7/16 try2 : added Code ID:1130 for debugging
        Serial.println("valve");
        Serial.println(F("Failed to connect to server."));

        initializeESP8266(); // [Kugan] 28/7/16 try2 : added Code ID:1129 reinitialize, connect, and display connection info
        connectESP8266();
        displayConnectInfo();

        return;
      }

      // print and write can be used to send data to a connected
      // client connection.
      client.print(httpRequest);

      // available() will return the number of characters
      // currently in the receive buffer.
      int onCount = 0;
      int offCount = 0;

      while (client.available())
      {
        char c = client.read();

        if(c == onCode[onCount])
        {
          onCount++;

          if(onCount == 22)
          {
            digitalWrite(solenoidValve, HIGH);
            break;
          }
        }
        else
        {
          onCount = 0;
        }

        if(c == offCode[offCount])
        {
              offCount++;

              if(offCount == 22)
              {
                digitalWrite(solenoidValve, LOW);
                break;
              }
        }
        else
        {
          offCount = 0;
        }
        Serial.write(c);
      }

      // connected() is a boolean return value - 1 if the
      // connection is active, 0 if it's closed.
      if (client.connected())
        client.stop(); // stop() closes a TCP connection.
    }

    // errorLoop prints an error code, then loops forever.
    void errorLoop(int error)
    {
      Serial.print(F("Error: ")); Serial.println(error);
      Serial.println(F("Looping forever."));
      for (;;)
        ;
    }

    // serialTrigger prints a message, then waits for something
    // to come in from the serial port.
    void serialTrigger(String message)
    {
      Serial.println();
      Serial.println(message);
      Serial.println();
      while (!Serial.available())
        ;
      while (Serial.available())
        Serial.read();
    }

Thanks in advance for your efforts to answer my question.

title: What are the logical errors in this piece of code?

Answers: 1

body:
The biggest obstacle to you getting this working is the somewhat bizarre way you are working out what has been sent to you, by counting characters that match and waiting until they reach 22.

Instead you should read the input character by character and place them into an array. Discard anything past the 22nd character so it doesn't overflow the array. Then you can compare what is in that array to strings stored in flash (using the `F()` macro) and the `strcmp_P()` function.


body:
How I can use multi smoke sensor in one code? I mean how can I use more than one sensor, where both sensors has the same purpose, like use smoke sensor in multi room. Similar to this code where one is used only. How I can more than one, in Arduino Uno R3,,

    <per>
        int redLed = 12;
    int greenLed = 11;
    int buzzer = 10;
    int smokeA0 = A5;
    // Your threshold value
    int sensorThres = 400;

    void setup() {
      pinMode(redLed, OUTPUT);
     pinMode(greenLed, OUTPUT);
    pinMode(buzzer, OUTPUT);
    pinMode(smokeA0, INPUT);
    Serial.begin(9600);
    }

    void loop() {
      int analogSensor = analogRead(smokeA0);

      Serial.print("Pin A0: ");
      Serial.println(analogSensor);
      // Checks if it has reached the threshold value
      if (analogSensor > sensorThres)
      {
        digitalWrite(redLed, HIGH);
        digitalWrite(greenLed, LOW);
        tone(buzzer, 1000, 200);
      }
      else
      {
        digitalWrite(redLed, LOW);
        digitalWrite(greenLed, HIGH);
        noTone(buzzer);
      }
      delay(100);
    }

How I can add more than one sensor to get same purpose. check detect 1 and detect2 and detect 3 if one of this detection LED Red ON, Thanks`

title: How I can use multi sensor in one code in Arduino?

Answers: 2

body:
You haven't mentioned what sensor you are using, so I can't offer any help on how to interface with it. Though you can add 'multi-sensor code' by adding code that will get the state of the sensor at times when you can afford to wait a few ms before checking the state of the other sensors. With the code you provided, you could after the if/else block but before the delay.

Also, it is typically not a good idea to put sensors far away from each other but still connect them to the same controller. You should give each room its own Arduino.

body:
just duplicate the parts of the code that handle the sensor.

    int redLed = 12;
    int greenLed = 11;
    int buzzer = 10;
    int smokeSensor1 = A5;
    int smokeSensor2 = A4;
    int smokeSensor3 = A3;
    // Your threshold value
    int sensorThres = 400;

    void setup() {
      pinMode(redLed, OUTPUT);
      pinMode(greenLed, OUTPUT);
      pinMode(buzzer, OUTPUT);
      pinMode(smokeSensor1, INPUT);
      pinMode(smokeSensor2, INPUT);
      pinMode(smokeSensor3, INPUT);
      Serial.begin(9600);
    }

    void loop() {
      int analogSensor1 = analogRead(smokeSensor1);
      int analogSensor2 = analogRead(smokeSensor2);
      int analogSensor3 = analogRead(smokeSensor3);

      Serial.print("Pin A0: ");
      Serial.println(analogSensor1);
      // Checks if it has reached the threshold value
      if( (analogSensor1 > sensorThres) || (analogSensor2 > sensorThres) || (analogSensor3 > sensorThres) )
      {
        digitalWrite(redLed, HIGH);
        digitalWrite(greenLed, LOW);
        tone(buzzer, 1000, 200);
      }
      else
      {
        digitalWrite(redLed, LOW);
        digitalWrite(greenLed, HIGH);
        noTone(buzzer);
      }
      delay(100);
    }


body:
It's been days that I'm trying to figure it out how to edit this perfectly working code in order to load load a webpage from the sd card.

    #include <SPI.h>
    #include <Ethernet2.h>
    byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };   //physical mac address
    byte ip[] = { 192, 168, 1, 178 };                      // ip in lan (that's what you need to use in your browser. ("192.168.1.178")
    byte gateway[] = { 192, 168, 1, 1 };                   // internet access via router
    byte subnet[] = { 255, 255, 255, 0 };                  //subnet mask
    EthernetServer server(80);                             //server port
    String readString;
    boolean L1chk;
    boolean L2chk;
    boolean L3chk;
    boolean L4chk;
    boolean L5chk;
    boolean L6chk;
    boolean L7chk;
    boolean L8chk;
    int led;

    void setup() {
     // Open serial communications and wait for port to open:
      Serial.begin(9600);

    pinMode(2, OUTPUT);
    pinMode(3, OUTPUT);
    pinMode(4, OUTPUT);
    pinMode(5, OUTPUT);
    pinMode(6, OUTPUT);
    pinMode(7, OUTPUT);
    pinMode(8, OUTPUT);
    pinMode(9, OUTPUT);
      // start the Ethernet connection and the server:
      Ethernet.begin(mac);
      server.begin();
      Serial.print("server is at ");
      Serial.println(Ethernet.localIP());
    }

    void loop() {
      // Create a client connection
      EthernetClient client = server.available();
      if (client) {
        while (client.connected()) {
          if (client.available()) {
            char c = client.read();

            //read char by char HTTP request
            if (readString.length() < 100) {
              //store characters to string
              readString += c;
              //Serial.print(c);
             }

             //if HTTP request has ended
             if (c == '\n') {
               Serial.println(readString); //print to serial monitor for debuging

               client.println("HTTP/1.1 200 OK"); //send new page
               client.println("Content-Type: text/html");
               client.println();
               client.println("");
               client.println("");
               client.println("<meta name='apple-mobile-web-app-capable' content='yes' />");
               client.println("<meta name='apple-mobile-web-app-status-bar-style' content='black-translucent' />");
               client.println("<TITLE>CONTROLLO LEDS</TITLE>");
               client.println("");
               client.println("");
               client.println("
FLASHATI
");
               client.println("
");
               client.println("LED1");
               client.println("LED2");
               client.println("LED3");
               client.println("LED4");
               client.println("LED5");
               client.println("LED6");
               client.println("LED7");
               client.println("LED8");
               client.println("
");
               client.println("
");
               client.println("
Created by Rui Santos. Visit http://randomnerdtutorials.com for more projects!
");
               client.println("
");
               client.println("");
               client.println("");

               delay(1);
               //stopping client
               client.stop();
               //controls the Arduino if you press the buttons
               if (readString.indexOf("?1") >0){
                   ledUno();
       }
               if (readString.indexOf("?2") >0){
                   ledDue();
       }
       if (readString.indexOf("?3") >0){
                   ledTre();
       }
       if (readString.indexOf("?4") >0){
                   ledQuattro();
       }
       if (readString.indexOf("?5") >0){
                   ledCinque();
       }
       if (readString.indexOf("?6") >0){
                   ledSei();
       }
       if (readString.indexOf("?7") >0){
                   ledSette();
       }
       if (readString.indexOf("?8") >0){
                   ledOtto();
       }
               readString="";
            }

      }
        }
    }
    }

So I came out with this after a lot of research:

    /*
     Created by Rui Santos
     Visit: http://randomnerdtutorials.com for more arduino projects

     Arduino with Ethernet Shield
    */

    #include <SPI.h>
    #include <Ethernet2.h>
    #include <SD.h>
    File webFile;
    byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };   //physical mac address
    byte ip[] = { 192, 168, 1, 178 };                      // ip in lan (that's what you need to use in your browser. ("192.168.1.178")
    byte gateway[] = { 192, 168, 1, 1 };                   // internet access via router
    byte subnet[] = { 255, 255, 255, 0 };                  //subnet mask
    EthernetServer server(80);                             //server port
    String readString;
    boolean L1chk;
    boolean L2chk;
    boolean L3chk;
    boolean L4chk;
    boolean L5chk;
    boolean L6chk;
    boolean L7chk;
    boolean L8chk;
    int led;

    void setup() {
     // Open serial communications and wait for port to open:
     Serial.begin(9600);

     pinMode(2, OUTPUT);
     pinMode(3, OUTPUT);
     pinMode(4, OUTPUT);
     pinMode(5, OUTPUT);
     pinMode(6, OUTPUT);
     pinMode(7, OUTPUT);
     pinMode(8, OUTPUT);
     pinMode(9, OUTPUT);
     // start the Ethernet connection and the server:
     Ethernet.begin(mac);
     server.begin();
     Serial.print("server is at ");
     Serial.println(Ethernet.localIP());
     if (!SD.begin(4)) {
      Serial.println("ERROR - SD card initialization failed!");
      return;    // init failed
     }
     Serial.println("SUCCESS - SD card initialized.");
     // check for index.htm file
     if (!SD.exists("index.htm")) {
      Serial.println("ERROR - Can't find index.htm file!");
      return;  // can't find index file
     }
     Serial.println("SUCCESS - Found index.htm file.");
    }

    void loop() {
     // Create a client connection
     EthernetClient client = server.available();
     if (client) {
      boolean currentLineIsBlank = true;
      while (client.connected()) {
       if (client.available()) {
        char c = client.read(); // read 1 byte (character) from client
        // last line of client request is blank and ends with \n
        // respond to client only after last line received
        if (c == '\n' && currentLineIsBlank) {
         // send a standard http response header
         client.println("HTTP/1.1 200 OK");
         client.println("Content-Type: text/html");
         client.println("Connection: close");
         client.println();
         // send web page
         webFile = SD.open("index.htm");        // open web page file
         if (webFile) {
          while(webFile.available()) {
           client.write(webFile.read()); // send web page to client
          }

          webFile.close();
         }
         break;

        }
        // every line of text received from the client ends with \r\n
        if (c == '\n') {
         // last character on line of received text
         // starting new line with next character read
         currentLineIsBlank = true;
         if (readString.indexOf("?1") >0){
          ledUno();
         }
         if (readString.indexOf("?2") >0){
          ledDue();
         }
         if (readString.indexOf("?3") >0){
          ledTre();
         }
         if (readString.indexOf("?4") >0){
          ledQuattro();
         }
         if (readString.indexOf("?5") >0){
          ledCinque();
         }
         if (readString.indexOf("?6") >0){
          ledSei();
         }
         if (readString.indexOf("?7") >0){
          ledSette();
         }
         if (readString.indexOf("?8") >0){
          ledOtto();
         }
         readString="";
        }
        else if (c != '\r') {
         // a text character was received from client
         currentLineIsBlank = false;
        }
        //controls the Arduino if you press the buttons

       }

      }
      delay(1);      // give the web browser time to receive the data
      client.stop();
      if (readString.indexOf("?1") >0){
       ledUno();
      }
      if (readString.indexOf("?2") >0){
       ledDue();
      }
      if (readString.indexOf("?3") >0){
       ledTre();
      }
      if (readString.indexOf("?4") >0){
       ledQuattro();
      }
      if (readString.indexOf("?5") >0){
       ledCinque();
      }
      if (readString.indexOf("?6") >0){
       ledSei();
      }
      if (readString.indexOf("?7") >0){
       ledSette();
      }
      if (readString.indexOf("?8") >0){
       ledOtto();
      }
      readString="";
     }
    }

    void ledUno(){
     led = 2;
     if (L1chk == 0){                                             //Il Ledled 1 è Spento
      digitalWrite(led, HIGH);
      L1chk = 1;
      return;                   //Led 1 acceso
     }

     if (L1chk == 1){                                             //Il Ledled 1 è Spento
      digitalWrite(led, LOW);
      L1chk = 0;
      return;                   //Led 1 acceso
     }
    }

    void ledDue(){
     led = 3;
     if (L2chk == 0){                                             //Il Ledled 1 è Spento
      digitalWrite(led, HIGH);
      L2chk = 1;
      return;                   //Led 1 acceso
     }

     if (L2chk == 1){                                             //Il Ledled 1 è Spento
      digitalWrite(led, LOW);
      L2chk = 0;
      return;                   //Led 1 acceso
     }
    }

    void ledTre(){
     led = 4;
     if (L3chk == 0){                                             //Il Ledled 1 è Spento
      digitalWrite(led, HIGH);
      L3chk = 1;
      return;                   //Led 1 acceso
     }

     if (L3chk == 1){                                             //Il Ledled 1 è Spento
      digitalWrite(led, LOW);
      L3chk = 0;
      return;                   //Led 1 acceso
     }
    }

    void ledQuattro(){
     led = 5;
     if (L4chk == 0){                                             //Il Ledled 1 è Spento
      digitalWrite(led, HIGH);
      L4chk = 1;
      return;                   //Led 1 acceso
     }

     if (L4chk == 1){                                             //Il Ledled 1 è Spento
      digitalWrite(led, LOW);
      L4chk = 0;
      return;                   //Led 1 acceso
     }
    }

    void ledCinque(){
     led = 6;
     if (L5chk == 0){                                             //Il Ledled 1 è Spento
      digitalWrite(led, HIGH);
      L5chk = 1;
      return;                   //Led 1 acceso
     }

     if (L5chk == 1){                                             //Il Ledled 1 è Spento
      digitalWrite(led, LOW);
      L5chk = 0;
      return;                   //Led 1 acceso
     }
    }

    void ledSei(){
     led = 7;
     if (L6chk == 0){                                             //Il Ledled 1 è Spento
      digitalWrite(led, HIGH);
      L6chk = 1;
      return;                   //Led 1 acceso
     }

     if (L6chk == 1){                                             //Il Ledled 1 è Spento
      digitalWrite(led, LOW);
      L6chk = 0;
      return;                   //Led 1 acceso
     }
    }

    void ledSette(){
     led = 8;
     if (L7chk == 0){                                             //Il Ledled 1 è Spento
      digitalWrite(led, HIGH);
      L7chk = 1;
      return;                   //Led 1 acceso
     }

     if (L7chk == 1){                                             //Il Ledled 1 è Spento
      digitalWrite(led, LOW);
      L7chk = 0;
      return;                   //Led 1 acceso
     }
    }

    void ledOtto(){
     led = 9;
     if (L8chk == 0){                                             //Il Ledled 1 è Spento
      digitalWrite(led, HIGH);
      L8chk = 1;
      return;                   //Led 1 acceso
     }

     if (L8chk == 1){                                             //Il Ledled 1 è Spento
      digitalWrite(led, LOW);
      L8chk = 0;
      return;                   //Led 1 acceso
     }
    }

So far the web page is correctly loaded, but the sketch of the LED light logic seems to not work anymore like it was working correctly before. I thought that maybe someone of you guys could help point me in the right direction.

title: How to correctly serve a webpage from an SD card

Answers: 1

body:
It looks that I found the solution to my problem, the first skecth was working correctly because  the **SD card is using the pin 4  for his purpose**, so the sketch was working good becuse the SD card was not used here, in the second code where I used th SD card to serve a webpage **was not working anymore not because of the code, but becuse the PIN 4 where I connected a led was used by SDcard** and so it messed up by blinking the LED

**DON'T USE PIN4 WITH AN ETHERNET SHIELD IF YOU PLAN TO USE THE SD CARD**


body:
I have a battery pack used to charge mobile phones. It's capacity is 13,000mAh and it has two output ports. Both are 5V but one is 1A and the other 2.1A
It also has an Input port of 5V 1A. (To which I will connect a solar panel).

I want to be able to power this [Adafruit Feather M0][1] as well as this Wind Speed Sensor [Wind Speed Sensor Voltage Type(0-5V) SKU:SEN0170][2]. Is it possible and if it is how?

  [1]: https://www.adafruit.com/product/3010
  [2]: https://www.dfrobot.com/wiki/index.php/Wind_Speed_Sensor_Voltage_Type(0-5V)_SKU:SEN0170

title: Is it possible to power this 12V Wind Speed Sensor with a 5V battery?

Answers: 1

body:
1. If you have a circuit diagram for your 13,000mAh 5V battery, check whether there are internal connections at higher than 5V.  Because 5V is not a common battery voltage, there probably are cells in a higher-voltage series connection, being converted to 5V output via a step-down (buck) circuit.

2. An item like a “5V DC to 9V DC Converter DC-DC Isolated Power Supply Module” as in picture below [from ebay seller *bidcenter*] might do the job.  Also available are less-expensive not-potted adjustable boost regulators.  [![bidcenter picture][1]][1]

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


body:
I have an Arduino MKR1000 and need to interface it to an Adafruit Music Maker shield, which has pinouts for an Arduino UNO.

Maybe I'll have to attach female headers, and then jumper pins over.
Which pins on MKR go to which pins on Music Maker?

I have to use the MKR1000 because I'm getting the audio from wifi (using MKR1000) and then sending it to Music Maker.

title: How to attach Arduino MKR1000 to a shield meant for Arduino UNO?

Answers: 0


body:
I'm working on a remote control code for ESP controller. Using ESPwebserver and Fastled. When I try to return a value of an uint8_t, as a POST response, i got strange result here is the relevant code:

    uint8_t PaletteBrightness = 255;

    server.on("/Sync", HTTP_POST, []() {
    String Sync = "PaletteBrightness:" + PaletteBrightness;
     Sync += ":end";
     Serial.println(Sync);
     server.send(200, "text/plain", Sync);
      });

The code complies, and runs fine but the result of 'Sync' in both serial, and POST response is:

    Phase:end

Why? What does even Phase mean?
What I want is:

    PaletteBrightness:255:end

Where the 255 is the value of 'uint8_t PaletteBrightness' Also, there will be more values, to add the 'Sync' string. Just trying to get one right.

title: Converting uint8_t to String - unexpected result

Answers: 1

body:
You should convert your number `uint8_t` into it's ASCII representation before appending it to your string, otherwise you are appending just one character using it's byte representation.

To do so you can use a standard function `itoa()` which has a decent documentation available [here][1].

So change line

     String Sync = "PaletteBrightness:" + PaletteBrightness;

into

     char buffer [4];
     String Sync = "PaletteBrightness:" + itoa(PaletteBrightness, buffer, 10);

  [1]: http://www.cplusplus.com/reference/cstdlib/itoa/


body:
I just bought these two WiFi Shields -> http://www.ebay.de/itm/262525969091?_trksid=p2060353.m2749.l2649&ssPageName=STRK:MEBIDX:IT

As they arrived I put one of them onto my Arduino Uno R3 and tried if my LED test sketch still works. It did.

After that I tried this WiFi tutorial (https://www.arduino.cc/en/Tutorial/ConnectWithWPA) to play around with the WiFi API a little bit. Sadly it prints to the serial monitor _"WiFi shield not present"_ which tells me I missed something when setting up the shield.

I just thought the WiFi shield will be already usable without wiring anything. Surely that might be naive somehow, but hey I'm still a noob ;)

Can you guys tell me or simply point out a tutorial where it tells me what wiring I have to do to at least get pass this _"WiFi shield not present"_ check?

Then I just realized that I do not have the "real" Arduino WiFi Shield and therefore the origin WiFi lib won't work for me according to this thread: http://forum.arduino.cc/index.php?topic=371362.0

Sadly I did not received any documenation on how to get this thing to work now. I found A LOT of threads about the "WiFi shield not present" error but none of them solved my specific problem with the shields I bought.

title: how to get an unofficial WiFi Shield to work?

Answers: 1

body:
Somewhere it should say this: It is really really difficult to implement enough of the TCP/IP stack on an Uno to handle talking over the Ethernet.  In other words, the shield is doing almost all the work.  As such, if you don't have any documentation, using this Ethernet shield will be difficult.  That said, it looks like this shield is using an [ESP8266 which IS widely documented][1]. And if you search around, can even find people creating [Arduino / ESP8266 software][2].

  [1]: https://en.wikipedia.org/wiki/ESP8266
  [2]: https://github.com/esp8266/Arduino


body:
I thought I finally had this working yesterday, the code compiled, and executed on the arduino, there were however some small quirks but today I went to fix a small timing issue, but got the following errors instead.  Nothing related to the errors was changed, they just showed up, in fact I went back to the original code which was compiling fine yesterday and it won't compile either.  The errors are directly below this followed by the libraries which appear to be the cause of the errors.  Please help, I just want to get this project finished.

    Arduino: 1.6.7 (Mac OS X), TD: 1.28-beta1, Board: "Arduino/Genuino Mega or Mega 2560, ATmega2560 (Mega 2560)"

    In file included from /Users/DMYoung1/Library/Arduino15/packages/arduino/hardware/avr/1.6.13/cores/arduino/Arduino.h:28:0,
    from /Users/DMYoung1/Documents/Arduino/libraries/Morse_EnDecoder/MorseEnDecoder.h:7,
    from /Users/DMYoung1/Documents/Arduino/libraries/Morse_EnDecoder/MorseEnDecoder.cpp:67:
    /Users/DMYoung1/Documents/Arduino/libraries/Morse_EnDecoder/MorseEnDecoder.cpp:75:19: error: variable 'morseTable' must be const in order to be put into read-only section by means of '__attribute__((progmem))'
    char morseTable[] PROGMEM =
                   ^
    exit status 1
    Error compiling for "Arduino/Genuino Mega or Mega 2560"

I am attaching my code and the libraries I am using.

Morse EnDecoder.h

    #ifndef MorseEnDecoder_H
    #define MorseEnDecoder_H

    #if (ARDUINO <  100)
    #include <WProgram.h>
    #else
    #include <Arduino.h>
    #endif

    #define MORSE_AUDIO true
    #define MORSE_KEYER false
    #define MORSE_ACTIVE_LOW true
    #define MORSE_ACTIVE_HIGH false

    class morseDecoder
    {
    public:
    morseDecoder(int decodePin, boolean listenAudio, boolean morsePullup);
    void decode();
    void setspeed(int value);
    char read();
    boolean available();
    int AudioThreshold;
    long debounceDelay;     // the debounce time. Keep well below dotTime!!
    boolean morseSignalState;
    private:
    int morseInPin;         // The Morse input pin
    int audioSignal;
    int morseTablePointer;
    int wpm;                // Word-per-minute speed
    long dotTime;           // morse dot time length in ms
    long dashTime;
    long wordSpace;
    boolean morseSpace;     // Flag to prevent multiple received spaces
    boolean gotLastSig;     // Flag that the last received morse signal is decoded as dot or dash
    boolean morseKeyer;
    boolean lastKeyerState;
    boolean morseAudio;
    boolean activeLow;
    long markTime;          // timers for mark and space in morse signal
    long spaceTime;         // E=MC^2 ;p
    long lastDebounceTime;  // the last time the input pin was toggled
    long currentTime;       // The current (signed) time
    char decodedMorseChar;  // The last decoded Morse character
    };

    class morseEncoder
    {
    public:
    morseEncoder(int encodePin);
    void encode();
    void setspeed(int value);
    void write(char temp);
    boolean available();
    int morseSignals;       // nr of morse signals to send in one morse character
    char morseSignalString[7];// Morse signal for one character as temporary ASCII string of dots and dashes
    private:
    char encodeMorseChar;   // ASCII character to encode
    boolean sendingMorse;
    int wpm;                // Word-per-minute speed
    long dotTime;           // morse dot time length in ms
    long dashTime;
    long wordSpace;
    int morseSignalPos;
    int sendingMorseSignalNr;
    long sendMorseTimer;
    long lastDebounceTime;
    long currentTime;
    protected:
    int morseOutPin;
    virtual void setup_signal();
    virtual void start_signal(bool startOfChar, char signalType);
    virtual void stop_signal(bool endOfChar, char signalType);
    };

    #endif

Here is Morse EnDecoder.cpp

    /*          MORSE ENDECODER

    - Morse encoder / decoder classes for the Arduino.

    Copyright (C) 2010-2012 raron

    GNU GPLv3 license:

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

    Details: http://raronoff.wordpress.com/2010/12/16/morse-endecoder/

    #include "MorseEnDecoder.h"

    // Morse code binary tree table (dichotomic search table)

    // ITU with most punctuation (but without non-english characters - for now)
    const int morseTreeLevels = 6; // Minus top level, also the max nr. of morse signals
    const int morseTableLength = pow(2,morseTreeLevels+1);
    const char morseTable[] PROGMEM =
    " ETIANMSURWDKGOHVF*L*PJBXCYZQ!*54*3***2&*+****16=/***(*7***8*90*"
    "***********?_****\"**.****@***'**-********;!*)*****,****:*******\0";

    morseDecoder::morseDecoder(int decodePin, boolean listenAudio, boolean morsePullup)
    {
    morseInPin = decodePin;
    morseAudio = listenAudio;
    activeLow = morsePullup;

    if (morseAudio == false)
    {
    pinMode(morseInPin, INPUT);
    if (activeLow) digitalWrite (morseInPin, HIGH);
    }

    // Some initial values
    wpm = 13;
    AudioThreshold = 700;
    debounceDelay = 20;
    dotTime = 1200 / wpm;       // morse dot time length in ms
    dashTime = 3 * 1200 / wpm;
    wordSpace = 7 * 1200 / wpm;

    morseTablePointer = 0;

    morseKeyer = LOW;
    morseSignalState = LOW;
    lastKeyerState = LOW;

    gotLastSig = true;
    morseSpace = true;
    decodedMorseChar = '\0';

    lastDebounceTime = 0;
    markTime = 0;
    spaceTime = 0;
    }

    void morseDecoder::setspeed(int value)
    {
    wpm = value;
    if (wpm <= 0) wpm = 1;
    dotTime = 1200 / wpm;
    dashTime = 3 * 1200 / wpm;
    wordSpace = 7 * 1200 / wpm;
    }

    boolean morseDecoder::available()
    {
    if (decodedMorseChar) return true; else return false;
    }

    char morseDecoder::read()
    {
    char temp = decodedMorseChar;
    decodedMorseChar = '\0';
    return temp;
    }

    void morseDecoder::decode()
    {
    currentTime = millis();

    // Read Morse signals
    if (morseAudio == false)
    {
    // Read the Morse keyer (digital)
    morseKeyer = digitalRead(morseInPin);
    if (activeLow) morseKeyer = !morseKeyer;

    // If the switch changed, due to noise or pressing:
    if (morseKeyer != lastKeyerState) lastDebounceTime = currentTime; // reset timer

    // debounce the morse keyer
    if ((currentTime - lastDebounceTime) > debounceDelay)
    {
      // whatever the reading is at, it's been there for longer
      // than the debounce delay, so take it as the actual current state:
      morseSignalState = morseKeyer;

      // differentiante mark and space times
      if (morseSignalState) markTime = lastDebounceTime;
      else spaceTime = lastDebounceTime;
    }
    } else {
    // Read Morse audio signal
    audioSignal = analogRead(morseInPin);
    if (audioSignal > AudioThreshold)
    {
      // If this is a new morse signal, reset morse signal timer
      if (currentTime - lastDebounceTime > dotTime/2)
      {
        markTime = currentTime;
        morseSignalState = true; // there is currently a Morse signal
      }
      lastDebounceTime = currentTime;
    } else {
      // if this is a new pause, reset space time
      if (currentTime - lastDebounceTime > dotTime/2 && morseSignalState == true)
      {
        spaceTime = lastDebounceTime; // not too far off from last received audio
        morseSignalState = false;     // No more signal
       }
     }
    }

    // Decode morse code
    if (!morseSignalState)
    {
      if (!gotLastSig)
      {
        if (morseTablePointer < morseTableLength/2-1)
        {
        // if pause for more than half a dot, get what kind of signal pulse (dot/dash) received last
        if (currentTime - spaceTime > dotTime/2)
        {
          // if signal for more than 1/4 dotTime, take it as a morse pulse
          if (spaceTime-markTime > dotTime/4)
          {
            morseTablePointer *= 2;  // go one level down the tree
            // if signal for less than half a dash, take it as a dot
            if (spaceTime-markTime < dashTime/2)
            {
               morseTablePointer++; // point to node for a dot
               gotLastSig = true;
            }
            // else if signal for between half a dash and a dash + one dot (1.33 dashes), take as a dash
            else if (spaceTime-markTime < dashTime + dotTime)
            {
               morseTablePointer += 2; // point to node for a dash
               gotLastSig = true;
            }
          }
        }
      } else { // error if too many pulses in one morse character
        //Serial.println("<ERROR: unrecognized signal!>");
        decodedMorseChar = '#'; // error mark
        gotLastSig = true;
        morseTablePointer = 0;
      }
    }
    // Write out the character if pause is longer than 2/3 dash time (2 dots) and a character received
    if ((currentTime-spaceTime >= (dotTime*2)) && (morseTablePointer > 0))
    {
      decodedMorseChar = pgm_read_byte_near(morseTable + morseTablePointer);
      morseTablePointer = 0;
    }
    // Write a space if pause is longer than 2/3rd wordspace
    if (currentTime-spaceTime > (wordSpace*2/3) && morseSpace == false)
    {
      decodedMorseChar = ' ';
      morseSpace = true ; // space written-flag
    }

    } else {
    // while there is a signal, reset some flags
    gotLastSig = false;
    morseSpace = false;
    }

    // Save the morse keyer state for next round
    lastKeyerState = morseKeyer;
    }

    morseEncoder::morseEncoder(int encodePin)
    {
      morseOutPin = encodePin;
      this->setup_signal();

    // some initial values
    sendingMorse = false;
    encodeMorseChar = '\0';

    wpm = 13;
    dotTime = 1200 / wpm;       // morse dot time length in ms
    dashTime = 3 * 1200 / wpm;
    wordSpace = 7 * 1200 / wpm;

    }

    void morseEncoder::setspeed(int value)
    {
    wpm = value;
    if (wpm <= 0) wpm = 1;
    dotTime = 1200 / wpm;
    dashTime = 3 * 1200 / wpm;
    wordSpace = 7 * 1200 / wpm;
    }

    boolean morseEncoder::available()
    {
    if (sendingMorse) return false; else return true;
    }

    void morseEncoder::write(char temp)
    {
    if (!sendingMorse && temp != '*') encodeMorseChar = temp;
    }

    void morseEncoder::setup_signal()
    {
    pinMode(morseOutPin, OUTPUT);
    digitalWrite(morseOutPin, LOW);
    }

    void morseEncoder::start_signal(bool startOfChar, char signalType)
    {
    digitalWrite(morseOutPin, HIGH);
    }

    void morseEncoder::stop_signal(bool endOfChar, char signalType)
    {
    digitalWrite(morseOutPin, LOW);
    }

    void morseEncoder::encode()
    {
    currentTime = millis();

    if (!sendingMorse && encodeMorseChar)
    {
    // change to capital letter if not
    if (encodeMorseChar > 96) encodeMorseChar -= 32;

    // Scan for the character to send in the Morse table
    int p;
    for (p=0; p<morseTableLength+1; p++) if (pgm_read_byte_near(morseTable + p) == encodeMorseChar) break;

    if (p >= morseTableLength) p = 0; // not found, but send a space instead

    // Reverse binary tree path tracing
    int pNode; // parent node
    morseSignals = 0;

    // Travel the reverse path from position p to the top of the morse table
    if (p > 0)
    {
      // build the morse signal (backwards morse signal string from last signal to first)
      pNode = p;
      while (pNode > 0)
      {
        if ( (pNode & 0x0001) == 1)
        {
          // It is a dot
          morseSignalString[morseSignals++] = '.';
        } else {
          // It is a dash
          morseSignalString[morseSignals++] = '-';
        }
        // Find parent node
        pNode = int((pNode-1)/2);
      }
    } else { // Top of Morse tree - Add the top space character
      // cheating a little; a wordspace for a "morse signal"
      morseSignalString[morseSignals++] = ' ';
    }

    morseSignalString[morseSignals] = '\0';

    // start sending the the character
    sendingMorse = true;
    sendingMorseSignalNr = morseSignals; // Sending signal string backwards
    sendMorseTimer = currentTime;
    if (morseSignalString[0] != ' ') this->start_signal(true, morseSignalString[morseSignals-1]);
    }

    // Send Morse signals to output
    if (sendingMorse)
    {
    char& currSignalType = morseSignalString[sendingMorseSignalNr-1];
    bool endOfChar = sendingMorseSignalNr <= 1;
    switch (currSignalType)
    {
      case '.': // Send a dot (actually, stop sending a signal after a "dot time")
        if (currentTime - sendMorseTimer >= dotTime)
        {
          this->stop_signal(endOfChar, currSignalType);
          sendMorseTimer = currentTime;
          currSignalType = 'x'; // Mark the signal as sent
        }
        break;
      case '-': // Send a dash (same here, stop sending after a dash worth of time)
        if (currentTime - sendMorseTimer >= dashTime)
        {
          this->stop_signal(endOfChar, currSignalType);
          sendMorseTimer = currentTime;
          currSignalType = 'x'; // Mark the signal as sent
        }
        break;
      case 'x': // To make sure there is a pause between signals
        if (sendingMorseSignalNr > 1)
        {
          // Pause between signals in the same letter
          if (currentTime - sendMorseTimer >= dotTime)
          {
            sendingMorseSignalNr--;
            this->start_signal(false, morseSignalString[sendingMorseSignalNr-1]); // Start sending the next signal
            sendMorseTimer = currentTime;       // reset the timer
          }
        } else {
          // Pause between letters
          if (currentTime - sendMorseTimer >= dashTime)
          {
            sendingMorseSignalNr--;
            sendMorseTimer = currentTime;       // reset the timer
          }
        }
        break;
      case ' ': // Pause between words (minus pause between letters - already sent)
      default:  // Just in case its something else
        if (currentTime - sendMorseTimer > wordSpace - dashTime) sendingMorseSignalNr--;
    }
    if (sendingMorseSignalNr <= 0 )
    {
      // Ready to encode more letters
      sendingMorse = false;
      encodeMorseChar = '\0';
    }
    }
    }

And finally, here is my code!!

    #include <avr/pgmspace.h>
    #include <MorseEnDecoder.h>
    #include <stdio.h>
    #include <morse.h>
    #define PIN_STATUS  13
    #define CPU_RESTART_ADDR (uint32_t *)0xE000ED0C
    #define CPU_RESTART_VAL 0x5FA0004
    #define CPU_RESTART (*CPU_RESTART_ADDR = CPU_RESTART_VAL);

    // Pin mapping
    const byte morseInPin = 7;
    const byte morseOutPin = 13;
    String check = "";
    String origin = "SOS";
    const int maxItems = 3;
    int x;
    char myArray[maxItems], curChar;
    char nextChar;
    int i;
    int y;

    // Instantiate Morse objects
    morseDecoder morseInput(morseInPin, MORSE_KEYER, MORSE_ACTIVE_LOW);
    morseEncoder morseOutput(morseOutPin);

    // Variables dealing with formatting the output somewhat
    // by inserting CR's (carriage returns)
    long lastTransmissionTime;
    long currentTime;
    boolean transmissionEnded = true; // Flag to mark old transmission is finished

    // Minimum transmission pause time to insert carriage returns (CR)
    // Adjust depending on Morse speed. IE 13 wpm = 646 ms between words (no CR).
    const long transmissionPaused   = 1000; // Suitable for 13 wpm?

    LEDMorseSender sender(PIN_STATUS);

    void setup()
    {
    Serial.begin(9600);
    Serial.println("Morse EnDecoder Geocache");

    // Setting Morse speed in wpm - words per minute
    // If not set, 13 wpm is default anyway
    morseInput.setspeed(5);
    morseOutput.setspeed(5);

    lastTransmissionTime = (long)millis();

    }

    void(* resetFunc) (void) = 0; //declare reset function @ address 0

    void loop()
    {
    currentTime = (long)millis();

    // Need to call these once per loop
    morseInput.decode();
    morseOutput.encode();

    // RECEIVE MORSE (INPUT)
    // If a character is decoded from the input, write it to serial port
    if (morseInput.available())
    {

    char receivedMorse = morseInput.read();
    Serial.print(receivedMorse);
    // A little error checking
    if (receivedMorse == '#') Serial.println("< ERROR:too many morse signals! >");
    morseOutput.write('#');
    morseOutput.encode();

    //Create Array out of receivedMorse Chars

        curChar = 0;
        nextChar = receivedMorse;
        curChar +=nextChar;
        myArray[i] = curChar;
        check.concat(myArray[i]);
        Serial.println(check);

    //Check input and respond
    if (check == origin)      //GOOD JOB!!  Your reward is as follows
    {
    Serial.println("check = origin");
    Serial.println(check);
    sender.setup();
    sender.setWPM(5);
    sender.setMessage(String("help is coming"));
    sender.startSending();
    }
    else if (check =="S") {}
    else if (check == "SO") {}
    else if (check == " SOS") {}
    else if (check.length() >4)
    {
    delay(100);
    Serial.println("resetting");
    delay(500);
    resetFunc();  //call reset
    delay(100);
    }
    else {}
    }
    sender.continueSending();
    }

title: I swear this worked yesterday!! - mysterious compiler error

Answers: 1

body:
Apparently you have made multiple copies of MorseEnDecoder.cpp, some of them modified, because the `morseTable[]` declaration shown in the error message is different than that shown in the code you said is MorseEnDecoder.cpp.  Specifically, line 32 of that code is

    const char morseTable[] PROGMEM =

while the error message refers to a line 75 which reads

    char morseTable[] PROGMEM =

The solution is to extirpate extraneous copies and restore MorseEnDecoder.cpp to a correct version.


body:
Code as shown below. I am unable to get the 16-bit data. Can someone help me identify my mistake?

    byte spiTransfer(volatile byte data) {
      SPDR = data;
      while (!(SPSR & _BV(SPIF)));
      return SPDR;
    }
    #define DOUT      (50)
    #define DIN       (51)
    #define SCLK      (52)
    #define CS_AD7705 (53)
    #define DRDY (4)

    void setup() {
      Serial.begin(9600);
      pinMode(DOUT, OUTPUT);
      pinM ode(DIN, INPUT);
      pinMode(SCLK,OUTPUT);
      pinMode(CS_AD7705,OUTPUT);
      pinMode(DRDY,INPUT);
      SPCR = _BV(SPE) | _BV(MSTR) | _BV(CPOL) | _BV(CPHA) | _BV(SPI2X) | _BV(SPR1) | _BV(SPR0);
      delay(10);
      digitalWrite(CS_AD7705, LOW);
      spiTransfer(00010000); //setup register
      spiTransfer(01100110);
      spiTransfer(00100000); //clock register
      spiTransfer(00001000);
      digitalWrite(CS_AD7705, HIGH);
    }

    void loop() {
      unsigned int data=0;
      digitalWrite(CS_AD7705,LOW); // enable device
      while(!digitalRead(DRDY));
      data = spiTransfer(00111000);  // select ch1 and setup read 16-bit data register
      data = spiTransfer(0)<<8;
      // Get the most significant 8 bits
      Serial.println("data : "+data);
      data |= spiTransfer(0); // Get the least significant 8 bits
      digitalWrite(CS_AD7705, HIGH); // release device
      delay(1000);
      Serial.println(data, HEX);
    }

title: Unable to interface AD7705 (SPI) with Arduino

Answers: 2

body:
I think the main problem is the values you are passing to spiTransfer().  By the way they are written I think you think you are passing binary values, you aren't you are passing decimal values.  So

    data = spiTransfer(00111000);  // select ch1 and setup read 16bit data

should be

    data = spiTransfer(B00111000);  // select ch1 and setup read 16bit data

The number needs prefixing with a B

Also passing a volatile parameter to this function looks wrong to me, especially when you only pass in constants.

body:
I've been trying to get one of these working too. I think before you can read the data register, you have to tell the COMMs register your intention to do so.

    // Select channel to read:
    // write to comm reg selecting channel and
    // setting up next op to be a read from data reg
    SPI.transfer( DRDY_DONT_CARE | REG_DATA | STDBY_OFF | COMMS_READ | CHAN_AIN1 );
    //  Do two 8-bit reads, MSByte first
    highByte = SPI.transfer(0xff);
    lowByte  = SPI.transfer(0xff);

    adcValue0 = highByte << 8;
    adcValue0 = adcValue0 | lowByte;

 Still, I've had sketchy and intermittent success reading the ADC. The looping code seems to lose sync with the ADC; I've been speculating that reading ASAP following DRDY going True is important.

Have you verified that your SPI interface is working? You can read the 24-bit calibration data, which should match the documented values. Doing so verifies that the SPI reads and writes properly, unless the SPI interface behaves differently for different functions. Are you using genuine Analog Devices silicon, or one of the widely available knock-offs (TM7705, like mine)?


body:
I'm using the following Makefile: https://github.com/sudar/Arduino-Makefile
It works very well and I was able to get my LED to blink.

Now I bought a WiFi Shield which is NOT supported officially by the Arduino WiFi library.
It is the following one I bought: **ESP8266 ESP-12E CC3000 UART WIFI Wireless Shield Board Modul für Arduino UNO R3** - you can find this on ebay: http://www.ebay.de/itm/262525969091?_trksid=p2060353.m2749.l2649&ssPageName=STRK:MEBIDX:IT

What I now am about to do is to include the open source library for the ESP8266 which you can find here: https://github.com/esp8266/Arduino#documentation

Now when I try to upload my sketch it tells me that certain dependencies are not resolved. Like this one here `#include <functional>` which I was not able to include manually. My main problem here is that the github page of the ESP8266 library isn't providing enough information for me how I can get the working lib to use in my sketch.
I need to know how I can get this library to work in my sketch!

title: using an ESP8266 shield on my Arduino Uno R3 with an unofficial library

Answers: 1

body: That is **not** a library for the Arduino. That is a **core** for programming the ESP8266 directly as if it were an Arduino itself.


body:
I have a Chinese Arduino nano clone, but I don't know if it's possible to connect the Arduino to external (5v) power and have a USB serial connection ongoing. I'm trying to make a PC controlled LED Strip that can also work on its own.

For example: the PC controls the Arduino sets it to a specific mode and I turn off the PC, but the Arduino should still be running even when the PC is turned off.

I'm new to the world of arduinos.

I'm planning to use this to control addressable LED RGB Strips and am planning to use a 4000mA max power supply.

title: External 5V Power and USB Serial

Answers: 4

body:
If you are new to something, you should start with reading manual.

Here's what official Wiki page of arduino nano says:
https://www.arduino.cc/en/Main/ArduinoBoardNano

>Power:
>
>The Arduino Nano can be powered via the Mini-B USB connection, 6-20V unregulated external power supply (pin 30), or 5V regulated external power supply (pin 27). The power source is automatically selected to the highest voltage source.

body:
You can connect the Arduino nano to recommended external power supply i.e 5V when it acts as a standalone device with other circuitry. As it is connected to PC it starts drawing power from PC(as PC is acting as a host here) and at the same time serial communication goes on. Now if you want to simultaneously connect the nano to PC or any other host say tablet and external power supply it is recommended that you go for an OTG cable cum power splitter y-cable.

But do not rely on power from PC if you have many sensors or components interfaced to aduino nano as PC is capable of giving max current 100mA in USB 2.0 and approx 150mA in USB 3.0

body:
The info about 100/150mA USB capability in PC is incorrect. Any normal (not "low-power embedded") USB host must supply 500mA (for USB2.0 ports) and 900mA for USB3.0 ports. In a typical PC this power comes from standby +5VSB rail from system Power Supply. Power rating for this rail is no less than 2A for AT12 compliant PC. Of course it is not advisable to take all this power from one port, due to contact rating limits, and possible polyswitch overcurrent protection of USB ports.

Therefore, if the attached USB device draws total less than 1-1.5A, the design should work fine even if PC is in standby mode (turned off but still connected to AC outlet).

However it is still preferable to use a stand-alone power for this kind of projects. The Arduino board must be designed in a way that, if connected to external higher-voltage source, it would not backdrive any significant current into USB VBUS pin. Usually it gets accomplished by means of one single Schottky diode between VBUS and internal power rail on Arduino board.

You can check if your Arduino drives anything back: power the Arduino with, say, 12V power supply, and check with a Multimeter if VBUS pin on the (unattached) USB connector has any voltage. You should load the VBUS with 10k-15k resistor, and the voltage should be small, 200mV or less, if I remember correctly.

ADDENDUM1: Just checked with Arduino-nano schematics. Yes, there is a "auto selecting" Schottky diode, so there will be no backvoltage on VBUS. However, the Arduino design violates another USB requirement - no signal on any connector pin when VBUS is inactive (low). In the Arduino-nano the VBUS does not control the state of FT232 bridge, so it will always pull-up D+ (USBDP) line as soon as 5V is applied, which is in violation of specs. The side effect of this back-driving is that your PC might not re-connect with the Arduino after waking-up, although it is a rare case these days.

body: Having used counterless Arduinos and clones, I can tell you that you can connect both without worrying about any danger. Unless you have a very faulty board, your pc won't be damaged, almost surely neither will the board, as is should select the most powerful source, between your usb or a battery/external PS, while leaving untouched the serial line.


body:
I'm experiencing an issue with an Arduino Mega 2560 :
I powered the board through the Vin using a +24 --> 9V voltage regulator. When I power the board and measure the 5V output from the board, the voltage quickly drops from 5 to ~3V within seconds.

However, while powering with USB, the 5V output from the board gives us a clear 4.8V.

I have checked the 9V Voltage regulator (connected to the Vin), and it has a +24V input which remains stable (as should the 9V).

Any thoughts ?

title: 9V Vin powered Mega - 3V instead of 5V

Answers: 1

body:
So, according to the comments the main problem should be a thermal protection in `LM7809C` regulator.

The voltage drop between regulator's input and output is about `15 Volts` and even with current consumption about `150mA` it means `2.25W` of power dissipation on it.

For such a big difference between input and output voltage switching regulator is recommended. (Or 9V power supply instead of 24V)

And it is not possible to have `2mA` current consumption. I've just measured power consumption of bare `Arduino Mega 2560` and it is `81mA` through barrel jack input (`9V`) without anything on it. Not even blinking Led. So if you've measured for example `0.2A` it's not `2mA` but `200mA`


body:
Over the course of my Arduino usage and learning, I've noticed that in some sketches people use the `#define` command to declare pins, while some others simply use `const int` for the same.

My question is, what's the difference between the two, and which one should be preferred for use?

title: What's the difference between #define and const int when declaring a pin?

Answers: 1

body:
"#define" is a preprocessor directive. It defines a lable and a value, that will be positioned in the preprocessed-source-code at the same place of each occurence of the label. No type is defined, so it is a basic and dumb substitution of strings before compilation. It can then lead to errors or misunderstandings during compilation.

"const int xxx" defines a type, and locks the value of that instance. It's safer to use this method. The compiler can check for type errors and throw messages (or break compilation) if you made a mistake.

Example:

    #define A 5
    int dummy_integer = A

... will be preprocessed as...

    int dummy_integer = 5
... and the compiler will read this statement.

However, if I remember good, you can always overwrite a preprocessor directive as follows:

    #define A 5
    int dummy_integer = A
    //some code here
    #undef A
    #define A "my_string"
    std::cout << A
That's not good. By using the "const" modifier, instead, you can't change the value (nor the type) of a variable (and so it's defined "constant").


body:
I'm working on a program with Arduino Uno which involves writing and reading EEPROM. I'm using a basic EEPROM library. My problem is: EEPROM values are preset to 255 whenever I burn my program. And there is nothing in my code which will write 255 in these bytes.

I even tried `EEPROM_read` example from the EEPROM library and got same result. I used `EEPROM_clear` code before `EEPROM_read` to set all values to 0. But when I read those values using `EEPROM_read`, they are 255.

Please help explain what is happening.

title: EEPROM bytes preset to 255 while programming

Answers: 2

body: In flash and eeprom memory an erased value is 255. It's all about how flash memory works. If you want something other than 255 in there you will have to write something other than 255 in there.

body:
**You need to set EESAVE fuse**

When the ATmega chip is programmed the memory is erased just before the new code is uploaded. Under normal circumstances the eeprom memory is erased as well as the program memory. The EESAVE fuse can be used to tell the chip not to erase the eeprom. This is useful when you want to upgrade code but keep user settings that are stored in eeprom.

The default value is EESAVE=1, not set and eeprom memory is erased during the chip erase cycle when programming.

This [fuse calculator][1] is quite handy.

  [1]: http://eleccelerator.com/fusecalc/fusecalc.php?chip=atmega328p


body:
I need an Arduino board for simple ADC, but 10 bits of resolution is sadly not enough. I am going to buy a board with 12 bits of resolution, but really couldnt decide on the exact model. It needs to be easily accessable and wont be used for anything else other then ADC. I have my eye on MO, but cant decide if i should buy the pro or the normal one, or just another Arduino board.

I take the data through USB port and the instrument will also be powered with the same USB cable.

*** My only option is to use an Arduino***

I know i can use the Aref pin or do oversampling but i really am not intrested in those options. thanks for your input

title: Cheapest and easiest Arduino board for 12 bit ADC, thinking of M0

Answers: 2

body: Use a Teensy 3.x. Those have 13 bit ADCs

body:
The statement **my only option is to use an Arduino** is not unambiguous whatsoever.

If you meant *"Compatible with Arduino IDE"* than the Teensy 3.2, officially priced on the Arduino store at 17.90 EUR + VAT is the cheapest official Arduino board providing a 12 bit ADC.

If you meant *"Branded as an Arduino"* then the Arduino/Genuino M0 Zero, officially priced at 22.00 42.90 EUR + VAT is the cheapest board providing a 12 bit ADC.

This is the result of a quick search on the [Arduino web site][1], which you could have checked yourself.

In my opinion the cheapest *"Arduino based"* solution would be an Arduino Pro Mini (officially discontinued) or a barebone ATmega328P along with an external 12 bit ADC. This opens up for many options, just use a parametric search on DigiKey, Octopart or any other website of your choice.

A quick search ended up with MAX1245ACAP priced at 1.30 USD + VAT, probably ending in a BOM cost for the entire solution below 10 USD + VAT, excluding the PCB.

**UPDATE:** as stated in the comments, the `M0` is a cheaper version of the `Zero`.

  [1]: http://arduino.cc


body:
I am working with Arduino Uno, I have tracker application running on Arduino Uno board. I am sending data in comma separated value. Now I want to view data into Visual Basic. I have code as below. The below code is working with fake values but as soon it live stream data split functions gives out error.

Serial output data looks like this.

    Start,Latitude:13.00,longitude:60.00,MODE:1,DIR:1,Local Date:0/0/0,Local Time:5:30:2,tracker_des_angle:0.00,tracker_actual_pos:57.22,Wind Speed :0.00,END
    Start,Latitude:13.00,longitude:60.00,MODE:1,DIR:1,Local Date:0/0/0,Local Time:5:30:4,tracker_des_angle:43.00,tracker_actual_pos:69.20,Wind Speed :0.95,END
    Start,Latitude:13.00,longitude:60.00,MODE:1,DIR:0,Local Date:0/0/0,Local Time:5:30:6,tracker_des_angle:43.00,tracker_actual_pos:16.34,Wind Speed :1.85,END
    Start,Latitude:13.00,longitude:60.00,MODE:1,DIR:0,Local Date:0/0/0,Local Time:5:30:8,tracker_des_angle:43.00,tracker_actual_pos:11.89,Wind Speed :2.77,END

visual basic code:

    Option Explicit On

    Imports System
    Imports System.IO.Ports
    Imports System.Text

    Public Class Solar_Track
        Dim comPORT As String
        Dim receivedData As String = ""
        Dim strArray() As String
        Dim Data As String
        Dim latitude() As String
        Dim longitude() As String
        Dim Local_date() As String
        Dim Local_Time() As String
        Dim Mode_oper() As String
        Dim Dir_motor() As String
        Dim Act_pos() As String
        Dim Dis_pos() As String
        Dim wind_pos() As String
        Dim start As Boolean
        Dim End_Result As Boolean
        Dim result As Boolean

        Sub Parse_receivedata(ByVal msg As String)

            RichTextBox1.Text &= msg
            Data = msg

            strArray = Split(Data, ",")
            latitude = Split(strArray(1), ":")
            Text_Latitude.Text = latitude(1)

            longitude = Split(strArray(2), ":")
            Text_Longitude.Text = longitude(1)

            Mode_oper = Split(strArray(3), ":")
            Text_Mode.Text = Mode_oper(1)

            Dir_motor = Split(strArray(4), ":")
            Text_MotorDir.Text = Dir_motor(1)

            Local_date = Split(strArray(5), ":")
            Text_LocalDate.Text = Local_date(1)

            Local_Time = Split(strArray(6), ":")
            Label_hour.Text = Local_Time(1)
            Label_min.Text = Local_Time(2)
            Label_Sec.Text = Local_Time(3)

            Dis_pos = Split(strArray(7), ":")
            Text_TrackerDesire.Text = Dis_pos(1)

            Act_pos = Split(strArray(8), ":")
            Text_TrackerActual.Text = Act_pos(1)

            wind_pos = Split(strArray(9), ":")
            Text_Windspeed.Text = wind_pos(1)

        End Sub

        Sub data_parse()
            Data = "Start,Latitude:13.00,longitude:60.00,MODE:1,DIR:1,Local Date:0/0/0,Local Time:5:30:2,tracker_des_angle:0.00,tracker_actual_pos:54.48,Wind Speed :0.00,END"
            strArray = Split(Data, ",")

            latitude = Split(strArray(1), ":")
            Text_Latitude.Text = latitude(1)

            longitude = Split(strArray(2), ":")
            Text_Longitude.Text = longitude(1)

            Mode_oper = Split(strArray(3), ":")
            Text_Mode.Text = Mode_oper(1)

            Dir_motor = Split(strArray(4), ":")
            Text_MotorDir.Text = Dir_motor(1)

            Local_date = Split(strArray(5), ":")
            Text_LocalDate.Text = Local_date(1)

            Local_Time = Split(strArray(6), ":")
            Label_hour.Text = Local_Time(1)
            Label_min.Text = Local_Time(2)
            Label_Sec.Text = Local_Time(3)

            Dis_pos = Split(strArray(7), ":")
            Text_TrackerDesire.Text = Dis_pos(1)

            Act_pos = Split(strArray(8), ":")
            Text_TrackerActual.Text = Act_pos(1)

            wind_pos = Split(strArray(9), ":")
            Text_Windspeed.Text = wind_pos(1)

        End Sub

        Private Sub Solar_Track_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            Timer1.Enabled = False
            comPORT = ""
            For Each sp As String In My.Computer.Ports.SerialPortNames
                comPort_ComboBox.Items.Add(sp)
            Next
        End Sub

        Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles comPort_ComboBox.SelectedIndexChanged
            If (comPort_ComboBox.SelectedItem <> "") Then
                comPORT = comPort_ComboBox.SelectedItem
            End If
        End Sub

        Private Sub BtConnect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles connect_BTN.Click
            If (connect_BTN.Text = "Connect") Then
                If (comPORT <> "") Then
                    SerialPort1.Close()
                    SerialPort1.PortName = comPORT
                    SerialPort1.BaudRate = 9600
                    SerialPort1.DataBits = 8
                    SerialPort1.Parity = Parity.None
                    SerialPort1.StopBits = StopBits.One
                    SerialPort1.Handshake = Handshake.None
                    SerialPort1.Encoding = System.Text.Encoding.Default
                    SerialPort1.ReadTimeout = 10000

                    SerialPort1.Open()
                    connect_BTN.Text = "Dis-connect"
                    Timer1.Enabled = True
                    Timer_LBL.Text = "Timer: ON"

                Else
                    MsgBox("Select a COM port first")
                End If
            Else
                SerialPort1.Close()
                connect_BTN.Text = "Connect"
                Timer1.Enabled = False
                Timer_LBL.Text = "Timer: OFF"
            End If

        End Sub
        Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
            receivedData = ReceiveSerialData()
            ''RichTextBox1.Text &= receivedData
            Parse_receivedata(receivedData)
            receivedData = ""
            '' data_parse()
        End Sub
        Function ReceiveSerialData() As String
            Dim Incoming As String
            Try
                Incoming = SerialPort1.ReadExisting()
                If Incoming Is Nothing Then
                    Return "nothing" & vbCrLf
                Else
                    Return Incoming
                End If
            Catch ex As TimeoutException
                Return "Error: Serial Port read timed out."
            End Try

        End Function

        Private Sub BtClear_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtClear.Click
            RichTextBox1.Text = ""
        End Sub

    End Class

title: Arduino Parse data serially on VB

Answers: 1

body:
Looks like you are using a timer to regularly read the data from the serial port... I think you'd be better using the `DataReceived()` event of the SerialPort class.

The other thing is that you are just reading whatever data is in the buffer (with `ReadExisting`) if all that is in the buffer is 2 or 3 characters (not a full line) then your `Parse_receivedata()` will not be able to split it based on `,`

You want to keep appending the received data to a StringBuilder (or similar) until you hit a CR/LF and then pass it to the `Parse_receivedata()` function:

Psuedo code would be something like:

    // class scoped variable
    rxData = ""

    ...
    // inside the DataReceived() event
    rxData += SerialPort1.ReadExisting()
    If (rxData.Contains(Environment.Newline)) Then
      lines = rxData.Split(Environment.NewLine)
      toParse = lines[0]
      rxData = lines[1]
      ParseRxData(toParse)
    End If


body:
Just to illustrate my work here, I found a tutorial on how to code an accelerometer, I wanted to understand how does it work, literally get how it works, and not simply using the code without understanding it.

In the beginning of the program,there's a char variable declared as :

`char values[10];`

then later on the code, there was couple lines of getting the information stored in this variable, I'll give this as as example :

`x = ((int)values[1]<<8)|(int)values[0];`

we want X to receive `values[0]` and `values[1]` , that's what that line does up there.

My question is : can someone explain to me how does that line work, and why can't we simply write it as `x = ((int)values[1])|(int)values[0];` ?

title: Accelerometer sample code

Answers: 2

body:
To understand this you have to start thinking in binary.

The `|` operator is "Perform a binary OR on these two values".

The `<<8` is "Shift this value 8 bits to the left".

If you have two 8-bit values, say (in hex) 0x37 and 0x42, and you OR them together you get:

    0x37 = 00110111
    0x42 = 01000010
    --------------- |
    0x77 = 01110111

In each column where there is a 1 in either value you get a 1 in the result.

Now if you shift the first number 8 bits to the left, you end up with:

    0x3700 = 0011011100000000
    0x0042 =         01000010
    ------------------------- |
    0x3742 = 0011011101000010

You do this when a 16-bit value has been split into two 8-bit values and you want to join them back together again into the original 16-bit value.

body:
> up in the beginning of the program, there's a char variable declared
> as: `char values[10];`

This is not a “char variable”, it's an “array of 10 chars”.

> `((int)values[1]<<8)|(int)values[0]`

Majenko's answer perfectly explains the _intent_ of the author of the
tutorial, but that is not necessarily what the code _actually_ does. As
it stands, this piece of code is buggy. Or, to say the least, it has a
serious portability problem: it will probably work fine on ARM-based
boards, but it will fail on AVR-based boards, and on x86.

The reason is that, in C and C++, the type `char` can be either signed
or unsigned, depending on the platform. On most platforms, including
AVR, it is signed. This implies that, when a `char` is converted to
`int`, it undergoes [sign extension][] instead of being just zero
padded. To put it graphically, let's assume the sign bit (most
significant bit) of `values[0]` is `s`, then:

    values[0]      =         sxxxxxxx
    (int)values[0] = sssssssssxxxxxxx

Here I am assuming an AVR (16-bit ints). If the sign bit happens to be
zero, this will work as intended. This is the case in Majenko's example.
But if we replace 0x42 with 0xa2, we will have:

    values[1]         =   0x37 =         00110111
    (int)values[1]    = 0x0037 = 0000000000110111
    (int)values[1]<<8 = 0x3700 = 0011011100000000
    values[0]         =   0xa2 =         10100010
    (int)values[0]    = 0xffa2 = 1111111110100010

Then, the bitwise OR gives

    0x3700 = 0011011100000000
    0xffa2 = 1111111110100010
    ------------------------- |
    0xffa2 = 1111111110100010

and the data in `values[1]` is lost.

**Conclusion**: `values` should be declared as an array of **unsigned**
chars, as this will enforce zero-padding instead of sign extension.
Always use unsigned types when doing bit manipulations. And you probably
should find a better tutorial to learn this kind of stuff.

[sign extension]: https://en.wikipedia.org/wiki/Sign_extension


body: I'm doing a first tx/rx on a pair of modules, and some hams have alluded that they 'autoadjust' - since I've soldered halfwave antennas onto the modules, what's the optimal range for first tests? And will I benefit from 1/2 or 1/4 wave radials? I was thinking about 4-6 spokes from a bicycle wheel. Also, what library would be best for RC control of a medium power pump - I'm pretty sure it's going to induce noise. How far away from the pump should I position the rx module? Thanks in advance.

title: 433M modules w. soldered 34.6cm antenna, first test

Answers: 0


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

Above illustration is the basic setup for the question. The scenario will be the following:

> A potentiometer(providing 0 to 5V) is an analog input to A0. This
> potentiometer voltage is converted to PWM(pin9) which controls a fan M1. Which
> means the human controls directly the M1 fan speed.
>
> This directly speed-controlled M1 fan creates air pressure on a sensor
> Sen1.
>
> On the other hand I want M2 fan to reach to a speed(via pin10 PWM) such that Sen2
> should output the same voltage as Sen1. Which means eventually voltage
> at A1 analog input should be equal to A2. So one can achieve same air pressures at Sen1 and Sen2.

I'm not experienced in PID or other type of controls. I would be glad if someone can help me to relate parameters and code this scenario.

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

title: Need help modelling and coding a feedback scenario

Answers: 3

body:
Well, (very) simply you could slowly increase/decrease the PWM value driving M2 until the voltage at A1 equals that of A2. If you make the time between adjustments long enough you should not get any (significant) oscillations.

However, more likely you want to get to the correct M2 PWM value quickly and for that you need a **Proportional, integral, Differential *(PID)*** control algorithm. Explaining this in detail is outside the scope of a S.E. answer, but in summary:

You have a value that signifies the current state of the system - which will be the A2 reading.
You also have a value that states where you want to get to - which will be the A1 reading.
You also have a control value - which will be the PWM value of M2

The `Proportial` part looks at how far away the A2 reading is from the A1 reading.
The  `Integral` part looks at how quickly we (the A2 reading) are moving towards (or away from) the desired value (the A1 reading). The `Differential` part looks at how long we have been away from the desired value.

Each of these (PID) parts (with tuning values that you set) contributes towards determining a new value for PWM at M2 and this iterates around with new values getting the current state closer and closer to the desired value.

There are lots of Arduino PID examples around. I'd suggest you read up on the algorithm itself and have a look at the [Arduino.cc samples here][1].

  [1]: http://playground.arduino.cc/Code/PIDLibrary

body:
PID loops are a good way to go for something like this, but, you don't need to implement all three parts.  I have done industrial control using just the P and I.  Start by implementing just the proportional part.

For this, you calculate the error between the input signal (Va0) and the feedback signal (Va1). This is just a subtraction Err = Va0 - Va1.

You now multiply the Err by a constant and add that to Va0 to adjust the PWM.

A bit like this pseudo code:

      k = 0.5;
      Err = Va0 - Va1;
      pwm = Va0 + (Err * k);

Then set the pwm to the new calculated value.

This gives a correction **p**roportional to the error.

Experiment with k.  Start at 1. See how it goes.

Depending on the sensors you may have to apply some gain and/or offset to the Va1 reading in order to make it so that when the motor is at the correct speed, the calculated Va1 reading reads the same as the Va0 input.  For example, say the output range of the sensor is 0V to 2.5V, you will need to multiply by 2 before calculating the Err.

The P part of PID can give acceptable results.  The next stage would be to implement an I part. Do the P and see whether the I is needed.

body:
>  I want M2 fan to reach to a speed(via pin10 PWM) such that Sen2 should output the same voltage as Sen1.

simple:

      adc_sens1 = readadc(SENS1_PIN); //read adc on sense 1 pin
      adc_sens2 = readadc(SENS2_PIN); //read adc on sense 2 pin
      if (adc_sens2>adc_sens1 + SENS_DELTA) pwm_set(M2_PIN, --dc_ms); //if sens2 value too high, slow down m2's duty cycle -> positive correlatin assumed
      if (adc_sens2<adc_sens1 - SENS_DELTA) pwm_set(M2_PIN, ++dc_ms); //otherwise, increment duty cycle

No error check, no boundary check, ..... but the basic idea is the same.


body:
I recently bought Adafruit's motor shield v2 only to find out it can only support upto 12v.

So I'm on the look out for another shield & found this one [
Arduino Dual L6470 Stepper Motor Shield][1]

I have an Arduino Mega & the documentation says it is fully compatible with the UNO.

Will there an issue using this shield with a Mega? Or if anyone else can point me at a decent stepper controller?

  [1]: http://altelectronics.co.uk/shop/arduino/arduino-stepper-motor-shield/prod_84.html

title: Stepper motor shield compatibilty question

Answers: 2

body:
That is an SPI based device, and it doesn't use the (now considered standard) 6-pin ICSP header for SPI.

Therefore it will only directly work on boards that have the SPI pins available on pins 10-13 of the digital headers.

To use it with other boards you will need to manually route the SPI pins to the right places using wires.

body:
Just so you know, the L6470 is a pretty sophisticated and high-performance driver with lots of options to tweak, but it is a voltage-mode driver that requires some tuning for best results (otherwise, expect to generate some heat). There is a separate ST microelectronics application note, not mentioned in the L6470 datasheet, that describes some tuning guidelines - but it's written for an engineering audience.

There is also a SparkFun version of the L6470 out there.


body:
I just managed to get a unofficial Arduino WiFi shield to work. But the ESP is flashed on its own now - providing only information to the USB->TTL converter and therefore the output goes straight to the Serial Monitor of the Arduino IDE.

Since the ESP is flashed and should be running now - I should be able to disconnected the USB->TTL converter and attach the Arduino RX/TX to the ESP TX/RX right?

Then I should receive Serial Data and should be able to process these in my Arduino Sketch right?

So what do I need to do now? Should I start trying a Serial read from the arduino with the baud rate specified by the ESP Flash (11520)? Or do I have to consider something else as well?

title: Communicate with ESP8266 RX/TX

Answers: 1

body:
Your analysis is indeed correct, you can communicate between Arduino and ESP using the serial protocol.

Electrically speaking you must ensure the `RX` and `TX` pins are _crossed_:

`Arduino RX` goes into `ESP TX`
`Arduino TX` goes into `ESP RX`

Also, the two devices **MUST** have a _common ground_, the `GND` pins of the Arduino and the ESP8266 must be tied together.

You don't need level shifters because, even if the ESP8266 runs at 3.3V, its IO ports are 5V tolerant.

Also, as you already pointed out, the two devices must set the same speed (aka BAUD rate) in order to comprehend each other.

In case you decide to transmit binary data please also consider the two devices use a different architecture: Arduino is 8bit, ESP8266 is 32bit, meaning they have different _word size_ (the minimum allocation unit size).

I had to face the word size issue when I first tried to exchange a `struct` between an Arduino and a RaspberryPI (also 32bit)...


body:
I have an optris CT IR sensor, data sheet below.

Is it possible to connect the Uno to the sensor, so I can send a hex string (01) and hopefully receive a hex string from the sensor (04 D3)?

https://www.google.co.uk/url?sa=t&rct=j&q=&esrc=s&source=web&cd=2&ved=0ahUKEwirjO3oxo7PAhVKDsAKHcjGAcMQFggvMAE&url=http://www.optris.com/optris-ct-lt?file=tl_files/pdf/Downloads/Compact%20Series/Data%20Sheet%20optris%20CT%20LT.pdf&usg=AFQjCNEb-UKhxvfBE7k7k8zOgEZE9TOJbg&cad=rja

Commands below: (Go to examples section for 01, 04 D3)
https://www.google.co.uk/url?sa=t&rct=j&q=&esrc=s&source=web&cd=3&cad=rja&uact=8&ved=0ahUKEwiM6_zAx47PAhXoIcAKHVdUCo8QFggoMAI&url=http://www.optris.co.uk/interfaces?file=tl_files/downloads/Manuals/addendums-de-en/ct-ctlaser-commands.pdf&usg=AFQjCNEkEtwUoiM6jsJYOnGD4-8Yo2Cprg&bvm=bv.132653024,d.ZGg

Thanks

title: Connecting an optris to an arduino uno to send and receive hex strings

Answers: 1

body:
Yes, there are interface options that are compatible with the Arduino. You just have to ensure that you choose the right model so you have the right interface available. Options include RS-232 (with a MAX232 adapter), RS-485 (with a suitable RS-485 shield), CAN (with a suitable CAN shield), Ethernet (with a suitable Ehernet shield) and maybe even the USB version (with the USB Host shield), though the latter is less likely to work.

Pick one that suits your needs best.


body:
I quit using the Arduino IDE, instead I am now using Crosspack via the command line on my Mac.

It is working totally fine. I use "make" to compile it, "make flash" to upload it to the Arduino.

This is the Makefile I got right now:

    # Name: Makefile
    # Author: <insert your name here>
    # Copyright: <insert your copyright message here>
    # License: <insert your license reference here>

    # This is a prototype Makefile. Modify it according to your needs.
    # You should at least check the settings for
    # DEVICE ....... The AVR device you compile for
    # CLOCK ........ Target AVR clock rate in Hertz
    # OBJECTS ...... The object files created from your source files. This list is
    #                usually the same as the list of source files with suffix ".o".
    # PROGRAMMER ... Options to avrdude which define the hardware you use for
    #                uploading to the AVR and the interface where this hardware
    #                is connected. We recommend that you leave it undefined and
    #                add settings like this to your ~/.avrduderc file:
    #                   default_programmer = "stk500v2"
    #                   default_serial = "avrdoper"
    # FUSES ........ Parameters for avrdude to flash the fuses appropriately.

    DEVICE     = atmega328p
    CLOCK      = 16000000    # 16 MHz for Arduino
    PROGRAMMER = #-c stk500v2 -P avrdoper <-- leave this commented since we already specified the default programmer above
    FUSES      = -U lfuse:w:0xFF:m -U hfuse:w:0xDE:m -U efuse:w:0x05:m # arduino defaults
    OBJECTS    = main.o

    # ATMega8 fuse bits used above (fuse bits for other devices are different!):
    # Example for 8 MHz internal oscillator
    # Fuse high byte:
    # 0xd9 = 1 1 0 1   1 0 0 1 <-- BOOTRST (boot reset vector at 0x0000)
    #        ^ ^ ^ ^   ^ ^ ^------ BOOTSZ0
    #        | | | |   | +-------- BOOTSZ1
    #        | | | |   +---------- EESAVE (set to 0 to preserve EEPROM over chip erase)
    #        | | | +-------------- CKOPT (clock option, depends on oscillator type)
    #        | | +---------------- SPIEN (if set to 1, serial programming is disabled)
    #        | +------------------ WDTON (if set to 0, watchdog is always on)
    #        +-------------------- RSTDISBL (if set to 0, RESET pin is disabled)
    # Fuse low byte:
    # 0x24 = 0 0 1 0   0 1 0 0
    #        ^ ^ \ /   \--+--/
    #        | |  |       +------- CKSEL 3..0 (8M internal RC)
    #        | |  +--------------- SUT 1..0 (slowly rising power)
    #        | +------------------ BODEN (if 0, brown-out detector is enabled)
    #        +-------------------- BODLEVEL (if 0: 4V, if 1: 2.7V)
    #
    # For computing fuse byte values for other devices and options see
    # the fuse bit calculator at http://www.engbedded.com/fusecalc/

    # Tune the lines below only if you know what you are doing:

    AVRDUDE = avrdude $(PROGRAMMER) -p $(DEVICE)
    COMPILE = avr-gcc -Wall -Os -DF_CPU=$(CLOCK) -mmcu=$(DEVICE)

    # symbolic targets:
    all: main.hex

    .c.o:
     $(COMPILE) -c $< -o $@

    .S.o:
     $(COMPILE) -x assembler-with-cpp -c $< -o $@
    # "-x assembler-with-cpp" should not be necessary since this is the default
    # file type for the .S (with capital S) extension. However, upper case
    # characters are not always preserved on Windows. To ensure WinAVR
    # compatibility define the file type manually.

    .c.s:
     $(COMPILE) -S $< -o $@

    flash: all
     $(AVRDUDE) -U flash:w:main.hex:i

    fuse:
     $(AVRDUDE) $(FUSES)

    # Xcode uses the Makefile targets "", "clean" and "install"
    install: flash fuse

    # if you use a bootloader, change the command below appropriately:
    load: all
     bootloadHID main.hex

    clean:
     rm -f main.hex main.elf $(OBJECTS)

    # file targets:
    main.elf: $(OBJECTS)
     $(COMPILE) -o main.elf $(OBJECTS)

    main.hex: main.elf
     rm -f main.hex
     avr-objcopy -j .text -j .data -O ihex main.elf main.hex
     avr-size --format=avr --mcu=$(DEVICE) main.elf
    # If you have an EEPROM section, you must also create a hex file for the
    # EEPROM and add it to the "flash" target.

    # Targets for code debugging and analysis:
    disasm: main.elf
     avr-objdump -d main.elf

    cpp:
     $(COMPILE) -E main.c

I cannot just include "Arduino.h", but I need (want) to use it anyway.

My question is how I would go about doing that? I know where Arduino.h is located, but I cannot just copy that file to the project folder because it needs other files too.

If more info is needed, please let me know.

title: Crosspack instead of Arduino IDE, how to include Arduino.h

Answers: 1

body:
You need to compile all the core `.c`, `.cpp` and `.S` files into `.o` files (optionally archiving them into a `.a` file) then link them with your main program. Your main program will then become a sketch where you use `setup()` and `loop()` instead of `main()` since the `main.cpp` file in the core has `main()` in it. Of course you need to include `Arduino.h` in your source files as well or nothing will work.

The same goes for libraries. You need to compile and link the source code with your code as well as including the header file(s) in your code (and providing the paths to them with `-I...` directives).