message:
EDB char array problem. New input word overlaps the previous words saved

I have been searching everywhere now and nothing seems to work out for me. When I try to input a new word, it overlaps the previously entered words.
Here is my struct definition:

    struct LogEvent{
      char fullname[30];
    } logEvent;

Here is how I assign a value to fullname:

    strcpy(logEvent.fullname, testName);

Here is how I print the output:

    for(int i = 0; i <= db.count(); i++)
    {
      EDB_Status result = db.readRec(i, EDB_REC logEvent);
      if(result == EDB_OK)
      {
         Serial.print(logEvent.fullname);
         Serial.print(" ");
      }
    }

Here is the sample output:

    Input 1 - Lebron James
    Output 1- Lebron James

    Input 2 - Kobe Bryant
    Output 2 - Kobe Bryant Kobe Bryant  (The output should be - Lebron James Kobe Bryant)

    Input 3 - LeGoat
    Output 3 - LeGoat LeGoat LeGoat (The output should be - Lebron James Kobe Bryant LeGoat)

**How to fix this?**

EDIT. Here is my code:

    #include "Arduino.h"
    #include <EDB.h>

    // Use the external SPI SD card as storage
    #include <SPI.h>
    #include <SD.h>

    int recnumber = 1;
    //Arbitrary definition
    struct LogEvent {
        int id;
        int temperature;
        char fullname[30];
    }
    logEvent;

    inline void writer (unsigned long address, const byte* data, unsigned int  recsize) {
        digitalWrite(13, HIGH);
        dbFile.seek(address);
        dbFile.write(data,recsize);
        dbFile.flush();
        digitalWrite(13, LOW);
    }

    inline void reader (unsigned long address, byte* data, unsigned int recsize) {
       digitalWrite(13, HIGH);
       dbFile.seek(address);
       dbFile.read(data,recsize);
       digitalWrite(13, LOW);
    }
      EDB db(&writer, &reader);

    // Run the demo
    void setup()
    {
        pinMode(13, OUTPUT);
        digitalWrite(13, LOW);

        Serial.begin(9600);
        Serial.println(" Extended Database Library + External SD CARD storage demo");
        Serial.println();

        randomSeed(analogRead(0));

        if (!SD.begin(SD_PIN)) {
            Serial.println("No SD-card.");
            return;
        }

        // Check dir for db files
        if (!SD.exists("/db")) {
            Serial.println("Dir for Db files does not exist, creating...");
            SD.mkdir("/db");
        }

        if (SD.exists(db_name)) {

            dbFile = SD.open(db_name, FILE_WRITE);

          // Sometimes it wont open at first attempt, espessialy after cold start
          // Let's try one more time
            if (!dbFile) {
                dbFile = SD.open(db_name, FILE_WRITE);
            }

            if (dbFile) {
                Serial.print("Openning current table... ");
                EDB_Status result = db.open(0);
                if (result == EDB_OK) {
                    Serial.println("DONE");
                } else {
                    Serial.println("ERROR");
                    Serial.println("Did not find database in the file " + String(db_name));
                    Serial.print("Creating new table... ");
                    db.create(0, TABLE_SIZE, (unsigned int)sizeof(logEvent));
                    Serial.println("DONE");
                    return;
                }
            } else {
                Serial.println("Could not open file " + String(db_name));
                return;
            }
        } else {
            Serial.print("Creating table... ");
            // create table at with starting address 0
            dbFile = SD.open(db_name, FILE_WRITE);
            db.create(0, TABLE_SIZE, (unsigned int)sizeof(logEvent));
            Serial.println("DONE");
        }
        deleteAll();
        recordLimit();
        countRecords();
    }
    char testName[30];

    void loop()
    {
      if(Serial.available())
      {
        Serial.println("Waiting for name...");
        index = 0;
        for(int i = 0; i < sizeof(testName); ++i)
        {
          testName[i] = (char)0;
        }
        while(Serial.available())
        {
          char character = Serial.read();
          testName[index] = character;
          index++;
        }
        createRecords(testName);
        selectAll();
        delay(1000);
      }
      delay(1000);
     }

    void createRecords(char *testName)
    {
      Serial.print("Creating Record... ");
      logEvent.id = recnumber;
      logEvent.temperature = random(1, 125);
      strcpy(logEvent.fullname, testName);
      recnumber++;
      EDB_Status result = db.appendRec(EDB_REC logEvent);
    }

    void selectAll()
    {
       for (int recno = 1; recno <= db.count(); recno++)
       {
          EDB_Status result = db.readRec(recno, EDB_REC logEvent);
          if (result == EDB_OK)
          {
            Serial.print("Recno: ");
            Serial.print(recno);
            Serial.print(" ID: ");
            Serial.print(logEvent.id);
            Serial.print(" Temp: ");
            Serial.print(logEvent.temperature);
            Serial.print(" Fullname: ");
            Serial.print(logEvent.fullname);
            Serial.print(" Length: ");
            Serial.println(strlen(logEvent.fullname));
          }
        }
     }

Here is the output:

    Extended Database Library + External SD CARD storage demo

    Openning current table... DONE
    Truncating table... DONE
    Record Limit: 2045
    Record Count: 0
    Record Count: 0
    Waiting for name...
    Name received: Kobe Bryant
    LogEvent Fullname:
    The sentence entered is 11 characters long
    Creating Record... Done Creating Record...
    Recno: 1 ID: 1 Temp: 64 Fullname: Kobe Bryant Length: 11
    Waiting for name...
    Name received: Lebron James
    LogEvent Fullname: Kobe Bryant
    The sentence entered is 12 characters long
    Recno: 1 ID: 1 Temp: 64 Fullname: Kobe Bryant Length: 11
    Creating Record... Done Creating Record...
    Recno: 1 ID: 1 Temp: 64 Fullname: Lebron James Length: 12
    Recno: 2 ID: 2 Temp: 78 Fullname: Lebron James Length: 12
    Waiting for name...
    Name received: Michael Jordan
    LogEvent Fullname: Lebron James
    The sentence entered is 14 characters long
    Recno: 1 ID: 1 Temp: 64 Fullname: Lebron James Length: 12
    Recno: 2 ID: 2 Temp: 78 Fullname: Lebron James Length: 12
    Creating Record... Done Creating Record...
    Recno: 1 ID: 1 Temp: 64 Fullname: Michael Jordan Length: 14
    Recno: 2 ID: 2 Temp: 78 Fullname: Michael Jordan Length: 14
    Recno: 3 ID: 3 Temp: 29 Fullname: Michael Jordan Length: 14

Update: I tried to use `memset` but the result is still the same as above.

body:
I've just tried to extend one of the examples (with internal EEPROM), and it's working as expected:

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

    /*
     EDB_Simple.pde
     Extended Database Library + Internal Arduino EEPROM Demo Sketch

     The Extended Database library project page is here:
     http://www.arduino.cc/playground/Code/ExtendedDatabaseLibrary

     */
    #include "Arduino.h"
    #include <EDB.h>

    // Use the Internal Arduino EEPROM as storage
    #include <EEPROM.h>

    // Uncomment the line appropriate for your platform
    #define TABLE_SIZE 512 // Arduino 168 or greater

    // The number of demo records that should be created.  This should be less
    // than (TABLE_SIZE - sizeof(EDB_Header)) / sizeof(LogEvent).  If it is higher,
    // operations will return EDB_OUT_OF_RANGE for all records outside the usable range.
    #define RECORDS_TO_CREATE 10

    // Arbitrary record definition for this table.
    // This should be modified to reflect your record needs.
    struct LogEvent {
      int id;
      int temperature;
      char test[20] = {};
    }
    logEvent;

    // The read and write handlers for using the EEPROM Library
    void writer(unsigned long address, byte data)
    {
      EEPROM.write(address, data);
    }

    byte reader(unsigned long address)
    {
      return EEPROM.read(address);
    }

    // Create an EDB object with the appropriate write and read handlers
    EDB db(&writer, &reader);

    void setup()
    {
      Serial.begin(115200);
      Serial.println("Extended Database Library + Arduino Internal EEPROM Demo");
      Serial.println();

      db.create(0, TABLE_SIZE, sizeof(logEvent));

      Serial.print("Record Count: "); Serial.println(db.count());

      Serial.println("Creating Records...");
      int recno;
      for (recno = 1; recno <= RECORDS_TO_CREATE; recno++)
      {
        logEvent.id = recno;
        logEvent.temperature = recno * 2;
        strcpy(logEvent.test, (String{recno*3} + " whatever " + recno).c_str());
        db.appendRec(EDB_REC logEvent);
      }

      Serial.print("Record Count: "); Serial.println(db.count());
      // Thanks to katts0...@gmail.com for the next line
      for (recno = 1; recno <= RECORDS_TO_CREATE; recno++)
      {
        db.readRec(recno, EDB_REC logEvent);
        Serial.print("ID: "); Serial.print(logEvent.id);
        Serial.print(" Temp: "); Serial.print(logEvent.temperature);
        Serial.print(" Data: "); Serial.println(logEvent.test);
      }
    }

    void loop()
    {
    }

The output:

    Extended Database Library + Arduino Internal EEPROM Demo

    Record Count: 0
    Creating Records...
    Record Count: 10
    ID: 1 Temp: 2 Data: 3 whatever 1
    ID: 2 Temp: 4 Data: 6 whatever 2
    ID: 3 Temp: 6 Data: 9 whatever 3
    ID: 4 Temp: 8 Data: 12 whatever 4
    ID: 5 Temp: 10 Data: 15 whatever 5
    ID: 6 Temp: 12 Data: 18 whatever 6
    ID: 7 Temp: 14 Data: 21 whatever 7
    ID: 8 Temp: 16 Data: 24 whatever 8
    ID: 9 Temp: 18 Data: 27 whatever 9
    ID: 10 Temp: 20 Data: 30 whatever 10


sender: user

sender: assistant

body:
I managed to solve the problem. The problem is with the SD card library of Arduino. I downloaded this library [sdFat library][1], included it in the sketch `#include "SdFat.h"`, and defined `SdFat SD`. I also removed the `#include <SD.h>`.

  [1]: https://github.com/greiman/SdFat/tree/master/examples


message:
3.3V Conversion

I'm writing a SPI Master module for my FPGA and I would like test it with my Arduino Uno.
What's the problem? My FPGA has 3.3V logic and Arduino has 5V TTL logic.
So, what's the simplest solution to convert 5V TTL logic into 3.3V logic?

I know this topic has been already discussed in many sites but I can't find an unified answer.

Thanks in advance!

body:
You can get 5, 4 channel bi-directional logic level converters for less than $1 USD [Logic Level Module][1]

  [1]: https://www.aliexpress.com/item/5PCS-IIC-I2C-Logic-Level-Converter-Bi-Directional-Module-5V-to-3-3V-For-Arduino/32216849765.html

Not only will they "translate" 3.3V to 5V and 5V to 3.3V, but they also work with higher voltages as well. For example, a vehicle with a 12V electrical system to 5V and vice versa works too.


message:
how to make this work auto on off led with fading

I'm working on a project with Arduino to make LED timer with fading feature. After doing some research finally I wrote some code but it's not working until now
P.S i don't have any knowledge in coding at all T_T

**Edit:** Adding more details about the issue;
when trying to check upload this error is always shown.

    Arduino: 1.8.5 (Windows 10), Board: "Arduino/Genuino Uno"

    \SunRisetimer.ino: In function 'void loop()':

    SunRisetimer:55: error: 'startOff' was not declared in this scope

         startOff();
    \SunRisetimer.ino: In function 'void startOn()':

    SunRisetimer:89: error: variable or field 'startOff' declared void

     void startOff

    SunRisetimer:91: error: expected '}' before ';' token

    analogWrite(uled, 1);

    SunRisetimer:116: error: expected '}' at end of input

     }
    exit status 1
    'startOff' was not declared in this scope

