body:
I think you need something like a relay driver.

On this site:

http://www.learningaboutelectronics.com/Articles/Relay-driver-circuit.php

i found this picture:

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

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

In "practical electronics for inventors (fourth edition)" is a similar picture with following text on page 445:

**"Here, an npn transistor is used to control a relay. When the transistor's base receives a control voltage/current, the transistor will turn on, allowing current to flow through the relay coil and causing the relay to switch states. The diode is used to eliminate voltage spikes created by the relay's coil. The relay must be chosen according to the proper voltage rating, etc."**

You can replace the relay with the magnet. But you will still need a diode. When you switch off the magnet it will generate a voltage and will try to push the current (there is energy saved in the coil). This diode will help it to unload the energy. Otherwise this energy can destroy something.


sender: user

message:
Pass a char array to a function that uses File as parameter

I am in serious need for help here. I have a rather small function that get's the number of files from within a given directory. Now, the directory name (that is the path) is stored in a char array within my main loop.

My problem is, I have no idea how to pass this char array to my function.

This is my code (it's of course just a subset but it's the part that is obviously wrong) and you can also see the complete program at the end:

In the setup() routine I define my current working directory:

    char plrCurrentFolder[9];

In the main loop I want to get the number of files of a given directory (in the final program this directory name will come from an NFC tag):

    String temp = "findorie";
    temp.toCharArray(plrCurrentFolder, 9);
    unsigned int numberOfFiles = countFiles(plrCurrentFolder);

This is the function to return the number of files:

    unsigned int countFiles(File dir){
      unsigned int counter = 0;
      while (true){
        File entry = dir.openNextFile();
        if (!entry){
          // no more files
          break;
        }
        counter++;
        entry.close();
      }
      dir.close();
      return counter;
    }

To be honest I have two issues with this. First, I don't really like to create a temp String variable to create the char array here as I would rather stick with the char array in itself to safe on memory and maybe this would also aid in performance (although I'm not sure about that).

**Second, The way this whole thing is structured right now, it simply doesn't work. When building, the compiler correctly complains:**

    exit status 1
    could not convert '(char*)(& plrCurrentFolder)' from 'char*' to 'SDLib::File'

Can anyone help me out and give me a code snippet how to make this work???

Kind regards to all,

Christian

