body:
I'm trying to send a .wav file to an API with an ESP32 using a HTTP Post request with a multipart/Form-data content type.
I can already send the API Key as it is a plain key and get a return from the server, but I fail on how to add the .wav file into the post request.
I am currently reading the wav file from an sd card, it's 5 secs long 16 bit,11025Hz. and about 400 kb.
If anyone have experience with this, your help would be greatly appreciated!

This is the code snippet where I send the key and where the data should come;
I tried putting the code into a buffer as and concatting the data but I'm not sure if this is the right way to do it
char buf[1024];

     if (https.begin(client, host, port, path)) {

       //https.addHeader("Content-Type", "multipart/Form-data");
       //int httpsCode = https.POST("apikey = XXX");
    Serial.println(WavFile);
         https.addHeader("content-type", "multipart/form-data; boundary=----123");
        String HTTPSPost ="------123\r\nContent-Disposition: form-data;
    `

    ----------

    name=\"apikey\"\r\n\r\XXX\r\n------123--\r\nContent-Disposition: form-data; name=\"wav\"; filename=\"test444.wav\"\r\nContent-Type: audio/x-wav\r\n\r\n\r\n";
      `
        //wav recording Comes here
        String WavData ;
       // for (int i = 0; i < 1024; i++) WavData.concat(buf[i]);; // Tried to put Wav file in a buffer
      // Serial.println(WavData);

        String End = "------123--";
        String full = HTTPSPost + WavData + End;
        int httpsCode = https.POST(full );
            if (httpsCode > 0) {
                  if (httpsCode == HTTP_CODE_OK) {
                    res =  https.getString();
                    JsonObject& obj = jb.parseObject(res);

                    String token = obj["error"];
                    if (obj.success()) {

                    } else {
                        res = "failed to parse json";
                    }
                  }
            } else {
                res = "failed to Post";
            }
       } else {
        res = "failed to connect to server";
       }
    https.end();
    return res;
    }
    `

better code because httpclient can't do sd cards, but wificlient can;

    File file = SD.open("/xxx.wav");

    if (!client.connect("XXX", 443)) {
      Serial.println("Connected FAILED!");
      return;
    }

    Serial.println("Connected ok!");

    client.println("POST  HTTP/1.1");
    client.println("Host: ");
    client.println("Cache-Control: no-cache");
    client.println("Content-Type: multipart/form-data; boundary=----123");
    client.println();
    client.println("------123");
    client.println("Content-Disposition: form-data; name=\"grant_type\"");
    client.println();
    client.println("client_credentials");
    client.println("------123");
    client.println("Content-Disposition: form-data; name=\"apikey\"");
    client.println();
    client.println("XXX");
    client.println("------123");
    client.println("Content-Disposition: form-data; name=\"wav\"; filename=\"xxx.wav\"");
    client.println("Content-Type: audio/wav");
    client.println("");
    client.print("Content-Length: ");
    client.println(file.size());
    //client.println();
    //while (file.available()){
    //      client.write(file.read());
    //}
    client.write(file);
    client.println("------123--");
    Serial.println(">>><<<");
    if (client.available())
        {
          String serverRes = client.readStringUntil('}');
          Serial.println(serverRes);
        }

title: Esp32 sending a wav file to API via POST

Answers: 0


body:
Hopefully this question is not too off-topic for this board. I need a ready-made programmable hand-held device with an ethernet-connection. Something like an Arduino with batteries and display and some buttons in a box.
This is for my company so a complete ground-up assembly is too expensive and time-consuming in this case. Any hints to companies that produce something like this are welcome. And yes, I tried searching with different search-engines already. :-)
Thanks for your time!

title: Hand-held programmable device needed

Answers: 1

body:
I have no opinion about this hardware (I don't own it) so please treat my answer as information only. When I was searching through web I found [M5Stack][1]

It looks like hardware made for IoT development.
It has a LCD and 3 buttons and think it can be programmed using ArduinoIDE.
It's designed that you can design any hardware you want and "stack" the device on top of it. Found if available to buy from China for below 30USD.

[![M5Stack parts][2]][2]

https://www.youtube.com/watch?v=U2es-l4z2Zg

  [1]: https://m5stack.com/
  [2]: https://i.stack.imgur.com/lwwsn.png


body:
I'm using nRF24L01 to send ECG samples from an Arduino to Raspberry Pi, the type of sample is double after denoising, and I stock them in a byte[8] to send 8 by 8 sample. When I print the sample before stockage that show the good results, but if I print data stored in the byte the signal show a lot of fluctuations. In Raspberry Pi, I can read correctly byte data like transmitted, but if I send them in a vector of double or int in reception (python) don't give the same frame transmitted.

    #include <IIRFilter.h>
    #include <FIRFilter.h>

    #include <SPI.h> // Call SPI Library
    #include <nRF24L01.h> // Call NRE Version Library
    #include <RF24.h> // RF24 Header File

    #define CE_PIN  9
    #define CSN_PIN 10
    const uint64_t pipe = 0xF0F0F0F0E1LL;
    RF24 radio(CE_PIN, CSN_PIN);

    const int ECG_samplefreq  = 200;//sampling frequcy
    const int DC_offset = 511;

    const double b_lp[] = {0.0026, 0.0155, 0.0388, 0.0517, 0.0388, 0.0155, 0.0026};
    const double a_lp[] = {1.0000, -2.3797, 2.9104, -2.0551, 0.8779, -0.2099, 0.0218};

    IIRFilter lp(b_lp, a_lp);
    unsigned int i = 0;

    void setup() {
      Serial.begin(9600);
      radio.begin();//Intializing NRF24L01 Module
      radio.setPALevel(RF24_PA_MAX);
      radio.setChannel(0x76);
      radio.openWritingPipe(pipe);// For Transmitting Operation, Must OpenWritingPipe
      radio.enableDynamicPayloads();
      radio.powerUp();
      pinMode(7, INPUT); // Setup for leads off detection LO +
      pinMode(8, INPUT); // Setup for leads off detection LO -

    }
    void loop() {
      const static unsigned long ECG_interval  = round(1e6 / ECG_samplefreq);  //sampling period = 5000 ms => 200 sample by 1 seconde
      static unsigned long ECG_prevmicros = micros();
      byte  s[8] = {0};

      if ((digitalRead(7) == 1) || (digitalRead(8) == 1)) {
        Serial.println('!');
      }

      else {
        for (int i = 0; i < 8; i++)
        {

          if (!Serial) {
            ECG_prevmicros = micros();
          }
          else if (micros() - ECG_prevmicros >= ECG_interval)
          {
            int value = analogRead(A5);
            double filtered = lp.filter( value - DC_offset);

            filtered = round( filtered + DC_offset);
            s[i] =  filtered
            Serial.println( s[i]);
            ECG_prevmicros += ECG_interval;

          }
        }
        radio.write(&s, sizeof(s) ); // sending in real time ECG sample. 8 sample by transmission . 8 => 4 oct of one sampe = 32 oct by transmission.

      }
    }

the problem thant i put in s[i] a double of four octs. im searching how can i send them whithout byte array, and receive the correctly. So thankful for your help

title: Send ECG signal with NRF24L01 from Arduino to Raspberry Pi 3

Answers: 1

body:
I see multiple flaws in your code:

* `radio.write(&s, sizeof(s));` does not what you think it would. The correct statement would be `radio.write(s, sizeof(s));` without the ampersand.
* You are using `double`. Not using floating point numbers at all would be preferable.
* Your `s` is of type byte. Thus it only holds 8 bytes. So your floating point calculations are being truncated to the range [0, 255]. From your problem description this is not what you are trying to achieve, I think.


body:
I have the a problem with my arduino MEGA 2560 and the SIM900 module.
I want to save the outputs of the AT commands, but I never get a chance. If I print mySerial.available() I only get 0.
Sending SMS works fine on the other hand.

```
Initializing...
AT+CMGF=1
AT+CNMI=2,2,0,0,0

OK
Done
AT+CMGL="REC UNREAD"

OK
0
0
0
0
0
0
0
0
0
0
0
```

This is the sketch I use:
```
#include <SoftwareSerial.h>

//Create software serial object to communicate with SIM900
SoftwareSerial mySerial(11, 10); //SIM900 Tx & Rx is connected to Arduino #7 & #8
String incoming="";
String incoming2="";
String messages="Test";
String auth_num="+49xxxxxxxxx";
char incoming_char=0;

String response = "";

const byte numChars = 32;
char receivedChars[numChars];
boolean newData = false;

int period = 6000;
unsigned long time_now = 0;

void setup()
{
  //Begin serial communication with Arduino and Arduino IDE (Serial Monitor)
  Serial.begin(9600);

  //Begin serial communication with Arduino and SIM900
  mySerial.begin(9600);

  Serial.println("Initializing...");
  delay(1000);

  mySerial.println("AT+CMGF=1");
  mySerial.println("AT+CNMI=2,2,0,0,0"); // Decides how newly arrived SMS messages should be handled
  //mySerial.println("ATE0");
  updateSerial();
  Serial.println("Done");

  //sms_versenden("xxxxxxxx", "text");
}

void loop()
{
  updateSerial();
  Serial.println(mySerial.available());
  if(millis() - time_now > period){
    time_now = millis();
    if(sms_erhalten()){
      sms_autorisiert();
    }
  }
}

void updateSerial()
{
  delay(500);
  while (Serial.available())
  {
    mySerial.write(Serial.read());//Forward what Serial received to Software Serial Port
  }
  while(mySerial.available())
  {
    Serial.write(mySerial.read());//Forward what Software Serial received to Serial Port
  }
}

void sms_versenden(String rufnummer,String text)
{
  mySerial.println("AT"); //Handshaking with SIM900
  updateSerial();

  mySerial.println("AT+CMGF=1"); // Configuring TEXT mode
  updateSerial();
  if(rufnummer.startsWith("0")){
    rufnummer.remove(0,1);
    mySerial.print("AT+CMGS=\"+49");
    mySerial.print(rufnummer);
    mySerial.println("\"");
  }else if(rufnummer.startsWith("+49")){
    mySerial.print("AT+CMGS=\"");
    mySerial.print(rufnummer);
    mySerial.println("\"");
  }else{
    return;
  }
  updateSerial();
  mySerial.print(text); //text content
  updateSerial();
  mySerial.write(26);
}

boolean sms_erhalten()
{
  mySerial.print("AT+CMGL=\"REC UNREAD\"\r");
  //recvWithEndMarker();
  Serial.println(mySerial.available());
  delay(30);
  while (mySerial.available()){
    String inData = mySerial.readStringUntil('\n');
    Serial.println("Got reponse from SIM900: " + inData);
  }
  /*if(mySerial.available()>0){

    incoming = mySerial.readString();
    Serial.print(incoming);
    delay(10);
  }*/
  updateSerial();
  if(incoming.startsWith("+CMGL:"))
  {
    return true;
  }
  else{
    return false;
  }
}

void recvWithEndMarker() {
    static byte ndx = 0;
    char endMarker = '\n';
    char rc;

    while (mySerial.available() != 0 && newData == false) {
        rc = mySerial.read();
        updateSerial();
        if (rc != endMarker) {
            receivedChars[ndx] = rc;
            ndx++;
            if (ndx >= numChars) {
                ndx = numChars - 1;
            }
        }
        else {
            receivedChars[ndx] = '\0'; // terminate the string
            ndx = 0;
            newData = true;
        }
    }
}

void showNewData() {
    if (newData == true) {
        Serial.print("This just in ... ");
        Serial.println(receivedChars);
        newData = false;
    }
}
String getResponse() {
    while(mySerial.available()>0){
        response += mySerial.read();
    }
    return response;
}
````

Thanks in advance for every idea.
Bravodelta

title: Arduino and SIM900 unavailable all the time

Answers: 1