**Code:**

    #include <DS3231.h> //Include the clock library

    // Changable Vars
    int fadeTimeOn = 30; // How long the light will fade to max
    int fadeTimeOff = 30; // How long the light will fade to min
    int setHourOn = 9; // Set hours to wake (military time)
    int setMinOn = 15; // Set minute to wake
    int setHourOff = 9; //set off h
    int setMinOff = 30; //
    int uled = 9; // Set pinout with with PWM

    // Set up Vars
    DS3231  rtc(SDA, SCL);
    Time t;
    void start();

    void setup()
    {
      pinMode(uled, OUTPUT);
      Serial.begin(9600); // Match to serial monitor
      rtc.begin();
    }

    void loop()
    {
      t = rtc.getTime(); // Make a time class called 't'

      // Send Day-of-Week
      Serial.print(rtc.getDOWStr());
      Serial.print(" ");

      // Send date
      Serial.print(rtc.getDateStr());
      Serial.print(" -- ");

      // Send time
      Serial.println(rtc.getTimeStr());

      if (t.hour == setHourOn && t.min == setMinOn) // Check if it's time to wake up!
      {
        startOn();
      }

      // Wait one second before repeating
      delay (1000);

     if (t.hour == setHourOff && t.min == setMinOff) // Check if it's time to off!
      {
        startOff();
      }

      // Wait one second before repeating
      delay (1000);
    }

    void startOn()
    {
      // Fix for SB LED
      analogWrite(uled, 1);
      delay((fadeTimeOn * 60000)/50);
      analogWrite(uled, 2);
      delay((fadeTimeOn * 60000)/50);
      analogWrite(uled, 3);
      delay((fadeTimeOn * 60000)/50);
      analogWrite(uled, 4);
      delay((fadeTimeOn * 60000)/50);
      analogWrite(uled, 4);
      delay((fadeTimeOn * 60000)/50);
      analogWrite(uled, 5);
      delay((fadeTimeOn * 60000)/50);

    for (int i = 6 ; i <= 255; i++)
        {
        analogWrite(uled, i);
        delay(((fadeTimeOn * 60000)/306));
        Serial.print(" mil sec ");
        Serial.print(((fadeTimeOn * 60000)/306));
        Serial.print(" PWM " );
        Serial.print(i);
        {
    }

    void startOff
    {
      analogWrite(uled, 1);
      delay((fadeTimeOff * 60000)/50);
      analogWrite(uled, 5);
      delay((fadeTimeOff * 60000)/50);
      analogWrite(uled, 4);
      delay((fadeTimeOff * 60000)/50);
      analogWrite(uled, 3);
      delay((fadeTimeOff * 60000)/50);
      analogWrite(uled, 2);
      delay((fadeTimeOff * 60000)/50);
      analogWrite(uled, 1);
      delay((fadeTimeOff * 60000)/50);

      // Fade script
      for (int i = 6 ; i <= 255; i++)
      {
        analogWrite(uled, i);
        delay(((fadeTimeOff * 60000)/306));
        Serial.print(" mil sec ");
        Serial.print(((fadeTimeOff * 60000)/306));
        Serial.print(" PWM " );
        Serial.print(i);

      }

    }

body:
Look at your function definitions:

    void startOn() // works
    void startOff    // doesn't work

You are missing the `()` after `startOff`.


message:
Problem to display Ntp time on an oled using U8G2 lib

So I have this code to get ntp time and display it on serial port. But I want to display it on a 1.30 inch I2C oled with a SH1106 controller using the U8G2 library. The only problem is I don't know the correct syntax. I have tried

    Serial.print((epoch  % 86400L) / 3600); // print the hour (86400 equals secs
    per day)
    int ho = ((epoch  % 86400L) / 3600+9);
    itoa(ho,hours,10);
    u8g2.clearBuffer();         // clear the internal memory
    u8g2.setFont(u8g2_font_ncenB14_tr); // choose a suitable font
    u8g2.drawStr(0,20,hours);

and also

    {
    u8g2.setFont(u8g2_font_ncenB14_tr);
    u8g2.firstPage();
    do {
    u8g2.setCursor(0, 20);
    u8g2.print(hours,DEC);
    u8g2.setCursor(33, 20);
    u8g2.print(minutes,DEC);
    }
    while ( u8g2.nextPage() );
    }

This is my code

    //This is a code to display ntp time using Nodemcu

    #include <ESP8266WiFi.h>
    #include <WiFiUdp.h>
    #include <Arduino.h>
    #include <U8g2lib.h>

    #ifdef U8X8_HAVE_HW_SPI
    #include <SPI.h>
    #endif
    #ifdef U8X8_HAVE_HW_I2C
    #include <Wire.h>
    #endif

    U8G2_SH1106_128X64_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/U8X8_PIN_NONE);

    char ssid[] = "123456";     //  your network SSID (name)
    char pass[] = "123456";     // your network password

    //Your UTC Time Zone Differance  India +5:30
    char HH = 5;
    char MM = 30;

    unsigned int localPort = 2390;      // local port to listen for UDP packets

    //* Don't hardwire the IP address or we won't get the benefits of the pool.
    //* Lookup the IP address for the host name instead */

    //IPAddress timeServer(129, 6, 15, 28); // time.nist.gov NTP server

    IPAddress timeServerIP; // time.nist.gov NTP server address

    const char* ntpServerName = "time.nist.gov";

    const int NTP_PACKET_SIZE = 48; // NTP time stamp is in the first 48 bytes
    // of the message

    byte packetBuffer[ NTP_PACKET_SIZE]; //buffer to hold incoming and outgoing
    //packets

    // A UDP instance to let us send and receive packets over UDP
    WiFiUDP udp;

                                  //SETUP

    void setup()
    {
    Serial.begin(115200);
    Serial.println();
    Serial.println();

    // We start by connecting to a WiFi network
    Serial.print("Connecting to ");
    Serial.println(ssid);
    WiFi.mode(WIFI_STA);
    WiFi.begin(ssid, pass);

    while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
    }
    Serial.println("");

    Serial.println("WiFi connected");
    Serial.println("IP address: ");
    Serial.println(WiFi.localIP());

    Serial.println("Starting UDP");
    udp.begin(localPort);
    Serial.print("Local port: ");
    Serial.println(udp.localPort());
    }

    //  Send an NTP request to the time server at the given address

    unsigned long sendNTPpacket(IPAddress& address)
    {
    Serial.println("sending NTP packet...");
    // set all bytes in the buffer to 0
    memset(packetBuffer, 0, NTP_PACKET_SIZE);

    // Initialize values needed to form NTP request
    // (see URL above for details on the packets)
    packetBuffer[0] = 0b11100011;   // LI, Version, Mode
    packetBuffer[1] = 0;     // Stratum, or type of clock
    packetBuffer[2] = 6;     // Polling Interval
    packetBuffer[3] = 0xEC;  // Peer Clock Precision
    // 8 bytes of zero for Root Delay & Root Dispersion
    packetBuffer[12]  = 49;
    packetBuffer[13]  = 0x4E;
    packetBuffer[14]  = 49;
    packetBuffer[15]  = 52;

    // all NTP fields have been given values, now
    // you can send a packet requesting a timestamp:

    udp.beginPacket(address, 123); //NTP requests are to port 123
    udp.write(packetBuffer, NTP_PACKET_SIZE);
    udp.endPacket();

    u8g2.begin();
    }
                                  //LOOP

    void loop()
    {
    char hours;
    char minutes;
    char seconds;

    // get a random server from the pool
    WiFi.hostByName(ntpServerName, timeServerIP);

    sendNTPpacket(timeServerIP);

    // send an NTP packet to a time server
    // wait to see if a reply is available
    delay(1000);

    int cb = udp.parsePacket();
    if (!cb) {
    Serial.println("no packet yet");
    }
    else {
    Serial.print("packet received, length=");
    Serial.println(cb);

    // We've received a packet, read the data from it
    udp.read(packetBuffer, NTP_PACKET_SIZE); // read the packet into the buffer
    //the timestamp starts at byte 40 of the received packet and is four bytes,
    // or two words, long. First, esxtract the two words:
    unsigned long highWord = word(packetBuffer[40], packetBuffer[41]);
    unsigned long lowWord = word(packetBuffer[42], packetBuffer[43]);

    // combine the four bytes (two words) into a long integer
    // this is NTP time (seconds since Jan 1 1900):
    unsigned long secsSince1900 = highWord << 16 | lowWord;
    Serial.print("Seconds since Jan 1 1900 = " );
    Serial.println(secsSince1900);

    // now convert NTP time into everyday time:
    Serial.print("Unix time = ");
    // Unix time starts on Jan 1 1970. In seconds, that's 2208988800:
    const unsigned long seventyYears = 2208988800UL;
    // subtract seventy years:
    unsigned long epoch = secsSince1900 - seventyYears;
    // print Unix time:
    Serial.println(epoch);

    // print the hour, minute and second:
    minutes = ((epoch % 3600) / 60);
    minutes = minutes + MM; //Add UTC Time Zone

    hours = (epoch  % 86400L) / 3600;
    if(minutes > 59)
    {
    hours = hours + HH + 1; //Add UTC Time Zone
    minutes = minutes - 60;
    }
    else
    {
    hours = hours + HH;
    }

    Serial.print("The UTC time is ");       // UTC is the time at Greenwich //Meridian (GMT)

    Serial.print(hours,DEC); // print the hour (86400 equals secs per day)
    Serial.print(':');

    if ( minutes < 10 ) {
    // In the first 10 minutes of each hour, we'll want a leading '0'
    Serial.print('0');
    }
    Serial.print(minutes,DEC); // print the minute (3600 equals secs per minute)
    Serial.print(':');

    seconds = (epoch % 60);
    if ( seconds < 10 ) {
    // In the first 10 seconds of each minute, we'll want a leading '0'
    Serial.print('0');
    }
    Serial.println(seconds,DEC); // print the second
    }
    // wait ten seconds before asking for the time again
    delay(10000);
    }

Adding the second block of code (print one) to the main code gives me correct time on the oled screen but only when the ntp receives a packet. Otherwise its some 10 digit number. How do I get rid of the number and keep displaying the time till it is update with a valid newer value. I have attached images of display.

![Correct time][1]

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