--- below you may find the complete code as of now ---

    /*
     * Fairytale Main program
     *
     * This programm will read an nfc tag. It will check for a directory name and optional a filename
     * and start playing this on the music maker shield.
     *
     * Restrictions:
     * 1. All filenames mus be in the format  trackXXX.mp3  - where XXX is a numbering from 001 to 999
     * 2. All directory names must be exactly 8 chars long
     *
     */

    // make sure to change this to 0 before uploading in production as it turns on lots and lots of serial messages
    #define DEBUG 1
    // we only show light effects, in case this is set to 1
    #define LIGHTEFFECTS 0
    // we only use the nfc reader if this is set to 1
    #define NFCREADER 0

    //
    // setup SPI, MP3 and SD libraries
    //
    #include <SPI.h>
    #include <Adafruit_VS1053.h>
    #include <SD.h>
    // These are the pins used for the music maker shield
    #define SHIELD_RESET  -1     // VS1053 reset pin (unused!)
    #define SHIELD_CS     7      // VS1053 chip select pin (output)
    #define SHIELD_DCS    6      // VS1053 Data/command select pin (output)
    #define CLK 13 // SPI Clock, shared with SD card
    #define MISO 12 // Input data, from VS1053/SD card
    #define MOSI 11 // Output data, to VS1053/SD card

    // These are common pins between breakout and shield
    #define CARDCS 4     // Card chip select pin
    // DREQ should be an Int pin, see http://arduino.cc/en/Reference/attachInterrupt
    #define DREQ 3       // VS1053 Data request, ideally an Interrupt pin

    Adafruit_VS1053_FilePlayer musicPlayer =
      // create shield-example object!
      Adafruit_VS1053_FilePlayer(SHIELD_RESET, SHIELD_CS, SHIELD_DCS, DREQ, CARDCS);

    //
    // setup NFC Adapter
    //
    #ifdef NFCREADER
    /*
      #include <PN532_SPI.h>
      #include <PN532.h>
      #include <NfcAdapter.h>

      #define PN532_SCK (13) //changed from pin 2
      #define PN532_MISO (12) //changed from pin 5
      #define PN532_MOSI (11) //changed from pin 3
      #define PN532_SS (10) //changed from 4

      PN532_SPI pn532spi(SPI, PN532_SS);
      NfcAdapter nfc = NfcAdapter(pn532spi);
    */
    #endif

    // these variables are used for the light effects
    int lightValue1, lightValue2, lightValue3;
    const int redPin = 7;
    const int greenPin = 8;
    const int bluePin = 9;

    // these are timing counters for the light effects
    long time=0;
    int periode = 20000;
    int displace = 500;

    // uptime counters
    unsigned int runCounter = 0;
    unsigned long startUpTime = 0;
    const unsigned long maxUpTime = 120000; // 1800000L;  // 30 Minutes

    // these are variables for the nfc card
    boolean cardScanned = false;    // did we already scan the card?? using this to suppress reading in the card data while it is on the reader
    char cardId[16];                // the uid of the card as read in through the nfc reader

    // mp3 player variables
    boolean plrIsPlaying = false;                         // is the mp3 player already playing?
    char plrCurrentFile[13];                              // which track is the player playing?
    char plrNextFile[13];                                 // which track is the player playing?
    char plrPrevFile[13];                                 // which track is the player playing?
    char plrCurrentFolder[9];                             // which directory is the player playing?
    uint8_t plrCurrentPosition = 0;                       // on which position in seconds are we in the current track?
    char currentTrackFileName[] = "/system/current.txt";  // a file we might use to store the last played track

    // volume control variables for the analog poti
    int volumePotPin = A0;        // the analog input pin that we use for the potentiometer
    int sensorDrift = 7;          // difference to last received sensor value that must be exceeded to activate a change in the volume
    int compareValue = 0;         // just a convenience variable to make comparison easier
    int sensorValue = 0;          // read the value from the potentiometer
    int lastSensorValue = 0;      // keeps the last read sensor value
    uint8_t soundVolume = 0;      // the sound volume is derived via a map function from the sensor value

    // other button settings
    int btnLinePin = A1;         // pin on which the button line (4 buttons) is connected
    int btnVal = 0;

    // these are the prototypes for the nfc card reader
    void getNfcCardData();

    // these are the prototypes for the mp3 player controller
    uint8_t getVolume(void);        // function that returns the volume setting based on the analog read
    char plrNext(void);             // play next file in album
    char plrPrev(void);             // play previous file in album
    void plrPlayTrack(char, char);  // play a single track
    void setupSound(void);          // initializes the sound system and plays the startup sound

    // these are the prototypes to work on files
    void printDirectory(File, int);   // print out the content of specified directory on serial console
    unsigned int countFiles(File);    // return the number of files in a directory passed as a File descriptor
    //unsigned int countFiles(char[]);    // return the number of files in a directory passed as a File descriptor

    // these are the prototypes for the light effects
    void fader(void);
    void startuplight(void);
    void highlight(int);
    void flash(int);
    void pulse(int);

    void setup() {
      #ifdef DEBUG
        Serial.begin(115200);
      #endif

      plrCurrentFile[0] = 0; // we initialize the fiirst element of the array to 0 to later check if a current file was given.

      // initialise the music player
      if (! musicPlayer.begin()) { // initialise the music player
        #ifdef DEBUG
          Serial.println(F("Couldn't find VS1053, do you have the right pins defined?"));
        #endif
        while (1);
      }
      #ifdef DEBUG
        Serial.println(F("Music Maker Shield VS1053 found"));
      #endif

      //musicPlayer.sineTest(0x44, 500);    // Make a tone to indicate VS1053 is working

      if (!SD.begin(CARDCS)) {
        #ifdef DEBUG
          Serial.println(F("failed to detect the SD-Card"));
        #endif
        while (1);  // don't do anything more
      }
      #ifdef DEBUG
        Serial.println("SD found and operational");
      #endif

      // set the buttons as input
      pinMode(volumePotPin, INPUT);
      pinMode(btnLinePin, INPUT);

      // setup music maker shield and start playing startup file
      setupSound();

      #ifdef DEBUG
        // list files
        printDirectory(SD.open("/"), 0);
      #endif

    /*
      // now as the last thing, start the nfc reader
      #ifdef DEBUG
        Serial.print("initializing NFC TAG reader ... ");
      #endif
      nfc.begin();
      delay(1000); // wait some time for
    */

      // check our current time, so we know when to stop
      startUpTime = millis();
      #ifdef DEBUG
        Serial.println("we are up and running and ready to play audio");
      #endif
    }

    //
    //      LL       OOOOOO    OOOOOO   PPPPPPP
    //      LL      OO    OO  OO    OO  PP    PP
    //      LL      OO    OO  OO    OO  PP    PP
    //      LL      OO    OO  OO    OO  PPPPPP
    //      LLLLLL   OOOOOO    OOOOOO   PP
    void loop() {
      #ifdef LIGHTEFFECTS
        // turn off all the lights. we only want to have fading lights, while the playr is active
        //analogWrite(redPin, 0);
        //analogWrite(greenPin, 0);
        //analogWrite(bluePin, 0);
      #endif

      // NFC Tag reader functions
      // now we only do this, when an nfc tag is present
    /*
      if (nfc.tagPresent()){
        Serial.println("NFC tag Found!\n");
        NfcTag tag = nfc.read();
        Serial.print("Tag Type: ");
        Serial.println(tag.getTagType());
        Serial.print("UID: ");
        Serial.println(tag.getUidString());

        getNfcCardData();
    */

        String temp = "findorie";
        temp.toCharArray(plrCurrentFolder, 9);

        // now let's get the number of files in the album directory
        //unsigned int numberOfFiles = 0;
        unsigned int numberOfFiles = countFiles(plrCurrentFolder);
        #ifdef DEBUG
          Serial.print("Directory ");Serial.print(plrCurrentFolder);Serial.print(" contains ");Serial.print(numberOfFiles);Serial.println(" files");
        #endif

        // if we did not get the current file from the tag, we are hardcoding it to track001.mp3
        if ((plrCurrentFile[0] == 0)) {
          temp = "track001.mp3";
          temp.toCharArray(plrCurrentFile, 13);
        }

        #ifdef DEBUG
          Serial.print("currentFolder holds: ");Serial.print(plrCurrentFolder);Serial.print(" / currentFile contains: ");Serial.print(plrCurrentFile);
        #endif

        temp = "/";
        temp.concat(plrCurrentFolder);
        temp.concat("/");
        temp.concat(plrCurrentFile);
        char filename[temp.length() + 1];
        temp.toCharArray(filename, sizeof(filename));
        Serial.print(" / filename contains: ");Serial.println(filename);

        if (SD.exists(filename)) {
          Serial.print(filename);Serial.println(" exists.");

          // mp3 player functions playback
          // Start playing a file, then we can do stuff while waiting for it to finish
          if (! musicPlayer.startPlayingFile(filename)) {
            #ifdef DEBUG
              Serial.print("Could not open file ");Serial.println(filename);
            #endif
            while (1);
          }
          #ifdef DEBUG
            Serial.print(F("Start playing "));Serial.println(filename);
          #endif

          while (musicPlayer.playingMusic) {
            // file is now playing in the 'background' so now's a good time
            // to do something else like handling LEDs or buttons :)

            // play some nice light effects, if wanted
            #ifdef LIGHTEFFECTS
              //fader();
            #endif

            // volume control functions
            // read the input on analog pin 0 and check if we have a change in volume.
            sensorValue = analogRead(volumePotPin);
            if (lastSensorValue > sensorValue) {compareValue = lastSensorValue - sensorValue;} else {compareValue = sensorValue - lastSensorValue;}
            // If we have a high enough difference in the sensor reading, calculate it so we may set it on the player
            if (compareValue > sensorDrift){
              #ifdef DEBUG
                Serial.print("changing volume: ");
              #endif
              soundVolume = getVolume();
              musicPlayer.setVolume(soundVolume,soundVolume);
            }
          }
          #ifdef DEBUG
            Serial.println("Done playing ");Serial.println(filename);
          #endif
          #ifdef LIGHTEFFECTS
            //startuplight();
          #endif
        } else {
          Serial.print(filename);Serial.println(" does not exist.");
        } // end of file does not exist

      //} // end of tag found
    } // end of loop

    //
    //        NN    NN  FFFFFF   CCCCCC
    //        NNNN  NN  FF      CC
    //        NN  N NN  FFFF    CC
    //        NN  NNNN  FF      CC
    //        NN    NN  FF       CCCCCC
    //  BELOW THIS LINE THE NFC CONTROL IS DEFINED
    //
    void getNfcCardData(){
    /*
      NfcTag tag = nfc.read();
      boolean usableContent = false;
      if (tag.hasNdefMessage()){
        NdefMessage message = tag.getNdefMessage();

        // If you have more than 1 Message then it wil cycle through them
        int recordCount = message.getRecordCount();
        for (int i = 0; i < recordCount; i++) {
          NdefRecord record = message.getRecord(i);

          int payloadLength = record.getPayloadLength();
          byte payload[payloadLength];
          record.getPayload(payload);

          String payloadAsString = ""; // Processes the message as a string vs as a HEX value
          for (int c = 0; c < payloadLength; c++) {
            payloadAsString += (char)payload[c];
          }

          String cleanString = payloadAsString;
          cleanString.remove(0,3);
          #ifdef DEBUG
            Serial.print("content element "); Serial.print(i); Serial.print(": "); Serial.println(cleanString);
          #endif

          // now populate the vars for the player
          int spacePosition = cleanString.indexOf(':');
          if (cleanString.charAt(spacePosition - 1) == 'A') {
            String contentString = cleanString.substring(3);
            #ifdef DEBUG
              Serial.print("Album info: ");Serial.println(contentString);
            #endif
          }
          if (cleanString.charAt(spacePosition - 1) == 'D') {
            usableContent = true;
            String contentString = cleanString.substring(3);
            plrCurrentFolder = contentString;
            #ifdef DEBUG
              Serial.print("Directory: ");Serial.println(contentString);
            #endif
          }
          if (cleanString.charAt(spacePosition - 1) == 'T') {
            String contentString = cleanString.substring(3);
            plrCurrentFile = contentString;
            #ifdef DEBUG
              Serial.print("Track: ");Serial.println(contentString);
            #endif
          }
          if (cleanString.charAt(spacePosition - 1) == 'P') {
            String contentString = cleanString.substring(3);
            plrCurrentPosition = contentString.toInt();
            #ifdef DEBUG
              Serial.print("Position: ");Serial.println(contentString);
            #endif
          }

          String uid = record.getId();
          if (uid != "") {
            #ifdef DEBUG
              Serial.print("  ID: ");
              Serial.println(uid);
            #endif
          }
        }
        if (!usableContent){
          #ifdef DEBUG
            Serial.println("THIS CARD DOES NOT HAVE THE NECESSARY MESSAGES FOR THE MP3 PLAYER");
          #endif
        }
      } else { // does the card have NDEF messages?
        #ifdef DEBUG
          Serial.println("THIS CARD DOES NOT HAVE MESSAGES AT ALL - NOT USABLE FOR THE MP3 PLAYER");
        #endif
      }
    */
    }

    //
    //        MM      MM   PPPPPP   33333
    //        MMMM  MMMM  PP    PP      33
    //        MM  MM  MM  PP    PP    3333
    //        MM      MM  PPPPPP        33
    //        MM      MM  PP        33333
    //  BELOW THIS LINE THE MP3 PLAYER CONTROL IS DEFINED
    //
    uint8_t getVolume(){
      soundVolume = map(sensorValue, 0, 1023, 0, 100); // map the sensor value to a sound volume

      #ifdef DEBUG
        Serial.print("last sensor value (if any) was ");Serial.print(lastSensorValue);Serial.print(" / new sensor value is ");Serial.print(sensorValue);Serial.print(" which is a volume of ");Serial.println(soundVolume);
      #endif
      lastSensorValue = sensorValue;
      return (soundVolume);
    }

    void plrPlayTrack(char dir, char file) {
      String temp = "/";
      temp.concat(dir);
      temp.concat("/");
      temp.concat(file);
      char myFile[temp.length() + 1];
      temp.toCharArray(myFile, sizeof(myFile));

      // mp3 player functions playback
      // Start playing a file, then we can do stuff while waiting for it to finish
      if (! musicPlayer.startPlayingFile(myFile)) {
        #ifdef DEBUG
          Serial.print("Could not open file ");Serial.println(myFile);
        #endif
        while (1);
      }
      #ifdef DEBUG
        Serial.print(F("Start playing "));Serial.println(myFile);
      #endif

      while (musicPlayer.playingMusic) {
        // file is now playing in the 'background' so now's a good time
        // to do something else like handling LEDs or buttons :)
        #ifdef DEBUG
          Serial.print(".");
        #endif
        #ifdef LIGHTEFFECTS
          //fader();
        #endif

      }
      #ifdef DEBUG
        Serial.println("Done playing ");Serial.println(myFile);
      #endif
    }

    char plrNext(void){
      char track[12] = "track003.mp3";
      #ifdef DEBUG
        Serial.println("plrNext toggled");
      #endif
      #ifdef LIGHTEFFECTS
        //pulse(bluePin);
      #endif

      return track;
    }
    char plrPrev(void){
      char track[12] = "track001.mp3";
      #ifdef DEBUG
        Serial.println("plrPrevious toggled");
      #endif
      #ifdef LIGHTEFFECTS
        //pulse(greenPin);
      #endif

      return track;
    }

    void setupSound(){
      // This option uses a pin interrupt. No timers required! But DREQ
      // must be on an interrupt pin. For Uno/Duemilanove/Diecimilla
      // that's Digital #2 or #3
      // See http://arduino.cc/en/Reference/attachInterrupt for other pins
      // *** This method is preferred
      if (! musicPlayer.useInterrupt(VS1053_FILEPLAYER_PIN_INT)) {
        #ifdef DEBUG
          Serial.println(F("DREQ pin is not an interrupt pin"));
        #endif
        while (1);
      }

      // Start playing a file, then we can do stuff while waiting for it to finish
      if (! musicPlayer.startPlayingFile("hello.mp3")) {
        #ifdef DEBUG
          Serial.println("Could not open file hello.mp3");
        #endif
      } else {
        #ifdef DEBUG
          Serial.print("playing welcome file hello.mp3 ");
        #endif
      }

      // now we play the welcome sound
      startUpTime = millis();
      while (musicPlayer.playingMusic) {
        if (millis() - startUpTime > 500) {
          #ifdef DEBUG
            Serial.print(".");
          #endif
          startUpTime = millis();
        }
        // file is now playing in the 'background' so now's a good time
        // to do something else like handling LEDs or buttons :)
        #ifdef LIGHTEFFECTS
          //startuplight();
        #endif
      }
      #ifdef DEBUG
        Serial.println(" done");
      #endif
      getVolume();
      musicPlayer.setVolume(soundVolume,soundVolume);
    }

    //
    //        FFFFFF  II  LL      EEEEEE
    //        FF      II  LL      EE
    //        FFFF    II  LL      EEEE
    //        FF      II  LL      EE
    //        FF      II  LLLLLL  EEEEEE
    // BELOW THIS LINE THE FILE HELPER FUNCTIONS CAN BE FOUND
    //
    // counts the number of files in directory
    //unsigned int countFiles(char dir[]){

    unsigned int countFiles(File dir){
      unsigned int counter = 0;
      while (true){
        File entry = dir.openNextFile();
        if (!entry){
          // no more files
          break;
        }
        counter++;
        entry.close();
      }
      dir.close();
      return counter;
    }

    // store last played track
    void rememberCurrentTrack(){

    }

    // read last played track
    void getLastPlayedTrack(){

    }

    // File listing helper
    void printDirectory(File dir, int numTabs) {
       while(true) {
         File entry =  dir.openNextFile();
         if (! entry) {
           // no more files
           //Serial.println("**nomorefiles**");
           break;
         }
         for (uint8_t i=0; i<numTabs; i++) {
           Serial.print('\t');
         }
         Serial.print(entry.name());
         if (entry.isDirectory()) {
           Serial.println("/");
           printDirectory(entry, numTabs+1);
         } else {
           // files have sizes, directories do not
           Serial.print("\t\t");
           Serial.println(entry.size(), DEC);
         }
         entry.close();
       }
    }

    //
    //        LL      EEEEEE  DDDDDD
    //        LL      EE      DD    DD
    //        LL      EEEE    DD    DD
    //        LL      EE      DD    DD
    //        LLLLLL  EEEEEE  DDDDDD
    //  BELOW THIS LINE THE LIGHT EFFECTS ARE DEFINED
    //
    // fading organically
    void fader(){
      time = millis();
      lightValue1 = 128+127*cos(2*PI/periode*time);
      lightValue2 = 128+127*cos(2*PI/periode*(displace-time));
      lightValue3 = 128+127*cos(2*PI/periode*(2*displace-time));
      analogWrite(redPin, lightValue1);           // sets the value (range from 0 to 255)
      analogWrite(greenPin, lightValue2);        // sets the value (range from 0 to 255)
      analogWrite(bluePin, lightValue3);         // sets the value (range from 0 to 255)
    }
    // illuminate the 3 led with some fancy lightning during startup
    void startuplight(){
      for (int i = 0; i<150; i++) {
        analogWrite(redPin, i);
        analogWrite(greenPin, i);
        analogWrite(bluePin, i);
        delay(10);
      }
      for (int i = 150; i>0; i--) {
        analogWrite(redPin, i);
        analogWrite(greenPin, i);
        analogWrite(bluePin, i);
        delay(10);
      }
      analogWrite(redPin, 0);
      analogWrite(greenPin, 0);
      analogWrite(bluePin, 0);
    }
    //turn on the desired pin for 5000 milliseconds
    void highlight(int pin){
      time = millis();
      while (millis()<time+5000){
        analogWrite(pin, 255);
      }
      analogWrite(pin, 0);
    }
    //turn on the desired pin for 5000 milliseconds
    void flash(int pin){
      time = millis();
      while (millis()<time+1000){
        analogWrite(pin, 255);
      }
      analogWrite(pin, 0);
    }
    //turn on the desired pin for 5000 milliseconds
    void pulse(int pin){
      for (int i=0;i<3;i++){
        time = millis();
        while (millis()<time+2500){
          analogWrite(pin, 255);
        }
        analogWrite(pin, 0);
      }
    }