body:
Rather than creating your own function used SerialEvent function in arduino. It acts as a serial interrupt in arduino. For example:

    String inputString;
    void serialEvent() {
          while (Serial.available()) {
            // get the new byte:
            char inChar = (char)Serial.read();
            // add it to the inputString:
            inputString += inChar;
            // if the incoming character is a newline, set a flag so the main loop can
            // do something about it:
            if (inChar == '\n') {
              Serial.Println(inputString);
            }
          }
        }


body:
I am doing this project wherein I want to display some image on the LCD screen. I am having a problem with the connecting nodemcu with my TFT LCD screen. I cannot find any references. Does a TFT screen go well with a NodeMCU? if yes, please help

I tried taking refrence from this website but i ended up damaging my nodeMCU

http://nobrok.com/connecting-tft-lcd-touch-screen-with-nodemcu-esp8266/

Also attaching images of TFT display and my NodeMCU.
[![Here's my TFT screen (ILI9341 non touch screen)][1]][1]

[![NodeMCU][2]][2]

It would be great if you can help. Thanks :)

  [1]: https://i.stack.imgur.com/gmIOZ.jpg
  [2]: https://i.stack.imgur.com/OQ6mN.jpg

title: How to Connect TFT LCD display with NodeMCU?

Answers: 2

body:
That kind of TFT doesn't work well with the NodeMCU (or the ESP8266 in general).

Simply put: that TFT requires a lot of GPIO pins - 10 at an absolute bare minimum, but better if you have more available.  The ESP8266 doesn't have many IO pins - and some of them are very sensitive about what they can be connected to without affecting the boot process.

It is better to choose a TFT screen with an SPI interface, which uses far fewer pins - although is slower to refresh the screen data.

If you are careful with your GPIO selection it *may* be possible to work with that screen. There are no specific requirements for what pins need to be connected to where (as far as hardware functionality goes), so it's up to you to find the right combination that doesn't cripple the boot process (stay away from GPIOs 0, 2 and 15 if you can).

body:
According to its web site, the TFT module does have SPI interface. https://www.jixin.pro/product/717.html
The site is in Chinese though.


body:
I am trying to recreate an RFID door lock that I saw on the Arduino project hub but have ran into several issues. I had to manipulate the code slightly to make sure it was including the correct libraries and I think that solved some issues but not all. If anyone could take a look at my code and help me out that'd be awesome, I am pretty new with coding and need all the help I can get.
Thank you!

Here are the error messages I receive when trying to upload the code to my arduino:
Arduino: 1.8.8 (Mac OS X), Board: "Arduino/Genuino Uno"

    rfid_based_door_automatic_management_system:66:17: error: expected unqualified-id before numeric constant
     #define SDA_D1O 9
                     ^
    /Users/gavinmiles/Documents/rfid_based_door_automatic_management_system/rfid_based_door_automatic_management_system.ino:70:9: note: in expansion of macro 'SDA_D1O'
     MFRC522(SDA_D1O, RESET_D1O);
             ^
    rfid_based_door_automatic_management_system:66:17: error: expected ')' before numeric constant
     #define SDA_D1O 9
                     ^
    /Users/gavinmiles/Documents/rfid_based_door_automatic_management_system/rfid_based_door_automatic_management_system.ino:70:9: note: in expansion of macro 'SDA_D1O'
     MFRC522(SDA_D1O, RESET_D1O);
             ^
    /Users/gavinmiles/Documents/rfid_based_door_automatic_management_system/rfid_based_door_automatic_management_system.ino: In function 'void setup()':
    rfid_based_door_automatic_management_system:120:10: error: expected unqualified-id before '.' token
       MFRC522.initial();
              ^
    /Users/gavinmiles/Documents/rfid_based_door_automatic_management_system/rfid_based_door_automatic_management_system.ino: In function 'void loop()':
    rfid_based_door_automatic_management_system:137:12: error: 'class MFRC522' has no member named 'isCard'
       if( rfid.isCard() )
                ^
    rfid_based_door_automatic_management_system:141:16: error: 'class MFRC522' has no member named 'readCardSerial'
           if( rfid.readCardSerial() )
                    ^
    rfid_based_door_automatic_management_system:152:33: error: 'class MFRC522' has no member named 'serNum'
                   Serial.print(rfid.serNum[i], HEX);
                                     ^
    rfid_based_door_automatic_management_system:154:30: error: 'class MFRC522' has no member named 'serNum'
                   lcd.print(rfid.serNum[i],HEX);
                                  ^
    rfid_based_door_automatic_management_system:165:42: error: 'class MFRC522' has no member named 'serNum'
                   if( My_RFID_Tag[i] != rfid.serNum[i] )
                                              ^
    rfid_based_door_automatic_management_system:274:8: error: 'class MFRC522' has no member named 'halt'
       rfid.halt();
            ^
    Multiple libraries were found for "LiquidCrystal.h"
     Used: /Users/gavinmiles/Documents/Arduino/libraries/LiquidCrystal
     Not used: /Applications/Arduino.app/Contents/Java/libraries/LiquidCrystal
    Multiple libraries were found for "Servo.h"
     Used: /Users/gavinmiles/Documents/Arduino/libraries/Servo
     Not used: /Applications/Arduino.app/Contents/Java/libraries/Servo
    exit status 1
    expected unqualified-id before numeric constant
    /Users/gavinmiles/Downloads/untitled_file.ino

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

    /*
     *  RFID Module RC522
     *  Simple Project:- Arduino will read RFID Tag and Display To the Serial Monitor!
     *
     *  RFID RC522 and Arduino Uno Pin Configuration
     *
     *  RFID RC522          Arduino Uno
     *  SS/SDA              D10
     *  SCK                 D13
     *  MOSI                D11
     *  MISO                D12
     *  IRQ                 Not Connected
     *  GND                 GND
     *  RST                 D9
     *  3.3V                3.3V
     *
     *  //Note: We connected LCD to the Analog Pins.
     *  Remember, Analog Pins can be act as a Digital Pins,
     *  But Digital Pins CAN NOT be act as a Analog Pins.
     *
     *  LCD(16x2) Connections
     *
     *  VSS pin to GND
     *  VCC pin to 5V
     *  //We are connecting "Contrast pin to GND for Maximum Brightness"
     *  //You can also connect it to 10K Pot if you wish to change the Brightness Of LCD.
     *  VEE pin to GND
     *  RS pin to Analog pin A0
     *  R/W pin to ground
     *  Enable pin to Analog pin A1
     *  D4 pin to Analog pin 5
     *  D5 pin to Analog pin 4
     *  D6 pin to Analog pin 3
     *  D7 pin to Analog pin 2
     *  LED+ pin to POWER
     *  LED- pin to GND
     *
     *  Servo is Connected to Digital Pin 5
     *
     *  RGB LED
     *  From RGB LED, We need Only Red and Green Color,
     *  So we are not connecting Blue pin of the RGB.
     *
     *  Red pin to Digital pin 6
     *  Green pin to Digital pin 7
     *
     *  Buzzer to Digital pin 8
     *
     *
     *  Note:- RFID uses SPI Protocol to transfer the information.
     *  I took the Melody(for the Buzzer) from,
     *  File -> Examples -> Digital -> ToneMelody
    */

    //Include sections
    #include <MFRC522.h>
    #include <SPI.h>
    #include <LiquidCrystal.h>
    #include <Servo.h>
    #include "pitches.h"

    //Define Component to Arduino Pins
    /* Define the DIO used for the SDA (SS) and RST (reset) pins. */
    #define SDA_D1O 9
    #define RESET_D1O 8

    /* Create an instance of the RFID library */
    MFRC522(SDA_D1O, RESET_D1O);
    #define SS_PIN 10
    #define RST_PIN 9

    #define SERVO_PIN 5

    #define Red_LED 6
    #define Green_LED 7

    #define Buzzer 8

    //initialize the library with the numbers of the interface pins
    LiquidCrystal lcd(A0, A1, A2, A3, A4, A5);
    Servo DoorLock;
    MFRC522 rfid(SS_PIN, RST_PIN );

    //Unique ID of RFID Tag, which you want to give access.
    int My_RFID_Tag[5] = {0x58,0x76,0x17,0x10,0x29};

    //variable to hold your Access_card
    boolean My_Card = false;

    // notes in the melody, taken from:
    //File -> Examples -> Digital -> ToneMelody
    int melody[] = {
      NOTE_C4, NOTE_G3, NOTE_G3, NOTE_A3, NOTE_G3, 0, NOTE_B3, NOTE_C4
    };

    // note durations: 4 = quarter note, 8 = eighth note, etc.:
    int noteDurations[] = {
      4, 8, 8, 4, 4, 4, 4, 4
    };

    void setup()
    {
      // put your setup code here, to run once:
      //set the pins as an input/output
      pinMode(Red_LED,OUTPUT);
      pinMode(Green_LED,OUTPUT);
      pinMode(Buzzer,OUTPUT);

      //Servo Connnected to pin Digital Pin 5
      DoorLock.attach(SERVO_PIN);
      //open the serial port at 9600 baudrate.
      Serial.begin(9600);
      //Initialise the LCD to 16x2 Character Format
      lcd.begin(16,2);
      //Initialise Servo and RFID
      SPI.begin();
      MFRC522.initial();
    }

    void loop()
    {
      // put your main code here, to run repeatedly:

      //First Assume detected card(Or tag) is My_Card,
      //Then later we will check is it My_Card or not!
      My_Card = true;
      DoorLock.write(0); //Servo at 0 Position, Door is Closed.
      lcd.clear();
      lcd.print("Robodia Technology");
      lcd.setCursor(0,1);
      lcd.print("gy Solutions!");

      //Check if any RFID Tags Detected or not?
      if( rfid.isCard() )
      {
          //if RFID Tag is detected, check for the Unique ID,
          //and print it on the Serial Window
          if( rfid.readCardSerial() )
          {
              lcd.clear();
              lcd.print("UNIQUE ID is:- ");
              delay(500);
              lcd.setCursor(0,1); //Set LCD Cursor to Second Row, First Character

          //Unique id is 5 Digit Number.
              //Printing in HEX for better Understanding
              for( int i = 0; i < 5; i++ )
              {
                  Serial.print(rfid.serNum[i], HEX);
                  Serial.print(" ");
                  lcd.print(rfid.serNum[i],HEX);
                  lcd.print(" ");
              }
              delay(500);

          //Compare this RFID Tag Unique ID with your My_RFID_Tag's Unique ID
              for(int i = 0; i < 5; i++)
              {
                  //if any one Unique ID Digit is not matching,
                  //then make My_Card = false and come out from loop
                  //No need to check all the digit!
                  if( My_RFID_Tag[i] != rfid.serNum[i] )
                  {
                    My_Card = false;
                    break;
                  }
              }
              Serial.println();
              delay(1000);

              //If RFID Tag is My_Card then give access to enter into room
              //else dont open the door.
              if(My_Card)
              {
                Serial.println("\nWelcome To Your Room, Robodia!");
                lcd.clear();
                lcd.print("Welcome to Your");
                lcd.setCursor(0,1);
                lcd.print("Room, Robodia!");
                delay(2000);

                //Turn on the Green LED as an indication of permission is given
                //to access the room.
                digitalWrite(Green_LED,HIGH);

                //Buzzer Config, taken from:
                //File -> Examples -> Digital -> ToneMelody
                // iterate over the notes of the melody:
                int i = 0;
                while(i < 2)
                {
                  for (int thisNote = 0; thisNote < 12; thisNote++)
                  {
                    // to calculate the note duration, take one second
                    // divided by the note type.
                    //e.g. quarter note = 1000 / 4, eighth note = 1000/8, etc.
                    int noteDuration = 1000 / noteDurations[thisNote];
                    tone(8, melody[thisNote], noteDuration);
                    // to distinguish the notes, set a minimum time between them.
                    // the note's duration + 30% seems to work well:
                    int pauseBetweenNotes = noteDuration * 1.30;
                    delay(pauseBetweenNotes);
                    // stop the tone playing:
                    noTone(8);
                  }
                  i =  i + 1;
                  delay(500);
                }
                delay(1000);

                //Now, Open the Door with the help of Servo Motor
                DoorLock.write(180);
                delay(200);
                lcd.clear();
                lcd.print("Door is Open");
                lcd.setCursor(0,1);
                lcd.print("Now!");
                delay(2000);
                lcd.clear();

                //Give 10 Sec delay to enter into room
                //After that door will again closed!
                for(int i = 10; i > 0; i--)
                {
                  lcd.print("Door will close");
                  lcd.setCursor(0,1);
                  lcd.print("in ");
                  lcd.print(i);
                  lcd.print(" Sec.HurryUp!");
                  delay(1000);
                  lcd.clear();
                }

                //Now,Door is closed and Green LED is Turned-Off.
                DoorLock.write(0);
                digitalWrite(Green_LED,LOW);
                delay(200);
                lcd.clear();
                lcd.print("Door is Close");
                lcd.setCursor(0,1);
                lcd.print("Now!");
                delay(2000);
              }

              // If RFID Tag is not My_Card then
              // Do not open the Door and
              //Turn-On Red LED and Buzzer as an indication of Warning:
              //Somebody else is trying to enter into your room.
              else
              {
                Serial.println("\nGet Out of Here !");
                lcd.clear();
                lcd.print("Card isNOT FOUND!");
                lcd.setCursor(0,1);
                lcd.print("Get Out of Here!");

                for(int i = 0; i < 7; i++)
                {
                  digitalWrite(Buzzer, HIGH);
                  digitalWrite(Red_LED,HIGH);
                  delay(500);
                  digitalWrite(Buzzer, LOW);
                  digitalWrite(Red_LED,LOW);
                  delay(500);
                }
                delay(1000);
              }
          }
       }
      //Put RFID Reader into Halt, untill it not detects any RFID Tag.
      rfid.halt();
    }

title: RFID Door Lock Coding Errors

Answers: 1

body:
I had seen many errors in your code. Some of them are as follows

 1. `MFRC522.initial();` replace it with `rfid.initial();`
 2. Libraries such as liquidcrystal, servo are default libraries in arduino so if you had download them from external source and copied them in your library folder please remove them.
 3. This logic won't help as if the first id didn't match it will break the loop and and comparison won't go further with other and your will always find false as a result in this case.

              for(int i = 0; i < 5; i++)
          {
              //if any one Unique ID Digit is not matching,
              //then make My_Card = false and come out from loop
              //No need to check all the digit!
              if( My_RFID_Tag[i] != rfid.serNum[i] ) // suggested change if( My_RFID_Tag[i] == rfid.serNum[i] )
              {
                My_Card = false;//My_Card = true
                break;
              }
          }

 4. Library functions used in code are different from those available in library, open library file and search for those function used for same purpose.

 5. Remove them

        #define SDA_D1O 9
        #define RESET_D1O 8
        MFRC522(SDA_D1O, RESET_D1O);
you are already defining them and using them here in your code

        #define SS_PIN 10
        #define RST_PIN 9
        MFRC522 rfid(SS_PIN, RST_PIN );


body:
I just bought 2 Digispark Micro to start learning some Arduino things.

But when I try to upload the code to my Digispark, it just send me an "Device search timed out" error.

My Digispark is plugged with an USB-C to USB connector and the Red dot on the Digispark is working. The connector is working well with any other device.

**Arduino app (1.8.9) settings:**

- Tools
 - Board → Digispark (Default - 16.5 mhz)
 - Programmer → Micronucleus

I tried using the [micronucleus CLI][1], but, even if I try plug/unplug several times (~10s between each unplug/plug) I got this :

    > Please plug in the device ...
    > Press CTRL+C to terminate the program.

  [1]: https://github.com/micronucleus/micronucleus/tree/master/commandline

title: Digispark Micro (ATTINY85) not working on Macbook Pro 2016

Answers: 1

body:
Digisparks are known to have problems with USB3 ports (which your USB-C adaptor probably provides). Try using a cheap USB2 hub between the DigiSpark and the adaptor.

It's always a good idea to use a cheap USB hub between whatever experimental device you want to connect and your machine, so that if you wire something up incorrectly you don't end up frying an expensive laptop. This is particularly true for a device such as the digispark which does not have a real USB interface but really bit-bangs the protocol out of ordinary I/O pins.

There is no guarantee that the hub will protect you from all wiring mistakes, but it's an added level of protection.


body: Earlier today, I was able to connect flawlessly to my HM-10 module via the Arduino serial monitor. I think I then changed some settings without thinking and now I can no longer connect to it. No errors, nothing. I have tried every baud setting but to no avail. I am able to connect to it through my Android phone but is there an app where I can send AT commands just like the Arduino serial monitor. I'm thinking I could do this to run the at+reset command to factory reset it? Are there any other ways of resetting the module?

title: How can I send AT commands to HM-10 module from my android phone?

Answers: 0


body:
I would like to change this clock to u8g2.

It works fine with the esp8266 and oled 128x64.

[![ESP8266 with Oled 128x64][1]][1]

I would start by including the u8g2 library with #include
and all display. with u8g2. replace.

What else should I consider.?

Thanks Else

This is my Code
```
#include <ESP8266WiFi.h>
#include <WifiUDP.h>
#include <String.h>
#include <Wire.h>
#include <SSD1306.h>
#include <SSD1306Wire.h>
#include <NTPClient.h>
#include <Time.h>
#include <TimeLib.h>
#include <Timezone.h>

#ifdef U8X8_HAVE_HW_SPI
#include <SPI.h>
#endif
#ifdef U8X8_HAVE_HW_I2C
#include <Wire.h>
#endif
// Define NTP properties
#define NTP_OFFSET   60 * 60      // In seconds
#define NTP_INTERVAL 60 * 1000    // In miliseconds
#define NTP_ADDRESS  "ca.pool.ntp.org"  // change this to whatever pool is closest (see ntp.org)

// Set up the NTP UDP client
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, NTP_ADDRESS, NTP_OFFSET, NTP_INTERVAL);

// Create a display object // SSD1306 display(0x3c, SDA, SCL);
SSD1306  display(0x3c, D2, D1); //0x3d for the Adafruit 1.3" OLED, 0x3C being the usual address of the OLED

//U8G2_SSD1306_128X64_NONAME_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ 5, /* data=*/ 4, /* reset=*/ U8X8_PIN_NONE);

const char* ssid = "my ssid";   // insert your own ssid
const char* password = "my password";    // and password
String date;
String t;
const char * days[] = {"So", "Mo", "Di", "Mi", "Do", "Fr", "Sa"} ;
const char * months[] = {"Jan", "Feb", "Mär", "Apr", "Mai", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dez"} ;

void setup ()
{
  Serial.begin(115200); // most ESP-01's use 115200 but this could vary
  timeClient.begin();   // Start the NTP UDP client

  Wire.pins(4, 5);
  Wire.begin(4, 5);
  display.begin();
  display.flipScreenVertically();

  // Connect to wifi
  Serial.println("");
  Serial.print("Connecting to ");
  Serial.print(ssid);
  display.drawString(0, 10, "Connecting to Wifi...");
  display.display();
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("Connected to WiFi at ");
  Serial.print(WiFi.localIP());
  Serial.println("");
  display.drawString(0, 24, "Connected.");
  display.display();
  delay(1000);
}

void loop()
{
  if (WiFi.status() == WL_CONNECTED) //Check WiFi connection status
  {
    date = "";  // clear the variables
    t = "";

    // update the NTP client and get the UNIX UTC timestamp
    timeClient.update();
    unsigned long epochTime =  timeClient.getEpochTime();

    // convert received time stamp to time_t object
    time_t local, utc;
    utc = epochTime;

  /*  // Then convert the UTC UNIX timestamp to local time
    TimeChangeRule usEDT = {"EDT", Second, Sun, Mar, 2, -0};  //UTC - 5 hours - change this as needed
    TimeChangeRule usEST = {"EST", First, Sun, Nov, 2, -60};   //UTC - 6 hours - change this as needed
    Timezone usEastern(usEDT, usEST); */

    TimeChangeRule CEST = {"CEST", Last, Sun, Mar, 2, 60};     //Central European Summer Time
    TimeChangeRule CET = {"CET ", Last, Sun, Oct, 3, 0};       //Central European Standard Time
    Timezone CE(CEST, CET);

    local = CE.toLocal(utc);

    // now format the Time variables into strings with proper names for month, day etc
    date += days[weekday(local)-1];
    date += ", ";
    date += day(local);
    date += " ";
    date += months[month(local)-1];
    date += " ";
    date += year(local);

    // format the time to 12-hour format with AM/PM and no seconds
    if(hour(local) < 10)  // add a zero if houre is under 10
      t += "0";
    t += hour(local);
    t += ":";
    if(minute(local) < 10)  // add a zero if minute is under 10
      t += "0";
    t += minute(local);
    t += ":";
    if(second(local) < 10)  // add a zero if minute is under 10
      t += "0";
    t+= second(local);

    // Display the date and time
    Serial.println("");
    Serial.print("Local date: ");
    Serial.print(date);
    Serial.println("");
    Serial.print("Local time: ");
    Serial.print(t);

    // print the date and time on the OLED
    display.clear();
    display.setTextAlignment(TEXT_ALIGN_CENTER);
    display.setFont(ArialMT_Plain_24);
    display.drawStringMaxWidth(64, 10, 128, t);
    display.setFont(ArialMT_Plain_10);
    display.drawStringMaxWidth(64, 48, 128, date);
    display.fillRect(1, 0, 126*timeClient.getSeconds()/59, 2);
    display.display();
  }
  else // attempt to connect to wifi again if disconnected
  {
    display.clear();
    display.drawString(0, 10, "Connecting to Wifi...");
    display.display();
    WiFi.begin(ssid, password);
    display.drawString(0, 24, "Connected.");
    display.display();
    delay(1000);
  }

  delay(1000);    //Send a request to update every 10 sec (= 10,000 ms)
}
```

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

title: Can someone help me to change this code to u8g2

Answers: 0


body:
I am new at arduino.
I want to write a sketch that would print the message if the temperature grows greater than 30 C.
Here is my sketch can you please tell me what's wrong with it

    #include "DHT.h"
    #define DHTTYPE DHT11
    #define dht_dpin D3

    DHT dht(dht_dpin, DHTTYPE);

    void setup()
    {
     Serial.begin(9600);
     }
    void loop()
    {
     float t = dht.readTemperature();
     Serial.print("temp=");
     Serial.println(t);
     attachInterrupt(dht_dpin, IntCallback, CHANGE);
    }
    void IntCallback()
    {
      float t = dht.readTemperature();
      if(t>30)
      {
        Serial.print("Alert");
      }
    }

title: Interrupt triggering using DHT-11

Answers: 2

body:
You can't use an interrupt the way you are attempting to. Attaching an interrupt to a pin like that will cause the interrupt to trigger any time the digital pin's value changes. The DHT11 uses serial communication to send temp values to the Arduino. Serial communication uses lots and lots of on/off pulses on the signal line to send characters of data. Your interrupt will fire every time the DHT11 toggles the signal line.

You need to read the temp from the DHT11 in your loop, and then add an if statement that does what you want when the temp exceeds your threshold. (It looks like you just need to get rid of the attachInterrupt() call, and instead call IntCallback() every couple of seconds.

body:
You don't even need an interrupt.Modification:

    #include "DHT.h"
    #define DHTTYPE DHT11
    #define dht_dpin D3

    DHT dht(dht_dpin, DHTTYPE);

    void setup()
    {
     Serial.begin(9600);
     }
    void loop()
    {
     float t = dht.readTemperature();
     Serial.print("temp=");
     if(t>30)
      {
        Serial.print("Alert");
      }
    }


body:
I am developing code on Arduino to read 9 bytes of data from other controller.

I am getting same arrya elements which is transmitted from controller, but when I convert the same it gives me garbage values, Please help.

Below is my code snippet:

    int Test::ID_001(void) {
      int result = 1;
      int i = 0;
      char FWV_AB[84];
      digitalWrite(DIR485,HIGH);
      delay(100);
      delay(10);

      int res = proto485Write(RS485_ADDRESS, CMD_COMMAND_FW_AB, CMD_ACTION_FW_AB, 0x0000);      // Send msg to controller board

      Serial.print("msgsend: ");
      Serial.println(" ");
      Serial.println("Received message from controller is: ");

      int  bufferIn1[9] = { int(0x00), int(0x00), int(0x00), int(0x00), int(0x00), int(0x00), int(0x00), int(0x00), int(0x00) };
      digitalWrite(DIR485,LOW);
      delay(100);
      delay(10);

      delay(DELAY);
      if (Serial2.available()== 0) {Serial.print("Error01 "); result = 0;} // Error for response timeout
      while(Serial2.available() > 0)
       {
       bufferIn1[i] = Serial2.read();

       Serial.print(bufferIn1[i],DEC);     // PRINTS CORRECT VALUES HERE SAME AS SENT BY CONTROLLER
       Serial.print(" ");
       i++;
       if(i == 9){
       Serial.println("Controller board version is: ");
       for(int j=3;j<7;j++){
        Serial.print(int(bufferIn1[j]-48)); } // HERE I AM CONVERTING VALUES INTO READABLE FORM
       }
       }
      digitalWrite(DIR485, HIGH);
      delay(100);
     return result;
    }

GETTING VALUES AS "9 49 51 48 48 48 50 48 54" while serial read takes place.
MY DATA is "48 48 48 50" i.e. START FROM 3rd POSITION TO 6th POSITION OF RECEIVED BYTE. IT SHOULD PRINT AS "0002" but it gives me "GQQQ" some times "s)))" and such garbage data instead of 0002 value. Kindly guide.

Thanks you

title: Arduino serial read data conversion, getting garbage values

Answers: 0


body:
I have been working successfully with the arduino uno and a thermal camera device called grid eye. There is a board available at the popular suppliers of arduino addons.
For the uno, the code looks something like this and works.

    // Load Grideye Library
    #include <SparkFun_GridEYE_Arduino_Library.h>
    uint8_t pixelTable[64];
    void setup() {
        grideye.setI2CAddress(104); //This means, that one pin of the device is pulled up
        grideye.begin();
        Serial.begin(115200);
    }
    void loop() {
    // loop through all 64 pixels on the device and map each float value to a number
    // between 0 and 15 using the HOT and COLD values we set at the top of the sketch
      for (unsigned char i = 0; i < 64; i++) {
        if (i % 8 == 0) {
          Serial.print("\n");
        }
        pixelTable[i] = grideye.getPixelTemperature(i);
        Serial.print(pixelTable[i]);
        Serial.print(" ");
      }

For the Metro I use Arduino IDE with the Libraries installed and the board selected. But all I get is an Array full of '0'.

Connected, both times, to the designated SDA and SCL pins, as well as the 3.3V and GND Pin.

Any Ideas?

title: Arduino IDE + Metro + I2C device (Grideye) + Code for Uno = weird results?

Answers: 0


body:
i am a Arduino beginner here. I start knowing about Arduino since my supervisor give me this project. In my project , i need to invent a car safety system to avoid animal hurting that hide under vehicle and solve drowsy driving problem. In sensor requirement, i choose to use PIR motion sensor (HC-SR501) to sense the movement of living things under the car, for the drowsy driving i choose to use pulse sensor and eye blink sensor to detect whether the driver is sleeping or not, it the driver is sleeping then it will activate alarm and led light on. But during research, i found that these 3 sensor have sharing the same pin with is the pin 2 (picture attach). So may is ask is possible to connect these all 3 sensor in one board ?? May i ask how can i do it if i connect the pins to the breadboard ??
Last question is do i need have MEMS MPU -6050 sensor in my project since i found this is with the eye blink sensor in other person research. Thank for accepting my question.

[![pulse sensor][1]][1]

[![pir motion sensor][2]][2]

[![mems mpu -6050 sensor][3]][3]

  [1]: https://i.stack.imgur.com/u4nLz.png
  [2]: https://i.stack.imgur.com/DcWly.png
  [3]: https://i.stack.imgur.com/FDRUF.png

title: May mulitple sensor connect to one arduino uno board since they shared same pin?

Answers: 2

body:
You did not provide a picture, or any other information.

Given how little info you provided, the answer is "it depends".

PIR sensors tend to use digital lines that change state when they detect motion. You would not want to share an input line with such a PIR. (I couldn't find a spec-sheet on your PIR with a quick search.)

For devices that use serial communication, the I2C interface standard **is** designed for connecting multiple devices on the same serial bus. If you have multiple I2C devices, you should connect them all to the same pins, and it works great as long as they have different device addresses on the I2C bus.

Other types of serial interfaces are only designed for 2 devices to communicate with each other, and cannot be shared.

body:
Your drawing seems to show plenty of pins available, with only pin 2 in common. If the pin is being used for an Interrupt, then one device can use a different pin instead and the code adapted to use PCINT for the interrupt.

I would suggest the PIR does not even need an interrupt, it is slow changing and polling it for activity would be just as effective.

Add some current limit resistors to your LEDs so you don't damage the IO pins.


body:
I am using **ESP32 Pico Kit** with Arduino Ide. I want to measure operation cycle for a few commands.

The code is so simple as below:
<!-- language-all: lang-cpp -->

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

    void loop() {
      unsigned long count = 10000;
      unsigned long i = 0;
      unsigned long _start;
      unsigned long _end;
      _start = ESP.getCycleCount();
      while(i < count)
      {
        i++;
      }
      _end = ESP.getCycleCount();
      Serial.println(_end - _start);
    }

When I run the code, the result is ***13***.

Then, I changed the `counter` variable to different values and ran it again (values: 10, 100, 1000, 10000, ...).

The result is always ***13***!

Why the execution cycle does not change and it seems that the code is compiled as just one loop and the loop count is not important?

Am I missing something?

title: Clock cycle count count for the same command is not equal in ESP32

Answers: 0


body:
I have an Arduino Uno connected to an ESp8266 via an ESP-01 adapter.  The Adapter is powered from the Arduino 5v and Gnd pins and the Tx/Rx to the Adapter use Arduino pins 2/3. I have basic code which sets the ESP8266 as an access point and I am able to connect to the AP from my phone, send a message and receive a reply from the ESP8266.  This works fine for 75% of the time.  other times, the message received by ESP8266 ( and printed on the serial monitor for debug ) is truncated, and/or corrupted.
I have tried a different ESp8266 and a different adapter; I don't get corruption errors with other programs run on the Uno; I have dropped the communications speed between the Uno and ESp8266 to 9600 baud.
What could be the cause of the corruption I am seeing in the data ? Thanks

I have updated my app an no longer get corrupted data, but there are characters data missing from the returned data stream.

Here is my sketch :
````
#include <SoftwareSerial.h>

//
// ESP8266 interface
////////////////////

SoftwareSerial wifiSerial(2, 3);            // RX, TX for ESP8266

#define TICK  100

bool DEBUG = true;
int responseTime = 1000;

#define ESP8266CMD_SET_UART_9600            "AT+UART_CUR=9600,8,1,0,3"
#define ESP8266CMD_SET_UART_38400           "AT+UART_CUR=38400,8,1,0,0"

#define ESP8266CMD_ECHO_OFF                 "ATE0"
#define ESP8266CMD_ECHO_ON                  "ATE1"
#define ESP8266CMD_SET_WIFI_STATION_MODE    "AT+CWMODE=1"
#define ESP8266CMD_SET_WIFI_SOFTAP_MODE     "AT+CWMODE=2"
#define ESP8266CMD_GET_IP_ADDRESS           "AT+CIFSR"
#define ESP8266CMD_CONFIG_AP_LIST_ALL       "AT+CWLAPOPT=1,2047" // Sort and display all netwroks
#define ESP8266CMD_CONFIG_AP_LIST           "AT+CWLAPOPT=1,3"    // Sort and display ECN / ESSID only
#define ESP8266CMD_LIST_AVAILABLE_APS       "AT+CWLAP"

#define ESP8266CMD_SEND_DATA                "AT+CIPSEND=0,"     // required data length to be appended
#define ESP8266CMD_CLOSE_ALL_CONNECTIONS    "AT+CIPCLOSE=5"

//
// LCD interface
////////////////

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

#define I2C_ADDR                            0x27
#define BACKLIGHT_PIN                       3
#define En_pin  2
#define Rw_pin  1
#define Rs_pin  0
#define D4_pin  4
#define D5_pin  5
#define D6_pin  6
#define D7_pin  7

LiquidCrystal_I2C  lcd(I2C_ADDR,En_pin,Rw_pin,Rs_pin,D4_pin,D5_pin,D6_pin,D7_pin);

//
// S E T U P
////////////

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

  lcd.begin( 16, 2 );                                 //  LCD is 16x2

  lcd.setBacklightPin(BACKLIGHT_PIN,POSITIVE);        // Switch on the backlight
  lcd.setBacklight(HIGH);

  lcd.home();
  lcd.print("Initialising...");

  wifiSerial.begin(9600);

  sendToWifi( ESP8266CMD_ECHO_OFF, responseTime, DEBUG );
  sendToWifi( ESP8266CMD_SET_WIFI_STATION_MODE, responseTime, DEBUG );

  sendToWifi( ESP8266CMD_CONFIG_AP_LIST, responseTime, DEBUG );

  Serial.println("Wifi connection is running!");

  lcd.clear();
  lcd.print("Ready");

  pinMode(13,OUTPUT);  //set build in led as output
}

//
// L O O P
//////////

void loop()
{
String APList = sendToWifi(ESP8266CMD_LIST_AVAILABLE_APS, responseTime, DEBUG);

  Serial.println(APList);

  delay(100 * TICK);
}

/*
* Name:         sendToWifi
* Description:  Send data to ESP8266.
* Params:       command - the data/command to send
*               timeout - the time to wait for a response
*               debug - print to Serial window?(true = yes, false = no)
* Returns:      Response from the esp8266 (if there is a reponse)
*/
String sendToWifi(String command, const int timeout, boolean debug){
 String response = "";

 if(debug)
    Serial.println( "Command[" + command + "]" );

 wifiSerial.println(command);       // send string esp8266

 long int time = millis();
 while( (time+timeout) > millis())
 {
   while(wifiSerial.available())
   {
   char c = wifiSerial.read();      // read resonse

    response += c;
    time = millis();                // data received - reset timeout
   }
 }
 if(debug)
    Serial.println( "Response[" + response + "]" );

 return response;
}
````
..and here is output debug data from a sample run.
````
Initialising...
Command[ATE0]
Response[
OK
]
Command[AT+CWMODE=1]
Response[
OK
]
Command[AT+CWLAPOPT=1,3]
Response[
OK
]
Wifi connection is running!
Command[AT+CWLAP]
Response[]

Command[AT+CWLAP]
Response[+CWLAP:(4,"VM2293456_EXT")
+CWLAP:(3,"NVR9ca3a92708f2")
+CWLA]
+CWLAP:(4,"VM2293456_EXT")
+CWLAP:(3,"NVR9ca3a92708f2")
+CWLA
Command[AT+CWLAP]
Response[+CWLAP:(4,"VM2293456_EXT")
+CWLAP:(4,"VM2293456")
+CWLAP:(5,"]
+CWLAP:(4,"VM2293456_EXT")
+CWLAP:(4,"VM2293456")
+CWLAP:(5,"
````
As well as the two networks VM2293456 and VM2993456_EXT there are a number of other netwroks available, and on some runs I see those networks shown. In any case, there are missing characters from the response text.

title: Sporadically corrupted data returned from ESP8266

Answers: 2

body:
AT firmware writes the data to Serial without any control. If the data are not read fast the Serial buffer overflows. If you count the bytes read by your sketch (including 2 not visible line ending characters per line) you count 64 bytes. That is the size of the RX buffer of SoftwareSerial. SoftwareSerial can tell you if the buffer overflowed. Call `wifiSerial.overflow()`.

The CWLAP takes time to execute on esp8266 side and then the AT firmware puts out the complete listing to Serial. Reading it byte by byte and storing millis() in-between is then too slow. You need to read it faster with a buffer.

I use `readBytesUntil` to read a line into buffer. This function waits for the next byte if there is a gap between bytes and stops reading if terminator is received or it times out. Default timeout is 1000 millis. It can by set with `setTimeout(t)`.

In your sketch you use String. I do not recommend it for a project, but in a test you could use:

    result += wifiSerial.readStringUntil('\n');

to read and append a whole line.

body:
Taking the information that people have kindly offered to me, I have re-written my code to use the AltSoftSerial library and I now have my small app working fine.  Thanks.  AltSoftSerial uses pins 8/9 in an interrupt driven manner, leaving the 'standard' pin 1/2 serial comms for a debug channel.  I have it running at 19200 baud.
I have remove String variable from the code and my final improvement will be to use malloc() to allocation data buffer in place of the current statically declared buffer.
The purpose of my test app is to connect to my home wifi network a to print out the IP address allocated.  All output goes to an LCD display, but the serial monitor could be used instead.

Here's my code :

````
#include <AltSoftSerial.h>
#include "ESP8266_cmd.h"

//
// Connect to home WiFi network using AltSoftSerial via pins 8/9 to ESP8266
///////////////////////////////////////////////////////////////////////////

//
// ESP8266 interface
////////////////////

AltSoftSerial wifiSerial;                   // RX, TX for ESP8266

#define TICK  100

#define DEBUG                               false
#define ResponseTime                        1000

#define NW_CREDENTIALS                      "\"VM2293456\",\"----------\""

//
// LCD defines
//////////////

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

#define I2C_ADDR          0x27
#define BACKLIGHT_PIN     3
#define En_pin  2
#define Rw_pin  1
#define Rs_pin  0
#define D4_pin  4
#define D5_pin  5
#define D6_pin  6
#define D7_pin  7

int n = 1;

LiquidCrystal_I2C  lcd(I2C_ADDR,En_pin,Rw_pin,Rs_pin,D4_pin,D5_pin,D6_pin,D7_pin);

//
// Buffer for ESP8266 data
//////////////////////////

#define BUFFER_LEN    512
char Buffer[BUFFER_LEN];

//
// State Machine
////////////////

enum {
 STATE_INIT_WIFI = 0,
 STATE_WIFI_CONNECT,
 STATE_WAIT_FOR_CONNECTED,
 STATE_GET_IP_ADDRESS,
 STATE_WAIT,

 STATE_ERROR,
} State;

int MachineState = STATE_ERROR;
int ErrorCode = 0;

void setup()
{
String response;

  Serial.begin(115200);
  Serial.println("Initialising...");

  lcd.begin( 16, 2 );                                 //  LCD is 16x2.  Cmd is Column, Row

  lcd.setBacklightPin(BACKLIGHT_PIN,POSITIVE);        // Switch on the backlight
  lcd.setBacklight(HIGH);

  lcd.clear();
  lcd.home();
  lcd.print( "Network Connect " );

  wifiSerial.begin(19200);

  MachineState = STATE_INIT_WIFI;
}

void loop()
{
String response;
char cmd[64];

  switch( MachineState )
  {
  case STATE_INIT_WIFI:
    lcd.setCursor( 0, 1);
    lcd.print("Initialising    ");

    sendToWifi( ESP8266CMD_ECHO_OFF, ResponseTime, DEBUG );
    if( strcmp( Buffer, "OK" ) != 0 )
    {
      ErrorCode = 1;
      MachineState = STATE_ERROR;
      break;
    }

    sendToWifi( ESP8266CMD_SET_WIFI_STATION_MODE, ResponseTime, DEBUG );
    if( strcmp( Buffer, "OK" ) != 0 )
    {
      ErrorCode = 2;
      MachineState = STATE_ERROR;
      break;
    }
    MachineState = STATE_WIFI_CONNECT;
    break;

  case STATE_WIFI_CONNECT:
    lcd.setCursor( 0, 1);
    lcd.print("Connecting           ");

    strcpy( cmd, ESP8266CMD_CONNECT_TO_AP );
    strcat( cmd, NW_CREDENTIALS );
    sendToWifi( cmd, ResponseTime, DEBUG );
    MachineState = STATE_WAIT_FOR_CONNECTED;
    break;

  case STATE_WAIT_FOR_CONNECTED:
    lcd.setCursor( 0, 1);
    lcd.print("Wait for connect");
    readFromWiFi( ResponseTime );
    if( strstr(Buffer, "WIFI GOT IP") != NULL )
       MachineState = STATE_GET_IP_ADDRESS;
    else
       delay( 1000 );
    break;

  case STATE_GET_IP_ADDRESS:
    lcd.setCursor( 0, 1);
    lcd.print("Getting IP Addr ");

    sendToWifi(ESP8266CMD_GET_IP_ADDRESS,ResponseTime,DEBUG);

    MachineState = STATE_ERROR;   // prime for error case
    ErrorCode = 3;

    if( strstr( Buffer, "OK" ) != NULL )
    {
      if( strncmp( Buffer, "+CIFSR:STAIP", 12 ) == 0 )
      {
        lcd.setCursor( 0, 1 );
        lcd.print( "                " );
        lcd.setCursor( 0, 1 );
        for( int i = 15; i < strlen(Buffer ); i++ )
        {
          if( Buffer[i] == '"' )
            Buffer[i] = '\0';
        }
        lcd.print( &Buffer[14] );   // Display extracted IP address
        MachineState = STATE_WAIT;
      }
    }
    break;

  case STATE_WAIT:
    delay(10000);
    MachineState = STATE_GET_IP_ADDRESS;
    break;

  case STATE_ERROR:
  default:
    lcd.setCursor( 0, 1 );
    lcd.print( "                " );
    lcd.setCursor( 0, 1 );
    strcpy( cmd, "Err " );
    itoa( ErrorCode, &cmd[strlen(cmd)], 10 );
    lcd.print( cmd );
    delay(10000);
    break;
  }
}

/*
* Name:         readFromWiFi
* Description:  Read data from ESP8266.
* Params:       timeout - the time to wait for a response
*               debug - print to Serial window?(true = yes, false = no)
* Returns:      Response from the esp8266 (if there is a reponse) in Global Buffer
*/
void readFromWiFi(int timeout)
{
int l = 0;
long int t = millis();

    while( ( t + timeout ) > millis() ){
      while( wifiSerial.available() > 0 ) {
        Buffer[l++] = wifiSerial.read();
        t = millis();
       }
    }

    Buffer[l] = '\0';

    trimRight( Buffer );
    trimLeft( Buffer );
}

/*
* Name: sendToWifi
* Description: Function used to send data to ESP8266.
* Params: command - the data/command to send; timeout - the time to wait for a response; debug - print to Serial window?(true = yes, false = no)
* Returns: The response from the esp8266 (if there is a reponse)
*/
void sendToWifi( const char *command, const int timeout, boolean debug){

 if(debug)
 {
    Serial.print( "Command[" );
    Serial.print( command );
    Serial.println( "]" );
 }

 wifiSerial.println( command );       // send string esp8266

 readFromWiFi( timeout);

 if(debug)
  {
    Serial.print( "Response[" );
    Serial.print( Buffer );
    Serial.println( "]" );
  }
}

void trimRight( char *src )
{
  int i = strlen(src)-1;

  for( ; i >= 0; i-- )
  {
    if( (src[i] != ' ' ) && ( src[i] != '\t' ) && ( src[i] != '\n' ) )
      break;
  }
  src[i] = '\0';
}

void trimLeft( char *src )
{
  int i, l = strlen(src);

  for( i = 0; i < l; i++ )
  {
    if( (src[i] != ' ' ) && ( src[i] != '\t' ) && ( src[i] != '\n' ) && ( src[i] != '\r' ) )
      break;
  }
  memmove( src, &src[i], l);
}
````

and here is the ESP822_cmd.h header file that I created :

````
// ESP82266_cmd.h
//
// #defines for ESP8266 interface
//

#define ESP8266CMD_SET_UART_9600            "AT+UART_DEF=9600,8,1,0,0"
#define ESP8266CMD_SET_UART_19200           "AT+UART_DEF=19200,8,1,0,0"
#define ESP8266CMD_SET_UART_38400           "AT+UART_CUR=38400,8,1,0,0"

#define ESP8266CMD_ECHO_OFF                 "ATE0"
#define ESP8266CMD_ECHO_ON                  "ATE1"
#define ESP8266CMD_SET_WIFI_STATION_MODE    "AT+CWMODE=1"
#define ESP8266CMD_SET_WIFI_SOFTAP_MODE     "AT+CWMODE=2"
#define ESP8266CMD_GET_IP_ADDRESS           "AT+CIFSR"
#define ESP8266CMD_CONFIG_AP_LIST_ALL       "AT+CWLAPOPT=1,2047" // Sort and display all netwroks
#define ESP8266CMD_CONFIG_AP_LIST           "AT+CWLAPOPT=1,3"    // Sort and display ECN / ESSID only
#define ESP8266CMD_LIST_AVAILABLE_APS       "AT+CWLAP"

#define ESP8266CMD_SEND_DATA                "AT+CIPSEND=0,"      // required data length to be appended
#define ESP8266CMD_CLOSE_ALL_CONNECTIONS    "AT+CIPCLOSE=5"

#define ESP8266CMD_CONNECT_TO_AP            "AT+CWJAP_CUR="      // required essid and password to be appended
```


body:
I am using a NodeMCU ESP 12E board which will be programmed using the Arduino IDE. I intend to use it to send GPS data to the Blynk app server. I also want to interface a Bluetooth module HC-05 to the board along with the GPS module. I am also interfacing a L239D motor driver IC to the NodeMCU in order to control two DC motors. I am also using a metal detector module with analog output which is connected to the A0 pin of the board. Motor driver inputs are given using D0,D1,D2 and D3 pins set as digital out.

I need the NodeMCU to receive data from the GPS module and also send and receive data through the Bluetooth module. So I need 2 UART serial ports. I understand that the UART0 port can be used as the Serial port using Serial.begin(BAUD-RATE). UART1 can be used only for transmission. UART2 can be configured on GPIO13 and GPIO15 as Rx and Tx using Serial.swap(). But this cannot be used along side the UART0 port.

So is there a way I can implement Software serial in the Arduino IDE in order to set 2 ports, one for receiving only and other for both sending and receiving serial data ?

title: Using 2 serial ports on NodeMCU

Answers: 0


body: I’m an industrial design major working on a studio project that involves electronics that are kind of out of my league. I have a few low power generators like piezos, thermoelectric (peltier) tiles etc... In order to progress with my project I need a way to measure the output of each one individually when harvesting human motion. As far as I know, I need a multimeter to hook up directly to these devices, and then I think there may be a way to record the results with an arduino. My question is more about specifically how to do this, or even if this is a feasible plan. Are there any plans for this sort of thing already out there? Any feedback will be greatly appreciated!

title: How can I make a data logging multimeter?(harvesting energy from human motion)

Answers: 0


body:
I have a 2D array of uint16_t arrays (IR Remote Codes). Due to the size of this data in RAM I'm having all kinds of trouble when my array is larger than one code. Thus, I have been trying to move this whole structure into PROGMEM. Following various tutorials and [this solution][1], I have come up with the code below for reading a single element out of the array and into a variable that I can feed to the IRLIB2 IRSendRaw function.

The variable that holds the code that is read out of PROGMEM is still huge and causing some problems. Is there a more direct way like a python list comprehension to access an arbitrary element and send it directly to the IRSender?

[This PROGMEM_readAnything library][2] looks promising, but I don't have enough C++ fu to make the mental leap to implement it in my code.

```
#include <IRLibSendBase.h>    //We need the base code
#include <IRLib_HashRaw.h>    //Only use raw sender

#define RAW_DATA_LEN 68
const uint16_t sources[3][RAW_DATA_LEN] PROGMEM =
  {{8550, 4306, 530, 1606, 530, 566, 502, 1610, //power on/off
  530, 566, 502, 574, 506, 1630, 506, 566,
  506, 1630, 506, 566, 502, 1610, 530, 566,
  502, 1634, 506, 1606, 530, 570, 498, 1634,
  506, 570, 510, 562, 506, 566, 502, 1634,
  506, 1606, 530, 1610, 530, 562, 538, 538,
  530, 542, 538, 1598, 538, 1570, 558, 542,
  538, 538, 530, 542, 538, 1598, 530, 1578,
  558, 1578, 562, 1000},

  {8546, 4310, 558, 1578, 562, 538, 498, 1638,  //source CD
  530, 542, 506, 570, 502, 1634, 502, 570,
  498, 1638, 534, 538, 498, 1638, 530, 542,
  506, 1606, 554, 1582, 558, 538, 510, 1602,
  554, 546, 506, 566, 502, 570, 510, 1602,
  554, 1582, 558, 538, 510, 566, 502, 1606,
  554, 546, 502, 1610, 558, 1574, 554, 546,
  502, 570, 510, 1602, 526, 1610, 526, 574,
  506, 1602, 526, 1000},

  {8550, 4306, 530, 1606, 534, 566, 502, 1606,  //source CDR
  534, 566, 502, 570, 510, 1602, 526, 570,
  510, 1602, 534, 566, 502, 1606, 534, 566,
  506, 1602, 530, 1606, 534, 566, 502, 1610,
  530, 570, 498, 574, 506, 566, 502, 570,
  510, 1602, 526, 570, 510, 566, 502, 570,
  510, 1602, 526, 1610, 526, 1606, 534, 1602,
  534, 566, 502, 1610, 530, 1602, 534, 1602,
  526, 574, 506, 1000}};

//Create a sender
IRsendRaw mySender;

//Read out one code into a variable and send to the IR transmitter
uint16_t myCode[RAW_DATA_LEN];
for (int i = 0; i < RAW_DATA_LEN; i++) {
   myCode[i] = pgm_read_word_near(sources[0] + i);
}
mySender.send(myCode,RAW_DATA_LEN,36);
```

  [1]: https://arduino.stackexchange.com/questions/61889/accessing-2-dimensional-array-in-progmem-inside-loop
  [2]: https://arduino.stackexchange.com/questions/13545/using-progmem-to-store-array-of-structs

title: Read nested array item from PROGMEM

Answers: 1

body:
The library, as it stands, doesn't support direct sending from PROGMEM.  However it's not too hard to get around that - if your C++ is up to it.

The IRsendRaw class is a child class that extends the IRsendBase with a single function.  You just need to do the same thing to create a new class that implements the functions in a way that can read from PROGMEM.

This is the original:

    class IRsendRaw: public virtual IRsendBase {
      public:
        void send(uint16_t *buf, uint8_t len, uint8_t khz) {
          enableIROut(khz);
          for (uint8_t i = 0; i < len; i++) {
            if (i & 1) {
              space(buf[i]);
            }
            else {
              mark(buf[i]);
            }
          }
          space(0); // Just to be sure
        }
    };

You just need to make your own one of those in your sketch, called something different, and which uses the progmem functions instead of accessing `buf[i]`:

    class IRsendRawPGM: public virtual IRsendBase {
      public:
        void send(const uint16_t *buf, uint8_t len, uint8_t khz) {
          enableIROut(khz);
          for (uint8_t i = 0; i < len; i++) {
            if (i & 1) {
              space(pgm_read_word_near(buf + i));
            }
            else {
              mark(pgm_read_word_near(buf + i));
            }
          }
          space(0); // Just to be sure
        }
    };

Now you can define your sender object as:

    IRsendRawPGM mySender;

And send the data directly:

    mySender.send(sources[0], RAW_DATA_LEN, 36);

(Note: this code is untested).


body:
I'm a software Engineer, and recently I’ve been working on a new Software
Part of this Software is to be able to turn off and on multiple TV screens using timers in the software <br>
First idea came to my mind is using relays with Arduino and connecting in to computer using Bluetooth chip but not all screens turns on once the power cable is plugged in
So, I tried IR CIRCUIT using NODEMCU and IR LEDS. And it worked but not perfectly,
The way I did this is by sending a combination of IR codes to screen to make a sleep timer so it will turn off the screen after some time.
But there was a delay when sending IR codes, and sometimes the code won’t be sent
This is the circuit I used (in addition to more  IR LEDS)
[![enter image description here][1]][1]
I just want to know why the codes are not sent every time
And if there is any better way to control the screens from computer?

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

title: Controlling multiple Screens using IR

Answers: 0


body:
I'm planning a project where I need to control a lot of Arduino Unos from a single PC. I'll need to send commands to the Arduinos and receive responses, as well as have the ability to update each Arduino from the PC, preferably without Arduino IDE at some point. Connecting via USB is out of the question, as I have already tried this and got miserable results, in part because of the number of Arduinos I need to control. So now I'm considering connecting the PC to an ethernet switch and then from there connect each Arduino with an ethernet shield.

Which brings me to my questions. Are there any limitations I should be aware of, if I want to pursue this setup? Will controllings tens, or even a hundred, Arduinos at the same time be a problem? How about stuff like updating a specific Arduino on the network?

My current working prototype uses a Windows PC that connects to one of multiple Raspberry Pis, which then in turn communicates with a number of Arduinos via I2C, and updates them via USB. But if I'm able to do all this directly from the main PC to the Arduinos via Ethernet, that would be fantastic.

Thanks for reading, looking forward to any answers.

title: Limitations of connecting to many Arduinos via Ethernet?

Answers: 1

body:
With a lot of devices on the ethernet, you may want to consider a private wire that is dedicated to those devices.  That is, a second ethernet port or a VLAN off a capable switch.

As the number of devices increases, and the number of simultaneous talkers increases, you will start getting contention.  Chances are a modern switch can handle this to some extent, but you were not clear on how much traffic you are planning on sending, or how often each device talks, or if it is centrally coordinated (aka "polled") or just speaking whenever.


body:
Is there a way to get at least three analog inputs to the esp8266 (without a multiplexer)?

Each digital or analog pin on an Arduino can be configured as digital or "analog" (e.g., [PWM software][1]).

Here is a way to squeeze one additional analog input pin: [hackaday.io/project/8435-2-analog-inputs-for-esp8266-without-multiplexer][2]

Any ideas or software[?][3]

  [1]: https://github.com/Palatis/arduino-softpwm
  [2]: https://hackaday.io/project/8435-2-analog-inputs-for-esp8266-without-multiplexer
  [3]: https://www.esp8266.com/viewtopic.php?f=6&t=19521

title: ESP8266: Multiple analog inputs using software

Answers: 1

body:
1) nope it's not possible "in a straightforward way". you should use analog muxes.

2) the statement "Each digital or analog pin on an Arduino can be configured as digital or "analog" (e.g., PWM software)." means for PWM or the so called "analog output". not intended the ADC unit.

3) the link provided uses software tricks to measure 2 signals in a muxed fashion. it's up to purpose.

workarounds :

1) use CD4066 CMOS bilateral switch. it works with analog signals.

2) use GPIOs to supply voltage to measurement units. like the link you provided. it works for passives like photoresistors and for devices like LM35 temp sensor. but can't be used for devices like 3 channels analog-out accelerometers.


body:
I bought several ESP8266 boards from an Amazon seller, and I have flashed them with custom firmware.  This firmware basically sends telemetry to an MQTT server, and has some OTA functionality to self-update from a web server I run.

I flashed them from the Arduino IDE initially, although have also since updated them OTA.

These devices properly connect to the AP I have defined, get an address, and send their mqtt messages.  However, they ALSO advertise an SSID that is `FaryLink_XXXXXX` where the XXXXXX relates to the MAC.

How is this possible, and how should I wipe their little brains fully?

title: esp8266 advertising AP even when flashed with custom firmware

Answers: 1

body:
The Espressif ESP8266 SDK is part of every Arduino sketch for the ESP8266. The SDK handles the WiFi and other basic functions of the chip.

If enabled, the SDK remembers WiFi STA and SoftAP settings and start to connect right after boot. At default it is enabled. In Arduino sketch this is controlled by [`WiFi.persistent(bool)`][1] and of course this setting is stored too.

To clear SoftAP settings, call `WiFi.softAPdisconnect()`. To only turn off SoftAP, use `WiFi.setMode(WIFI_STA)`.

  [1]: https://arduino-esp8266.readthedocs.io/en/latest/esp8266wifi/generic-class.html#persistent


body:
I'm trying to control the brushed motor in a Traxxas Slash RC car with the built-in XL5 ESC using the Servo library on Arduino. I previously had success controlling this car with a Pololu Micro Maestro, but it died on me, and so, while waiting for a replacement to arrive, I thought I'd give a more manual approach a try.

The problem is, the motor moves *way* too fast. My understanding is that, for this ESC (which allows for reverse driving), 90 degrees / 1500 ms should be the neutral point, with anything above this leading to progressively faster forward speed; and, below, reverse.
But, while it seems there is some speed modulation, the motor just abruptly begins with a very high speed at an angle (`Serial.write(95)`) of 95 or so, and then gets even faster from there.

A minimal version of my code is pasted below; my circuit has the signal pins of the steering and ESC servo connectors (white wires) attached to pins 2 and 9, respectively on a Pro Micro, their two 5V pins connected to each other (since the ESC supplies its own 5V), and their grounds connected to the Arduino's ground pins.

While it's possible that I need a special arming sequence to get this ESC to work properly (I do operate in the three-blink "training" mode, which is supposed to be slower), I would expect that problem to manifest as no motion at all, not too *much* motion.

I've tried powering the ESC with the original 9.1V battery (nominal 8.4V), and with a 8.4V regulated supply attached to a ~15V battery.

What could I be doing wrong here?

    #include <Servo.h>

    Servo throttle;

    void setup(){

        Serial.begin(115200);

        throttle.attach(9);
        // throttle.write(91);
        // delay(300);

        int first = 90;
        for(int angle=first; angle < first+20; angle++) {
            Serial.println(angle);
            throttle.write(angle);
            delay(10);
        }

        // This doesn't work any better.
        // int first = 1500;
        // for(int us=first; us < first+10; us++) {
        //     Serial.println(us);
        //     throttle.writeMicroseconds(us);
        //     delay(50);
        // }

        throttle.write(90);
    }

    void loop() {
    }

title: Brushed ESC won't move slowly

Answers: 1

body:
Per @jsotola 's suggestion, I looked more closely at the [manual][1] (see the section "XK-5 Setup Programming"):

> XL-5 Setup Programming (Calibrating your ESC and transmitter)
>
> Read
> through all of the programming steps before you begin. If you get lost
> during programming or receive unexpected results, simply unplug the
> battery, wait a few seconds, plug the battery pack in, and start over.
>
> 1. Disconnect one of the motor wires between the XL-5 and the motor. This is a precaution to prevent runaway when the speed control is
> turned on before it is programmed.
>
> 2. Connect a fully charged battery pack to the XL-5.
>
> 3. Turn on the transmitter (with the throttle at neutral).
> 4. Press and hold the EZ-Set button (A). The LED will first turn green and then red. Release the button.
>
> 5. When the LED blinks RED ONCE, pull the throttle trigger to the full throttle position and hold it there (B).
>
> 6. When the LED blinks RED TWICE, push the throttle trigger to the full reverse and hold it there (C).
>
> 7. When the LED blinks GREEN ONCE, programming is complete. The LED will then shine green or red (depending on LowVoltage Detection
> setting), indicating the XL-5 is on and at neutral (D).

I wrote a short program to send specified servo angles in [0, 180] interactively. The manual says to apply "full throttle" and "full reverse", but I wasn't exactly sure what these translated to in terms of servo angle/pulse width milliseconds. I gather that these are often given as 45° and 135° (1.25 ms and 1.75 ms), respectively, but that setting the limits to [0, 180] during this training period also worked. It's valuable to get the full range, so I can get finer gradations in speed. Since I don't expect to ever reach full speed in my application, and will only use the near-90 part of the range, this will be particularly helpful.

I'm still perplexed about what caused the original problem--the Pololu servo controller never needed this tuning process. Perhaps the limits were set to [45, 135], and I mistakenly sent 180, which put the ESC into some state not described in the manual. And I don't know whether I'll need to repeat this in the future, or
whether my new [0, 180] limits will prevent the above mistake from being a problem. For that matter, I don't know how non-volatile the non-volatile memory is on the ESC in which these limits are stored. Does it require periodic battery power to refresh?

Finally, while it might be even more particular to the XL-5 ESC and my power supply setup, another useful note is that the low-voltage detection mode might prevent movement independent of the setup process.

  [1]: https://traxxas.com/sites/default/files/58024-OM-EN-R01.pdf


body:
I need to use a specific library that issues error messages in the form of String texts. The library uses the `Serial.println()` function to send the messages to the Arduino IDE's serial monitor.

The problem is that I have the Serial lines from the Arduino linked to another device, therefore I can't use the Serial Monitor to see the messages. I have a method in the Main Arduino sketch that sends any String text msg generated to another device using Udp commands (wireless). This device is connected to a serial monitor unit.

My question is: How can I invoke the Udp method inside the main sketch of the Arduino program from within the aforementioned library? This would help me to convert the `Serial.print()` text messages from the library directly into Udp messages to be able to visualize them.

The Udp method I'm using is declared as `void UdpSend(String msg)` in the Arduino sketch. I'd like to use something similar inside the library to wrap the text msg and send it over to the method on the main program.

Any example or link to get this information will help.

EDIT1:

@Majenko,

 1. On the target library, added:  `void libUdpSend(const char *libMsg);`
 2. On the sketch, I added this method (Udp comm handler):

         void libUdpSend(const char *libMsg)
         {
           Udp.begin(localPort);
           Udp.beginPacket(Udp.remoteIP(), localPort);
           Udp.write(libMsg);
           Udp.endPacket();
           delay(40);
         }

 3. Added this line on the library (right after the declaration on 1.) to test through the remote serial interface:

        libUdpSend("String wrapper has been implemented SUCCESSFULLY!");

When trying to compile linking the library, the following exception occurrs:

> error: expected constructor, destructor, or type conversion before '(' token
> `libUdpSend("String wrapper has been implemented SUCCESSFULLY!");`

I then switched to String as this is the type I want to wrap, Same steps:

 1. On the target library, added:  `void libUdpSend(String *libMsg);`
 2. On the sketch:

        void libUdpSend(String *libMsg)
        {
          Udp.begin(localPort);
          Udp.beginPacket(Udp.remoteIP(), localPort);
          Udp.write(libMsg.c_str());
          Udp.endPacket();
          delay(40);
        }

Now the error message says:
>request for member 'c_str' in 'libMsg', which is of pointer type 'String*' (maybe you meant to use '->' ?)

I am not an expert on pointers so I'd need some help on how to assign the pointer as argument on the `UdpWrite` function using the '->' command proposed by the compliler?

Let me know your thoughts on this.

title: Invoke a method in the main sketch from within a library

Answers: 1

body:
The connection between a sketch and a library is not one-way as many suppose.  Things can go quite happily in both directions.

What you are proposing is something I do quite often when developing a library and I need to get some debugging information out of the library. Yes, it's possible to directly use `Serial` in the library, but that's something I don't like, and often isn't appropriate anyway, as in your situation.

However, doing it the way you propose (and I use) is actually very simple.

You just make your function in your sketch and tell the library to use it.

For example, in your sketch:

    void debug(const char *msg) {
        Serial3.println(msg);
    }

And in the library add the line:

    void debug(const char *msg);

Then at any point in the same file (or translation unit) you can use

    debug("I am here");

That is assuming that the file that you are using it in is a C++ file (`.cpp`).  If it's a C file (`.c`) then you have to treat things very slightly differently.  You see, C++ makes a mess of the function names (even vanilla functions like that) which means they can't be seen by C files.  So you have to tell the compiler "I'd like this to be usable in a C file, please".

Which you do with a special "extern" wrapper around your function:

    extern "C" {
        void debug(const char *msg) {
            Serial3.println(msg);
        }
    }

And then `debug()` is usable in a C file in the same way as above.

However now it won't work in a C++ file...  (round and round we go...)

Simple to fix: add the `extern "C"` to the prototype in the C++ file:

    extern "C" {
        void debug(const char *msg);
    }

If you want to include your "extern" in a header file that could be included into either C or C++ files it's very common to use a construct such as:

    #if defined(__cplusplus)
    extern "C" {
    #endif

    void debug(const char *msg);

    #if defined(__cplusplus)
    }
    #endif

That will add the `extern "C"` wrapper for C++ files (identified by the presence of the macro `__cplusplus`) but omit it for C files.

I have used "const char *" as the parameter for this example, but you can choose whatever parameters are appropriate for your usage.


body:
**Update:**

Here is my first try based on the code I found and it did not work.
The first time I uploaded it, it move to the "current positional value". But did not do the void loop part. Just holds the positions.

Thanks.

        //Includes
        #include <Servo.h>

        //Defines
        #define LINEAR_1_100PIN 11        //Linear Actuator Digital Pin
        #define LINEAR_2_100PIN 6      //Linear Actuator Digital Pin

        String msg;

        //max/min pulse values in microseconds for the linear actuators
        #define LINEAR_1_100_MIN      1050  //
        #define LINEAR_1_100_MAX      2000 //
        #define LINEAR_2_100_MIN  1050     //
        #define LINEAR_2_100_MAX  2000    //

        Servo LINEAR_1_100, LINEAR_2_100;  // create servo objects to control the linear actuators
        //int knobValue, sliderValue;  //variables to hold the last reading from the analog pins

        int linear100Value_1 = 1051;   //current positional value being sent to the linear actuator.
        int linear100Value_2 = 1051;  //current positional value being sent to the linear actuator.

        int speed = 10;

        void setup()
        {
          //initialize servos
          LINEAR_1_100.attach(LINEAR_1_100PIN, LINEAR_1_100_MIN, LINEAR_1_100_MAX);      // attaches/activates the linear actuator as a servo object
          LINEAR_2_100.attach(LINEAR_2_100PIN, LINEAR_2_100_MIN, LINEAR_2_100_MAX);  // attaches/activates the linear actuator as a servo object

          //Analog pins do not need to be initialized

          //use the writeMicroseconds to set the linear actuators to their default positions
          LINEAR_1_100.writeMicroseconds(linear100Value_1);
          LINEAR_2_100.writeMicroseconds(linear100Value_2);
        }

        void loop()
        {
       LINEAR_1_100.write(90);
       delay(1000);
       LINEAR_1_100.write(0);
       delay(1000);
       LINEAR_2_100.write(90);
       delay(1000);
       LINEAR_2_100.write(0);
       delay(1000);
        }

**Old Question:**

I am trying to make the code described in this tutorial:

http://learn.robotgeek.com/demo-code/118-arduino-linear-actuator-tutorial-analog-direct-control-of-small-linear-actuator.html

https://github.com/robotgeek/firgelliDirectControl/blob/master/firgelliDirectControl/firgelliDirectControl.ino

work with PWM from an Arduino, without the additional board.

So far the Arduino Examples>Servo>Sweep works as I would like to achieve it (delay changed to 30 ms) but very slowly and it does not seem to just go 180 steps out wait 30 ms and 180 steps in again. It sometimes moves twice in one direction. If I change the steps from 1 to 5 the servo does not move anymore (I expected it to go faster).

With the code above I understand I can control the servo with a Knob or Slider, but I would like to understand how I can control this Linear Actuator Servo with PWM from an Arduino PMW Pin (e.g. 11) and change the speed. Finally I would like to make the Servo consistently go x amount of steps out, wait for x ms and the same amount back in again.

Most importantly I would like to make sure it always ends at position 0, and that it does not accumulate errors.

Thank you for any help.

title: Linear Actuator Arduino Control

Answers: 1

body:
About being sure about returning to position 0 this is not a problem. You are not actually controlling anything with your PWM. You are only sending a signal to the IC inside the servo to tell it where to move the actuator. That IC knows in what position the actuator is located in any moment, usually using some kind of encoder (it's called a closed loop system) and it will make sure that it will move back exactly to `0` whenever you tell it to move to `0`.

If you want to make things clearer you can use `write` method to send value to the servo.

    void Servo::write(int value)
    {
      if(value < MIN_PULSE_WIDTH)
      {  // treat values less than 544 as angles in degrees (valid values in microseconds are handled as microseconds)
        if(value < 0) value = 0;
        if(value > 180) value = 180;
        value = map(value, 0, 180, SERVO_MIN(),  SERVO_MAX());
      }
      this->writeMicroseconds(value);
    }

Any value from `0` to `180` will set a position to which servo will move from MIN to MAX possible position. No need for manual calculation of microseconds.

You have to remember that PWM works constantly. If you write for example `LINEAR_1_100.writeMicroseconds(1051)` this code will set some timers, counters and prescalers inside the ATmega chip on the Arduino board and the value of PWM will be sent constantly until you change it.

So the `delay(2000)` doesn't stop the PWM signal, and servo remains in constant position.

The issue is here:

    LINEAR_1_100.writeMicroseconds(1800);
    LINEAR_1_100.writeMicroseconds(1051);

You set the value of `1800` and then immediatelly set value of `1051`, but the ATmega didn't even have the time to send the first value to the servo.
Add a `delay(1000)` after every call of `write` or `writeMicroseconds` to allow the PWM to actually be sent to the servo.


body:
I am trying to create a charliplexed display of 6x8 LEDS using a Arduino Nano with the ATMega328p chip. Because of the limited storage I am trying to use PROGMEM. I did my research and found some usefull examples, but when I try to create a char[] of 48 charaters (0 = LED off, 1 = LED on), the monitor only shows a line filled with squares. Im not sure what this indicates, but when I limit the amount of characters to lets say 10, it works as expected. I made sure the buffer size matches the amount of max characters. What am I missing here?

I know it would be easier to use a multiplexer, but I prefer to find a working solution using progmem since this is a assignment where I would like to have my students find a solution to store the "LED data" for the whole alphabet without using external memory or a multiplexer chip. If this simply is not possible, I will look into using other hardware.

TIA!

This is the code I am using:

    #include <avr/pgmspace.h>
    const char string_0[] PROGMEM = "000000000000000000000000000000000000000000000000"; // "String 0" etc are strings to store - change to suit.
    const char string_1[] PROGMEM = "String 1";
    const char string_2[] PROGMEM = "String 2";
    const char string_3[] PROGMEM = "String 3";
    const char string_4[] PROGMEM = "String 4";
    const char string_5[] PROGMEM = "String 5";

    // Then set up a table to refer to your strings.

    const char *const string_table[] PROGMEM = {string_0, string_1, string_2, string_3, string_4, string_5};

    char buffer[48];  // make sure this is large enough for the largest string it must hold

    void setup() {
      Serial.begin(9600);
      while (!Serial);  // wait for serial port to connect. Needed for native USB
      Serial.println("OK");
    }

    void loop() {
      /* Using the string table in program memory requires the use of special functions to retrieve the data.
         The strcpy_P function copies a string from program space to a string in RAM ("buffer").
         Make sure your receiving string in RAM  is large enough to hold whatever
         you are retrieving from program space. */

      for (int i = 0; i < 6; i++) {
        strcpy_P(buffer, (char *)pgm_read_word(&(string_table[i])));  // Necessary casts and dereferencing, just copy.
        Serial.println(buffer);
        delay(500);

title: Using a 48 characters char[] for PROGMEM

Answers: 0


body:
I couldn't find a proper answer anywhere on internet.

I want to use the FLASH button as input in the setup() function and do not use the loop() with deepsleep mode (this part comes later).

I tried demos wherein the button events are sometimes failed to be captured. How can I make it 100% sure to get detected as soon as I press reset or along with reset? Because there is a mismatch in the time when reset is clicked and the flash button press gets detected.

title: ESP8266 /ESP12F use flash button as input without using loop()

Answers: 0


body:
Hi I am new to the Arduino world. I was playing around with my Arduino UNO making LEDs go on and off in a sequence. Then I connected a motor to the N.0 pins but found it doesn't work so I plugged it doesn't work so I plugged it in 3.3V pin and it worked. I tried to reverse the connections but the one cable slipped and it connected to the metal shielding of the motor now it is not working when plugging it in USB it. Power LED just flashes red and turns off emediatly. Reset button doesn't seem to do annything. Is there a possible fix for this.[![enter image description here][1]][1]

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

title: Arduino Uno 3.3V pin to GND short how to fix

Answers: 0


body:
For a project I've to parse a big json file. Unfortunately it does not work as expected.

Here is the json file:

    {
      "data1": "[encoded data, 4800 characters]",
      "data2": "[encoded data, 4800 characters]",
      "data3": "736",
      "data4": "266",
      "data5": "3211",
      "data6": "0"
    }

I was able to successfully implement the whole thing on an ESP8266 with this code:

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

    // WiFi Parameters
    const char* ssid = "SSID";
    const char* password = "PASSWORD";

    void setup() {
      Serial.begin(115200);
      WiFi.begin(ssid, password);

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

    void loop() {
      // Check WiFi Status
      if (WiFi.status() == WL_CONNECTED) {
        HTTPClient http;  //Object of class HTTPClient
        http.begin("http://jsonplaceholder.typicode.com/users/1");
        int httpCode = http.GET();
        //Check the returning code
        if (httpCode > 0) {
          // Parsing
          const size_t bufferSize = JSON_OBJECT_SIZE(2) + JSON_OBJECT_SIZE(3) + JSON_OBJECT_SIZE(5) + JSON_OBJECT_SIZE(8) + 370;
          DynamicJsonBuffer jsonBuffer(bufferSize);
          JsonObject& root = jsonBuffer.parseObject(http.getString());

          const char* data1 = root["data1"];
          const char* data2 = root["data2"];
          const char* data3 = root["data3"];
          const char* data4 = root["data4"];
          const char* data5 = root["data5"];
          const char* data6 = root["data6"];

          Serial.print("data1:");
          Serial.println(data1);
          Serial.print("data2:");
          Serial.println(data2);
          Serial.print("data3:");
          Serial.println(data3);
          Serial.print("data4:");
          Serial.println(data4);
          Serial.print("data5:");
          Serial.println(data5);
          Serial.print("data6:");
          Serial.println(data6);
        }
        http.end();   //Close connection
      }
      delay(60000);
    }

The ESP Code works perfect for me, but for my application I need an microcontroller with ethernet. So I bought an enc28j60 and a W5500 Board to migrate the ESP Code to the Arduino UNO.
The Code result is this:

    #include <ArduinoJson.h>
    #include <Ethernet.h>
    #include <SPI.h>

    void setup() {
      // Initialize Serial port
      Serial.begin(9600);
      while (!Serial) continue;

      // Initialize Ethernet library
      byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
      if (!Ethernet.begin(mac)) {
        Serial.println(F("Failed to configure Ethernet"));
        return;
      }
      delay(1000);

      Serial.println(F("Connecting..."));

      // Connect to HTTP server
      EthernetClient client;
      client.setTimeout(10000);
      if (!client.connect("192.168.178.5", 80)) {
        Serial.println(F("Connection failed"));
        return;
      }

      Serial.println(F("Connected!"));

      // Send HTTP request
      client.println(F("GET /test.json HTTP/1.0"));
      client.println(F("Host: arduinojson.org"));
      client.println(F("Connection: close"));
      if (client.println() == 0) {
        Serial.println(F("Failed to send request"));
        return;
      }

      // Check HTTP status
      char status[32] = {0};
      client.readBytesUntil('\r', status, sizeof(status));
      if (strcmp(status, "HTTP/1.1 200 OK") != 0) {
        Serial.print(F("Unexpected response: "));
        Serial.println(status);
        return;
      }

      // Skip HTTP headers
      char endOfHeaders[] = "\r\n\r\n";
      if (!client.find(endOfHeaders)) {
        Serial.println(F("Invalid response"));
        return;
      }

      // Allocate JsonBuffer
      // Use arduinojson.org/assistant to compute the capacity.
      const size_t capacity = JSON_OBJECT_SIZE(3) + JSON_ARRAY_SIZE(2) + 60;
      DynamicJsonBuffer jsonBuffer(capacity);

      // Parse JSON object
      JsonObject& root = jsonBuffer.parseObject(client);
      if (!root.success()) {
        Serial.println(F("Parsing failed!"));
        return;
      }

      // Extract values
      Serial.println(F("Response:"));
      Serial.println(root["data1"].as<char*>());
      Serial.println(root["data2"].as<char*>());
      Serial.println(root["data3"].as<char*>());
      Serial.println(root["data4"].as<char*>());
      Serial.println(root["data5"].as<char*>());
      Serial.println(root["data6"].as<char*>());

      // Disconnect
      client.stop();
    }

    void loop() {

    }

Every time a run the sketch I get the following error:

"Parsing failed!"

So I got to the following page:

https://arduinojson.org/v5/faq/why-parsing-fails/

I've tested the sketch with different buffer sizes, without success?

Is it possible that the memory simply is too small?
Or did I miss something?

title: Can't parse large json file

Answers: 0


body:
I am trying to divide a incoming high frequency signal 600kHz by 4 and output wave at arduino MEGA2560 digital pin.

 - The input to arduino comes from incremental Encoder which is connected to motor that runs at 9000 rpm and the generates 1024 pulses per rotation.
 - I am trying to downsample the frequency I am getting from arduino to 250kHz or less.
 - I tried following approaches :

   a. I counted the rising edge of the incoming wave and a interrupt is triggered as number of rising edge reaches certain value and ISR toggle an output pin.
   b. I tried to get hardware counter work at T0 pin but I was not able to hit ISR when the count has reached specific value.

The problem with approach 1 is: As my frequency of incoming wave increases the output wave starts missing some pulses and generates one half cycle for 6/8/10 pulses of incoming wave. It should actually generate one half cycle for 4 pulses.

**Here is approach 2 code:**

    #define outPin1 10
    volatile short encoder = 4;

    void setup ()
    {
       pinMode (outPin1, OUTPUT);
       Serial.begin(9600);
       cli();
       // reset Timer 0
       TCCR0A = 0;
       TCCR0B = 0;

     }  // end of setup

     ISR(TIMER0_COMPA_vect)
     {
         digitalWrite(outPin1, !digitalRead(outPin1));

     }

     void loop ()
     {
        TCNT0 = 0;      //counter to zero

        // set compare match register to desired timer count:
       OCR0A = encoder;
        // turn on CTC mode:

       bitSet(TCCR0A, WGM01);
       // Timer 0 - counts events on pin D4

      bitSet(TIMSK0, OCIE0A);    // interrupt on Timer 0 CTC
       // start Timer 0
      // External clock source on T0 pin (D4). Clock on rising edge.

       bitSet(TCCR0B, CS02);
       bitSet(TCCR0B, CS01);
       bitSet(TCCR0B, CS00);
    }

**Please someone help me out with this issue**

title: How to sample incoming 600khz pin and divide it by 4 and generate low frequency signal at output pin of arduino

Answers: 2

body:
This is probably too fast to have have software involved in the loop.
You should try to use a hardware-only solution. Note the Arduino timers
should be usable as hardware frequency dividers:

* configure a timer to be clocked off the input signal, so that it
  behaves like a counter.
* configure it for delivering a PWM output with a period of 4 timer
  clock cycles and a duty cycle of 50%.

You may try this, but beware I have not tested it:

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

    void setup()
    {
        // Configure Timer 5 as a frequency divider:
        //   input: digital pin 47 = PL2 = T5
        //   ouput: digital pin 46 = PL3 = OC5A
        DDRL  |= _BV(PL3);    // set pin PL3 as output
        TCCR5A = 0;           // undo the Arduino core's configuration
        TCCR5B = 0;
        ICR5   = 4 - 1;       // period = 4 timer clock cycles
        OCR5A  = 2 - 1;       // output HIGH for 2 timer clock cycles
        TCCR5A = _BV(COM5A1)  // non-inverting PWM on pin OC5A
               | _BV(WGM51);  // mode 14: fast PWM, TOP = ICR5
        TCCR5B = _BV(WGM52)
               | _BV(WGM53)
               | _BV(CS50)    // clock on rising edges of T5
               | _BV(CS51)
               | _BV(CS52);
    }

    void loop(){}

body:
I am writing another answer because what I propose here is radically
different from the previous answer. In that answer I wrote that this is
too fast for being done in software, and here I am going to contradict
myself. :-/

At 600 kHz, the input stays low for roughly 13 CPU cycles,
then high for another 13 cycles. You cannot do much in 13 cycles.
Notably, the prologue of an ISR can quite often take more than this.
Also, whenever the Timer 0 overflow ISR from the Arduino core fires, it
can delay your own ISR for way more than 13 cycles. That's why it
is usually illusory to expect any job to be reliably done in this time
frame. Especially if interrupts are involved.

That being said, if the CPU has _absolutely nothing else_ to do. And
specifically if it is never interrupted, Then it can keep up with that
pace. Here is a program that should do what you expect. I initially
thought about writing it in assembly, but it can also be written in C,
as the compiler translates it in a quite straightforward way. If in
doubt, however, check the generated assembly:

<!-- language: c -->

    /*
     * From one square wave generate two waves in quadrature at 1/4 of the
     * original frequency.
     *
     * https://arduino.stackexchange.com/questions/63202
     *                               _   _   _   _   _   _
     *  input:  digital 13 = PB7    / \_/ \_/ \_/ \_/ \_/ \_/
     *                               _______         _______
     *  output: digital 10 = PB4    /       \_______/       \
     *                                   _______         ____
     *  output: digital 11 = PB5    ____/       \_______/
     */

    int main(void)
    {
        DDRB = _BV(PB4) | _BV(PB5);  // PB4 and PB5 as outputs
        for (;;) {
            loop_until_bit_is_clear(PINB, PB7);  // wait for rising input
            loop_until_bit_is_set(PINB, PB7);
            PORTB |= _BV(PB4);                   // rise PB4
            loop_until_bit_is_clear(PINB, PB7);  // wait for rising input
            loop_until_bit_is_set(PINB, PB7);
            PORTB |= _BV(PB5);                   // rise PB5
            loop_until_bit_is_clear(PINB, PB7);  // wait for rising input
            loop_until_bit_is_set(PINB, PB7);
            PORTB &= ~_BV(PB4);                  // fall PB4
            loop_until_bit_is_clear(PINB, PB7);  // wait for rising input
            loop_until_bit_is_set(PINB, PB7);
            PORTB &= ~_BV(PB5);                  // fall PB5
        }
    }

Note that, since this is not using the Arduino core, I wrote `main()`
rather than `setup()` and `loop()`. This overrides the `main()` provided
by the core, thus you don't have the initializations that come with it
and, in particular, you don't have the Timer 0 interrupt.