![10 digit value](https://i.stack.imgur.com/kjjyC.jpg)

body:
EDIT: I checkout Internet access is working OK. Problem is the server.

Your sketch works well (after some refactoring) against my local LAN NTP server and ntp.shoa.cl, but not against time.nist.gov, the one in your sketch.

It looks like the NTP server time.nist.gov itself is having problems. `ntpdate` reports:

    > look@gear ~/Downloads/mover $ ntpdate -q time.nist.gov server
    > 129.6.15.28, stratum 0, offset 0.000000, delay 0.00000 11 Feb 13:11:05 ntpdate[5855]: no server suitable for synchronization found

so that may explain that your code fails.

Anyway, I refactored your code before testing before `delays` are source of all kind of problems. I run OK at the first test.

I only modify `loop`; everything else is the same. I made it a state machine with three states: `idle`, your are reading to send an UDP packet; `reading`, you are trying to read the answer; and `waiting`, where you spend 10 seconds doing nothing.

I also move all printing to a new `processPacket` function, to keep `loop` short and easy to read.

Never use delay(). Use the scheme provide here to wait using millis().

    void loop() {
     enum st {idle, reading, waiting};
     static st status;
     static unsigned long prev = 0;
     unsigned long now = millis();

     switch(status) {
     case idle:
      // get a random server from the pool
      WiFi.hostByName(ntpServerName, timeServerIP);

      sendNTPpacket(timeServerIP);
      status = reading;
      prev = now;
      break;

     case reading:
      if(now - prev > 1000L) {
       int cb = udp.parsePacket();

       if(cb) {
        status = idle;
        Serial.print("packet received, length=");
        Serial.println(cb);
        processPacket();
       } else {
        Serial.println("no packet yet");
       }

       prev = now;
      }

      break;

     case waiting:
      if(now - prev > 10000L) {
       status = idle;
       prev = now;
      }
     }
    }

    void processPacket()
    {
     char hours;
     char minutes;
     char seconds;

     // We've received a packet, read the data from it
     udp.read(packetBuffer, NTP_PACKET_SIZE); // read the packet into the buffer
     //the timestamp starts at byte 40 of the received packet and is four bytes,
     // or two words, long. First, esxtract the two words:
     unsigned long highWord = word(packetBuffer[40], packetBuffer[41]);
     unsigned long lowWord = word(packetBuffer[42], packetBuffer[43]);

     // combine the four bytes (two words) into a long integer
     // this is NTP time (seconds since Jan 1 1900):
     unsigned long secsSince1900 = highWord << 16 | lowWord;
     Serial.print("Seconds since Jan 1 1900 = ");
     Serial.println(secsSince1900);

     // now convert NTP time into everyday time:
     Serial.print("Unix time = ");
     // Unix time starts on Jan 1 1970. In seconds, that's 2208988800:
     const unsigned long seventyYears = 2208988800UL;
     // subtract seventy years:
     unsigned long epoch = secsSince1900 - seventyYears;
     // print Unix time:
     Serial.println(epoch);
     // print the hour, minute and second:
     minutes = ((epoch % 3600) / 60);
     minutes = minutes + MM; //Add UTC Time Zone
     hours = (epoch  % 86400L) / 3600;
     if(minutes > 59) {
      hours = hours + HH + 1; //Add UTC Time Zone
      minutes = minutes - 60;
     } else {
      hours = hours + HH;
     }
     Serial.print("The UTC time is ");       // UTC is the time at Greenwich //Meridian (GMT)
     Serial.print(hours,DEC); // print the hour (86400 equals secs per day)
     Serial.print(':');
     if(minutes < 10) {
        // In the first 10 minutes of each hour, we'll want a leading '0'
      Serial.print('0');
     }
     Serial.print(minutes,DEC); // print the minute (3600 equals secs per minute)
     Serial.print(':');
     seconds = (epoch % 60);
     if(seconds < 10) {
      // In the first 10 seconds of each minute, we'll want a leading '0'
      Serial.print('0');
     }
     Serial.println(seconds,DEC); // print the second
       u8g2.setFont(u8g2_font_ncenB14_tr);
     u8g2.firstPage();
     do {
        u8g2.setCursor(0, 20);
        u8g2.print(hours,DEC);
        u8g2.drawStr(25, 17,":");
        u8g2.setCursor(33, 20);
        u8g2.print(minutes,DEC);
        }
     while(u8g2.nextPage());
      }

And this is the output:

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

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


message:
Servo causes disconnection

I've only started using Arduino in the last week, and I'm having a problem with the servo supplied with the kit I purchased. It's a SG90 microservo. I'm trying to connect the servo as shown on the [Arduino tutorial site][1]:

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

But when I connect the power and ground pins to the board, the board powers down and disconnects from the USB. I've had the servo working before without a problem.

Yesterday I was trying out another tutorial without any luck, and I noticed the servo getting hot (not too hot to touch though).

Could I have accidentally fried the control board in the servo?

  [1]: https://www.arduino.cc/en/Tutorial/Sweep
  [2]: https://i.stack.imgur.com/ZRNo3.png

body:
Have a look at the current requirements of the SG90 and compare this to the maximum current available from an Arduino Uno.

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

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

Another thing to look at is how much current your computer's USB port can supply. My laptop, for example, can only supply 500mA per USB port.

My advise is to use a separate 5V power supply for the servo.


message:
How do I get multiple readings(binary) based on my arduino output?

I am new to arduino and therefore not much experience in handling codes, please be forgiving and help me!

For my school project, make use of arduino to make 4 capacitive sensors (which has already been successful). Now I am trying to make use of the 4 sensors to be shown in a table format(one for each output) so that I can use that data to be plotted into either Excel or Matlab. Hence I would like to ask how do I group up my data into different columns? Also is it possible to get convert my results into binary format so that it would be easier when trying to plot the data?

My arduino code is here:

    #include <CapacitiveSensor.h>

    CapacitiveSensor   cs_2_4 = CapacitiveSensor(2,4); // 1M resistor between pins 4 & 8, pin 8 is sensor pin, add a wire and or foil
    CapacitiveSensor   cs_5_7 = CapacitiveSensor(5,7);
    CapacitiveSensor   cs_8_10 = CapacitiveSensor(8,10);
    CapacitiveSensor   cs_11_13 = CapacitiveSensor(11,13);
    void setup()
    {
       cs_2_4.set_CS_AutocaL_Millis(0xFFFFFFFF);// turn off autocalibrate on channel 1 - just as an example
       cs_5_7.set_CS_AutocaL_Millis(0xFFFFFFFF);
       cs_8_10.set_CS_AutocaL_Millis(0xFFFFFFFF);
       cs_11_13.set_CS_AutocaL_Millis(0xFFFFFFFF);
     Serial.begin(9600);
       pinMode(3,OUTPUT);
       pinMode(6,OUTPUT);
       pinMode(9,OUTPUT);
       pinMode(12,OUTPUT);
    }

    void loop()
    {
     long sensor1 =  cs_2_4.capacitiveSensor(50);
     long sensor2 =  cs_5_7.capacitiveSensor(50);
     long sensor3 =  cs_8_10.capacitiveSensor(50);
     long sensor4 =  cs_11_13.capacitiveSensor(50);

    Serial.println(sensor1);  // print sensor output
        Serial.print("\t");
        Serial.println(sensor2);
        Serial.print("\t");
        Serial.println(sensor3);
        Serial.print("\t");
        Serial.println(sensor4);
     if(sensor1 >= 1000)
       {
        digitalWrite(3,HIGH);
       }
      else{
        digitalWrite(3,LOW);
       }
         if(sensor2 >= 1000)
       {
        digitalWrite(6,HIGH);
       }
       else{
        digitalWrite(6,LOW);
       }
        if(sensor3 >= 1000)
       {
        digitalWrite(9,HIGH);
       }
       else{
        digitalWrite(9,LOW);
       }
        if(sensor4 >= 1000)
       {
        digitalWrite(12,HIGH);
       }
       else{
        digitalWrite(12,LOW);
       }

       }

And with that code above the output I receive when I use the serial monitor is:

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

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

body:
>     Serial.println(sensor1);  // print sensor output
    Serial.print("\t");
    Serial.println(sensor2);
    Serial.print("\t");
    Serial.println(sensor3);
    Serial.print("\t");
    Serial.println(sensor4);

If you want 4 columns don't use `println` for each number, as that starts a new line.

---

> Also is it possible to get convert my results into binary format so that it would be easier when trying to plot the data?

Yes it's possible however I don't see how that makes anything easier.


message:
Is there a way to play .mp3 files from an SD card on Arduino?

Is there a way to have mp3 files on an SD card in the SD card shield for the Arduino and play an mp3 file on that SD card with a buzzer?

If possible also with something like:

    playmp3(thismp3.mp3);

So that if I execute that command, the Arduino will play thismp3.mp3 through a buzzer.

Thank you.

body:
It's not as easy as that. The SD card and playing audio are two different things.

However, probably the easiest way is to buy an MP3 shield (but that spoils the fun to make it yourself).

On the other hand, to make it yourself, takes quite some effort.

Also, the audio quality will be very low.
Besides that, decoding MP3 is far from trivial.

In case you want to make it yourself:

- First write a program to read (stream) bytes from the SD card
- Write an MP3 decoder (maybe/probably there are open source variants)
- Forward the MP3 bytes to the decoder
- Forward the audio bytes to the buzzer

Of course, there are time constraints otherwise you hear gaps in the music.


body: If you're not specifically trying to make the arduino itself do the decoding and playback, you can get something like the [Mini DFPlayer](https://www.dfrobot.com/product-1121.html) which would let you do essentially what you're asking for and offloads the decoding and playback so your arduino can do something else while the audio is playing.


message:
How do I get status of contactors using Arduino (more than 50 contactors)

I am new to Arduino. Sorry if my question sounds wrong.

Interest areas: Multiple devices inter-connected on the cloud.
Single GSM for equipment in a typical panel connectivity for non-electrical parameter sensing devices e.g. Temperature, humidity.
Mechanical operations & connection status
Parameters of individual devices [non-communication capable]
Connectivity with cloud

Interest areas: Connectivity for electromechanical devices – Contactors, MCBs, RCCB etc
Parameters possible on IOT
Device Status possible on IOT
Size [Compactness] of the IOT solution to be integrated
Aux Power requirement & possible ways to provide the same
Memory retention
Remote access/control and driving of the devices
The estimated cost of the IoT connectivity devices should be a fraction of the device cost [e.g. Contactor of 9A].
Voltage level high

I am trying to read the status of more than 50 contactors i.e whether they are in ON\OFF\trip state using Arduino and display it on screen.

Can I use a single microcontroller to read the status of 50 or more contactors?

I searched on the net and I found out it can be done using shift registers or a latching system, but I didn't understand the method at all.

Please, can anyone explain me the method of doing this?Thanks.

body:
Yes you can.

There are special ICs, called Shift-In registers to do this job. You can daisy chain 4 of them, each capable of handling 8 outputs or inputs.

The most known is for outputs (e.g. LEDs) which is a 74HC595 (called shift-out register).

For inputs. you can use a CD4021BE. See the [Shiftin Example][1] how to use them.
It will cost 3 pins (except VCC/GND) to control 32 inputs, so you need 6 pins for 50 (max 64). You need 50 / 8 = 7 of these ICs, but they are very cheap (10 for about 2 dollars).

Note that you will receive either a 0 or 1, so it's up to you how to detect trip states.

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


body:
Due to lack of specifics, I cannot be more precise with my answer, but since you are working with "high" voltage (I'll assume 220V/415V) I would suggest the best solution to monitoring the current will be current transformers.

These are non-intrusive devices that you pass a single conductor through. It generates a small current in proportion to a large current flowing through the conductor.

This small current is then converted into a small voltage by passing it through a resistor and then measuring the voltage across that resistor.

Since it is AC you are dealing with simple digital IO pins will not suffice (except see below) - no matter how many you have. You need analog inputs, and you need to be able to sample that analog signal fast enough to at least capture the peaks and troughs of the incoming waveform. That means sampling at many times the frequency of the supply. For 50Hz you want to sample either at, say, 500 sps or more, or to sample at a rate that isn't a multiple of, or factor of, 50, but for a longer period of time.

Interfacing an AC voltage like this involves adding an offset voltage to it so that the zero point of the AC voltage lies in the middle of the ADC's range. This is most often done by feeding a voltage of 50% Vcc into the current transformer as a "virtual ground", so all output from it is superimposed on this offset voltage.

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

Once you know the peak to peak voltage across the load resistor of the current transformer you can use that to calculate the peak to peak current the current transformer generated (Ohm's law), and thus the current through the central conductor.

This not only gives you the actual current through the conductor, but by simple logical reasoning, also gives you the state of the contactor: no current = contactor is off.

To reduce programming complexity at the cost of increased BOM cost it could be possible to build a simple rectifying and smoothing circuit (i.e., a simple integrating circuit) from diodes and a capacitor (either a single diode and a capacitor as a half-wave rectifier and smoothing, or a full-wave rectifier and smoothing) which will give you a simple DC voltage proportional to the current. Don't forget to take into account the voltage drop of the diode (or diodes) when doing your calculations, of course.

The integrating circuit could also be used, if you don't care about the current, to directly drive a digital input, as long as the voltage generated under normal load is above the threshold (VIH) of the IO pin, and never exceeds the maximum input voltage for the pin (a little over 5V).  Adding a 5.1V zener diode and series resistor can help protect the input. The same should be done to an analog input as well to protect it from overvoltage.

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

One important thing with this integrating circuit, though, is that any downward changes in the current will take time to be reflected in the output. That is caused by the time C1 takes to discharge down to the new voltage level through R1. Balancing these values so you get a reasonable amount of responsiveness yet minimum amount of ripple on the signal will take a little experimentation and calculation.

You can read more about current transformers and interfacing them to an Arduino [here](https://openenergymonitor.org/forum-archive/node/156.html).

----

For interfacing so many sensors to an Arduino you can, depending on if you are wanting to measure the current directly, or integrate the current to a DC voltage and use it as a threshold to a GPIO pin:

* Use shift registers (Parallel-to-Serial) for digital threshold reading,
* Use IO expanders (eg MCP23017) for digital threshold reading,
* Use external ADC chips (eg MCP3208) to provide more ADC inputs, or
* Use analog multiplexers (eg CD4051) to switch different analog voltages to a limited number of ADC inputs

Another option is to break your system down into smaller, more manageable, chunks.  Group your signals into small subsections and have each subsection handled by a separate controller - be that an Arduino (maybe a Mini, or a Micro, or something) to handle a small group of signals. These can then feed their data into a more powerful management system (maybe a Raspberry Pi) through a serial protocol of some form (or wirelessly if you want to spend extra money), which then forwards the readings on to your chosen web service.


message:
High pass filtering accelerometer data on Arduino

I'm trying to use an accelerometer for user input to a device. The idea is that the user input will be tied to "taps" on the accelerometer, one tap means something, two taps something else, etc.

I'm using an Adafruit Feather M0 as my microcontroller, controlling an accelerometer that feeds me x,y,z-data at a sampling rate of 100 Hz. I now then want to high pass filter the data with a cutoff frequency of 10 Hz, since taps on the accelerometer give rise to much higher frequencies than other "noise", such as movement.

The accelerometer uses a FIFO buffer to output the data, so I collect 20 samples at a time, and I want to filter those 20 samples with a high pass filter to see if there is a tap within that sampling window. I am currently using the filter function on Arduino playground, https://playground.arduino.cc/Code/Filters.

However, and here is my problem; When I implement this in my code, the filtering "restarts" each window, so that my filtered data looks like this:

    [X], [Y], [Z]
    0.00,0.00,0.00
    -39.67,94.13,-85.18
    -29.89,71.66,-64.18
    -24.02,53.99,-49.08
    -17.39,40.78,-37.09
    -13.00,30.51,-27.74
    -9.80,22.99,-20.91
    -7.58,17.00,-16.17
    -7.01,13.88,-14.01
    -4.86,12.04,-10.53
    -4.02,9.96,-8.71
    -2.44,8.05,-7.04
    -1.99,6.57,-5.74
    -1.60,5.26,-3.80
    -2.76,3.27,-4.45
    -1.43,2.67,-3.63
    -1.16,2.16,-2.13
    -0.94,2.55,-1.72
    -0.76,1.26,-0.58
    -0.62,0.21,-1.29

    0.00,0.00,0.00
    -40.26,94.51,-84.88
    -30.38,70.55,-64.78
    -22.13,53.89,-48.04
    -17.42,40.60,-37.69
    -13.91,29.87,-27.68
    -10.99,23.61,-22.67
    -10.05,19.04,-16.00
    -5.78,14.79,-13.94
    -4.69,12.82,-11.31
    -3.84,9.69,-9.27
    -3.14,7.91,-7.56
    -2.52,6.35,-6.08
    -2.07,5.22,-4.18
    -0.88,4.29,-3.43
    -2.35,4.32,-3.62
    -0.29,3.54,-2.97
    -1.07,2.94,-3.29
    -1.63,0.74,-1.02
    -0.50,1.38,-1.60

    0.00,0.00,0.00
    -40.51,95.10,-85.37
    -30.32,70.41,-65.39
    -22.86,53.10,-49.31
    -17.26,40.83,-35.71
    -13.45,31.81,-27.81
    -9.37,22.43,-20.92
    -7.80,17.62,-15.74
    -6.50,13.01,-13.10
    -4.04,9.56,-8.16
    -3.02,7.15,-6.85
    -2.29,5.42,-4.43
    -2.70,3.63,-4.46
    -1.38,4.56,-3.61
    -1.14,2.95,-2.16
    -1.73,2.38,-1.75
    -1.32,2.59,-2.10
    -1.05,0.47,-1.67
    -0.04,1.12,-1.28
    -0.03,0.90,-1.03

I don't understand why this happens, and why the data in the subsequent windows aren't suppressed from the start. I have implemented a very similar solution in Python which works very well with the filtering. Have I misunderstood how Arduinos filtering functions work?

Here is my code:

    // Include SPI library
    #include <SPI.h>
    #include <Filters.h>

    // List of addresses: 7-bit adresses, 8th bit is R/W bit, and is set in the functions readRegister and writeRegister.
    char X_data_low = 0x28;
    char X_data_high = 0x29;
    char Y_data_low = 0x2A;
    char Y_data_high = 0x2B;
    char Z_data_low = 0x2C;
    char Z_data_high = 0x2D;

    char CTRL_REG1 = 0x20; // Controls data rate selection, low power mode, and X-, Y- and Z-axis enable
    char CTRL_REG1_value = 0b00101111; // 0001 1111 = 1 Hz, LP mode, XYZ enable.

    char CTRL_REG5 = 0x24; // Enables FIFO mode, among others.
    char CTRL_REG5_value = 0b01000000; // 0100 0000, FIFO enabled, all else is zero.

    char STATUS_REG = 0x27; // Flags for new XYZ values.

    char FIFO_CTRL_REG = 0x2E; // Controls FIFO mode (Bypass, FIFO, Stream, Stream-To-FIFO)
    char FIFO_CTRL_REG_value = 0b01000000; // Selects FIFO mode

    char FIFO_SRC_REG = 0x2F; // Watermark level, FIFO Overrun, FIFO empty, FSS. Can read FSS to know how many unread samples FIFO buffer contains currently.

    //int smpls = 20; // Number of samples

    char values[240]; // buffer for storing read values.

    int x_val[40]; // Arrays for storing values before filtering
    int y_val[40];
    int z_val[40];

    float filtered_x_val[40]; // Arrays for storing values after filtering
    float filtered_y_val[40];
    float filtered_z_val[40];

    int CS = 5; // Chip select pin

    int concat_val = 0b00011111; // For concatenation with values[0] to find number of samples in FIFO buffer
    int number_of_FIFO_values; // Number of FIFO samples

    // Testing Arduinos own filtering

    // filters out changes slower that 10 Hz.
    float filterFrequency = 10.0;

    // create a one pole (RC) lowpass filter
    FilterOnePole highpassFilter_x( HIGHPASS, filterFrequency );
    FilterOnePole highpassFilter_y( HIGHPASS, filterFrequency );
    FilterOnePole highpassFilter_z( HIGHPASS, filterFrequency );

    void setup() {
      // put your setup code here, to run once:
      // Opening pins
      pinMode(22, INPUT_PULLUP); // MISO
      pinMode(24, OUTPUT); // SCK
      pinMode(23, OUTPUT); // MOSI
      pinMode(CS, OUTPUT);  // CS
      pinMode(14, OUTPUT);  // VDD_IO, for use when no breadboard is available to connect both VDD and VDD_IO to 3.3V output
      digitalWrite(CS, HIGH);
      digitalWrite(14, HIGH);
      delay(50);

      // Communication with computer
      Serial.begin(9600);

      // SPI
      SPI.begin();
      SPI.beginTransaction(SPISettings(10000000, MSBFIRST, SPI_MODE0));
      // Loading settings
      delay(10);
      writeRegister(CTRL_REG1,CTRL_REG1_value);
      delay(10);
      writeRegister(CTRL_REG5,CTRL_REG5_value);
      delay(10);
      writeRegister(FIFO_CTRL_REG,FIFO_CTRL_REG_value);
      delay(10);

    }

    void loop() {
      readRegister(0x2F,1,values);
      number_of_FIFO_values = values[0] & concat_val;

      if (number_of_FIFO_values >= 20){ // It is enough to read high values since LP mode is only 8 bits
        readRegister(0x28,120,values);
        int x_count = 0; // Counters to keep track of which value in x_val, y_val, z_val to be assigned
        int y_count = 0;
        int z_count = 0;
        for(int i=0; i<120; i++){
          if (i % 6 == 1) {
            x_val[x_count] = int(values[i]);
            if(x_val[x_count] > 127)
              x_val[x_count] -= 256;
            x_count += 1;
            }
          if (i % 6 == 3) {
            y_val[y_count] = int(values[i]);
            if(y_val[y_count] > 127)
              y_val[y_count] -= 256;
            y_count += 1;
            }
          if (i % 6 == 5) {
            z_val[z_count] = int(values[i]);
            if(z_val[z_count] > 127)
              z_val[z_count] -= 256;
            z_count += 1;
            }
          }
        Serial.print('\n');
        filtering(x_val,y_val,z_val);
        writeRegister(FIFO_CTRL_REG,0b00000000);
        delay(10);
        writeRegister(FIFO_CTRL_REG,FIFO_CTRL_REG_value);
        delay(10);
      }
    }

    void filtering(int x_arr[], int y_arr[], int z_arr[]){
        for(int i=0; i<20; i++) {
          highpassFilter_x.input(x_arr[i]);
          highpassFilter_y.input(y_arr[i]);
          highpassFilter_z.input(z_arr[i]);
          filtered_x_val[i] = highpassFilter_x.output();
          filtered_y_val[i] = highpassFilter_y.output();
          filtered_z_val[i] = highpassFilter_z.output();
          Serial.print(filtered_x_val[i]);
          Serial.print(",");
          Serial.print(filtered_y_val[i]);
          Serial.print(",");
          Serial.print(filtered_z_val[i]);
          Serial.print('\n');
        }
      }

    //This function will write a value to a register on the sensor.
    // Parameters:
    //  char registerAddress - The register to write a value to
    //  char value - The value to be written to the specified register.
    // The bits to specify write or read operation on slave device, and single
    // or multiple register reading in reading operation, are included in the
    // registeraddress.
    // As defined by protocol, the MSB of the address indicates write/read, and the following bit indicate single/multiple reading. Cause ADXL345 support Byte operation,
    // The MSB is the 8th bit, the following bit is the 7th bit. (note: if indicating multiple bits reading, ADXL345 will increasing the register address automatically to the
    // next successive register like a pointer.
    void writeRegister(char registerAddress, char value){
      //Set Chip Select pin low to signal the beginning of an SPI packet.
      digitalWrite(CS, LOW);
      //Transfer the register address over SPI.
      // All ADXL345 register address are smaller than 0100 0000, all are like 00** ****, so that any register address of ADXL345 can be used directly for register write operation
      // without any change on the MSB and its following bit, but the case for reading operation is the opposite.
      // Might need a delay here between CS going low and data transfer.
      SPI.transfer(registerAddress);
      //Transfer the desired register value over SPI.
      // ignored the reture of SPI.transfer in writer operation
      SPI.transfer(value);
      //Set the Chip Select pin high to signal the end of an SPI packet.
      digitalWrite(CS, HIGH);
    }

    //This function will read a certain number of registers starting from a specified address and store their values in a buffer.
    //Parameters:
    //  char registerAddress - The register addresse to start the read sequence from.
    //  int numBytes - The number of registers that should be read.
    //  char * values - A pointer to a buffer where the results of the operation should be stored.
    void readRegister(char registerAddress, int numBytes, char * values){
      //Since we're performing a read operation, the most significant bit (bit 7(counting starts from bit 0)) of the register address should be set high.
      char address = 0x80 | registerAddress;
      //If we're doing a multi-byte read, bit 6 (counting starts from bit 0)needs to be set high as well.
      if(numBytes > 1)address = address | 0x40;

      //Set the Chip select pin low to start an SPI packet.
      digitalWrite(CS, LOW);
      //Transfer the starting register address that needs to be read.
      SPI.transfer(address);
      //Continue to read registers until we've read the number specified, storing the results to the input buffer.
      //SPI is full duplex transsmission. Every signle time SPI.transfer can and can only transmit 8 bits. the input parameter will be delived to slave, and it's return will be
      // the data that master device and get from the slave device. The data returned during master device's write operation makes no sense, hence always been ignored by not
      // doing any assignment operation.
      for(int i=0; i<numBytes; i++){
        values[i] = SPI.transfer(0x00);
      }
      //Set the Chips Select pin high to end the SPI packet.
      digitalWrite(CS, HIGH);
    }

body:
This filter library is sensitive to the timing of you calling
`FilterOnePole::input()`. It assumes that the delays between consecutive
calls are the same as the delays between the samples being measured.
C.f. the first statement in the method, which is [a call to
`micros()`][micros]. The pauses between your 20-sample buffers are then
interpreted like long times during which the input only changed very
little.

If you are sampling at a constant data rate, I recommend you reimplement
the filter yourself: it is simple enough and it will be way more
efficient than the one you found on Playground.

------------------------------------------------------------------------

**Edit**: Here is a simple implementation of a first-order high-pass
filter like the one in the library, but using a constant sampling rate:

    class HigPassFilter
    {
    public:
        HigPassFilter(float reduced_frequency)
        : alpha(1-exp(-2*M_PI*reduced_frequency)), y(0) {}
        float operator()(float x) {
            y += alpha*(x-y);
            return x-y;
        }
    private:
        float alpha, y;
    };

You would use it like this:

    // Create the filters.
    HigPassFilter highpassFilter_x(cutoffFrequency/samplingFerquency);
    HigPassFilter highpassFilter_y(cutoffFrequency/samplingFerquency);
    HigPassFilter highpassFilter_z(cutoffFrequency/samplingFerquency);

    // Apply them.
    filtered_x_val[i] = highpassFilter_x(x_arr[i]);
    filtered_y_val[i] = highpassFilter_y(y_arr[i]);
    filtered_z_val[i] = highpassFilter_z(z_arr[i]);

[micros]: https://github.com/JonHub/Filters/blob/aeb294b4a66cf5dc30d5998cc221115dec95eb80/FilterOnePole.cpp#L20


message:
Is the arduino hackable when using communication shields?

Let's say I have an arduino Uno connected to a W5100 ethernet shield. The arduino communicates with the ethernet shield using the tx0 and rx0 pins. When I upload a new script to the arduino using USB, it uses the same tx0 and rx0. So that made me think.

What if I run a script on my arduino that fetches some data from a webpage using HTTP requests but someone manages to hack into my server. Is it possible for the hacker to upload some kind of code to my server, which will erase (when fetched by the arduino) the old script and upload a new arduino script, by making the arduino think it's uploading a new script while it's getting data from the ethernet shield (or other communication shields?)

EDIT: Let's expand the question a bit.. How can I add security to my code to prevent this situation from happening?

body:
You should be pretty safe, at least as long as your code handles the
incoming data properly.

When you upload a new sketch through USB, the USB-to-serial interface
uses the Arduino pins TX0, RX0 **and RESET**. Your Ethernet shield, on
the other hand, does not control the RESET pin. Pulling the RESET pin
LOW is needed to make the processor enter the bootloader, which in turn
is needed in order to upload a new program. For pulling this pin low,
the malicious code would need not only to break into the Ethernet
shield's firmware, it would also need a **hardware hack** to access the
pin.

Now, if your own code is not safe, it is conceivable that the malicious
payload tricks your program into jumping to the bootloader or, as
suggesting by Juraj, into triggering a watchdog reset (which ends up
being equivalent). Thus you should treat _anything_ coming from the
network as potentially malicious.


body:
No it's not possible. Assuming you mean [this shield](https://www.arduino.cc/en/Main/ArduinoEthernetShieldV1) (and if you don't, please clarify):

> Arduino communicates with both the W5100 and SD card using the SPI bus (through the ICSP header). This is on digital pins 10, 11, 12, and 13 on the Uno and pins 50, 51, and 52 on the Mega.

Further on it mentions:

> The shield contains a number of informational LEDs:
>
>    ...
>
>    RX: flashes when the shield receives data
>
>    TX: flashes when the shield sends data

That's Rx and Tx on the shield, not the Arduino. Since it does not connect to the Tx/Rx on the Arduino, and since it cannot reset the Arduino, it therefore cannot reprogram it.

If you are worried, disable the BOOTRST fuse on the Arduino so that the bootloader is not active after a reset.

If you are *really* worried, disable the SPIEN fuse so that you cannot even reprogram it using SPI. Of course, then you won't be able to reprogram it either.

Personally I would be more worried that a cockatoo would come and peck at the shield.


message:
ESP8266 - Webserver not working in loop

I have simple example, where in loop is called webServer to handle clients and also text drawing on display.
The thing is that webServer is not responding, but when I remove second part of loop - drawing text to display then web server starts to work normally.

Server does not respond:
<!-- language-all: lang-cpp -->

     void loop() {
          server.handleClient();
          unsigned long timeNow = millis();
          if ((timeNow > screenChangeTime))  {
              display.clear();
              display.setFont(ArialMT_Plain_16);
              display.setTextAlignment(TEXT_ALIGN_CENTER);
               display.drawString(12, 20,"Loaded: "+String(particles));
               screenChangeTime= timeNow + delay;
               display.display();
          }
        }

Server responds:

    void loop() {
          server.handleClient();
    }

body:
My guess is, that you're wasting too much time within the drawing-part.

What is the value for `delay`? I guess you have a number too low chosen here. And you should really set this new time **after** you have updated the display by `display.display();`.

Your webserver doesn't respond because he's not called often enough inside this code.


message:
Arduino --> RPI I2C issue

ok, I feel like this should be simple, but I am at a loss

Simple code mock up to send 4 bytes(mimicking a float)  over I2C from Arduino to rpi. I am trying to create a state machine so that I can request certain "registers" containing 4 bytes each. I send a byte from pi to arduino indicating what "register" I want, then read back 4 bytes.  I was attemping to reset the state back to NO_STATE after the end of the switch statement, but it effects the bytes received by the pi, and I dont see how.

    #include <Wire.h>
    #define SLAVE_ADDRESS 0x04

    //States
    #define NO_STATE 0x00
    #define GET_BAT_TEMP 0x03

    byte state = NO_STATE;
    void setup() {
      Serial.begin(9600);
      pinMode(13, OUTPUT);
      Wire.begin(SLAVE_ADDRESS);
      Wire.onReceive(receiveData);
      Wire.onRequest(sendData);
    }

    void loop() {
      delay(100);
    }

    // callback for received data
    void receiveData(int byteCount){

      while(Wire.available()) {
        state = Wire.read();
      }
      Serial.print("Got:");
      Serial.println(state);
    }

    // callback for sending data
    void sendData(){
      Serial.println("Sending...");
      byte b[4]={1,1,1,1};

      switch (state){
        case NO_STATE:
          //bad state   not sure if can return only byte, may need to return 4 zeros or somthing
          Wire.write(0);
          Wire.write(0);
          Wire.write(0);
          Wire.write(0);
          break;
        case GET_BAT_TEMP:
          //send battery temp
          Wire.write(3);
          Wire.write(3);
          Wire.write(3);
          Wire.write(3);
          break;
        default:
          Wire.write(9);
          Wire.write(9);
          Wire.write(9);
          Wire.write(9);
          //send back error code
      }
      //reset state to none
      state=NO_STATE;

    }

with this code I receive [3,0,0,0]

if I comment out the line

    //state=NO_STATE;

I then receive back [3,3,3,3]

which is what I would expect. But I do not see how reseting the state "after" all the bytes are sent would cause an issue

output from arduino shows entering that function only once, and sending the 4 bytes

    Got:3
    Sending...
    Sending...
    Sending...
    Sending...

body:
I'm not an expert, but I think I found why it is not working.

The main problem is that you are using always the same byte (0, 3 or 9) for debugging, so you are not noticing that it is not sending four bytes, but only one, and the function gets called four times. This is obvious however from the reply on the serial interface (+1 for adding it in the question, good work).

What you can do is to track how many bytes you sent, and send the successive one. After the bytes are all sent you can reset back the state. The code can be something like

    //States
    #define NO_STATE 0x00
    #define GET_BAT_TEMP 0x03

    byte sentData;
    byte batteryLevel[4]={3,4,5,6};

    byte state = NO_STATE;
    void setup() {
     Serial.begin(9600);
     pinMode(13, OUTPUT);
     Wire.begin(SLAVE_ADDRESS);
     Wire.onReceive(receiveData);
     Wire.onRequest(sendData);
    }

    void loop() {
      // delay(100); // Useless, let it cycle at its max speed
    }

    // callback for received data
    void receiveData(int byteCount){
     while(Wire.available()) {
      state = Wire.read();
      sentData = 0;
     }
     Serial.print("Got:");
     Serial.println(state);
    }

    // callback for sending data
    void sendData(){
     Serial.println("Sending...");

     switch (state){
      case NO_STATE:
       //bad state   not sure if can return only byte, may need to return 4 zeros or somthing
       Wire.write(0);
       break;
      case GET_BAT_TEMP:
       //send battery temp
       Wire.write(batteryLevel[sentData]);
       if (sentData < 3)
        sentData++;
       else
        //reset state to none
        state=NO_STATE;
       break;
      default:
       Wire.write(9);
       //send back error code
     }
    }

I haven't tested it, so forgive any bugs. But I'm sure  you understood the main point.

Just some remarks: the delay is useless (you are not saving energy or other with it, so just remove it); the serial is ok for debugging, but I think you should remove it from the code you will use (not ok to stop the interrupts for such a long time).

And most important: I hope you considered the 5V vs 3.3V voltage problem on the I2C ;)

In any case, I second Look Alterno: good way to ask a question, with all the information needed.

EDIT: as pointed out in the comments, there exist a function to send all the data together. I'm not sure how it behaves in different conditions (e.g. when less bytes are requested), but if you trust the communication the function can be simplified in

    // callback for sending data
    void sendData(){
     Serial.println("Sending...");

     switch (state){
      case NO_STATE:
       //bad state   not sure if can return only byte, may need to return 4 zeros or somthing
       Wire.write(0);
       break;
      case GET_BAT_TEMP:
       //send battery temp
       Wire.write(batteryLevel, 4);
       state=NO_STATE;
       break;
      default:
       Wire.write(9);
       //send back error code
     }
    }

(and the `sentData` variable becomes useless)


message:
How to Write a function or Loop or program to receive fixed number of Integers or characters over Serial?

I am want to receive a 5 character hexadecimal input from user over serial port of arduino Uno.

    int count = 0;                                    // count = 0
    char userInput[5];

    void setup()
    {
      delay(1000);
      Serial.begin(19200);                            // begin serial port with baud rate 9600bps

    }
    void loop()
    {
      if (Serial.available() > 5)
      {
        Serial.read();
      }

      else if (Serial.available() < 4)
      {
        Serial.read();
      }

      else if (Serial.available() == 5)
      {
        for (int i = 0; i < 5; i++)
        {
          userInput[i] = Serial.read();
        }

        Serial.print("User Input - ");
        Serial.println(userInput);
      }

      delayMicroseconds(10000);
    }

But I want to discard the input if user inters less than 5 characters or more than 5?

Since the Serial.flush() have a different meaning now, I can not clear the buffer if user enters less than or more than 5 characters and the characters gets added to next input.

e.g. If I upload above program and entered input in following sequence:

    abcde
    abcd
    abcd
    abcd
    abcd
    abcdef
    abcde

I got the following output:

    User Input - abcde
    User Input - dabcd
    User Input - dacbd
    User Input - bcdef
    User Input - abcde

Two invisible characters appear in output which are not visible but when I copied the output from serial monitor but these characters appear when I copy paste the output into Text Editor.

So How can I modify the program to receive only 5 hex character input from user (Which user will input from Hex Keypad)? And if user enters more or less character I want to clear the input buffer for next user input so that characters from previous input doesn't get added to next one.

body:
As noted in the comments, since your prototype is receiving data from the serial port, you need some way for the user to indicate to the program that they are finished entry, since a 4-character entry is a necessary point along the way to a 5-character entry.

What you are doing now, by checking if `Serial.available()>5` is letting the serial buffer hold 6 characters before you read from it (note: 5 is not >5), but then your `else` statement:

    else if (Serial.available() < 4)
    {
      Serial.read();
    }

Clears out the buffer (`Serial.read()` removes one character from the buffer), so you will never get to 5 characters anyway, unless all 6 characters come in between runs of `loop()`, which is not likely at 19200 baud.

Not to mention that while data is sitting in the buffer, you don't know what it is and can't act on it. It is better to use the buffer as intended, which is to allow the Arduino to collect serial data, even while your program is working on other things, and then grab any pending data from the buffer as the program `loop()`s.

You have declared the `userInput[5]` array to hold user input, but note that if you only declare it at 5 `char`s long, it cannot hold the null-character terminator that is standard for C-style strings. It would be better to declare this as:

    char userInput[6];  // Holds 5 user characters, plus null terminator.

In your `loop()`, you should copy out the contents of the buffer into your `userInput`, check the length or for a termination character, such as a carriage return or newline (i.e., pressing 'Enter' on the serial terminal.) and act accordingly. Here is an example, showing just the relevant bits for the user input and hiding the rest in [...]:

    char userInput[6];  // Holds 5 user characters, plus null terminator.

    void setup() {
      userInput[0] = '\0';  // Initialize string to empty
      Serial.begin(9600);
    }

    void loop() {
      uint8_t processInput = 0;   // Set to 1 if we have complete entry
      while (Serial.available()>0) {
        char input = Serial.read();
        if (input=='\r' || input=='\n') {
          // Have received a terminating character,
          // Flush the rest of the buffer
          while (Serial.available()) {
            Serial.read();
          }

          processInput = 1;

        } else {
          int s_len = strnlen(userInput, 5); // Get current length of userInput
          if (s_len<5) {
            userInput[s_len++] = input;      // Append character
            userInput[s_len] = '\0';         // Null-terminate string
          } else {
            // User has entered more than 5 characters and no terminating
            // character; here is where you can decide to clear the userInput
            // and start over, or just drop the first character and care
            // about the most recent 5, etc. Here, we will clear the input
            // and start over; The 6th character is dropped/ignored and
            // user input starts again. It is as though the 6th character
            // entered is like pressing Enter, but it does not process
            // the incoming data, beacuse 6 characters is an invalid input.
            userInput[0] = '\0';
            s_len = 0;
            processInput = 0;
            // Invalid input
            Serial.println("Error: invalid data");
          }
        }
      }

      if (processInput) {
        Serial.print("User input - ");
        Serial.println(userInput);

        if (strnlen(userInput, 5)==5) {
          // Do something **here** with the input string!!

          // Reset input string
          userInput[0] = '\0';
        } else {
          // Invalid input
          userInput[0] = '\0';
          Serial.println("Error: invalid data");
        }
        processInput = 0;
      }
    }

Note, this code is not fully tested and may contain bugs. In particular, I did not intensely check if the `while (Serial.available()) {}` properly handles a lot of extra data.

One final note, you don't need the `delay()` with this code.

**EDIT:**

I tried the sample code above and it had a couple of bugs, one of which was that after a successful 5-digit entry, the input string was not reset to empty. I have now updated the code and it's a valid, working program to receive and process a 5-character input on the serial port and to toss an error if fewer than 5 or more than 5 characters are entered. Entry is terminated with a carriage return or newline (enter key).


message:
Adafruit Motor Shield steppers not turning

The Adafruit Motor Shield is connected to 2 steppers which are wired correctly and work when I just use the onestep function. I understand that I cannot drive both at once, so I am using a while loop with two if statements. The Motors were wired:

The left motor was wired:

Green -> m3+

White -> m3-

Red -> m4+

Blue -> m4-

The right motor was wired:

Red -> M2+

Blue -> M2-

Green -> M1+

Black -> M1-

Here is the code:

    #include <Wire.h>
    #include <Adafruit_MotorShield.h>
    #include "utility/Adafruit_MS_PWMServoDriver.h"

    Adafruit_MotorShield AFMS = Adafruit_MotorShield();
    Adafruit_StepperMotor *leftMotor = AFMS.getStepper(200, 2);
    Adafruit_StepperMotor *rightMotor = AFMS.getStepper(200, 1);
    //79 steps per half inch
    //half inch is a coordinate
    //declaring global variables for Hypotenuses (cord lengths)
    int leftHyp;
    int rightHyp;
    int prevX = 0;
    int prevY = 0;
    //space from shaft to shaft is 30"
    //calculating function
    void CordCalc(int xCord, int yCord)
    {
     Serial.begin(9600);
      //cords start at 0,0
     xCord = xCord - prevX;
     yCord = yCord - prevY;
     int xSquared = sq(xCord);
     int ySquared = sq(yCord);
     int addSquares = xSquared + ySquared;
     int leftHyp = sqrt(addSquares);
      //now for the right
     int rightX = 60 - xCord;
     int rightXsq = sq(rightX);
     int rightSquares = rightXsq + ySquared;
     int rightHyp = sqrt(rightSquares);
      //leftMotor->step(leftHyp * 79, FORWARD, MICROSTEP);
      //rightMotor->step(rightHyp * 79, FORWARD, MICROSTEP);
     int lStepsTaken = 0;
     int rStepsTaken = 0;
     leftHyp = leftHyp * 79;
     rightHyp = rightHyp * 79;
     bool stepsComplete = false;

      //This is the section for moving the Motors
     while(stepsComplete == false) {
      if(lStepsTaken <= leftHyp) {
       leftMotor->onestep(FORWARD,DOUBLE);
       lStepsTaken++;
       Serial.print("Left");
      }

      if(rStepsTaken < rightHyp) {
       rightMotor->onestep(FORWARD,DOUBLE);
       rStepsTaken++;
       Serial.print("Right!");
      }

      if(rStepsTaken >= leftHyp && lStepsTaken >= leftHyp) {
       stepsComplete = true;
      }
     }

     int prevY = yCord;
     int prevX = xCord;
     stepsComplete = false;
    }

    void setup()
    {
    // direction from project point of view
     int leftLength = 0;
     int rightLength = 0;
     leftMotor->setSpeed(122);
     rightMotor->setSpeed(122);
     Serial.begin(9600);

     CordCalc(15, 15);
    }

    void loop()
    {
    }

Loop is empty on purpose because only need to move to coordinates once.

body: The missing line was afms.begin(); which starts communication with the adafruit motor shield.


message:
Two Arduino boards - one IDE

Have been using UNO MEGA for small projects. Recently bought an UNO for other projects. Can I just go into the IDE an under Tools select UNO and a different port to do projects and rename sketches to keep track of sketches. Do not wish to use boards at the same time.

body:
That's the way to do it.

You need to select the type of board first:

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

And then the port. You can have both devices connected at the time and select which one you want to program.

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

With Arduino you can do OTA (Over The Air uploads) to NodeMCU and other ESP8266 based systems.

If you want to run two instances of the IDE, to work with two different boards at the same time, use [UECIDE][3].

  [1]: https://i.stack.imgur.com/AgnSX.png
  [2]: https://i.stack.imgur.com/6ClKZ.png
  [3]: http://uecide.org


message:
changed behaviour in I2C LCD

I reinstalled a previously working sketch to my UNO and now the behaviour of the lcd has changed.

Previously this example worked perfectly:

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

    LiquidCrystal_I2C lcd(0x27,16,2);  // set the LCD address to 0x27 for a 16 chars and 2 line display

    void setup()
    {
      lcd.init();                      // initialize the lcd

      // Print a message to the LCD.
      lcd.backlight();
      lcd.print("Hello, world!");
    }

    void loop()
    {
    }

Now it only displays the very first character 'H'

This version does work though:

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

    LiquidCrystal_I2C lcd(0x27,16,2);  // set the LCD address to 0x27 for a 16 chars and 2 line display

    void setup()
    {
      lcd.init();                      // initialize the lcd

      // Print a message to the LCD.
      lcd.backlight();
      lcd.print("H");
      lcd.print("e");
      lcd.print("l");
      lcd.print("l");
      lcd.print("o");
      lcd.print(" ");
      lcd.print("W");
      lcd.print("o");
      lcd.print("r");
      lcd.print("l");
      lcd.print("d");
    }

    void loop()
    {
    }

Can anyone shed me any light what is the reason of this change in behaviour and how to solve it?

Running version 1.8.3 on a W7pro PC

body:
There seems to be an incompatibility between recent versions of the IDE and the library I was using.

Installing the latest version of the library from GitHub and replacing the `lcd.init()` command with `lcd.begin()` in my sketches solved the problem.


message:
Connection Problems with GPRS Shield

I recently bought a GPRS shield from Seeed Studio but was having issues running the programs described in their documentation.  Here is everything you need to know about my shield:

[Documentation for GPRS Shield V2.0][1]

[Website to purchase GPRS Shield V2.0][2]

I assumed that there was a connection problem. I used the following code to try to debug my SIM900 and its connections to the sim card and the cellular network:

    #include <SoftwareSerial.h>
    SoftwareSerial gprsSerial(7,8);

    void setup(){
      gprsSerial.begin(19200); // GPRS shield baud rate
      Serial.begin(19200);
      delay(500);
    }

    void loop(){
      if(Serial.available()) {
        switch(Serial.read()) {
          case '0': testSIM900(); break;
            // AT OK
          case '1': testSIMCARD(); break;
            // +CPIN: READY
            // +CREG: 0,1
          case '2': testNETWORK(); break;
            // +CGATT: 1
        }
      }

      if(gprsSerial.available()) Serial.write(gprsSerial.read());
    }

    void testSIM900() {
      gprsSerial.println("AT");
      // AT OK
      delay(100);

    }

    void testSIMCARD() {
      gprsSerial.println("AT+CPIN?");
      // +CPIN: READY
      delay(100);
      gprsSerial.println("AT+CREG?");
      // +CREG: 0,1
      delay(100);
    }

    void testNETWORK() {
      gprsSerial.println("AT+CGATT?");
      // +CGATT: 1
      delay(100);
    }

When I entered 0, 1, and 2 into the serial monitor, I got the following response:

    AT

    OK
    AT+CPIN?

    +CPIN: READY

    OK
    AT+CREG?

    +CREG: 1,2

    OK

    +CREG: 0

    +CGREG: 0
    AT+CGATT?

    +CGATT: 0

    OK

What does this tell me about the current state of my shield, sim card, and network connection? Is there anything else I can do to isolate issues?

 [1]:https://seeeddoc.github.io/GPRS_Shield_V2.0/
 [2]:https://www.seeedstudio.com/GPRS-Shield-V2.0-p-1379.html

body:
It seems it can't register on the network, GSM modems are power hungry, are you sure you're powering it up with the external power source (through Vin)? Pretty sure the Arduino isn't enough, but I could be wrong, that's a shield that has those issues in mind.

Also try to see the signal strength using AT+CSQ.


message:
convert byte and float to char

I am trying to send sensor values to internet via enc28j60 module and web client example.

My problem is that i chose byte and float form for some sensors i can't convert these values to char form.

Code example below

    UVSensorValue = analogRead(A0);               // UVSensorValue is in byte form
    concentration = 1.1*pow(duration,3)-3.8*p...  // concentration is in float form

I want to store them in a char variable like this:

> param = "uv=5&temp=23.2&dust=0.62..."

And send them here:

    ether.browseUrl(PSTR("/measures?"), param, website, browseUrlCallback);

I tried strcpy function or String convention but nothing worked. I know its a silly question however i stuck and cant find solution.

If someone could help me i would be pleased. Thanks in advance!

body:
In any other C/C++ platform, you can use "%f" as a format specifier when you want to print (or convert to string) a float using `printf` or its siblings. Any, except in Arduino.

To convert a float you need use `dtostrf()`,

    char * dtostrf(
     double __val,
     signed char __width,
     unsigned char __prec,
     char * __s)

> The dtostrf() function converts the double value passed in val into an
> ASCII representationthat will be stored under s. The caller is
> responsible for providing sufficient storage in s.
>
> Conversion is done in the format "[-]d.ddd". The minimum field width
> of the output string (including the possible '.' and the possible sign
> for negative values) is given in width, and prec determines the number
> of digits after the decimal sign. width is signed value, negative for
> left adjustment.
>
> The dtostrf() function returns the pointer to the converted string s.

To convert a byte (or anything not float) to ascii, use `snprintf()`

    int snprintf ( char * s,
                   size_t n,
                   const char * format,
                   ... );

> Write formatted output to sized buffer.

> Composes a string with the same
> text that would be printed if format was used on printf, but instead
> of being printed, the content is stored as a C string in the buffer
> pointed by s (taking n as the maximum buffer capacity to fill).

You can read the details by yourself, but here is a demo.

The idea is to produce in `buffer` a traditional C-style string (null terminated). That string you can print or transmit.

The float value is printed in two step. First, we use `dtostrf` to convert the float value to his ascii representation. Then we use `snprintf` to include that value (as a string) inside a whole line, latter to be printed.

    void setup() {
      Serial.begin(9600);
      while(!Serial);
      Serial.println("Start");

      float value = 123.45;
      byte balue = 128;

      char buffer[80];
      char fValue[16];
      dtostrf(value, 3, 2, fValue);
      snprintf(buffer, sizeof(buffer), "float %s", fValue);
      Serial.println(buffer);
      snprintf(buffer, sizeof(buffer), "byte value is %d", (int) balue);
      Serial.println(buffer);
    }

    void loop() {

    }


message:
Using C - How do I make my button press nearly instant without using interrupts

How can I make the press of a button nearly instant, WITHOUT using interrupts or millis() - and NO preset arduino functions, just C.
There is a delay at the end of my while loop of 500ms - perhaps the solution lies in breaking up the delay (NOTE: I need to keep the delays)

body: You can delay a small period, check button,  delay again.  Loop this until the full delay is achieved


message:
ESP8266 Connection to Arduino Mega 2560

Im trying to connect my **esp8266-01** to my **arduino mega 2560** to get the code working from the following video tutorial found on youtube:

https://www.youtube.com/watch?v=zGgUfAB4m24

This is the code Im using from the youtube video:

    #include <SoftwareSerial.h>

    #define ESP8266_rxPin 4
    #define ESP8266_txPin 5

    //SSID + KEY
    const char SSID_ESP[] = "SSID";
    const char SSID_KEY[] = "PASSWORD";

    // URLs
    const char URL_youtube[] = "GET https://api.thingspeak.com/apps/thinghttp/send_request?api_key=S7QNK85SG9D9YD27 HTTP/1.0\r\n\r\n";
    const char URL_current_temp[] = "GET https://api.thingspeak.com/apps/thinghttp/send_request?api_key=S7QNK85SG9D9YD27 HTTP/1.0\r\n\r\n";

    //MODES
    const char CWMODE = '1';//CWMODE 1=STATION, 2=APMODE, 3=BOTH
    const char CIPMUX = '1';//CWMODE 0=Single Connection, 1=Multiple Connections

    SoftwareSerial ESP8266(ESP8266_rxPin, ESP8266_txPin);// rx tx

    //DEFINE ALL FUNCTIONS HERE
    boolean setup_ESP();
    boolean read_until_ESP(const char keyword1[], int key_size, int timeout_val, byte mode);
    void timeout_start();
    boolean timeout_check(int timeout_ms);
    void serial_dump_ESP();
    boolean connect_ESP();
    void get_youtube();
    void get_current_temp();
    void get_hilo_temp();

    //DEFINE ALL GLOBAL VAARIABLES HERE
    unsigned long timeout_start_val;
    char scratch_data_from_ESP[20];//first byte is the length of bytes
    char payload[150];
    byte payload_size=0, counter=0;
    char ip_address[16];
    char youtube_subs[10];
    char youtube_views[13];
    char current_temp[5];
    char hi_temp[5];
    char lo_temp[5];

    //DEFINE KEYWORDS HERE
    const char keyword_OK[] = "OK";
    const char keyword_Ready[] = "Ready";
    const char keyword_no_change[] = "no change";
    const char keyword_blank[] = "#&";
    const char keyword_ip[] = "192.";
    const char keyword_rn[] = "\r\n";
    const char keyword_quote[] = "\"";
    const char keyword_carrot[] = ">";
    const char keyword_sendok[] = "SEND OK";
    const char keyword_linkdisc[] = "Unlink";

    //keywords for youtube
    const char keyword_html_start_b[] = "b>";
    const char keyword_html_end_b[] = "</b";

    //keywords for current temp
    const char keyword_html_start_temp[] = "p\">";
    const char keyword_html_end_temp[] = "<s";
    const char keyword_html_start_body = "<body>";
    const char keyword_html_end_body = "</body>";

    void setup(){//        SETUP     START
      //Pin Modes for ESP TX/RX
      pinMode(ESP8266_rxPin, INPUT);
      pinMode(ESP8266_txPin, OUTPUT);

      ESP8266.begin(9600);//default baudrate for ESP
      ESP8266.listen();//not needed unless using other software serial instances
      Serial.begin(115200); //for status and debug
      delay(5000);//delay before kicking things off

      setup_ESP();//go setup the ESP
    }//                    SETUP     END

    void loop(){//         LOOP     START

      //get_youtube(); // get youtube views and subs
      //delay(15000);//thingspeak needs ~12 secs before next connection

      get_current_temp();//current temperature
      delay(15000);

    }//                    LOOP     END

Whenever I run the code everything just fails and Im not able to send **AT** commands from my arduino to the **ESP**.

Im using the following connection between the arduino and the ESP:

    **ESP <---------------------> ARDUINO
    GND -------------------------- GND
    GP2 -------------------------- Not connected
    GP0 -------------------------- Not connected
    RXD -------------------------- DIGITAL PIN 4
    TXD -------------------------- DIGITAL PIN 5
    CHPD ------------------------ 3.3V
    RST -------------------------- Not connected
    VCC -------------------------- 3.3V**

If I connect RESET pin on the arduino to GND and the RX and TX pins on the ESP to digital pins 1 and 0 on the arduino and run the serial monitor and try the AT commands they work fine.

But when I try to run the **AT** commands by sending them from the arduino to the ESP (by running the code) I get the failed every time. What am I doing wrong?

Here is the link to the full code:

http://www.kevindarrah.com/wp-content/uploads/2015/01/ESP8266_BASE_01_28_15.zip

body:
I fixed it by changing everything on the code from **SoftwareSerial ESP8266** to the hardware serial: **Serial1**.

I used the pins 18 and 19 of the hardware serial. I also made sure connect the **RX** pin of the ESP to the **TX** pin of the **Arduino** and do the same with the **TX** pin.


message:
Repairing Analogue Inputs on Uno?

After a long afternoon, chasing a fault on my project, I've come to find that I've damaged 2 out of the 6 Analogue Inputs. Their ADC reading doesn't display 0 when grounded, nor a known ADC value from a sensor.

I've identified the problem to the voltage divider sensors that were connected to these particular Analogue Inputs, I've since researched that topic and made some alterations.

I don't suppose by buying a replacement chip, will solve the problem of 2 bad Analogue Inputs? So I can save the hardware and reduce cost?

Thanks in advance for any help you can provide.

Stu

body:
If the Analog input of your Arduino Uno is damaged, then unfortunately you have damaged the pins on the ATMEAGA328P chip directly.

As per the schematic below of Arduino Uno R3, the pins A0 to A5 are connected directly on the Pins 23 to 28 of the ATMEGA328P chip.

[![Arduino UNO R3 Micro-controller Schematic][1]][1]

Therefore if you say that the 2 out of 6 Analog pins have been damaged then ***the only way to fix that is to replace the ATMEGA328P chip with a new one.***

More can be read [here about the UNO's hardware design][2].

PS. When replacing the ATMEGA328P chip, be sure to program the new chip with the Arduino Bootloader so you can upload sketches to it, otherwise it won't work ;)

Cheers!

  [1]: https://i.stack.imgur.com/oDAoX.jpg
  [2]: https://www.allaboutcircuits.com/technical-articles/understanding-arduino-uno-hardware-design/


message:
Elechouse MP3 shield play random song

Using this code to try and play a random song when someone walks by my distance sensor I get an error, the same song (track 0001) plays every time. Any advice?

    #include <SoftwareSerial.h>
    SoftwareSerial Geno(7, 8); // Rx, Tx

    unsigned char Data[10];
    unsigned char i;

    // defines pins numbers
    const int trigPin = 8;
    const int echoPin = 9;

    // defines variables
    long duration;
    int distance;

    void setup() {
      delay(1000);
      Geno.begin(9600);
      delay(1000);
      SetVolume(30);
      pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
      pinMode(echoPin, INPUT); // Sets the echoPin as an Input
      Serial.begin(9600); // Starts the serial communication
    }

    void playTrack(int num) {
        delay(100);

        Data[0] = 0x7E;
        Data[1] = 0x04;
        Data[2] = 0xA0;
        Data[3] = 0x00;
        Data[4] = 0x00 + num;
        Data[5] = 0x7E;
        Command(Data,5);

        play_pause();

        delay(10000);
    }

    void SetVolume(int vol) {
       Data[0] = 0x7E; // START
       Data[1] = 0x03; // Length Not 0x02
       Data[2] = 0xA7; // Command
       Data[3] = vol;  // new volume
       Data[4] = 0x7E; // END
       Command(Data,5);
    }

    void play_pause() {
      Data[0] = 0x7E; // START
      Data[1] = 0x02; // Length
      Data[2] = 0xA3; // Command
      Data[3] = 0x7E; // Mode parameter
      Command(Data,4);
    }

    void Command(unsigned char *Data, int length) {
      for (int i=0; i<length; i++) {
        Geno.write(Data[i]);
      }
    }

    void loop() {
      //Assigns a random number
      int song = random(0,200);
      Serial.print("Song is:");
      Serial.print(song);
      Serial.print("\n");
      // Clears the trigPin
      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;

      Serial.print("Distance: ");
      Serial.println(distance);
      if (distance < 20) {
        playTrack(random(1,25));
      }
      //playTrack(1);
      //playTrack(2);
    }

body:
Disclaimer: I know nothing about this media player except what's in this question.  I'd never heard of it before.  The following is simply from observation of the code you posted.

Look at your `play_pause()` function where the meanings of all the elements are described.

    Data[0] = 0x7E;          // START
    Data[1] = 0x02;          // Length
    Data[2] = 0xA3;          // Command
    Data[3] = 0x7E;          //Mode parameter
    Command(Data,4);

It seems a message starts with `0x7E`, followed by the length , followed by a command and whatever else, followed by another `0x7E`.

The length field is 1 less than the total length, so I guess it doesn't include the 'start', or whatever - there are various equivalent ways you could look at it.

In `playTrack()` you set 6 elements, but with the length element set to 4. You then tell `Command()` there are 5.  So the last element (`0x7E`) won't get sent, and the length element which you have sent is wrong anyway.

The receiver is going to get into some weird state, I presume. Perhaps that explains the problem you're seeing.


body:
`random(1,25)` is deterministic. It's PRNG should produce the same sequence of outputs in the same order each time. You need to call [randomSeed()][1] at some point, passing it an unpredictable value. Something like:

    if(distance < 20){
      randomSeed(micros());
      playTrack(random(1,25));
    }

  [1]: https://www.arduino.cc/reference/en/language/functions/random-numbers/randomseed/


message:
Attiny13 project with leds and electret microphone

I want to make a project similar to this [Turn Signal Biking Jacket][2]

[![Turn Signal Biking Jacket][1]][1].

But, instead of using Arduino Lilypad I want to use an 8 pin [attiny13A-SH][3] and want to use one [electret microphone][4] instead of the buttons.

I want to use led's only for the left, right and a stop indicator(on the back, i don't want the leds on the sides like the instructable project).

According to me, the leds require 1 pin each and will share a common gnd(that's 4 pins).

The microphone will require 1 additional pin, with 1 going to the gnd (5 pins).

And I might require 2 pins for the power outlet (6 pins out of 8).

Now, i am a newbie in all this stuff so i don't want to go about experimenting with the chips. I am ready to disable the reset pin cause i wont require the chip again. I have got a couple of instructable's to help me in the programming and set-up plan(though they have used Arduino Uno or Lilypad), so **I only want to know if it is possible to make the project with the attiny13a chip without the requirement of any additional parts.**

Also, as an alternative, i wanted to use [these leds][5] instead of the lilypad led's, so i want to know if i can do the model in exactly the same way without using any mofsets etc(i just want 6 leds on each side). I'm extremely sorry for my horrible drawing(First time and no correct tools. used paint!)[![enter image description here][6]][6] <br>
**ANY HELP IS APPRECIATED.**

  [1]: https://i.stack.imgur.com/SPvLk.jpg
  [2]: http://www.instructables.com/id/turn-signal-biking-jacket/
  [3]: http://www.microchip.com/wwwproducts/en/ATtiny13A
  [4]: https://www.sparkfun.com/products/8635
  [5]: https://www.aliexpress.com/item/0-5M-1M-2835-SMD-RGB-Led-Strip-Light-60Leds-M-DC-12V-Non-Waterproof-Kitchen/32767999594.html?spm=2114.search0204.3.16.6df854bcWWLDT1&ws_ab_test=searchweb0_0,searchweb201602_3_10152_10151_10065_10344_10068_10342_10343_10340_10341_10084_10083_10618_10307_5711211_5722315_10313_10059_10534_100031_10629_10103_10626_10625_10624_10623_10622_10621_10620_10142,searchweb201603_2,ppcSwitch_5_ppcChannel&algo_expid=6432d851-7fac-4c64-9ee5-6d40405fbdc9-2&algo_pvid=6432d851-7fac-4c64-9ee5-6d40405fbdc9&priceBeautifyAB=0
  [6]: https://i.stack.imgur.com/a9uvd.png

body:
> want to use 1 electret microphone instead of the buttons.

In what way do you want to use the microphone? You do realise, don't you, that an Arduino can't understand speech (or much of anything really) without powerful extra hardware? A microphone by itself is pretty much useless, especially without any form of preamp and signal conditioning.

> i only want to know if it is possible to make the project with the attiny13a chip without the requirement of any additional parts.

No, it's not possible. You will require lots more parts. You can't just take an arbitrary chip and connect it to a battery and expect it to work properly. You need to consider correct supply voltages (voltage regulation or boosting depending on your power source), decoupling capacitors, drive circuitry, amplification, signal processing, etc...

> i wanted to use these leds instead of the lilypad led's, so i want to know if i can do the model in exactly the same way without using any mofsets etc

Again, no.  Those are 12V LED strips. You need both a 12V supply (and the associated regulation down to 5V to power the ATTiny etc) and MOSFETs (or something similar) to allow the ATTiny to switch that 12V to the LED strips as needed.


body:
A simple answer would be "**No, it's not possible**"

You cannot run a single chip independently without any protection and regulating components(e.g. capacitor, regulator, current limiting resistor)

Also by replacing components with other ones, it would require you additional adjustments in the code and also in the hardware(Referring to the replacing buttons with Electret Microphone). There is a reason for the Arduino Lilypad to have additional components so that it can run smoothly and avoid damages to both the user and the device itself.


message:
DFPlayer Noise: Researched, Tried, and Bep Bep Bep Bep Bep

Spent an entire day researching and attempting to fix the DFPlayer noise problem. The amp works as expected, so it is not the problem. I have made a video to help you better understand the sound produced: [https://www.youtube.com/watch?v=uK2kkR0XjFs&feature=youtu.be][1]

This is the amp/speaker used: [https://sites.google.com/site/wayneholder/chiptunes][2]

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

The amp with speaker works as expected using another similar mp3 player like from a computer or possibly a phone.

[![enter image description here][4]][4]

Here we get the bep bep bep bep bep... as the amp/speaker has its own battery power.

[![enter image description here][5]][5]
Here I made everything as one power source. Bep bep bep bep bep...

I think I exhausted my research and made the following attempts:

    > -Electrolytic Capacitor at the power terminals
    > -Electrolytic Capacitor parallel with ceramic capacitor from negative terminal to VCC in DFPlayer
    > -Diode from positive terminal to VCC in DFPlayer
    > -Battery Power source; USB power source; Power Supply power source; 5V USB plug regulator power source
    > -1k Resistor from TX RX; Rx Tx
    > -1-10k resistor from Rx Tx
    > -1k between channel to GND
    > -Separate power source for each the Arduino, amp, and DFPlayer
    > -Tried multiple DFPlayers

Keep note that the amp/speaker works well. The files are the same both on the computer and in the SD card.

Here is my code:
<!-- language-all: lang-cpp -->

    #include <DFRobotDFPlayerMini.h>

    /***************************************************
    DFPlayer - A Mini MP3 Player For Arduino
     <https://www.dfrobot.com/index.php?route=product/product&product_id=1121>

     ***************************************************
     This example shows the basic function of library for DFPlayer.

     Created 2016-12-07
     By [Angelo qiao](Angelo.qiao@dfrobot.com)

     GNU Lesser General Public License.
     See <http://www.gnu.org/licenses/> for details.
     All above must be included in any redistribution
     ****************************************************/

    /***********Notice and Trouble shooting***************
     1.Connection and Diagram can be found here
     <https://www.dfrobot.com/wiki/index.php/DFPlayer_Mini_SKU:DFR0299#Connection_Diagram>
     2.This code is tested on Arduino Uno, Leonardo, Mega boards.
     ****************************************************/

    #include <Arduino.h>
    #include <SoftwareSerial.h>
    #include <DFRobotDFPlayerMini.h>
    int counter = 0;
    SoftwareSerial mySoftwareSerial(10, 11); // RX, TX
    DFRobotDFPlayerMini myDFPlayer;
    void printDetail(uint8_t type, int value);

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

      Serial.println();
      Serial.println(F("DFRobot DFPlayer Mini Demo"));
      Serial.println(F("Initializing DFPlayer ... (May take 3~5 seconds)"));

      if (!myDFPlayer.begin(mySoftwareSerial)) {  //Use softwareSerial to communicate with mp3.
        Serial.println(F("Unable to begin:"));
        Serial.println(F("1.Please recheck the connection!"));
        Serial.println(F("2.Please insert the SD card!"));
        while(true);
      }
      Serial.println(F("DFPlayer Mini online."));

      myDFPlayer.volume(15);  //Set volume value. From 0 to 30
      delay(1000);
    myDFPlayer.enableDAC();  //Enable On-chip DAC
    }

    void loop()
    {
      static unsigned long timer = millis();
      if(millis() - timer > 1000 && counter == 0)
      {
       myDFPlayer.play(1);
       Serial.println(F("Music Started"));
       delay(1000);
       Serial.println(F("1 second later..."));
       delay(6000);
       Serial.println(F("7 seconds later..."));
       delay(1000);
       counter =1;
      }

    delay(7000);

      if (myDFPlayer.available()) {
        printDetail(myDFPlayer.readType(), myDFPlayer.read()); //Print the detail message from DFPlayer to handle different errors and states.
      }
    }

    void printDetail(uint8_t type, int value){
      switch (type) {
        case TimeOut:
          Serial.println(F("Time Out!"));
          break;
        case WrongStack:
          Serial.println(F("Stack Wrong!"));
          break;
        case DFPlayerCardInserted:
          Serial.println(F("Card Inserted!"));
          break;
        case DFPlayerCardRemoved:
          Serial.println(F("Card Removed!"));
          break;
        case DFPlayerCardOnline:
          Serial.println(F("Card Online!"));
          break;
        case DFPlayerPlayFinished:
          Serial.print(F("Number:"));
          Serial.print(value);
          Serial.println(F(" Play Finished!"));
          break;
        case DFPlayerError:
          Serial.print(F("DFPlayerError:"));
          switch (value) {
            case Busy:
              Serial.println(F("Card not found"));
              break;
            case Sleeping:
              Serial.println(F("Sleeping"));
              break;
            case SerialWrongStack:
              Serial.println(F("Get Wrong Stack"));
              break;
            case CheckSumNotMatch:
              Serial.println(F("Check Sum Not Match"));
              break;
            case FileIndexOut:
              Serial.println(F("File Index Out of Bound"));
              break;
            case FileMismatch:
              Serial.println(F("Cannot Find File"));
              break;
            case Advertise:
              Serial.println(F("In Advertise"));
              break;
            default:
              break;
          }
          break;
        default:
          break;
      }
    }

  [1]: https://www.youtube.com/watch?v=uK2kkR0XjFs&feature=youtu.be
  [2]: https://sites.google.com/site/wayneholder/chiptunes
  [3]: https://i.stack.imgur.com/6rIO7.jpg
  [4]: https://i.stack.imgur.com/3iVtY.jpg
  [5]: https://i.stack.imgur.com/GuY9s.jpg

body:
The "bep bep bep" you are hearing is power supply noise introduced by the SD card. Every time the SD card reads the power supply dips and the ground raises.  This is because these boards have really terrible grounding in their design. There is no coherent ground plane, and the analog audio sections and noisy digital sections both share the same ground with no isolation or filtering between them.

To reduce the impedance of the ground plane you must connect both the GND pins together, and do it with a short wire.  Better would be to modify the board itself and solder a wire directly between the two ground pins.

There are also strategic ground points around the place you could also solder directly to one of those ground pins - such as the ground side of the SD card's decoupling capacitors, and the GND pin of the SD card itself (if your soldering skills are up to it - those pins are pretty fine pitch).

The whole issue stems from trying to fit too much into too small a space. The board really should have been made as a 4-layer board with a (near) solid ground and power plane to reduce the power impedance. Better decoupling and filtering on the SD card's power pin (such as a "PI" filter with two capacitors and a ferrite bead, or two capacitors and a small resistor) would have been a big benefit as well.