sender: assistant

body:
OMG. I'm so sorry for posting such a stupid question. And I'm also sorry for not seeing the obvious even after Majenko pointed me to it.

Of course I need to call the function like this:

    numberOfFiles = countFiles(SD.open(plrCurrentFolder));

That way, the directory get's opened and my function can operate on it.

I see I still have to learn a lot :-)


message:
Unclear GET request mixed values

In my Uno code, I access to a page in my server and retrieve that value and make decision upon that value.

I get this kind of response,

    Connected to server
    on
    on
    off
    off
    on
    off
    [WiFiEsp] TIMEOUT: 116

    Disconnecting from server.

Which should just be `on` or `off`.

This is my code for testing :

    #include "WiFiEsp.h"

    // Emulate Serial1 on pins 6/7 if not present
    #ifndef HAVE_HWSERIAL1
    #include "SoftwareSerial.h"
    SoftwareSerial Serial1(2,3); // RX, TX
    #endif

    char ssid[] = "RPi";            // your network SSID (name)
    char pass[] = "raspberry";        // your network password
    int status = WL_IDLE_STATUS;     // the Wifi radio's status

    char server[] = "192.168.50.1";

    // Initialize the Ethernet client object
    WiFiEspClient client;

    int c =0;
    int testLED = 12;

    void setup()
    {
      pinMode(testLED, OUTPUT);
      // initialize serial for debugging
      Serial.begin(9600);
      // initialize serial for ESP module
      Serial1.begin(9600);
      // initialize ESP module
      WiFi.init(&Serial1);

      // check for the presence of the shield
      if (WiFi.status() == WL_NO_SHIELD) {
        Serial.println("WiFi shield not present");
        // don't continue
        while (true);
      }

      // attempt to connect to WiFi network
      while ( status != WL_CONNECTED) {
        Serial.print("Attempting to connect to WPA SSID: ");
        Serial.println(ssid);
        // Connect to WPA/WPA2 network
        status = WiFi.begin(ssid, pass);
      }

      // you're connected now, so print out the data
      Serial.println("You're connected to the network");

      printWifiStatus();

      Serial.println();
      Serial.println("Starting connection to server...");
      // if you get a connection, report back via serial
      if (client.connect(server, 80)) {
        Serial.println("Connected to server");
        // Make a HTTP request
        client.println("GET /simple.txt HTTP/1.1");
        client.println("Host: localhost");
        client.println("Connection: close");
        client.println();
      }
    }

    void loop()
    {
      // if there are incoming bytes available
      // from the server, read them and print them
      if (client.available()) {
         c = client.read();

         switch(c){
              case '0':
                     Serial.println("off");
                     digitalWrite(testLED, LOW);
                     delay(2500);
                     break;

              case '1':
                     Serial.println("on");
                     digitalWrite(testLED, HIGH);
                     delay(2500);
                     break;
          }
            }

      // if the server's disconnected, stop the client
      if (!client.connected()) {
        Serial.println();
        Serial.println("Disconnecting from server...");
        client.stop();

        // do nothing forevermore
        while (true);
      }
    }

    void printWifiStatus()
    {
      // print the SSID of the network you're attached to
      Serial.print("SSID: ");
      Serial.println(WiFi.SSID());

      // print your WiFi shield's IP address
      IPAddress ip = WiFi.localIP();
      Serial.print("IP Address: ");
      Serial.println(ip);

      // print the received signal strength
      long rssi = WiFi.RSSI();
      Serial.print("Signal strength (RSSI):");
      Serial.print(rssi);
      Serial.println(" dBm");
    }

My `simple.txt` file just has 1.

Why this code outputs a gibberish value? Is it a problem with the way I retrive data?
Raspberry pi is working as my network server.

Thanks in advance.

body:
When you send a GET request in HTTP you get a HTTP response back, not just the contents of the file you requested.

For instance, your request may result in a response of:

    HTTP/1.1 200 OK
    Date: Thu, 28 Dec 2017 11:02:21 GMT
    Server: Apache/2.4.25 (Ubuntu)
    Last-Modified: Wed, 05 Apr 2017 09:40:30 GMT
    ETag: "2c39-54c682ee19688"
    Accept-Ranges: bytes
    Content-Length: 3
    Vary: Accept-Encoding
    Connection: close
    Content-Type: text/plain

    1

As you can see there's plenty of occurrences of 0 and 1 in there to trigger your LED.

You need to parse the incoming data better. Read it line by line and only start reacting to the content after the blank line that indicates the division between header and body.


body:
I found the answer for my question. @Majenko's answer helped me a lot.

I removed HTTP response given by the server and just changed few line in my original code. Also added `#` in-front of the number in my server's `simple.txt` file.

Also this [arduino-forum post][1]

    void loop()
    {
      // if there are incoming bytes available
      // from the server, read them and print them
    while(client.available() > 0)
    {
      char c = client.read();
      if(c == '#')
      {
         while(client.available() == 0) { } // Do nothing while we wait for the next value
         c = client.read();
         if(c == '1'){
            Serial.println("On");
            digitalWrite(testLED, HIGH);
            delay(2500);
         }
         else if(c == '0'){
            Serial.println("Off");
            digitalWrite(testLED, LOW);
            delay(2500);
         }
      }
    }

      // if the server's disconnected, stop the client
      if (!client.connected()) {
        Serial.println();
        Serial.println("Disconnecting from server...");
        //client.stop();

        // do nothing forevermore
        while (true);
      }
    }

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


message:
RF receiver for integer only, how to cast uint8_t to int?

I'm using the RadioHead library with ASK Driver to transmit/receive data with generic RF modules. It works fine, but I'm lacking some knowledge in programming the code to use the data received. Most examples I could find show how to send a string, but I only need to send and receive an integer.

I'm sending the decimal value '1' through the **transmitter**:

        uint8_t *data;
        uint8_t value;

        void loop() {
        value = 1;
        data = &value;
        driver.send(data, sizeof(value));
        driver.waitPacketSent();
        delay(200);
        }

And I have in the **receiver**:

    void loop() {
      uint8_t buf[RH_ASK_MAX_MESSAGE_LEN];
      uint8_t buflen = sizeof(buf);
      int value;

      if (driver.recv(buf, &buflen)) {
        driver.printBuffer("Received:", buf, buflen); //prints 1.
        value = (int) buf; //my attempt to cast
        Serial.println(value); // the output is 2233, so this is wrong.
      }
      if (value == 1){ //example
      Serial.println("good");
      }
    }

So what I think it is, I'm receiving bytes from the transmitter, which the library function 'driver.printBuffer' reinterprets as decimals and prints the value '1'. But how do I interpret (or cast) this as an integer so I can use it for other things like in the example (If condition) at the end? Any help is very much appreciated. Thanks.

body: `buf` is a pointer to the received bytes. Try `value = buf[0];` instead.


message:
Arduino Due not executing code after power on

My Arduino Due does not execute its code when powered on after being powered off for ten seconds or longer. I have to press the reset button for the code to execute.

I've read some older threads about a firmware issue and saw people doing solder jobs on their boards to fix it.

My question is, does this issue happen with all/any Arduino Due boards? Are just some clones (like mine) affected and the original works fine?

What's the best way to fix this problem? In this state the board serves no purpose anymore and I've downgraded to the Uno for now.

EDIT: Adding picture and link to the board used.
https://www.amazon.de/gp/product/B016D5KYF6/ref=oh_aui_detailpage_o00_s00?ie=UTF8&psc=1

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

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

body:
After some more research I found out that

a) the issue applies to some Due boards only, not all

b) newer boards seem to have fixed the issue

c) there's a software (firmware update) and hardware (10k resistor) solution

I went with the hardware fix shown here:
http://www.dimdim.gr/2016/03/fixing-startup-issues-with-arduino-dues/

I did not have an SMD resistor at hand, so mine looks ancient but does the job.
Hope that helps others, too.

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

addendum:

The problem occurs only on some DUE boards and is due to some undocumented behaviour of the ATSAM3X8E processor combined with the behaviour of some MOSFETS installed on the DUE boards. So its occurence is largely a matter of luck.

The fix is simple: you just solder a 10K resistor across the top of this mosfet:

resistor about to be soldered on

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

resistor designated as R99

[![enter image description here][3]][3]

  [1]: https://i.stack.imgur.com/gywtn.jpg
  [2]: https://i.stack.imgur.com/FX8a7.jpg
  [3]: https://i.stack.imgur.com/ZeWgn.png


message:
Where is the definition of system_adc_read() in the esp8266 Arduino code?

Where is the definition of [`uint16 system_adc_read(void)`][1] in the [esp8266 Arduino code][2]?

I can see it being declared in `Arduino/tools/sdk/include/user_interface.h`, however there seems to be no definition of this. `system_adc_read()` gets called in [`analogRead()`][3] in `Arduino/cores/esp8266/core_esp8266_wiring_analog.c`

I suspect `system_adc_read()` calls [`system_adc_read_fast()`][4] to read the ADC, but can't actually find it in the code! Could somebody please point me to this? I've been struggling for quite some time.

***Purpose:** To manipulate the system_adc_read() in ESP8266 to get higher ADC sampling rates. Right now ADC sampling rate is 10ksps. I want it to be more than 30-40ksps.*

  [1]: https://github.com/esp8266/Arduino/blob/d24a358817f0c11f7087b3c8acbf24629b15998f/tools/sdk/include/user_interface.h#L119
  [2]: https://github.com/esp8266/Arduino
  [3]: https://github.com/esp8266/Arduino/blob/4897e0006b5b0123a2fa31f67b14a3fff65ce561/cores/esp8266/core_esp8266_wiring_analog.c#L33
  [4]: https://github.com/esp8266/Arduino/blob/d24a358817f0c11f7087b3c8acbf24629b15998f/tools/sdk/include/user_interface.h#L120

body:
The "definition" of `uint16 system_adc_read(void)` is inside the compiled archive/object file `libmain.a` inside one of the `NONOSDK` folders which is located in `/tools/sdk/lib/` . The version is selected in `platform.txt`. For example in my platform.txt:

    # default SDK for all boards
    # (generic board overrides this variable)
    build.sdk=NONOSDK22x_190703
    #build.sdk=NONOSDK22x_191024
    #build.sdk=NONOSDK22x_191105

Running the `xtensa-lx106-elf-objdump.exe -d` on this file I can find this section inside:

    00000258 <system_adc_read>:
         258: 020c                 movi.n a2, 0
         25a: f0c112                addi a1, a1, -16
         25d: 0109                 s32i.n a0, a1, 0
         25f: fffc01                l32r a0, 250 <system_pp_recycle_rx_pkt+0x18>
         262: 0000c0                callx0 a0
         265: fff901                l32r a0, 24c <system_pp_recycle_rx_pkt+0x14>
         268: f42020                extui a2, a2, 0, 16
         26b: 1b1207                beq a2, a0, 28a <system_adc_read+0x32>
         26e: b30c                 movi.n a3, 11
         270: 902220                addx2 a2, a2, a2
         273: 1122e0                slli a2, a2, 2
         276: fff701                l32r a0, 254 <system_pp_recycle_rx_pkt+0x1c>
         279: 0000c0                callx0 a0
         27c: f42020                extui a2, a2, 0, 16
         27f: 00a402                movi a0, 0x400
         282: 013027                bltu a0, a2, 287 <system_adc_read+0x2f>
         285: 020d                 mov.n a0, a2
         287: f42000                extui a2, a0, 0, 16
         28a: 0108                 l32i.n a0, a1, 0
         28c: 10c112                addi a1, a1, 16
         28f: f00d                 ret.n
         291: 00                       .byte 00
         292: 00                       .byte 00
         293: 00                       .byte 00
         294: ff ff 00 00
     ...

    000002a0 <system_adc_read_fast>:
         2a0: e0c112                addi a1, a1, -32
         2a3: 11c9                 s32i.n a12, a1, 4
         2a5: 21d9                 s32i.n a13, a1, 8
         2a7: 31e9                 s32i.n a14, a1, 12
         2a9: 5129                 s32i.n a2, a1, 20
         2ab: 41f9                 s32i.n a15, a1, 16
         2ad: 0109                 s32i.n a0, a1, 0
         2af: 03fd                 mov.n a15, a3
         2b1: fff901                l32r a0, 298 <system_adc_read+0x40>
         2b4: 0000c0                callx0 a0
         2b7: 4fbc                 beqz.n a15, 2ef <system_adc_read_fast+0x4f>
         2b9: fff6e1                l32r a14, 294 <system_adc_read+0x3c>
         2bc: 0c0c                 movi.n a12, 0
         2be: 51d8                 l32i.n a13, a1, 20
         2c0: 90dcd0                addx2 a13, a12, a13
         2c3: 001d32                l16ui a3, a13, 0
         2c6: 1a13e7                beq a3, a14, 2e4 <system_adc_read_fast+0x44>
         2c9: 902330                addx2 a2, a3, a3
         2cc: 1122e0                slli a2, a2, 2
         2cf: b30c                 movi.n a3, 11
         2d1: fff201                l32r a0, 29c <system_adc_read+0x44>
         2d4: 0000c0                callx0 a0
         2d7: f44020                extui a4, a2, 0, 16
         2da: 00a402                movi a0, 0x400
         2dd: 003d                 mov.n a3, a0
         2df: 013047                bltu a0, a4, 2e4 <system_adc_read_fast+0x44>
         2e2: 043d                 mov.n a3, a4
         2e4: 005d32                s16i a3, a13, 0
         2e7: cc1b                 addi.n a12, a12, 1
         2e9: f4c0c0                extui a12, a12, 0, 16
         2ec: ce9fc7                bne a15, a12, 2be <system_adc_read_fast+0x1e>
         2ef: 11c8                 l32i.n a12, a1, 4
         2f1: 21d8                 l32i.n a13, a1, 8
         2f3: 31e8                 l32i.n a14, a1, 12
         2f5: 41f8                 l32i.n a15, a1, 16
         2f7: 0108                 l32i.n a0, a1, 0
         2f9: 20c112                addi a1, a1, 32
         2fc: f00d                 ret.n
         2fe: 00                       .byte 00
         2ff: 00                       .byte 00
         300: ff ff 00 00
     ...


message:
Uno r3 - Can't get USB Keyboards to work with an USB Host Shield

I'm a day 1 beginner to Arduino, and I am trying to obtain input from a USB keyboard. I've connected the USB keyboard to an Arduino USB host shield attached to an Arduino Uno r3, and I am using the example HID sketch (USBHIDBootKeyboard.ino) provided with the USB Host Shield libraries : https://github.com/felis/USB_Host_Shield_2.0/blob/master/examples/HID/USBHIDBootKbd/USBHIDBootKbd.ino

I am powering the Arduino Uno r3 + USB Host Shield via USB. Upon init, only Start is written to the Serial Monitor. Tests show that SetReportParser exits with 0. Yet the keyboards are silent. I've tried three keyboards, all of which work properly when connected to the computer.

When using USBHidBootMouse.ino with a mouse, movements & buttons are perceived and print messages as intended.

https://www.circuitsathome.com/mcu/hid-support-for-usb-host-shield-library-2-0-released/ states that

> Also, it is recommended to use external power supply while working with HID devices – I’ve seen many devices which would refuse to function when Arduino receives power from its USB port only.

EDIT : I tried to test if the power was the issue, so I used a 5V generator with intensity measurement. The results are : the Arduino Uno r3 uses 60mA, the keyboard uses 60 mA, connecting to the serial port uses 40 mA (much to my surprise).

This means the keyboard's power requirements shouldn't be the problem.

Then what would the problem be ? I'm helpless here. If the library linked on the official Arduino site doesn't work, then it should mean i'm using it wrong.

body:
I looked for the difference between USBHIDBootMouse & USBHIDBootKbd, and noticed line 100,

>USBHub     Hub(&Usb);

was commented in the BootKbd side. Uncommenting it got the code to work.

I'm quite unsure how what interpretation to have from this. There should be a reason this line is commented in the library github.

Or maybe it is simply an error. In any case, uncommenting it got the code to work here.


body:
see last paragraph of this page https://github.com/felis/USB_Host_Shield_2.0

it says this:

> FAQ
>
>
> When I plug my device into the USB connector nothing happens?
>
>
> Try to connect a external power supply to the Arduino - this solves
> the problem in most cases.
>
>
> You can also use a powered hub between the device and the USB Host
> Shield.
>
>
> You should then include the USB hub library: `#include <usbhub.h>`
>
>
> and create the instance like so: `USBHub Hub1(&Usb);`.

your keyboard may be multiple HID devices with a USB hub to connect them


message:
A function-definition is not allowed here before '{' token

I'm trying to light up 81 on a 4-digit 7-segment display, but when I try to upload the code to my Uno R3 it gives me this error: "a function-definition is not allowed here before '{' token". I'm new to Arduino and this is my second day using it, so I would like to get help and know how to fix this problem. Here is my code:

    int isej1 = 2;
    int isej2 = 3;
    int vienetas[] = { 12, 11 };
    int astuonetas[] = { 13, 12, 11, 10, 9, 8, 7 };

    void setup() {
      pinMode (vienetas[2], OUTPUT);
      pinMode (astuonetas[8], OUTPUT);
      pinMode (isej1, OUTPUT);
      pinMode (isej2, OUTPUT);
    }

    void uz_vien() {
      digitalWrite (vienetas[0], HIGH);
      digitalWrite (vienetas[1], HIGH);
    }

    void uz_astuon() {
      digitalWrite (astuonetas[0], HIGH);
      digitalWrite (astuonetas[1], HIGH);
      digitalWrite (astuonetas[2], HIGH);
      digitalWrite (astuonetas[3], HIGH);
      digitalWrite (astuonetas[4], HIGH);
      digitalWrite (astuonetas[5], HIGH);
      digitalWrite (astuonetas[6], HIGH);
    }

    void is_vien() {
      digitalWrite (vienetas[0], LOW);
      digitalWrite (vienetas[1], LOW);
    }

    void is_astuon() {
      digitalWrite (astuonetas[0], LOW);
      digitalWrite (astuonetas[1], LOW);
      digitalWrite (astuonetas[2], LOW);
      digitalWrite (astuonetas[3], LOW);
      digitalWrite (astuonetas[4], LOW);
      digitalWrite (astuonetas[5], LOW);
      digitalWrite (astuonetas[6], LOW);

    void loop() {
      digitalWrite (isej1, LOW);
      digitalWrite (isej2, HIGH);
      void uz_vien();
      delay(5);
      void is_vien();
      digitalWrite (isej1, HIGH);
      digitalWrite (isej2, LOW);
      void uz_astuon();
      delay(5);
      void is_astuon();
    }

body:
You are missing a "}" just before `loop`

      void is_astuon() {
        digitalWrite (astuonetas[0], LOW);
        digitalWrite (astuonetas[1], LOW);
        digitalWrite (astuonetas[2], LOW);
        digitalWrite (astuonetas[3], LOW);
        digitalWrite (astuonetas[4], LOW);
        digitalWrite (astuonetas[5], LOW);
        digitalWrite (astuonetas[6], LOW);
       } // <- missing here.
      void loop() {


body:
The importance of proper indentation is clear here...

I thought you were missing a closing curly braces. When you type code, press regularly cmd/ctrl-T to ident your code -- it helps catching mistakes. You are indeed missing one, for `is_astuon()`.

Moreover these lines are wrong too:

    **void** uz_vien();
    delay(5);
    **void** is_vien();
    digitalWrite (isej1, HIGH);
    digitalWrite (isej2, LOW);
    **void** uz_astuon();

The `void` part is not needed and creates the error.


message:
Is my HC-SR04 sensor broken?

I am extremely new to Arduino and electrical engineering, and the project I am attempting involves a ultrasonic sensor.  I am using the HC-SR04 with the Elegoo Mega2560 Arduino board.  A few days ago I was able to print out the distance correctly with an Arduino library, but after adding a h-bridge, 2 motors, and 2 9-volt batteries, the sensor didn't seem to work properly.  I went back to a simple circuit with only the HC-SR04, and the distance readouts were all over the place.  No matter what, the distance stayed between 90 and 120, mainly staying in the 110s.  These numbers seemed to have no correlation with the actual distance.  I even tried to calculate the distance myself in case there was something wrong with the library.

I have the VCC pin on the HC-SR04 connected to the 5v on the Arduino, the GND pin connected to the GND pin on the Arduino, the Trigger pin connected to pin 50 on the Arduino, and the Echo pin on the Arduino connected to pin 52 on the Arduino.  The Arduino is connected to my computer through USB.

Here is my sketch for printing out the distance without a library:

    const int triggerPIN = 50;  //these are digital pins on the Arduino board
    const int echoPIN = 52;     //I'm sure these pins aren't broken because I never used them before now

    long duration;
    int distance;

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

        pinMode (triggerPIN, OUTPUT);
        pinMode (echoPIN, INPUT);

        delay(1000);
    }

    int getDistance () {
        digitalWrite (triggerPIN, LOW);
        delayMicroseconds (2);

        digitalWrite (triggerPIN, HIGH);
        delayMicroseconds (10);
        digitalWrite (triggerPIN, LOW);

        duration = pulseIn (echoPIN, HIGH);
        distance = duration * 0.034 / 2;

        Serial.println (distance);
    }

    void loop() {
        getDistance ();  //I tried putting the code directly in the loop function with the same result
    }

I am afraid that I broke either a part of the Arduino board or the sensor when I was fiddling around with the two batteries.  Is it possible to break a HCSR04 sensor by connecting two much voltage to the VCC pin on the sensor?  If so, how should I prevent this in the future?  I know that the working voltage for a HCSR04 is 5V, does this mean it needs at least 5V or no more than 5V?  I wanted to know for sure that it was broken and not an error on my part before I bought a new one.    Thanks in advance!

body:
The code that you have provided for the distance calculation is fine according to me. There is a high chance that you might have damaged your HC-SR04, Ultrasonic sensor.

As you have asked about how to prevent this from happening in the future, I would suggest that you should use a voltage regulator in the circuit, LM7805, it restricts the output voltage to 5V - just matching your ultrasonic sensor's operating voltage as it works perfectly at 5 Volts.


body: I guess the main problem is a serial printing. It always bother the system mainly the analog reading. It's quiet good for check some sub result while you programing (what the return value from a method etc) but not good to test your project result. In this case the distance measurement. Try a different way, put some led into the circuit and if the distance over 10cm switch on first, if over 20 cm switch on the second and so on. Or write the result  on an lcd panel, or 8x8 led.


body:
A major functional difference between the code in your question and the usual ping sensor example is that your code repetitively measures as fast as it or the output stream will allow.

In contrast, the normal example has a `delay(100)` after each measurement cycle.  This allows 1/10th of a second time for any longer room echoes to die out, and thus avoid confusing new measurements.

While that might not be your immediate or only problem, it is generally a good idea not to try to take sonar measurements so closely spaced in time that they could overlap.

Should your sketch also need to do other things, instead of a blocking `delay()` you can check the elapsed time and only take a new sonar measurement once a certain amount of time has passed; in the meantime your program can continue with any other critical operations.


message:
Arduino Uno versus Arduino Nano power consumption

I have both an Arduino Uno and an Arduino Nano but I can't decide which one to use for my project. My aim is to maximize battery lifetime. I have also implemented an 8-second watchdog timer to periodically sleep and wake up the ATMega328P.

 - Option 1: Arduino Uno R3 + DHT11 sensor: The board is powered on by 4 * 1.25V (2700 mAh) Nickel Metal Hydride batteries and the 3.3V output voltage of the Arduino is supplied to VCC of DHT11. (**Arduino Uno specification** DC Current per I/O Pin 40 mA, DC Current for 3.3V Pin 50 mA).

 - Option 2: Arduino Nano + DHT11 sensor. The board is powered on by 4 * 1.25V (2700 mAh) Nickel Metal Hydride batteries and the 3.3V output voltage of the Arduino is supplied to VCC of DHT11. (**Arduino Nano specification**: DC Current per I/O Pin: 40 mA but **NO** information for DC current for 3.3V or 5V).

I would like to know which one will be more power-efficient.

body:
Don't use either use something with no USB, regulator - e.g. Pro Mini (run from 3.3V)

Just running the Arduino (or indeed most digital circuitry) from a lower voltage will already reduce power consumption - admittedly at a slight cost in processor speed. The Atmega328P will run at 12MHz on 3.3V, although the Pro Mini uses the more conservative 8MHz.


body:
A Uno which isn't doing anything useful except being turned on will use about 50 mA of current from the power jack at 9V.

If you use 3 x alkaline AA batteries (giving a nominal voltage of 4.5V) directly into the 5V pin of the Arduino then you might get 2500 mAh which would be 50 hours at 50 mA per hour.

You can save a considerable amount of power by using sleep modes as I describe on [my page about power](http://www.gammon.com.au/power). It also helps to use a bare processor (no voltage regulator, no LEDs).

I made a [temperature and humidity sensor](http://www.gammon.com.au/forum/?id=12106) which runs from 3 x AA batteries. Using sleep mode, plus various other techniques, that is running for **over a year** without needing new batteries.

---

> I would like to know which one will be power efficient?

Both the Uno and the Nano use the same Atmega328P processor. Thus the technical considerations would be the same. Both have a voltage regulator and a "power on" LED which alone would use a lot of current, compared to everything else.

---

It's *not that hard* to make a minimal board. I have a [page about doing that](http://www.gammon.com.au/breadboard). Example of all you need:

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

---

If you use a deep sleep mode, combined with using the watchdog timer to wake every 8 seconds (and check the time, say every 10 times it wakes) you can reduce power consumption right down.

My temperature sensor uses an average of 42 µA which is a **lot** less than 50 mA. (A thousand times less). Thus your 50 hours run time becomes 50,000 hours which is 2083 days. Your batteries will probably self-discharge sooner. :)

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


message:
Why is my servo spinning over 360 degrees?

I decided to try out my servo on my Arduino. I'm pretty new to this and I can't seem to figure out why this is happening. My servo will spin for about 5 seconds in one direction and then it will spin the opposite way for less than a second and pause for about 3 seconds. This is the code I uploaded to my Arduino:

    # include <Servo.h>
    const int servopin = 8;
    Servo servo;

    void setup() {
      Serial.begin(9600);
      servo.attach(servopin);
      servo.write(0);
    }

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

I believe the servo is a Tower Pro Micro Servo 99 (either 9 might be a g) SG90.

body:
I might want to try decreasing the range, e.g. start from 10 instead of 0, or finish at 170 instead of 180. Here is an example:

    # include <Servo.h>
    const int servopin = 8;
    Servo servo;

    void setup() {
      Serial.begin(9600);
      servo.attach(servopin);
      servo.write(0);
    }

    void loop() {
      servo.write(10);
      delay(5000);
      servo.write(170);
      delay(5000);
    }

After checking it works, try experimenting with different ranges to see how your servo reacts.

**For me starting at 7 instead of 0 did the job.**


body:
When I am getting started with my Servo motor SG90, I have experience the same issue, and finally I have solved the issue. I have used external power supply for Servo and my Arduino with laptop USB port and control signal from Arduino to Servo motor make my Servo motor to spinning continuously.

Make sure ground reference of power supply of Servo motor and Arduino are same.


message:
Getting error ets jan 8 2013,rst cause:4,boot mode(1,6) wdt reset

I'm working on a project to send ultrasonic sensor data to my webserver. For that I'm using ESP8266  WiFi module, 3.3V regulator IC by giving input volt of 5v from aduino uno.

I successfully uploaded a code but in serial monitor I got an error

    ets jan 8 2013,rst cause:4,boot mode(1,6) wdt reset.

Please, tell what does it mean?

Here is my code. Guide me if I made something wrong. Thanks in  advance.

**Note:**
Before sending sensor values I successfully send a raw data  manually to webserver, i.e string data, but when I try to send sensor values, I got an error.

    #include <ESP8266WiFi.h>
    #include <ESP8266HTTPClient.h>

    const char* ssid = "VENTURE 11";
    const char* pass = "12345678";

    WiFiClient clientx;
    const int trigPin = 8;  //Digital port D5
    const int echoPin = 9;  //Digital port D6

    long duration;
    float distance;
    float Mdistance;
    float MAX_HEIGHT = 0;

    void setup() {

      Serial.begin(115200);                                  //Serial connection
      pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
      pinMode(echoPin, INPUT);

      WiFi.begin("VENTURE 11", "12345678");   //WiFi connection
      Serial.println("Setup iniated");
      while (WiFi.status() != 3) {  //Wait for the WiFI connection completion
        delay(500);
        Serial.println("Waiting for connection");
        Serial.print("WIFI STATUS : ");
        Serial.println(String(WiFi.status()));
      }
      Serial.println(String(WiFi.status()));
    }

    void loop() {
      Serial.println(String(WiFi.status()));
      if (WiFi.status() != 3)
      {
        WiFi.begin("VENTURE", "12345678");   //WiFi connection
        while (WiFi.status() != 3)
        {
          Serial.println("Waiting for connection");
        }
      }
      else
      {
        digitalWrite(trigPin, LOW);
        delayMicroseconds(2);

        // Sets the trigPin on HIGH state for 10 micro seconds
        digitalWrite(trigPin, HIGH);
        delayMicroseconds(10);
        digitalWrite(trigPin, LOW);

        // Reads the echoPin, returns the sound wave travel time in microseconds
        duration = pulseIn(echoPin, HIGH);

        // Calculating the distance
        distance = (duration * 0.034) / 2;

        if (MAX_HEIGHT == 0) {
          //MAX_HEIGHT = distance;
          Serial.print("Max height has been set to ");
          //Serial.print(distance);
          Serial.println(" cm");
          Serial.println("Waiting for 5 seconds...");
          delay(5000);
        } else {
          Serial.print("Distance:\n");
          Serial.print(distance);
          Serial.print("cm\n");
          Serial.print("Distance:\n");
          Serial.print(distance / 100);
          Serial.print("m\n");
          delay(1000);

        }

        HTTPClient http;
        String Data = "x=" + (String)distance + "&y=" + (String)MAX_HEIGHT + "&z=0";
        //String Data = "x=Finally&y=Did&z=it;)";
        http.begin("http://testingblahblah.000webhostapp.com/IOTCON.php");
        http.addHeader("Content-Type", "application/x-www-form-urlencoded");
        int sent = http.POST(Data);
        Serial.println(sent);
        String httpPayload = http.getString();
        Serial.println(httpPayload);
        if (sent > 0)
        {
          Serial.println("Message has been sent");
        } else {
          Serial.println("unable to send data");
        }
        delay(20000);

      }
    }`

body:
Your `loop()`:

    void loop() {
      Serial.println(String(WiFi.status()));
      if (WiFi.status() != 3)
      {
        WiFi.begin("VENTURE", "12345678");   //WiFi connection
        while (WiFi.status() != 3)
        {
          Serial.println("Waiting for connection");
        }
      }
      else
      {
        // Other code...
      }
    }

While waiting for the connection, you are creating `String` objects at a very high rate, since your `delay(20000)` is in the `else` clause.

This means you are possibly running out of memory, as you are creating the `String` objects with every iteration, which is in the Megahertz range.

You likely don't need the `String(...)` wrappers, as the `Serial.println()` function can work with C-style strings returned by the `WiFi` library. Then, your program won't be allocating memory to hold the result of `WiFi.status()` millions of times per second, which you don't use later on in your program.


body:
Found a possible solution.
I was facing with the same problem.
Apparently this is a hardware stack overflow watch dog preventing malfunction. This may not apply to every possible scenario but I discovered that the allocated pin number on the board itself is incorrect.
What is numbered 03 is in fact D15 for example. So assigning the pin to D15 worked but 3 created this error.
I hope this helps others.


message:
Controlled power-down for automotive application

I'm working on an automotive project that uses an Arduino Mega 2560.

What I need is a circuit that allows the unit to sense when the external power feed drops (triggering an interrupt?) so that the software can preserve state to the non-volatile memory and then shut down.

I was thinking some sort of capacitor/battery to run it once the eternal feed drops, but the hardware side of things is not my strong skillset - I'm more of a software kinda person.

body:
Consider a battery backup for low power devices.  [This article][1] from allaboutcircuits.com discusses how to build a 12 to 5 volt power supply with its own battery backup.

In your specific case, run a second 12 to 5 volt regulated signal to one of the processor's digital inputs.  When the 12 volts shuts off, the signal to the processor's digital input will go low.  Poll this input and when you see it go low shutdown the processor or put the processor into a deep sleep mode to draw as little current as possible from the back up battery.

The [ATmega2560][2] processor may not be the best chose for this. There are processors that can drop down into the nA range and still wake up periodically to check if they should be powered all the way back up.

  [1]: https://www.allaboutcircuits.com/projects/battery-backup-power-supplies/
  [2]: http://www.atmel.com/Images/Atmel-2549-8-bit-AVR-Microcontroller-ATmega640-1280-1281-2560-2561_datasheet.pdf


message:
How to send MFRC522 data to a C# app using a NodeMCU TCP server?

I am trying to send MFRC522 data to a C# application through a NodeMCU acting as an access point for the C# app. I have modified the code I got from [this site][1].

    #include ESP8266WiFi.h>
    #include SPI.h>
    #include MFRC522.h>

    const char* AP_SSID ="IoT4143" ;
    const char* AP_PASSWORD ="iot4143";

    #define RST_PIN D3
    #define SS_PIN D4

    MFRC522 mfrc522(SS_PIN, RST_PIN);  // Create MFRC522 instance

    WiFiServer server(80);
    WiFiClient client;

    void wifiConnect() {
      WiFi.disconnect();
      WiFi.softAP(AP_SSID, AP_PASSWORD);

      int watchDog = 0;
      while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        watchDog++;
        if(watchDog == 60) {
          WiFi.disconnect();
          WiFi.printDiag(Serial);
          watchDog = 0;
          return;
        }
      }
      server.begin();
    }

    void setup() {
      Serial.begin(115200);
      SPI.begin();      // Init SPI bus
      mfrc522.PCD_Init();   // Init MFRC522
      mfrc522.PCD_DumpVersionToSerial();  // Show details of PCD - MFRC522 Card Reader details
      Serial.println(F("Scan PICC to see UID, SAK, type, and data blocks..."));
      wifiConnect();
    }

    void loop() {
      //Are we connected to WiFi?
      if(WiFi.status() != WL_CONNECTED) {
        wifiConnect();
      }

      //Wait for a connection attempt
      client = server.available();
      if (!client) {
        return;
      }

      // Wait until the client sends some data
      int watchDog = 0;
      while(!client.available()) {
        delay(1);
        if(watchDog == 10000) {
          watchDog = 0;
          return;
        }
        watchDog++;
      }
      sendData();
    }

    void sendData() {
      // Read the first line of the request
      String request = client.readStringUntil('\r');
      client.flush();

      // Match the request
      while(request=="READSTOP") {
        Serial.println("RFID READING STARTED..."); //Forward to C# App
        if (!mfrc522.PICC_IsNewCardPresent()) {
          return;
        }
        // Select one of the cards
        if (!mfrc522.PICC_ReadCardSerial()) {
          return;
        }
        // Dump debug info about the card; PICC_HaltA() is automatically called
        client.print(mfrc522.uid));
      }
      Serial.println("RFID READING STOPPED"); //Stop server
      delay(1);
      client.stop();
    }

I am very new to hardware/network programming. I don't know what will be possible errors in this code and whether it will work or not.

When I verified the code in the Arduino IDE, there was an error on this line of code:

    client.print(mfrc522.uid));

>error:= no matching function for call to 'WiFiClient::print(MFRC522::Uid&)'

When the connect button in the application is clicked the "READSTART" string is sent to NodeMCU and when disconnect is clicked the "READSTOP" string is sent.

Please help!

  [1]: http://tdmts.net/2017/02/04/controlling-an-arduino-with-a-wifi-esp8266-adapter-using-a-windows-10-universal-app/

body:
MFRC522::uid is a struct ([see source code][1]). There's no defined way to print it.

If you want to write the raw bytes over the TCP connection, you can just use

    client.write((uint8_t*)mfrc522.uid.uidByte, mfrc522.uid.size);

If you want to write it as ASCII text, you can use the following:

    void byte_to_str(char* buff, uint8_t val) {  // convert an 8-bit byte to a string of 2 hexadecimal characters
      buff[0] = nibble_to_hex(val >> 4);
      buff[1] = nibble_to_hex(val);
    }

    char nibble_to_hex(uint8_t nibble) {  // convert a 4-bit nibble to a hexadecimal character
      nibble &= 0xF;
      return nibble > 9 ? nibble - 10 + 'A' : nibble + '0';
    }

    void printHEX(Stream &s, uint8_t *data, size_t length) {
      char *buffer = new char[length*2];
      for (size_t i = 0; i < length; i++) {
        byte_to_str(&buffer[i*2], data[i]);
      }
      s.write(buffer, length*2);
      delete[] buffer;
    }

Then use it like this:

      printHEX(client, mfrc522.uid.uidByte, mfrc522.uid.size);

It loops over all bytes in the UID, converts them to ASCII (hexadecimal representation, so 2 characters per byte), and then writes the text over the TCP connection.

(Note that there are many other problems with your code as well, e.g. the includes are missing the opening '<'.)

  [1]: https://github.com/miguelbalboa/rfid/blob/19461b34d38871ba2722dab7a3a76028eddebaa1/src/MFRC522.h#L315-L320


message:
Detecting if a push button was pressed and released

I want to detect if a push button was pressed and released again. So I thought the right approach would be to first wait while the pin yields `LOW` and then wait while the pin yields `HIGH`:

    void push(int pin) {
      // wait until button was pushed down...
      while (digitalRead(pin) == LOW);
      // ... and released again
      while (digitalRead(pin) == HIGH);
    }

That function can be easily reused. The code works fine, but I am just wondering if that solution is considered clean and a good practice.

body:
No, I wouldn't consider that good practice - for one good reason: it's blocking.

Your system can't be doing anything else at all while you're waiting on the button. That may be fine for some situations, but far from ideal for 99% of others.

It is better to remember the state of the button and detect that change of state.

Personally, to make it properly portable, I would implement a class to contain all the state information.  Something like:

    class Button {
        private:
            bool _state;
            uint8_t _pin;

        public:
            Button(uint8_t pin) : _pin(pin) {}

            void begin() {
                pinMode(_pin, INPUT_PULLUP);
                _state = digitalRead(_pin);
            }

            bool isReleased() {
                bool v = digitalRead(_pin);
                if (v != _state) {
                    _state = v;
                    if (_state) {
                        return true;
                    }
                }
                return false;
            }
    };

Then you can do something like:

    Button myButton(3);

    void setup() {
        myButton.begin();
        Serial.begin(115200);
    }

    void loop() {
        if (myButton.isReleased()) {
            Serial.println(F("Released"));
        }
    }

Every time `myButton.isReleased()` is called the current button state is compared against the state it was last time it was called. If it's changed then the button must either have been pressed or released. So you remember that change. If it's been released then you return a `true`, otherwise return a `false`.

You can now easily have it work with many buttons:

    Button myButton(3);
    Button myOtherButton(4);

    void setup() {
        myButton.begin();
        myOtherButton.begin();
        Serial.begin(115200);
    }

    void loop() {
        if (myButton.isReleased()) {
            Serial.println(F("Released 1"));
        }
        if (myOtherButton.isReleased()) {
            Serial.println(F("Released 2"));
        }
    }


body:
I concur with [Majenko][1], although your code would work, the code is blocking, meaning that your code stops at that point until the button is released again. The remaining code in your loop does not execute until the button is resolved.

A much better method is to check the state of the button in each passing of the loop. If the state changes (ie goes low) you can set a flag. Then when you read that the button is high again and the flag has been set then you execute the appropriate code. For example:

    const int buttonPin = 2;     // the number of the pushbutton pin
    boolean buttonWasLow = false;         // variable flag for when the pushbutton goes low

    void setup() {
        pinMode(buttonPin, INPUT);    // initialize the pushbutton pin as an input:
    }

    void loop() {
        // read the state of the pushbutton and set a flag if it is low:
        if (digitalRead(buttonPin) == LOW)  {
            buttonWasLow = true;
        }

        // This if statement will only fire on the rising edge of the button input
        if (digitalRead(buttonPin) == HIGH && buttonWasLow)  {
            // reset the button low flag
            buttonWasLow = false;

            // Button event here
        }
    }

My favorite way to detect a rising edge of an input is actually much simpler:

    void loop() {
        button = digitalRead(buttonPin);

        // If the button is pressed
        if (button && !buttonLast)
        {
            // Button event here
        }

        // Update button flag
        buttonLast = button;
    }

[user8886193][2] brings up the very good point about [button debounce][3].

>Bouncing is the tendency of any two metal contacts in an electronic device to generate multiple signals as the contacts close or open; debouncing is any kind of hardware device or software that ensures that only a single signal will be acted upon for a single opening or closing of a contact.

I prefer to debounce the pushbutton inputs through hardware by adding a 100nF (or larger) from the input pin to ground. Note that this requires a 10K (or larger) resistance in series with the button circuit in order for the capacitor to charge/discharge.

Alternatively, in software, the most common debounce for beginners is adding a delay such as `delay(100);`, which would look something like this:

    void loop() {
        button = digitalRead(buttonPin);

        // If the button is pressed
        if (button && !buttonLast)
        {
            // Button event here
            delay(100);  // <---- Delay inserted after the button event
        }

        // Update button flag
        buttonLast = button;
    }

This has the downside that it is blocking for 100ms while the delay executes. A better method is to debounce without a delay. One of the built in examples demonstrates [button debounce][4]. The main loop is shown below:

    void loop() {
        // read the state of the switch into a local variable:
        int reading = digitalRead(buttonPin);

        // check to see if you just pressed the button
        // (i.e. the input went from LOW to HIGH), and you've waited long enough
        // since the last press to ignore any noise:

        // If the switch changed, due to noise or pressing:
        if (reading != lastButtonState) {
            // reset the debouncing timer
            lastDebounceTime = millis();
        }

        if ((millis() - 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:

            // if the button state has changed:
            if (reading != buttonState) {
                buttonState = reading;

                // only toggle the LED if the new button state is HIGH
                if (buttonState == HIGH) {
                    ledState = !ledState;
                }
            }
        }

        // set the LED:
        digitalWrite(ledPin, ledState);

        // save the reading. Next time through the loop, it'll be the lastButtonState:
        lastButtonState = reading;
    }

  [1]: https://arduino.stackexchange.com/a/48244/19409
  [2]: https://arduino.stackexchange.com/a/48250/19409
  [3]: http://whatis.techtarget.com/definition/debouncing
  [4]: https://www.arduino.cc/en/Tutorial/Debounce


body:
> "I usually put a capacitor next to my push button"

A 1uF capacitor across the button is easy, cheap and means no need to fiddle with debouncing codes. See Nick Gammon's [excellent switch tutorial][1] that covers almost any conceivable situation when using switches with Arduinos and clones (high or low, GND or +5V, internal pull-up or pull-down, capacitor debounce or software debounce, etc.). In any case, Nick Gammon has many great explanatory examples on his site and where else he comments online.

  [1]: http://www.gammon.com.au/switches


message:
Purpose of USB (FTDI) and ICSP connectors

As an Arduino newbie I am a little bit confused about possible ways of programming and communicating with this device. I have done some research and it seems that:

ICSP is used for programming with a bootloader in MCU.

The USB (FTDI) port is used (mostly) for sending text messages to the PC and programming without a bootloader.

Am I right? How can I detect whether I have a bootloader installed (Uno R3 clone)? Thank you very much!

body:
The ICSP is used for 'bare metal' programming. This what you'd use if you wanted to replace or remove the bootloader, change the clock oscillator settings, or program the device as a bare 328.

The USB port is for communicating with a program running on the Arduino. When it's first booted, the bootloader program checks to see if there's any activity on the serial link from the Arduino host program on a PC. If there is, then it allows downloading of a program from it. If not, it continues on to the last code that was programmed into it.

The easiest way to see whether a bootloader is installed is simply to start it up with the PC host, and see whether it can talk to it.


message:
Is there GUI to flash a sketch with new variables?

I'm dabbling in a project and would like to add a feature, but I need some help from the community.

My project returns a response from the wunderground api and lights an led based on the temperature in the response. I plan to enclose the circuits and use a single led on the enclosure to display the temperature. I have most of the sketch logic knocked out, but need help with sharing the project.

If I gave this project to someone, they would need to update the sketch to include their wifi name and password, as well as the zip code where they live.

Is there a way I can do this without using the arduino ide? A use case for this would be: the user plugs the arduino into their machine, the gui loads, the user would enter variables, and then the board would get flashed with the new variables.

Is this a pie in the sky proposition, or something that could be implemented?

Thanks for your input.

body:
The common way to do this is to build the configuration UI into your program. Then the user has no need to be messing with the firmware.

Since your device has WiFi this can easily be done by serving a configuration web page that is loaded in the browser. But how can you make a connection before the credentials for the WiFi router have been configured? The answer is for the device to serve as an access point (AP). So you connect a computer with WiFi to the device's AP, open the configuration page in the browser on that computer, and then configure the credentials as well as any other configurations you might like.

The configuration parameters are written to EEPROM so that they will be preserved.

In its most simple form there would be a specific IP address that must be opened in the browser but more user friendly is to create a captive portal so that after connecting to the AP any URL opened in the browser will load the configuration page.

Of course all this will increase the memory usage of your program and apparently you are using the Arduino Uno so this is fairly scarce to begin with. You'll need to determine whether there is enough extra memory for it.


message:
Connecting multiple clients to a server in Wifi

What is the best method or retrieving information such as temperature from multiple wifi clients with a ESP8266-01 ?
I have one server and five client running with ESP8266.
I have seen post ang Get method. JSON files. client-server transfers.
What is the best method to do that ?
I am reading temperature so I do not need the clients to be all connected at the same time. So reading the client one after another in a loop would be great.
thanks in advance

Ken

body:
you do not need http for this. use plain socket communication. create a WiFiServer on every 'sensor' and ask from the main esp8266 over WiFiClient object. the WiFiServer creates a WiFiClient object and the Clients can exchange what you want.

snippet from my code:

    void loop() {
      WiFiClient client = telnetServer.available();
      if (!client) {
        delay(100);
        return;
      }
      if (client.status() != 4) {
        client.stop();
        delay(1000);
        return;
      }
      while (client.connected()) {
        if (!client.available())
          continue;
        char c = client.read();
        if (c == '\n') {
          long v = s.toInt();
          s = "";
          analogWrite(PWM_PIN, v);
          v = readElSens();
          client.println(v);
        } else {
          s += c;
        }
      }
      delay(100);
    }


message:
prgramming arduino led on then off

i want the led to light at the beginning and stays like this for a while then turns off, so i wrote:

    int led=13;
    void setup() {
      pinMode(led,OUTPUT);
    }
    void loop() {
        digitalWrite(led,HIGH);
        delay (5000);
        digitalWrite (led,LOW);
    }

as i understand it should start with high means on digitalWrite(led,HIGH)...and stays like this for 5000us  delay (5000)  then it should turn off with  digitalWrite (led,LOW).
but why its not working, it starts with off for afew seconds then stays on..what i understand wrong with these simple steps ????

body: It immediately loops, from the digital write low to digital write high. Add a second delay after the low, so that it waits before it loops to the top again.


body:
The "loop()" will keep repeating itself, turning the led on and off forever.
If you want turn the led on just once, put the commands for turn the led on in "setup()" section:

void setup() {
    pinMode(led,OUTPUT);
    digitalWrite(led,HIGH);
    delay (5000);
    digitalWrite (led,LOW);
}
void loop() {
}

Other method would be add a variable to count how much times the led should light. I copied the following sketch from [here][1]

int ledPin =  13;    // LED connected to digital pin 13
int alreadyBlinked = 0;

// The setup() method runs once, when the sketch starts
void setup()   {
pinMode(ledPin, OUTPUT);    // initialize the digital pin as an output:
}

// the loop() method runs over and over again,
// as long as the Arduino has power
void loop()
{
     if(alreadyBlinked == 0)
     {
            digitalWrite(ledPin, HIGH);   // set the LED on
            delay(5000);                  // wait for five seconds
            digitalWrite(ledPin, LOW);    // set the LED off
            alreadyBlinked = 1;
      }
}

When the variable "alreadyBlinked" is set to 1, the led will not turn on again.

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


message:
Multiple delays

I have a sketch with multiple functions in it. The 2 main functions in that sketch are `get_data` and `post_data`.

Now these functions are called from `loop()`. The thing is I want these functions to run at different times. Basically I want the `get_data` function to run once every 4 minutes and the `post_data` function to run once every hour. How can I achieve that?

As far as I know, you can't run multiple programs together on an Arduino Mega.

P.S: I'm new to Arduino programming.

body:
I think you can use timer for it. In microcontroller with c you can use interrupts. You will need one timer and two compare interrupts. In the interrupts you can set different flags.

For example in first interrupt:

    ....
    getSomething = true;
    ....

For example in second interrupt:

    ....
    postSomething = true;
    ....

For example in your loop:

    ....
    if(postSomething){
    //your code to post something
    postSomething = false;
    }

    if(getSomething){
    //your code to get something
    getSomething = false;
    }

These functions are only called when the timer interrupt is called (the time reached). In the Handler you set the flag (do not execute big code). In loop you can check if a flag is set and execute than the code. I think in Arduino you can do the same.


body:
If you don't need absolute precision, I've written a timer class that doesn't use an interrupt: [TimerAction][1]. Usage to simply subclass the base object, define an `action()` method in the subclass, construct your subclass defining the time interval to run, and place a call to the object's `loop()` method in your main `loop()` function in every sketch.

In your case, you'd create a subclass for each of your `get_data` and `post_data` actions. This would require two objects to be constructed, and both of them having their `loop()` method called in the main `loop()` function.

  [1]: https://github.com/michaelkamprath/ShiftRegisterLEDMatrixLib/blob/master/src/TimerAction.h


body:
I imagine that you tried to figure out how to do it whit the `delay()` function (if it's not your case, it is for most Arduino beginners). Well... you can't use `delay()` in this case (and in most other cases) because it completely blocks the program for a given time (1) (except for interrupts, but i won't treat interrupts here). In general it is better not to use delays, except for very simple programs or in initialisation routines (i.e. in stuff you usually put in `setup()`).

---
Since your delays are quite long I imagine that you don't need much precision (i.e. you don't need to be more precise than a millisecond). So you could do like that:

<!-- language: lang-c++ -->

    void setup() {}

    // Times at which we last called the functions
    // (These are global variables, which are in general best avoided)
    unsigned long lastGetData = 0;
    unsigned long lastPostData = 0;

    void loop() {

        //                           min.  sec.  milliseconds
        if(millis() - lastGetData >= 4   * 60  * 1000) {

            lastGetData = millis();
            get_Data();
        }

        //                            min.  sec.  milliseconds
        if(millis() - lastPostData >= 60  * 60  * 1000) {

            lastPostData = millis();
            post_Data();
        }
    }

    void get_Data() {
        // ...
    }

    void post_Data() {
        // ...
    }

**Notes:**

* millis() returns the time since the startup of the Arduino in millisecond. To get more precision you could also use micros() which returns the same but in microseconds (then you would need to multiply the number in the if condition by 1000).
* you can add as much functions as you want whit different execution delays. But you must keep every function as short as possible, i.e. you must not use `delay()`s, because while executing a function if the time to execute another function comes that function will only be called after the end of the current one.
* I used the `=>` sign, and not `==`, so that even if the loop doesn't evaluates one if condition in the very milliseconds in which it becomes true it can positively evaluate it some milliseconds later (e.g. after the end of another running function).


body:
If it works in your situation:

    void loop() {
      static int n;

      delay(4 * 60000);
      get_data();

      if (n-- == 0) {
        post_data();
        n = 14;
      }
    }

You may need to adjust the 14 and post-decrement to fit your needs.


message:
Accessing digital pins from the Atmega 16u2 on the Uno

I'm running a custom firmware on the ATmega16U2 (Switch-Fightstick).
Is it possible to access the digital pins of the UNO from the ATmega16U2?

body: No, only the ATmega328P has access to the external pins of the Uno. You would need to write code for both the '328P and the '16U2 to communicate the pin values and changes over serial since that is the only channel connecting the MCUs.


body:
There is a 4-pin header JP2 on the board that brings out the following pins from the '16U2

    PB4, PB5, PB6, PB7

and the ICSP connector

    PB1, PB2, PB3


message:
Need to set a FAILSAFE in an if else loop

This works but I would like to have a timed failsafe...

If the `FLOAT_PIN` goes `LOW` for more than 3 seconds, it will turn `SOLENOID_PIN` to `LOW`.

I can't figure out how to incorporate it into my loop. I tried `delay()` and started playing with `millis()` but all I keep finding is LED blinking samples...

I'm not very good with C++ - still learning.

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

    const int FLOAT_PIN = 8; // Pin connected to FLOAT switch
    const int SOLENOID_PIN = A0; // SOLENOID pin - active-high

    void setup() {
      Serial.begin(9600);
      // Since the other end of the FLOAT switch is connected to ground, we need
      // to pull-up the FLOAT switch pin internally.
      pinMode(FLOAT_PIN, INPUT_PULLUP);
      pinMode(SOLENOID_PIN, OUTPUT);
    }

    void loop() {
      int floatswitch = digitalRead(FLOAT_PIN); // Read the state of the float switch

      if (floatswitch == HIGH) {
        // If the pin reads high, water is OFF.
        Serial.println("Switch closed");
        digitalWrite(SOLENOID_PIN, HIGH); // Turn the SOLENOID on
      } else {
        digitalWrite(SOLENOID_PIN, LOW); // Turn the SOLENOID off
      }
    }

body:
This is one of those cases when thinking in terms of a [finite state
machine][fsm] makes the programming quite straightforward. Here I would
use three states:

* In the `OFF` state, the switch is `LOW` and the solenoid is off
* in the `ON` state, the switch is `HIGH` and the solenoid is on
* in the `DELAYING` state, the switch is `LOW`, but the program is
  keeping the switch `HIGH` for three seconds.

The possible transitions are:

* `OFF` → `ON` when the switch goes `HIGH`
* `ON` → `DELAYING` when the switch goes `LOW`
* `DELAYING` → `OFF` after three second in this state
* `DELAYING` → `ON` when the switch goes `HIGH`.

The last transition is meant to ensure that `LOW` states of the switch
that last less than three seconds do not turn the solenoid off.

And here is a tentative implementation. Keep your constants and your
`setup()`, and replace your `loop()` with this:

    const uint32_t DELAY_TIME = 3000;  // time to deay the -> off transition

    void loop() {
        static enum {OFF, ON, DELAYING} state;
        static uint32_t start_delay;
        int floatswitch = digitalRead(FLOAT_PIN);

        switch (state) {
            case OFF:
                if (floatswitch == HIGH) {
                    Serial.println("Switch closed");
                    digitalWrite(SOLENOID_PIN, HIGH); // Turn the SOLENOID on
                    state = ON;
                }
                break;
            case ON:
                if (floatswitch == LOW) {
                    start_delay = millis();
                    state = DELAYING;
                }
                break;
            case DELAYING:
                if (floatswitch == HIGH) {
                    state = ON;
                }
                else if (millis() - start_delay >= DELAY_TIME) {
                    digitalWrite(SOLENOID_PIN, LOW); // Turn the SOLENOID off
                    state = OFF;
                }
                break;
        }
    }

[fsm]: https://hackingmajenkoblog.wordpress.com/2016/02/01/the-finite-state-machine/