title: HTTP PUT method on NodeMCU/ESP8266

text:
# Question
Title: HTTP PUT method on NodeMCU/ESP8266
I've been trying to send a put request from my esp8266 for a while not but I can't figure out why it doesn't work and there are barely any posts about put requests online I keep getting errors around `int httpCode = http.sendRequest("PUT", String(data));`

Error log: https://gist.github.com/dkbay/ab3fedf5e89d841d25b24fb829df74ef

```
#include <ESP8266HTTPClient.h>

#define LED_BUILTIN 2

const char* ssid     = "Some SSDI";
const char* password = "Some wifi password";

int wifiStatus;

void setup() {

  Serial.begin(115200);\
  pinMode(LED_BUILTIN, OUTPUT);
  delay(200);

  // We start by connecting to a WiFi network

  Serial.println();
  Serial.println();
  Serial.print("Your are connecting to;");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    digitalWrite(LED_BUILTIN, LOW);
    delay(500);
    digitalWrite(LED_BUILTIN, HIGH);
    Serial.print(".");
  }

}

void loop() {
  wifiStatus = WiFi.status();

  if(wifiStatus == WL_CONNECTED){

    HTTPClient http;

    http.begin("http://google.com/");
    http.addHeader("Content-Type", "application/json");
    String data = "{\"on\":false}";
    int httpCode = http.sendRequest("PUT", String(data));
    String payload = http.getString();

    Serial.println(httpCode);
    Serial.println(payload);

    http.end();
     Serial.println("");
     Serial.println("Your ESP is connected!");
     Serial.println("Your IP address is: ");
     Serial.println(WiFi.localIP());
  }
  else{
    Serial.println("");
    Serial.println("WiFi not connected");
  }
  delay(1000); // check for connection every once a second

}

```

# Answer
```
HTTPClient http;
http.begin("http://google.com?on=false");
http.addHeader("Content-Type", "application/json");
int httpCode = http.sendRequest("PUT", "");
String payload = http.getString();

```

try with this code, if server .php, get data by $\_REQUEST
> 1 votes

---
Tags: esp8266, arduino-ide, nodemcu, http
---


# Question
Title: Monitoring multi analog ports with ACS712 current sensors
Making a Auto Blast Gate for dust collection in my wood shop. Arduino Nano using ACS712's to detect when tool is in use. Using DRV8825 to drive a single Stepper motor that will spin a disk to line up blast gate for the tool in use. Code works as expected with one sensor coded but I can't figure out how to make it work with additional sensor coded in. **Not sure if this is the way the question shows up, Thanks**

```
/*This one is atarting to work.   When tool is turn on the ACS712 detects it and the stepper moves 90 deg/steps.

```

When the tool is turned off it remains in position which is desireable as I would use the same tool multiable times in a row. Need to add sensor A1 and assign different steps to it. Can I declare the values of each sensor 1 time to be used whenever that analog port read \> current Threshold? Can I have a statement that will check all the analogs and act on the one that is \>current Threshold? Need for the stepper to only move if a different sensor (than the previous analog#) is \> current Threshold? IF/Else \*/

```
#include <Arduino.h>
#include "BasicStepperDriver.h"
#include "DRV8825.h"

#define MOTOR_STEPS 360 // Motor steps per revolution. Most steppers are 200 steps or 1.8 degrees/step
#define RPM 200
#define MICROSTEPS 1    // Since microstepping is set externally, make sure this matches the selected mode
                        // If it doesn't, the motor will move at a different RPM than chosen
                        // 1=full step, 2=half step etc.
#define DIR 2           // All the wires needed for full functionality
#define STEP 3
#define ENABLE 4        // 2-wire basic config, microstepping is hardwired on the driver
BasicStepperDriver stepper(MOTOR_STEPS, DIR, STEP, ENABLE);

#define CURRENT_SENSOR_PIN A0 // Current sensor is connected to analog pin A0

#define CURRENT_THRESHOLD 570 // The analog value above which the relay shall be triggered
#define CURRENT_SAMPLE_PERIOD 500 // The number of milliseconds to sample the current reading

int analogValue = 0; // Stores ADC values read in from the current sensor
unsigned long stopwatch = 0; // Used to keep track of elapsed time

void setup() {
  Serial.begin(9600);
  pinMode(DIR, OUTPUT);
  pinMode(STEP, OUTPUT);
  pinMode(ENABLE, OUTPUT);
 // pinMode (A0, INPUT);

    stepper.begin(RPM, MICROSTEPS);
    stepper.setEnableActiveState(LOW);
  }

void loop() {
    analogValue = 0; // Initialize analogValue to a known state
    stopwatch = millis(); // Store a snapshot of the current time since the program started executing

    // Collect the max ADC value from the current sensor for the predetermined sample period
    while (millis() - stopwatch < CURRENT_SAMPLE_PERIOD) {
      analogValue = max(analogValue, analogRead(CURRENT_SENSOR_PIN));
      Serial.println(analogValue);
    }

    // If the max ADC value from the current sensor exceeds the threshold, set the state to LOW
    if (analogValue > CURRENT_THRESHOLD) {
      stepper.enable();  //  energize coils - the motor will hold position
      stepper.rotate(90);  //Moving motor using the degree notation in ()

   }
    while(analogValue > CURRENT_THRESHOLD)
      stepper.disable();  // pause and allow the motor to be moved by hand
}
// need to return to top of loop

```

# Answer
> 1 votes
First: As written in the comments, your current code will only work once. After the first reaching of the threshold it will permanently stay in the last while loop, since `analogValue` can never change in there (you don't assign a new value to it). Thus this part should be removed.

---

To extend your code for multiple sensors, you can organize all the relevant data into arrays, so that you can loop over them. First we define an array of the used analog input pins (together with a define for the array size, so that we can later easily loop over the array and still be able to easily add further sensors):

```
#define SENSOR_N    2
uint8_t sensor_pins[SENSOR_N] = {A0, A1};

```

Then we are defining similar arrays for the thresholds and stepper positions:

```
uint16_t sensor_thresholds[SENSOR_N] = {570, 400};
uint8_t stepper_positions[SENSOR_N] = {90, 180};

```

Now in the `loop()` function we can surround the measurement and stepper code into a loop over the arrays. Where you used defines before, we are now using the array elements of the corresponding index:

```
for(uint8_t i=0;i<SENSOR_N;i++){
    analogValue = 0; // Initialize analogValue to a known state
    stopwatch = millis(); // Store a snapshot of the current time since the program started executing

    // Collect the max ADC value from the current sensor for the predetermined sample period
    while (millis() - stopwatch < CURRENT_SAMPLE_PERIOD) {
        analogValue = max(analogValue, analogRead(sensor_pins[i]));
        Serial.println(analogValue);
    }

    // If the max ADC value from the current sensor exceeds the threshold, set the state to LOW
    if (analogValue > sensor_thresholds[i]) {
        stepper.enable();  //  energize coils - the motor will hold position
        stepper.rotate(stepper_positions[i]);  //Moving motor using the degree notation in ()
    }
}

```

Now you still have 2 things to consider:

* Depending of the number of sensors, your code currently can take rather long. With lets say 6 sensor, you are measuring for 3s in total at the worst case (when the last machine is turned on). You might want to reduce your measurement duration (500ms is rather long).
* You need to add code for defining, what happens, when you turn multiple machines on at the same time. Currently that would lead to the stepper motor going back and forth; surely not what you want. The easiest thing would be to only consider the first sensor, that reaches the threshold, which then gets to set the position ("first" not in chronological sense, but in the order of the pin in the `sensor_pins` array). You can reach that with a `break;` command at the end of the threshold if condition.

---

Notes:

* The arrays hold, what they say. `sensor_thresholds` holds all the thresholds. In my example `570` is the threshold of the first sensor and `400` is the threshold of the second sensor. `90` in `stepper_positions` is the position of the stepper for the first sensor. `180` is the position for the second sensor.
* I used 2 sensors in my example. You can extend that yourself by setting the define `SENSOR_N` to the number of sensors and adding elements for every sensor into the arrays.
* `uint8_t` and `uint16_t` are unsigned integer types with the mentioned number of bits: `uint8_t` has 8 bits (1 byte), `uint16_t` has 16 bits (2 bytes). `uint8_t` is the same as `unsigned char` or `byte`. `uint16_t` is the same as `unsigned int` on the Uno/Nano. I used these types, because it is a good practice to use types, that have the same size on every platform. When changing to a different platform, types like `unsigned int` might have a different size, like being a 32 bit unsigned integer instead of a 16 bit one. As that might break code, that relies on the specific size of the type, I try to always use types with the same size on all platforms. These types have always the same pattern. There are also: `uint32_t`, `int16_t` (signed integer) or `int8_t`.
* I've chosen the type sizes according to the expected values. Pin numbers are typically 8bit/1 byte. That is sufficient. The thresholds are above 255, thus 8 bits are not enough, so I chose a 16 bit integer. Depending on the stepper positions, that you need, you might want to change it's type also to `uint16_t`.

---
Tags: code-review
---


title: Error compiling for board Arduino Uno

text:
# Question
Title: Error compiling for board Arduino Uno
I am relatively new to Arduino and I am trying to code some neo pixels and every time I try to verify my code this error comes up:

> Arduino: 1.8.12 (Mac OS X), Board: "Arduino Uno"
>
> loading libs from /Users/erinshankland/Documents/Arduino/libraries: reading dir \>/Users/erinshankland/Documents/Arduino/libraries: open \>/Users/erinshankland/Documents/Arduino/libraries: operation not permitted
>
> Error compiling for board Arduino Uno.
>
> This report would have more information with "Show verbose output during compilation" option enabled in File -\> Preferences.

this is my code:

```
#include <Adafruit_NeoPixel.h>

#define PIN        6

#define NUMPIXELS 15

Adafruit_NeoPixel pixels(NUMPIXELS, PIN, NEO_GRBW + NEO_KHZ800);

// this constant won't change:

const int  btnRed = 2;  // the pin that the pushbutton is attached to

const int  btnBlue = 3;  // the pin that the pushbutton is attached to

const int  btnGreen = 4;  // the pin that the pushbutton is attached to

const int  btnPurple = 5;  // the pin that the pushbutton is attached to

void setup() {

  randomSeed(analogRead(A0));

  // put your setup code here, to run once:

  pinMode(btnRed, INPUT);

  pinMode(btnBlue, INPUT);

  pinMode(btnGreen, INPUT);

  pinMode(btnPurple, INPUT);

  // initialize the LED as an output:

  // initialize serial communication:

  Serial.begin(9600);

  pixels.begin(); // INITIALIZE NeoPixel strip object (REQUIRED)

    pixels.clear(); // Set all pixel colors to 'off'

    pixels.show();

    delay(1000);

}

void loop() {

if (digitalRead(btnRed)==HIGH){

    rndRed();

  delay(100);

}

if (digitalRead(btnBlue)==HIGH){

    rndBlue();

  delay(100);

}

if (digitalRead(btnGreen)==HIGH){

    rndGreen();

  delay(100);

}

if (digitalRead(btnPurple)==HIGH){

    rndPurple();

  delay(100);

}

}

void rndRed() {

  int led = random(0, 15);

  pixels.setPixelColor(led, pixels.Color(255, 0, 0,0));

  pixels.show();   // Send the updated pixel colors to the hardware.

  delay(500);

}

void rndBlue() {

  int led = random(0, 9);

  pixels.setPixelColor(led, pixels.Color(0, 0, 255,0));

  pixels.show();   // Send the updated pixel colors to the hardware.

  delay(500);

}

void rndGreen() {

  int led = random(0, 9);

  pixels.setPixelColor(led, pixels.Color(0, 255, 0,0));

  pixels.show();   // Send the updated pixel colors to the hardware.

  delay(500);

}

void rndPurple() {

  int led = random(0, 9);

  pixels.setPixelColor(led, pixels.Color(171, 0, 255, 0));

  pixels.show();   // Send the updated pixel colors to the hardware.

  delay(500);

}

```

I am using a new library for the neo pixels but this has been downloaded and updated. Hopefully someone can help me!

# Answer
> 1 votes
> loading libs from /Users/erinshankland/Documents/Arduino/libraries: reading dir /Users/erinshankland/Documents/Arduino/libraries: open /Users/erinshankland/Documents/Arduino/libraries: operation not permitted

This is not an Arduino problem but an OS problem.

Either your `/Users/erinshankland/Documents/Arduino/libraries` is not accessible by your user (check the permissions) or it's not a directory.

You can try, from a terminal:

```
sudo chown -R erinshankland /Users/erinshankland/Documents/Arduino/libraries
chmod -R 755 /Users/erinshankland/Documents/Arduino/libraries

```

which will reset ownership and file permissions on the directory and everything underneath it.

If not, then delete your libraries folder (which may in fact be a file, not a folder) and recreate it and repopulate it with your desired libraries.

---
Tags: arduino-uno, compilation-errors, neopixel
---


# Question
Title: SCLK pulses not seen when using SPI on ESP32
I am using the following code in my esp32 using Arduino IDE for spi communication which is an example code -

```
    #include <SPI.h>

    static const int spiClk = 1000000; // 1 MHz

    //uninitalised pointers to SPI objects
    SPIClass * vspi = NULL;
    SPIClass * hspi = NULL;

    void setup() {
      //initialise two instances of the SPIClass attached to VSPI and HSPI respectively
      vspi = new SPIClass(VSPI);
      hspi = new SPIClass(HSPI);

      //clock miso mosi ss

      //initialise vspi with default pins
      //SCLK = 18, MISO = 19, MOSI = 23, SS = 5
      vspi->begin();
      //alternatively route through GPIO pins of your choice
      //hspi->begin(0, 2, 4, 33); //SCLK, MISO, MOSI, SS

      //initialise hspi with default pins
      //SCLK = 14, MISO = 12, MOSI = 13, SS = 15
      hspi->begin();
      //alternatively route through GPIO pins
      //hspi->begin(25, 26, 27, 32); //SCLK, MISO, MOSI, SS

      //set up slave select pins as outputs as the Arduino API
      //doesn't handle automatically pulling SS low
      pinMode(5, OUTPUT); //VSPI SS
      pinMode(15, OUTPUT); //HSPI SS

    }

    // the loop function runs over and over again until power down or reset
    void loop() {
      //use the SPI buses
      vspiCommand();
      hspiCommand();
      delay(100);
    }

    void vspiCommand() {
      byte data = 0b01010101; // junk data to illustrate usage

      //use it as you would the regular arduino SPI API
      vspi->beginTransaction(SPISettings(spiClk, MSBFIRST, SPI_MODE0));
      digitalWrite(5, LOW); //pull SS slow to prep other end for transfer
      vspi->transfer(data);
      delay(500);
      digitalWrite(5, HIGH); //pull ss high to signify end of data transfer
      vspi->endTransaction();
    }

    void hspiCommand() {
      byte stuff = 0b11001100;

      hspi->beginTransaction(SPISettings(spiClk, MSBFIRST, SPI_MODE0));
      digitalWrite(15, LOW);
      hspi->transfer(stuff);
      delay(500);
      digitalWrite(15, HIGH);
      hspi->endTransaction();
    }

```

I am able to see the toggling of the **SS** pin, but the **SCLK** pin does not show any pulses on the oscilloscope. It is a constant low. Should the pulses be given from an external source? If so, what is the purpose of this line - `static const int spiClk = 1000000; // 1 MHz`?

# Answer
> 1 votes
Try to set the pins explicitly to Output
**EDIT**Different issues with the test programs indicate that acc. to espressif the pin has to explicitly set to high which is not done by the libs begin method (as of core 1.04)

```
  digitalWrite(30, HIGH); // turn on pullup resistors
  digitalWrite(xxx, HIGH); // turn on pullup resistors
  pinMode(30, OUTPUT); //VSPI SLCK
  pinMode(XX, OUTPUT); //HSPI SCLK

```

The ESP32 docs say:

> gpio18 will output low level(because gpio18 is input mode by default). If you don’t want this behavior, you should configure gpio18 as output mode and set it to hight level before calling

As this is not the issue - the Wroom32 modules v1-3 have a problem with SPI when flashed in certain modes with 80Mhz So try flashing with 40Mhz. I check for my test program in the meantime.

So here is a working test routine:

```
/* SPI Test routine for Wroom32
Connect the MISO with  the MOSI pin*/
#include<SPI.h>       //Library for SPI

#define SPI_SCK 18 // Serial Clock (Master Output)
#define SPI_MOSI 23 // Master Output,Slave Input
#define SPI_MISO 19 // Master Input, Slave Output
#define SPI_CS 5 // Chip Select, Slave Transmit Enable (active low, Master Output)
#define SS 5

char returnStr[40] = {'\0'};
char returnChr;

void setup () {
  Serial.begin(115200); // Set baud rate to 115200 for usart
  pinMode(SPI_CS, OUTPUT);
  pinMode(SPI_SCK, OUTPUT);
  pinMode(SPI_MOSI, OUTPUT);
  pinMode(SPI_MISO, INPUT);

  digitalWrite(SS, HIGH); // disable Slave Select
  SPI.begin (SPI_SCK, SPI_MISO, SPI_MOSI);
  SPI.setBitOrder(MSBFIRST);
  SPI.setDataMode(SPI_MODE0);
  SPI.setClockDivider(SPI_CLOCK_DIV8); // divide the clock by 8=2 MHz @ESP32
}

void loop () {
  char c;
  digitalWrite(SS, LOW); // enable Slave Select
  /* Send test string in a loop */
  for (const char *p = "SPI TEST! We are online over SPI\n\r" ; (c = *p); p++)  {
    returnChr = SPI.transfer (c);
    Serial.print(c);
    Serial.print(returnChr); // MOSI MISO Link sends echo back
  }
  digitalWrite(SS, HIGH); // disable Slave Select
  delay(500);
}

```

To measure the signals you have to trigger to the falling edge of SS/CS and set the resolution to 2µs per grid field (round about). I tested on an AIThinker module (ESP32) and everything worked with that sketch.

---
Tags: arduino-ide, spi, esp32
---


title: Arduino atmega328p

text:
# Question
Title: Arduino atmega328p
This program should prompt the user for an encryption key to be input through the serial monitor. The encryption key contains 16 characters. However, the message that will be encrypted can be up to 128 characters. As such, when storing the encryption key in the EEPROM, you should repeat it so that it fills locations 0-127.

in the code, I'm trying to repeat the 16 character key 8 times

```
volatile bool prese_button = false;
String Password;
int counter = 8;
boolean right_pass;
void setup() {
  DDRD &= 0b11111011;
  PORTD |=0b00000100;
  EICRA |= 0b00000010;
  EIMSK |= 0b00000001;
  Serial.begin(9600);
}

void loop() {
  Serial.println("Please enter a 127 character password:");
  while (Serial.available() == 0) {}  //wait for serial terminal to be ready
  Password = Serial.readString();
  Serial.print("your password is: ");  //just to verify it was read correctly
  Serial.println(Password);
  for ( int j = 0 ;j < 128; j++) //   28 char
  {
    for (int i = 0; i<16 ; i++) {     //16 char
      EEPROM_write ( (j), Password[i] );
    }
  }
}

```

# Answer
> 1 votes
```
   for ( int j = 0 ;j < 128; j++) //   28 char
  {
    for (int i = 0; i<16 ; i++) {     //16 char
      EEPROM_write ( (j), Password[i] );
    }
  }

```

In these two for loops you are writing 128 times 16 characters. That seems more than you described in your post. If you have 16 things and need to repeat to fill 128 slots then you need 128 / 16 = 8 repeats of the 16 character sequence. It's just basic math. So that outer loop should count to 8, not 128.

```
for ( int j = 0 ;j < 8; j++) //  8 repeats of the 16 char
      {
        for (int i = 0; i<16 ; i++) {     //16 char
          EEPROM_write ((i + (16*j)), Password[i] );
        }
      }

```

---
Tags: arduino-uno
---


# Question
Title: Arduino webserver POST receive varriables
I have been learning lower level data reading on internet communication As a part of bigger project I am testing web interface.
So far I could get main website displayed and by seeing the web-address read the data from GET request.
As I intend to send codes I wish to use POST method.
I am Trying to make this as standalone class for mine future projects, so I am only sending the class method itself. (Latter it would take websites content as a string, but for now input variables are yet to be implemented)
I am using esp8266, but would prefer to avoid esp8266 specific libraries as I wish it to eventually run on its realtek equivalent.
The code:

```
uint8_t Stranky::Stav(String obsahStranky, uint8_t obnovovat){
    WiFiClient client = server.available();
  if (client) {
    // an http request ends with a blank line
    char vstupRiadok[150]={'\0'};
    uint8_t i=0;
    bool currentLineIsBlank = true;
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        vstupRiadok[i]=c;
        if(c=='\n' || i>=149) {
            Serial.println(vstupRiadok);
            //------------Extract variables here--------
            for(uint8_t j=0; j<149; j++) {
                //Serial.print(vstupRiadok[j]);
                vstupRiadok[j]='\0';
            }
            i=0;
        } else i++;
        if (c == '\n' && currentLineIsBlank) {
            Serial.println("Sending page");
            client.println(ohlasSa(1,1));
            client.println("<!DOCTYPE HTML>");
          // send a standard http response header
            client.println("<html><head> <meta charset=\"utf-8\"></head><body>");
            client.println("<h1> Nic nove</h1>");
            client.println("<form method='POST'>");
            client.println("Name:<input type=\"text\" id=\"Name\" name=\"Name\"/><br>\nSurname:<input type=\"text\" id=\"Surname\" name=\"Surname\"><br>\n<input type=\"submit\" value=\"Submit\"/><input   type='reset'/>  </form> </body>");
            client.println("</html>");
          break;
        }
        if (c == '\n') {
          // you're starting a new line
          currentLineIsBlank = true;
        } else if (c != '\r') {
          // you've gotten a character on the current line
          currentLineIsBlank = false;
        }
      }
    }
    // give the web browser time to receive the data
    delay(1);

    // close the connection:
    client.stop();
    Serial.println("Prehliadač dpojený");
  }
}

```

This results in Browser code:

```
<!DOCTYPE HTML>
<html><head> <meta charset="utf-8"></head><body>
<h1> Nic nove</h1>
<form method='POST'>
   Name:<input type="text" id="Name" name="Name"/><br>
   Surname<input type="text" id="Surname" name="Surname"><br>
<input type="submit" value="Submit"/><input type='reset'/>  </form> </body>
</html>

```

When I send any data over the form it does not get received and only receive these:

```
WS:ac
:ref 1
WS:av
:ref 2
:ur 2
:rn 469
POST / HTTP/1.1

Host: 192.168.43.209

User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:63.0) Gecko/20100101 Firefox/63.0

Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8

Accept-Language: sk,cs;q=0.8,ru;q=0.6,en;q=0.4,en-US;q=0.2

Accept-Encoding: gzip, deflate

Referer: http://192.168.43.209/

Content-Type: application/x-www-form-urlencoded

Content-Length: 25

Connection: keep-alive

Upgrade-Insecure-Requests: 1

Sending page

```

No post, or Cookie variables that I could extract

I am far from home and too short of data to be installing more software like wire-shark over phones network sharing

# Answer
Based on codebreakers code I have been able to combine it into working one
The problem was on a fact that communication starts with header variables, then empty line, then body containing the variables
First get the connection: and create base variables

```
uint8_t Stranky::Stav(){
    WiFiClient client = server.available();
  if (client) {
    // an http request ends with a blank line
    bool currentLineIsBlank = 0;
    bool body=0;             // Helps seeing if this is still header
    bool finished=0;         // To know if to terminate connection
    uint8_t i = 0;           // To prevent iterator from resetting to 0
    char fullLine[81]={'\0'};  // buffer for input character to line
    // char *pch;

    Serial.print("User connected\n");
    while (client.connected()) {
        while (client.available()) {
            bool linEnd=0;          // When to deal with line (print it)

```

Get one incoming character:

```
            char c = client.read();

```

Now deal with new line character first
If the last line was empty That would mean: Header is finished and moving to the body of the incoming data
If not change currentLineIsBlank (until new line gets its first character)

```
            if(c=='\n') {
                if(currentLineIsBlank) {
                    if(!body) body=1;
                    currentLineIsBlank=0;
                } else {
                    Serial. print("/");
                    currentLineIsBlank=1;
                    linEnd=1;
                }

```

Now lets deal with any other character then new line:

```
            } else {
                currentLineIsBlank=0;   //If it has a character then its not empty
                fullLine[i]=c;
                i++;                //Move to the next letter
            }

```

Make sure that our array doesn't overflow

```
            if(i>=81) linEnd=1;

```

Now we know what is happening we can take some action after the buffer line is finished

if we are at the body stage, but we havent "finised" sending code

```
            if(linEnd){
                if(body && !finished) {
                    finished=1;          // Finishing sending page
                    Serial.printf(F("Variables:\n\t"));

```

Start extracting characters from body of the incoming data.
In a simple form like ours POST variables are on a last line, so we will just keep rewriting the line

```
                    uint8_t k=0;
                    while (client.available()) {
                        fullLine[k]=client.read();
                        Serial.printf(F("%c"),fullLine[k]);
                        if(k<80) k++;
                        if(fullLine[k]=='\n') {
                            k=0;
                            Serial.println();
                        }
                    }
                    // Here you can extract variables as shown in codebreakers' answer

```

Finaly send then websites html code:

```
                    Serial.print("Sending page\n");
                    client.println(heatheRoutine()); //I have extra routine to inject heather so I do not have to write it every time I write a page
                    client.println("<!DOCTYPE HTML>");
                    // send a standard http response header
                    client.println("<html><head> <meta charset=\"utf-8\"></head><body>");
                    client.println("<h1>Fill the form now !!!</h1>");
                    client.println("<form method='POST'>");
                    client.println("Meno:<input type=\"text\" id=\"Name\" name=\"Name\"/><br>\nPriezvisko:<input type=\"text\" id=\"Surname\" name=\"Surname\"><br>\n<input type=\"submit\" value=\"Submit\"/><input    type='reset'/>  </form> </body>");
                    /*Serial.printf(F("Page source send\n"));*/
                    client.println("</html>\n");
                    break;
                }

```

If we are not dealing with the body yet:

```
                currentLineIsBlank=1;
                for(uint8_t j=0; j<i; j++) { //Print the last line
                    Serial.print(fullLine[j]);
                    fullLine[j]='/0';     //restore default values To prevent characters leaking into next line
                }
                Serial.println();
                i=0;    //Since we are on an end of a line we are starting from first position in a buffer
            }
        }

```

If we have finished what we have wanted we need to get out of communication loop

```
        if(finished) {
            Serial.printf(F("Ending\n"));
            break;
        }
    }

```

And close the connection:

```
    // give the web browser time to receive the data
    delay(1);

    // close the connection:
    client.stop();
    Serial.println("browser disconnected");
  }
}

```

Complete code:

```
uint8_t Stranky::Stav(){
    WiFiClient client = server.available();
  if (client) {
    // an http request ends with a blank line
    bool currentLineIsBlank = 0;
    bool body=0;             // Helps seeing if this is still header
    bool finished=0;         // To know if to terminate connection
    uint8_t i = 0;           // To prevent iterator from resetting to 0
    char fullLine[81]={'\0'};  // buffer for input character to line
    // char *pch;

    Serial.print("User connected\n");
    while (client.connected()) {
        while (client.available()) {
            bool linEnd=0;          // When to deal with line (print it)
            char c = client.read();
            if(c=='\n') {
                if(currentLineIsBlank) {
                    if(!body) body=1;
                    currentLineIsBlank=0;
                } else {
                    Serial. print("/");
                    currentLineIsBlank=1;
                    linEnd=1;
                }
            } else {
                currentLineIsBlank=0;   //If it has a character then its not empty
                fullLine[i]=c;
                i++;                //Move to the next letter
            }
            if(i>=81) linEnd=1;
            if(linEnd){
                if(body && !finished) {
                    finished=1;          // Finishing sending page
                    Serial.printf(F("Variables:\n\t"));
                    uint8_t k=0;
                    while (client.available()) {
                        riadok[k]=client.read();
                        Serial.printf(F("%c"),riadok[k]);
                        if(k<80) k++;
                        if(riadok[k]=='\n') {
                            k=0;
                            Serial.println();
                        }
                    }
                    // Here you can extract variables as shown in codebreakers' answer

                    Serial.print("Sending page\n");
                    client.println("HTTP/1.1 200 OK\r\n");
                    client.println("Content-Type: text/html\r\n");
                    client.println("Connection: close\r\n");
                    client.println();
                    client.println("<!DOCTYPE HTML>");
                    client.println("<html><head> <meta charset=\"utf-8\"></head><body>");
                    client.println("<h1>Fill the form now !!!</h1>");
                    client.println("<form method='POST'>");
                    client.println("Meno:<input type=\"text\" id=\"Name\" name=\"Name\"/><br>\nPriezvisko:<input type=\"text\" id=\"Surname\" name=\"Surname\"><br>\n<input type=\"submit\" value=\"Submit\"/><input    type='reset'/>  </form> </body>");
                    /*Serial.printf(F("Page source send\n"));*/
                    client.println("</html>\n");
                    break;
                }
                currentLineIsBlank=1;
                for(uint8_t j=0; j<i; j++) { //Print the last line
                    Serial.print(fullLine[j]);
                    fullLine[j]='/0';     //restore default values To prevent characters leaking into next line
                }
                Serial.println();
                i=0;    //Since we are on an end of a line we are starting from first position in a buffer
            }
        }
        if(finished) {
            Serial.printf(F("Ending\n"));
            break;
        }
    }
    // give the web browser time to receive the data
    delay(1);

    // close the connection:
    client.stop();
    Serial.println("browser disconnected");
  }
}

```
> 0 votes

# Answer
Check your definition of

```
String vstupRiadok

```

it should not be

```
String vstupRiadok="                                      "; //80 blanks

```

I would replace it with a decent sized fixed char anyway

```
char vstupRiadok[81] = {'\0'};

```

if you create an empty line or other text do not forget to write the end terminator `'\0'` and make sure the char array is +1 the size for the longest string totake

As String class is a problem on its own as an Arduino class.
The HTML code generated has a missing

```
<head> <meta charset    ="utf-8"></head>

```

error in the dev-tools. Aside from that whats the server code running on the Arduino,its not given. The class creates a html page, but at least in FF75 it tries to call server.ip\odpoved - so there has to be some js or Arduino code to decode this route there are no params attached from the form.

**EDIT**An extraction routine would look like:

```
bool currentLineIsBlank = true;
bool currentLineIsGet = true;
uint8_t tCount = 0;
char tBuf[64];
uint8_t n=0;
uint8_t s=0;
char *pch;

Serial.print("Client request: ");

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

    if (currentLineIsGet && tCount < 63) {
      tBuf[tCount] = c;
      tCount++;
      tBuf[tCount] = 0;
    }

    if (c == '\n' && currentLineIsBlank) {
      Serial.println(tBuf);
      // retrieve the POST data
      Serial.print("POST data: ");
      while (client.available()) Serial.write(client.read());
      Serial.println();

      pch = strtok(tBuf, "?");

      while (pch != NULL) {
        if (strncmp(pch, "Name=", 5) == 0) {
          pch = pch+6;
          char Name [24] = {'\0'};
          while(pch != '&'){
             char Name [n] = pch;
             n++;
           }
          char Name [n+1] = {'\0'};
          Serial.print("Name="); Serial.println(Name);
        }

        if (strncmp(pch, "Surname=", 8) == 0) {
          pch=pch+9;
          char Surname[24] = {'\0'};
          while(pch != '\r') {   // check if your response has that after the content or if its '\0'
             char Surname [s] = pch;
             s++;
           }
          char Surname [s+1] = {'\0'};
          Serial.print("Surname="); Serial.println(Surname);
        }
        pch = strtok(NULL, "& ");
      }
  // here the Sending response part starts

```

You do not need a JSON parser for this just get the post request
> 0 votes

---
Tags: web-server
---


# Question
Title: Send/receive data from/to Raspberry Pi to/from Arduino with HM-10 (Bluetooth LE module)
My goal is to send a string from an Arduino via an HM-10 bluetooth module to a Rasperry Pi. I do this today by connecting the HM-10 on the Arduino to another HM-10 module (master/slave) and then from that module to the Raspberry Pi via USB Serial adapter which gives me a /dev/ttyUSB0 that I can read. I would like to just have the Arduino's HM-10 connect up directly to the Bluetooth of the Raspberry Pi without any extra modules at all.

I found the app "Arduino Bluetooth Controller" (Android) that can connect to the module and serial communication is working.

I also have the HC-05 module and there I can solve it by using rfcomm bind 2 , but that doesn't work on the HM-10.

I'm open to any solution that can do this. Either bind the serial communication using rfcomm (or alternative) like on the HC-05, or try to build an app that is doing the same thing the Android app does, only on the Raspberry Pi.

# Answer
> 1 votes
HM-10 is a BLE device. You'll need to understand BLE programming, which is quite different than classic Bluetooth. There is no standard BLE service for serial communication. The best way on a Pi to use BLE is with the

If you are fit in Phyton: The HM-10 style device will send notifications that the Pi's BLE device can read. Basically you need to attach a 'delegate' call-back function to the Peripheral object, and then wait for notifications. The call-back can then process the received data. You'll have to install the bluepy lib on the PI. This sample code writes to an Arduino HC-10 device

```
import bluepy.btle as btle

p = btle.Peripheral("AA:BB:CC:DD:EE:FF")
s = p.getServiceByUUID("0000ffe0-0000-1000-8000-00805f9b34fb")
c = s.getCharacteristics()[0]

c.write(bytes("Hello world\n", "utf-8"))
p.disconnect()

```

Here is some code for reading from an Arduino HC-10 device

```
import bluepy.btle as btle

class ReadDelegate(btle.DefaultDelegate):
    def handleNotification(self, cHandle, data):
        print(data.decode("utf-8"))

p = btle.Peripheral("AA:BB:CC:DD:EE:FF")
p.withDelegate(ReadDelegate())

while True:
    while p.waitForNotifications(1):
        pass

p.disconnect()

```

---
Tags: arduino-uno, bluetooth, raspberrypi, ble
---


# Question
Title: What is the difference between delay() and delaymicroseconds()
Does delaymicroseconds() provide something more than the time accuracy

# Answer
There is a more important difference between the two functions other than the unit of time the accept as parameters the function delay() calculates time using the time interript of the arduino. However Delaymicroseconds() does not use the time interrupt As you may know once an interrupt is called it stops all other interrupts So the real difference is you can not use delay() in a program in which you are using an interrupt and instead, use delaymicroseconds() but be aware that it has a range where it is accurate and it is between 3 and 16383 micro seconds
> 0 votes

---
Tags: arduino-uno, arduino-mega, arduino-nano
---


# Question
Title: How can I control Servo motor properly by using TimerOne and ServoTimer2 Library?
In this project I want smooth rotation of the Servo(Pin (D10) periodically where period time select by a potentiometer(actually I will use pressure sensor in this pin now it is unavailable to me so I am using g potentiometer).The Time period controlled by by a potentiometer position(two) change at Pin A0.Two Led(blue & red) (D7,D9)(in this pin I will use two valve controller servo) blink with same period and other yellow Led blink same period but oppositely.All working except Servo which rotation is not smooth .It's rotation sometime maintain proper period and sometime unnecessarily stop.Before I tried TimerOne and Servo Library but they are creating some conflict and not uploaded to Board.I am using Arduino Uno Board.What change should I do either in Circuit or in Code.I am new in this field.Any kind help would be grateful for me thank you.And my code is

```
#include <TimerOne.h>
#include "ServoTimer2.h"
const int potPin = A0;
const int bluePin =7;
const int redPin =8;
const int whitePin = 9;
const int yellowPin = 11;
const int myServoPin = 10;
ServoTimer2 myServo;
int angle;
int speed;
int potVal;
int breathPress;
int lowPress=12;
int upPress=24;
int lowCount=0;
int upCount =0 ;
int time1;
int time2;
int timeDiff;
int temp;
int potPin1 = A2;
int breathRatio;
int ratioVal;
void setup() {
  pinMode(potPin,INPUT);
  pinMode(bluePin,OUTPUT);
  pinMode(redPin,OUTPUT);
  pinMode(potPin1,INPUT);
  pinMode(whitePin,OUTPUT);
  pinMode(yellowPin,OUTPUT);
  myServo.attach(10);

  Timer1.initialize(100000);
  Timer1.attachInterrupt(Blink);
  Serial.begin(9600);
 }

void loop() {
  breathRatio=analogRead(potPin1);
  ratioVal = map(breathRatio,0,1023,1,6);

  digitalWrite(bluePin,HIGH);
  digitalWrite(yellowPin,HIGH);
  digitalWrite(whitePin,LOW);
  myServo.write(90);

  delay(timeDiff);
  digitalWrite(bluePin,LOW);
  digitalWrite(yellowPin,LOW);
  digitalWrite(whitePin,HIGH);
  myServo.write(60);
  delay(timeDiff);

}

void Blink(){
  potVal = analogRead(potPin);
  breathPress = map(potVal,0,1023,0,30);
  Serial.print("Pressure=");
  Serial.println(breathPress);
  Serial.println(time1);
  Serial.println(time2);
  Serial.print("Time Difference :");
  Serial.println(timeDiff);
  if(breathPress<10){
  digitalWrite(redPin,LOW);
  }
  if(breathPress>27){
    digitalWrite(redPin,LOW);
  }
  else {
    digitalWrite(redPin,HIGH);
  }
  if ((breathPress - 10 )<= 0){
    lowCount = 1;
    upCount =0;
    time1 = millis();
  }
  if((breathPress - 27)>=0){
    lowCount = 0;
    upCount = 1;
    time2 = millis();
  }
  if(time1-time2 >= 0){
    timeDiff = time1-time2;
  }
  else{
    timeDiff = time2-time1;
  }

```

And output showing

13096 14994 Time Difference :1898 Pressure=15 13096 14994 Time Difference :1898 Pressure=15 13096 14994 Time Difference :1898 Pressure=15 13096 14994 Time Difference :1898 Pressure=15

# Answer
What you are claiming does not makes sense to me. In your code you are not moving the sensor smoothly. You are setting it to 60 and 90 degrees successively. You don't control the movement between these values. That's, what the servo does. It moves directly, where you tell it to move. You cannot control how the servo moves between two values, that you set. To move slower (you could call that smooth) between the values, you would need to set the inbetween values for the servo. So instead of going directly from 60 to 90, you would go in steps, from 60 to 61, to 62, ... to 89, to 90 degrees.

Also you are not controlling the servo with the Timer1 library, at least not directly. You measure a time difference with the library. This time difference is then the time, that the servo will stay in the current position, until it is moved again.

---

Note, that this

```
if((breathPress - 27)>=0)

```

is an over-complicated way of writing

```
if(breathPress >= 27)

```
> 0 votes

---
Tags: arduino-uno, servo
---


title: Arduino vs Wemos Fan control

text:
# Question
Title: Arduino vs Wemos Fan control
I have a working fan control with the correct wiring that works with arduino.

I would like to change the arduino with a Wemos D1 mini board.

When I hook everything up. The fans are not activated.

The fan is driven by a 12v charger. And the irf540n cicruit powers that. They just share a common ground and the pwm pin D5

Is there something I need to know about the difference in both of them?

Below is the code, I've changed D5 in the code to 14.

Still nothing seems to work.

```
    #define fan D5

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  Serial.println("start");
  pinMode(fan, OUTPUT);

  digitalWrite(fan, LOW);
}

void loop() {
  // put your main code here, to run repeatedly:
  delay(1000);
  digitalWrite(fan, HIGH);

  delay(1000);
  digitalWrite(fan, LOW);
}

```

# Answer
> 0 votes
The IRF540 is not suitable to be controlled by a 3.3V device because it has a gate-source-threshold voltage of 2-4V (that's the voltage at which the mosfet **starts** to conduct, but you need to be above that voltage). While this worked at 5V logic level on the arduino, the 3.3V are not enough to make the mosfet switch entirely.

A suitable mosfet has a threshold voltage below 1V. Also for a fan, you eon't need a big mosfet rated for 30A, a tiny one will do it.

---
Tags: esp8266
---


# Question
Title: SIM7600 A-H not responding directly when connected through pins
I am working on a project which utilizes three components:

1. Arudino Pro Mini(5v)
2. Breakout SIM7600 A-H from AND technologies
3. 9V Battery (connected to RAW and GND on the Arduino board)

I am trying to communicate through the device using the pins provided on the SIM board, which unfortunately is not successful.

**I am able to connect to the board directly using an usb-c cable. After installing the right drivers, I am able to communicate with the board using AT commands from my Windows PC.**

However, I want to be able to send AT commands through the arduino. The set up looks like this: I connect the following pins of arduino mini and SIM 7600A-H.

* SIM 7600 TXD --\> Arduino Pin 2
* SIM 7600 RXD --\> Arduino Pin 3
* SIM 7600 Supply --\> 5V
* SIM 7600 GND --\> GND

The code that I am using, I tried it with every possible baud rate:

```
#include <SoftwareSerial.h>

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

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

  Serial.println("Goodnight moon!");

  // set the data rate for the SoftwareSerial port
  mySerial.begin(115200);
}

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

```

After sending an AT command, there is no response, the module has both LED's on, indicating that it is up and running.

# Answer
> 1 votes
Is your issue resolved? If not... I'm using the same module and having the same problem. Jump the resistors on the R and T pins on the module, they seem to be introducing high impedance on the line. After doing that on my module, the UART worked.

Now my problem now is the module is sending some weird characters, maybe my baud rate is not same or etc, still under investigation.

# Answer
> 1 votes
The SIM7600 UART interface works with 1.8 levels:

I'm guessing that the AND board has a level shifter from 3.3 to 1.8 to work with the 7600. Since your Arduino Por Mini is a 5V board your UART levels must be at 5V too, try adding a voltage divider to bring down the UART to 3.3V.

Also try lowering the SIM7600 baudrate, the software\_serial library doesn't work good with high speeds.

---
Tags: gsm, arduino-mini
---


# Question
Title: Restart sequence of NeoPixel stick with a push button at any time
I am really happy with my new Arduino stuff and playing around with all those pixels :).

I am new to programming and it's difficult to understand it, but with every success, I grow in knowledge.

My latest problem now is to restart my loop of incrementing the strip at any time with the push of a button.

I know that `delay();` will stop the code completely and wait till the time passes, but I wrote some code without the use of `delay();` and used `millis();` instead.

So far my LEDs are incrementing through my strip, but I am not able to restart it until it passes though completely. I read that the `while();` part in my code works kinda like a `delay();` and that would prevent it from restarting until a full cycle. I used some `millis();` code from a different sample so it's not like the ones from Blink Without Delay.

I searched so many sites and cannot write another code to increment without a delay, so hopefully you can help me with it.

```
#include <FastLED.h>

#define NUM_LEDS_PER_STRIP 16
CRGB ledStrip[NUM_LEDS_PER_STRIP];

const int signalButtonPin = 4;
const int ledStripPin = 8;

int buttonState = 0;
int lastButtonState = 0;

int delaySignalAnimation = 100;

unsigned long currentMillis = 0;
unsigned long previousMillis = 0;

void setup() {
  pinMode(signalButtonPin, INPUT_PULLUP);
  pinMode(ledStripPin, OUTPUT);
  FastLED.addLeds<NEOPIXEL, 8>(ledStrip, NUM_LEDS_PER_STRIP);
}

void loop() {
  buttonState = digitalRead(signalButtonPin);
  if (buttonState != lastButtonState) {
    if (buttonState == LOW) {
      fill_solid(ledStrip, NUM_LEDS_PER_STRIP, CRGB::Black);
      for (int i = 0; i < 16; i++) {
        ledStrip[i] = CRGB::Blue;
        FastLED.setBrightness(100);
        FastLED.show();
        currentMillis = previousMillis = millis();
        while (previousMillis + delaySignalAnimation >= currentMillis) {
          currentMillis = millis();
        }
      }
    } else {
      lastButtonState = buttonState;
    }
    fill_solid(ledStrip, NUM_LEDS_PER_STRIP, CRGB::Black);
    FastLED.setBrightness(0);
  }
  FastLED.show();
}

```

Thanks in advance for you help.

# Answer
> 1 votes
Firstly, good for you trying to avoid `delay()`.

However your `while` loop pretty much does exactly what `delay()` does anyway.

Instead you need to change your way of thinking. Instead of "I want to light LEDs 0 to 15 in sequence" you need to instead think "I have 6 LEDs lit. Now I need to light the 7th".

Each time through the loop, if enough time has passed (check the BlinkWithoutDelay example) then light *just one more LED*. Once you have lit all 16 you can then restart your sequence.

And when you know how to restart your sequence at the end you should also know how to restart the sequence when you press a button.

For example `loop()` might look something like this (untested):

```
void loop() {
    static uint8_t lednum = 0;
    static uint32_t animTicker = millis();

    if (millis() - animTicker >= 1000) { // Once per second
        animTicker = millis();

        lednum++;
        if (lednum > NUM_LEDS_PER_STRIP) lednum = 0; // This resets the sequence

        // Turn on up to lednum LEDs and turn off the others
        for (uint8_t i = 0; i < NUM_LEDS_PER_STRIP; i++) {
            if (i < lednum) {
                ledStrip[i] = CRGB::Blue;
            } else {
                ledStrip[i] = CRGB::Black;
            }
        }

        FastLED.show();
    }

    buttonState = digitalRead(signalButtonPin);

    if (buttonState != lastButtonState) {
        lastButtonState = buttonState;
        if (buttonState == LOW) {
            lednum = 0;
        }
    }
}

```

The key there is that the variable `lednum` contains the number of LEDs that you want to display. Once per second, controlled by `millis()`, the LEDs are updated to display that number of LEDs.

# Answer
> 0 votes
This is not an answer, but an expansion on Majenko's code.

It adds another layer between the button press and the led display functions to make the program more flexible

```
void loop() {

    static bool     tick          = false;                 // periodic trigger signal
    static bool     zap           = false;                 // enable signal to run sequence
    static bool     buttonClicked = false;                 // button moved from "released" to "pressed"

    static uint8_t  mode          = 0;                     // chooses the light sequence to run
    static uint8_t  lednum        = 0;

    static uint32_t animTicker    = millis();

    if (millis() - animTicker >= 1000) {                   // Once per second
        animTicker = millis();
        tick = true;                                       // set the tick flag
    }

    if (buttonClicked) {                                   // you could check for a double-click here
        buttonClicked = false;
        zap = !zap;                                        // start/stop with button  ... zap is used for the separation of the button click function and the display function
        if (zap) {
            lednum = 0;                                    // start animation sequence at beginning
            mode += 1; if (mode > 2) mode = 0;             // select the next mode .... this could be done with a double-click
        }
    }

    if (tick && zap) {
        tick = false;                                                   // clear the tick flag .... zap stays set for the duration of the animation sequence
        lednum++;

        if (lednum > NUM_LEDS_PER_STRIP) {
            zap = false;                                                // This stops the sequence (runs only once) ... use a counter if multiples are needed
        }

        else {
            switch (mode) {                                             // pick one of the sequences ....  only colors change in this example

                case 0:
                    for (uint8_t i = 0; i < NUM_LEDS_PER_STRIP; i++) {  // Turn on up to lednum LEDs and turn off the others
                        if (i < lednum) {
                            ledStrip[i] = CRGB::Blue;
                        } else {
                            ledStrip[i] = CRGB::Black;
                        }
                    }
                    break;

                case 1:
                    for (uint8_t i = 0; i < NUM_LEDS_PER_STRIP; i++) {
                        if (i < lednum) {
                            ledStrip[i] = CRGB::Red;
                        } else {
                            ledStrip[i] = CRGB::Black;
                        }
                    }
                    break;

                case 2:
                    for (uint8_t i = 0; i < NUM_LEDS_PER_STRIP; i++) {
                        if (i < lednum) {
                            ledStrip[i] = CRGB::Green;
                        } else {
                            ledStrip[i] = CRGB::Yellow;
                        }
                    }
                    break;
            }

            FastLED.show();
        }
    }

    buttonState = digitalRead(signalButtonPin);

    if (buttonState != lastButtonState) {        // button state transition
        lastButtonState = buttonState;           // new "last state"
        if (buttonState == LOW) {                // transition from "released" to "pressed"
            buttonClicked = true;
        }
    }
}

```

---
Tags: button, millis, neopixel
---


title: Is my Arduino skipping a statement?

text:
# Question
Title: Is my Arduino skipping a statement?
So, I made this code (I'm rather new to this). The only thing that the Arduino should do, is when I press the button on pin 2, turn on the LED on pin 4 and emulate CTRL + R on the keyboard for the computer. Then, if the LED is on and I hit the button again, turn it off and hit the spacebar on my computer. But as soon as I hit the button for the first time, it does indeed press CTRL + R and the LED turns on, but after the delay, it immediately skips checking if I am pressing the button and assumes that I am pressing the button. Thereby it only sees that the LED is on and it turns it off while hitting the spacebar. Any suggestions?

```

#include <Keyboard.h>

int buttonPin = 2;
int ledPin    = 4;
int val = 0;

void setup() {
  // put your setup code here, to run once:
  pinMode(ledPin, OUTPUT);
  pinMode(buttonPin, INPUT_PULLUP);
  Keyboard.begin();
}

void loop() {
  val = digitalRead(buttonPin);
  // check if the pushbutton is pressed. If it is, the buttonState is HIGH:
  if ((val == LOW) && (digitalRead(ledPin) == LOW)) {
    // turn LED on:
    digitalWrite(ledPin, HIGH);
    Keyboard.press(KEY_LEFT_CTRL);
    Keyboard.press('r');
    delay(100);
    Keyboard.release(KEY_LEFT_CTRL);
    Keyboard.release('r');
    delay(500);
  }
  if ((val == LOW) && (digitalRead(ledPin) == HIGH)) {
    digitalWrite(ledPin, LOW);
    Keyboard.write(32);
  }
  if ((val == HIGH) && (digitalRead(ledPin) == LOW)) {
    digitalWrite(ledPin, LOW);
  }
  if ((val == HIGH) && (digitalRead(ledPin) == HIGH)) {
    digitalWrite(ledPin, HIGH);
  }
}

```

# Answer
Try something like this.

The code does not use button states in its decision making.

Instead, it looks for the transition between button states, so holding the button does not generate events.

```
void loop() {

  val = digitalRead(buttonPin);

  if (val != oldButtonState) {      // button state transition
    oldButtonState = val;
    if (val == LOW) {               // transition from "released" to "pressed"
      buttonClicked = true;         // set click flag
    }
  }

  if ( buttonClicked ) {

    buttonClicked = false;                // clear click flag

    if (digitalRead(ledPin) == LOW) {
      digitalWrite(ledPin, HIGH);         // turn LED on
      Keyboard.press(KEY_LEFT_CTRL);      // send CTRL-R
      Keyboard.press('r');
      delay(100);
      Keyboard.release(KEY_LEFT_CTRL);
      Keyboard.release('r');
      delay(500);
    }

    else {
      digitalWrite(ledPin, LOW);          // turn LED off
      Keyboard.write(32);                 // send space
    }
  }
}

```
> 1 votes

# Answer
Your code isn't checking for a button. It's checking the value in val. That only gets updated once per loop. Let's say the code enters the first if statement because the val is LOW and the LED is also LOW. This sets the LED to HIGH. Now the next if statement, val is still LOW and now LED is HIGH so that one is true as well.

I think what you want is to use "else if" so it will skip the rest once it finds a true one.

```
void loop() {
  val = digitalRead(buttonPin);
  // check if the pushbutton is pressed. If it is, the buttonState is HIGH:
  if ((val == LOW) && (digitalRead(ledPin) == LOW)) {
    // turn LED on:
    digitalWrite(ledPin, HIGH);
    Keyboard.press(KEY_LEFT_CTRL);
    Keyboard.press('r');
    delay(100);
    Keyboard.release(KEY_LEFT_CTRL);
    Keyboard.release('r');
    delay(500);
  }
  else if ((val == LOW) && (digitalRead(ledPin) == HIGH)) {
    digitalWrite(ledPin, LOW);
    Keyboard.write(32);
  }
  else if ((val == HIGH) && (digitalRead(ledPin) == LOW)) {
    digitalWrite(ledPin, LOW);
  }
  else if ((val == HIGH) && (digitalRead(ledPin) == HIGH)) {
    digitalWrite(ledPin, HIGH);
  }
}

```
> 0 votes

---
Tags: digital
---


# Question
Title: Increasing distance of IR remote / transmitter
I am trying to set up my Arduino as a replacement remote control. The setup works and I can use it to turn on/off my things, for example my fan.

However, the working distance is quite short. Around a meter. The actual remote for my fan works across the distance of my apartment.

What can I do to improve the working distance of my Arduino remote? Does the LED need a back reflector or something? Does it need a different LED?

The LED I am using is this, it came in a bundle I purchased. https://www.amazon.com/dp/B07PJC7WSQ/#detail-bullets

# Answer
I assume that the led you purchased just isn't as bright as the led that came with your remote. As I've seen from your link you could quite easily swap the led from the board. If the new led has the same voltage, the board should work just fine with any other led. Maybe just search for a brighter led with the same wavelength.

I don't think that a back reflector would have such a big effect to boost the range to the distance you need. Also I think it would be rather complicated to install one on the tiny board.
> 1 votes

# Answer
Judging form the picture of the IR breakout board you shown, it seems that the board is drive the LED directly via Arduino GPIO pin. The current of the GPIO pin could supply is typically around 20mA @5v (and about 10mA @3v3) which is not sufficient. A typical 940nm IR LED has the spec like this:

```
Max. Continuous forward current: 100mA
Max. Forward Voltage: 1.5 typ., 1.8V max.@50mA

```

In order to drive the LED, a circuitry like this would be required:

simulate this circuit – Schematic created using CircuitLab

Assuming the LED has a voltage drop of 1.8v, and you are supply the circuit with 3.3v, the 18 ohm resistor should limit the LED current to about 83 mA ((3.3 - 1.8)/18 = 83mA) - safely under its maximum rating of 100 mA. Use a 20 ohms if want to be on the safer side. The transistor's emitter must be connected to the Arduino ground.
> 0 votes

---
Tags: remote-control, infrared
---


# Question
Title: Sending Variable to IFTTT via ESP32 using Asynchronous Web Server
I have been trying to send three variables to IFTTT from my ESP32 using Asynchronous Web Server. However, I couldn't set the "URL" that was supposed to be the response that will trigger my IFTTT. Here's is my code:

```
server.on("/ifttt", HTTP_GET, [](AsyncWebServerRequest *request){

String jsonObject = "{\"value1\":\"" + Global_T + "\"" + ",\"value2\":\"" + Global_H  + "\"" + ",\"value3\":\"" + Global_K +  "\"}";

AsyncWebServerResponse *response = request->beginResponse(200, "application/json", jsonObject);

response ->addHeader("Host", server_ifttt);
request ->send(response);
});

```

It shall get triggered every fixed interval that I have set, and enter here to send it to IFTTT, but this is how it looks like. I not sure where should I add in the "URL" so that the response could be directed to IFTTT.

# Answer
As already said in the comments you need client code - Here are ready to use blocks for your scenario - **NEVER use String class** if you want to have a stable running IoT device, so define global char arrays (compiled to flash) and keep heap fragmentation at a minimum, The code is commented to get you started, change to your needs:

```
/* Your constants */
#define READ_THIS_PIN 4
const char MakerIFTTT_Key[] = "r8X-blahblahYourKeyGoesHere";
const char MakerIFTTT_Event[] = "stack_exchange_example";

/* Define global char arrays to get rid of string class */
    char numBuf[20];       // We "just know" this is big enough for (un)signed longs
    char postRequest[256];    // Hand-calculated to be big enough (size to your needs)
/* Helper functions for constructing the POST data
    append a string or int to a buffer, return the resulting end of string */

char *appendStr(char *tempChr, char *s) {
    while ((*tempChr++ = *s++))
        ;
    return tempChr-1;
}

char *appendUl(char *tempChr, unsigned long u) {
    return appendStr(tempChr, ultoa(u, numBuf, 10));
}
/*
 This is called once per iteration to read the pin
 and send a POST to trigger the IFTTT/Maker event
*/

void updateEvent() {
    WiFiClient client;

    /* Connect to the Maker event server */
    client.connect("maker.ifttt.com", 80);

    /* Construct the POST request */

    postRequest[0] = {'\0'}; /* Reset char array */
    char *p = postRequest;
    p = appendStr(p, "POST /trigger/");
    p = appendStr(p, "MakerIFTTT_Event");
    p = appendStr(p, "/with/key/");
    p = appendStr(p, "MakerIFTTT_Key");
    p = appendStr(p, " HTTP/1.1\r\n");
    p = appendStr(p, "Host: maker.ifttt.com\r\n");
    p = appendStr(p, "Content-Type: application/json\r\n");
    p = appendStr(p, "Content-Length: ");

    /* We need to remember where the content length will go, which is: */
    char *contentLengthHere = p;

    /* It's always two digits, so reserve space for them (the NN) */
    p = appendStr(p, "NN\r\n");

    /* End of headers */
    p = appendStr(p, "\r\n");

    /* Construct the JSON; remember where we started so we will know len */
    char *jsonStart = p;

    // This example reports a pin, uptime, and "hello stack" change to your need */
    p = appendStr(p, "{\"value1\":\"");
    p = appendUl(p, 12);    //analogRead(READ_THIS_PIN));
    p = appendStr(p, "\",\"value2\":\"");
    p = appendUl(p, millis());
    p = appendStr(p, "\",\"value3\":\"");
    p = appendStr(p, "hello, stack!");
    p = appendStr(p, "\"}");

    /* Go back and fill in the JSON length
       we just know this is at most 2 digits (and need to fill in both) */
    uint8_t i = strlen(jsonStart);
    contentLengthHere[0] = '0' + (i/10);
    contentLengthHere[1] = '0' + (i%10);

    // finally we are ready to send the POST to the server!
    client.print(postRequest);
    client.stop();
}

```
> 1 votes

---
Tags: esp32, web-server, http
---


# Question
Title: ESP32 on Arduino IDE: Identify the board type in code (preprocessor macro)
I have read the answers on this post, but they do not seem to be providing a solution for ESP32 boards.

Is there a way to get the .name that is used from the boards.txt without modifying the platform.txt?

for example for uno there is uno.name=Arduino Uno for esp32 esp32wrover.name=ESP32 Wrover Module

For ESP32 I can only find .name having the specific board name

This is a sample of the first 2 boards defined in boards.txt for esp332

```
menu.UploadSpeed=Upload Speed
menu.CPUFreq=CPU Frequency
menu.FlashFreq=Flash Frequency
menu.FlashMode=Flash Mode
menu.FlashSize=Flash Size
menu.PartitionScheme=Partition Scheme
menu.DebugLevel=Core Debug Level
menu.PSRAM=PSRAM
menu.Revision=Board Revision

##############################################################
### DO NOT PUT BOARDS ABOVE THE OFFICIAL ESPRESSIF BOARDS! ###
##############################################################

esp32.name=ESP32 Dev Module

esp32.upload.tool=esptool_py
esp32.upload.maximum_size=1310720
esp32.upload.maximum_data_size=327680
esp32.upload.wait_for_upload_port=true

esp32.serial.disableDTR=true
esp32.serial.disableRTS=true

esp32.build.mcu=esp32
esp32.build.core=esp32
esp32.build.variant=esp32
esp32.build.board=ESP32_DEV

esp32.build.f_cpu=240000000L
esp32.build.flash_size=4MB
esp32.build.flash_freq=40m
esp32.build.flash_mode=dio
esp32.build.boot=dio
esp32.build.partitions=default
esp32.build.defines=

esp32.menu.PSRAM.disabled=Disabled
esp32.menu.PSRAM.disabled.build.defines=
esp32.menu.PSRAM.enabled=Enabled
esp32.menu.PSRAM.enabled.build.defines=-DBOARD_HAS_PSRAM -mfix-esp32-psram-cache-issue

esp32.menu.PartitionScheme.default=Default 4MB with spiffs (1.2MB APP/1.5MB SPIFFS)
esp32.menu.PartitionScheme.default.build.partitions=default
esp32.menu.PartitionScheme.defaultffat=Default 4MB with ffat (1.2MB APP/1.5MB FATFS)
esp32.menu.PartitionScheme.defaultffat.build.partitions=default_ffat
esp32.menu.PartitionScheme.default_8MB=8M Flash (3MB APP/1.5MB FAT)
esp32.menu.PartitionScheme.default_8MB.build.partitions=default_8MB
esp32.menu.PartitionScheme.default_8MB.upload.maximum_size=3342336
esp32.menu.PartitionScheme.minimal=Minimal (1.3MB APP/700KB SPIFFS)
esp32.menu.PartitionScheme.minimal.build.partitions=minimal
esp32.menu.PartitionScheme.no_ota=No OTA (2MB APP/2MB SPIFFS)
esp32.menu.PartitionScheme.no_ota.build.partitions=no_ota
esp32.menu.PartitionScheme.no_ota.upload.maximum_size=2097152
esp32.menu.PartitionScheme.noota_3g=No OTA (1MB APP/3MB SPIFFS)
esp32.menu.PartitionScheme.noota_3g.build.partitions=noota_3g
esp32.menu.PartitionScheme.noota_3g.upload.maximum_size=1048576
esp32.menu.PartitionScheme.noota_ffat=No OTA (2MB APP/2MB FATFS)
esp32.menu.PartitionScheme.noota_ffat.build.partitions=noota_ffat
esp32.menu.PartitionScheme.noota_ffat.upload.maximum_size=2097152
esp32.menu.PartitionScheme.noota_3gffat=No OTA (1MB APP/3MB FATFS)
esp32.menu.PartitionScheme.noota_3gffat.build.partitions=noota_3gffat
esp32.menu.PartitionScheme.noota_3gffat.upload.maximum_size=1048576
esp32.menu.PartitionScheme.huge_app=Huge APP (3MB No OTA/1MB SPIFFS)
esp32.menu.PartitionScheme.huge_app.build.partitions=huge_app
esp32.menu.PartitionScheme.huge_app.upload.maximum_size=3145728
esp32.menu.PartitionScheme.min_spiffs=Minimal SPIFFS (1.9MB APP with OTA/190KB SPIFFS)
esp32.menu.PartitionScheme.min_spiffs.build.partitions=min_spiffs
esp32.menu.PartitionScheme.min_spiffs.upload.maximum_size=1966080
esp32.menu.PartitionScheme.fatflash=16M Flash (2MB APP/12.5MB FAT)
esp32.menu.PartitionScheme.fatflash.build.partitions=ffat
esp32.menu.PartitionScheme.fatflash.upload.maximum_size=2097152
esp32.menu.PartitionScheme.app3M_fat9M_16MB=16M Flash (3MB APP/9MB FATFS)
esp32.menu.PartitionScheme.app3M_fat9M_16MB.build.partitions=app3M_fat9M_16MB
esp32.menu.PartitionScheme.app3M_fat9M_16MB.upload.maximum_size=3145728

esp32.menu.CPUFreq.240=240MHz (WiFi/BT)
esp32.menu.CPUFreq.240.build.f_cpu=240000000L
esp32.menu.CPUFreq.160=160MHz (WiFi/BT)
esp32.menu.CPUFreq.160.build.f_cpu=160000000L
esp32.menu.CPUFreq.80=80MHz (WiFi/BT)
esp32.menu.CPUFreq.80.build.f_cpu=80000000L
esp32.menu.CPUFreq.40=40MHz (40MHz XTAL)
esp32.menu.CPUFreq.40.build.f_cpu=40000000L
esp32.menu.CPUFreq.26=26MHz (26MHz XTAL)
esp32.menu.CPUFreq.26.build.f_cpu=26000000L
esp32.menu.CPUFreq.20=20MHz (40MHz XTAL)
esp32.menu.CPUFreq.20.build.f_cpu=20000000L
esp32.menu.CPUFreq.13=13MHz (26MHz XTAL)
esp32.menu.CPUFreq.13.build.f_cpu=13000000L
esp32.menu.CPUFreq.10=10MHz (40MHz XTAL)
esp32.menu.CPUFreq.10.build.f_cpu=10000000L

esp32.menu.FlashMode.qio=QIO
esp32.menu.FlashMode.qio.build.flash_mode=dio
esp32.menu.FlashMode.qio.build.boot=qio
esp32.menu.FlashMode.dio=DIO
esp32.menu.FlashMode.dio.build.flash_mode=dio
esp32.menu.FlashMode.dio.build.boot=dio
esp32.menu.FlashMode.qout=QOUT
esp32.menu.FlashMode.qout.build.flash_mode=dout
esp32.menu.FlashMode.qout.build.boot=qout
esp32.menu.FlashMode.dout=DOUT
esp32.menu.FlashMode.dout.build.flash_mode=dout
esp32.menu.FlashMode.dout.build.boot=dout

esp32.menu.FlashFreq.80=80MHz
esp32.menu.FlashFreq.80.build.flash_freq=80m
esp32.menu.FlashFreq.40=40MHz
esp32.menu.FlashFreq.40.build.flash_freq=40m

esp32.menu.FlashSize.4M=4MB (32Mb)
esp32.menu.FlashSize.4M.build.flash_size=4MB
esp32.menu.FlashSize.8M=8MB (64Mb)
esp32.menu.FlashSize.8M.build.flash_size=8MB
esp32.menu.FlashSize.8M.build.partitions=default_8MB
esp32.menu.FlashSize.2M=2MB (16Mb)
esp32.menu.FlashSize.2M.build.flash_size=2MB
esp32.menu.FlashSize.2M.build.partitions=minimal
esp32.menu.FlashSize.16M=16MB (128Mb)
esp32.menu.FlashSize.16M.build.flash_size=16MB

esp32.menu.UploadSpeed.921600=921600
esp32.menu.UploadSpeed.921600.upload.speed=921600
esp32.menu.UploadSpeed.115200=115200
esp32.menu.UploadSpeed.115200.upload.speed=115200
esp32.menu.UploadSpeed.256000.windows=256000
esp32.menu.UploadSpeed.256000.upload.speed=256000
esp32.menu.UploadSpeed.230400.windows.upload.speed=256000
esp32.menu.UploadSpeed.230400=230400
esp32.menu.UploadSpeed.230400.upload.speed=230400
esp32.menu.UploadSpeed.460800.linux=460800
esp32.menu.UploadSpeed.460800.macosx=460800
esp32.menu.UploadSpeed.460800.upload.speed=460800
esp32.menu.UploadSpeed.512000.windows=512000
esp32.menu.UploadSpeed.512000.upload.speed=512000

esp32.menu.DebugLevel.none=None
esp32.menu.DebugLevel.none.build.code_debug=0
esp32.menu.DebugLevel.error=Error
esp32.menu.DebugLevel.error.build.code_debug=1
esp32.menu.DebugLevel.warn=Warn
esp32.menu.DebugLevel.warn.build.code_debug=2
esp32.menu.DebugLevel.info=Info
esp32.menu.DebugLevel.info.build.code_debug=3
esp32.menu.DebugLevel.debug=Debug
esp32.menu.DebugLevel.debug.build.code_debug=4
esp32.menu.DebugLevel.verbose=Verbose
esp32.menu.DebugLevel.verbose.build.code_debug=5

##############################################################

esp32wrover.name=ESP32 Wrover Module

esp32wrover.upload.tool=esptool_py
esp32wrover.upload.maximum_size=1310720
esp32wrover.upload.maximum_data_size=327680
esp32wrover.upload.wait_for_upload_port=true

esp32wrover.serial.disableDTR=true
esp32wrover.serial.disableRTS=true

esp32wrover.build.mcu=esp32
esp32wrover.build.core=esp32
esp32wrover.build.variant=esp32
esp32wrover.build.board=ESP32_DEV

esp32wrover.build.f_cpu=240000000L
esp32wrover.build.flash_size=4MB
esp32wrover.build.flash_freq=40m
esp32wrover.build.flash_mode=dio
esp32wrover.build.boot=dio
esp32wrover.build.partitions=default
esp32wrover.build.defines=-DBOARD_HAS_PSRAM -mfix-esp32-psram-cache-issue

esp32wrover.menu.PartitionScheme.default=Default 4MB with spiffs (1.2MB APP/1.5MB SPIFFS)
esp32wrover.menu.PartitionScheme.default.build.partitions=default
esp32wrover.menu.PartitionScheme.defaultffat=Default 4MB with ffat (1.2MB APP/1.5MB FATFS)
esp32wrover.menu.PartitionScheme.defaultffat.build.partitions=default_ffat
esp32wrover.menu.PartitionScheme.default_8MB=8M Flash (3MB APP/1.5MB FAT)
esp32wrover.menu.PartitionScheme.default_8MB.build.partitions=default_8MB
esp32wrover.menu.PartitionScheme.minimal=Minimal (1.3MB APP/700KB SPIFFS)
esp32wrover.menu.PartitionScheme.minimal.build.partitions=minimal
esp32wrover.menu.PartitionScheme.no_ota=No OTA (2MB APP/2MB SPIFFS)
esp32wrover.menu.PartitionScheme.no_ota.build.partitions=no_ota
esp32wrover.menu.PartitionScheme.no_ota.upload.maximum_size=2097152
esp32wrover.menu.PartitionScheme.noota_3g=No OTA (1MB APP/3MB SPIFFS)
esp32wrover.menu.PartitionScheme.noota_3g.build.partitions=noota_3g
esp32wrover.menu.PartitionScheme.noota_3g.upload.maximum_size=1048576
esp32wrover.menu.PartitionScheme.noota_ffat=No OTA (2MB APP/2MB FATFS)
esp32wrover.menu.PartitionScheme.noota_ffat.build.partitions=noota_ffat
esp32wrover.menu.PartitionScheme.noota_ffat.upload.maximum_size=2097152
esp32wrover.menu.PartitionScheme.noota_3gffat=No OTA (1MB APP/3MB FATFS)
esp32wrover.menu.PartitionScheme.noota_3gffat.build.partitions=noota_3gffat
esp32wrover.menu.PartitionScheme.noota_3gffat.upload.maximum_size=1048576
esp32wrover.menu.PartitionScheme.huge_app=Huge APP (3MB No OTA/1MB SPIFFS)
esp32wrover.menu.PartitionScheme.huge_app.build.partitions=huge_app
esp32wrover.menu.PartitionScheme.huge_app.upload.maximum_size=3145728
esp32wrover.menu.PartitionScheme.min_spiffs=Minimal SPIFFS (1.9MB APP with OTA/190KB SPIFFS)
esp32wrover.menu.PartitionScheme.min_spiffs.build.partitions=min_spiffs
esp32wrover.menu.PartitionScheme.min_spiffs.upload.maximum_size=1966080
esp32wrover.menu.PartitionScheme.fatflash=16M Flash (2MB APP/12.5MB FAT)
esp32wrover.menu.PartitionScheme.fatflash.build.partitions=ffat

esp32wrover.menu.FlashMode.qio=QIO
esp32wrover.menu.FlashMode.qio.build.flash_mode=dio
esp32wrover.menu.FlashMode.qio.build.boot=qio
esp32wrover.menu.FlashMode.dio=DIO
esp32wrover.menu.FlashMode.dio.build.flash_mode=dio
esp32wrover.menu.FlashMode.dio.build.boot=dio
esp32wrover.menu.FlashMode.qout=QOUT
esp32wrover.menu.FlashMode.qout.build.flash_mode=dout
esp32wrover.menu.FlashMode.qout.build.boot=qout
esp32wrover.menu.FlashMode.dout=DOUT
esp32wrover.menu.FlashMode.dout.build.flash_mode=dout
esp32wrover.menu.FlashMode.dout.build.boot=dout

esp32wrover.menu.FlashFreq.80=80MHz
esp32wrover.menu.FlashFreq.80.build.flash_freq=80m
esp32wrover.menu.FlashFreq.40=40MHz
esp32wrover.menu.FlashFreq.40.build.flash_freq=40m

esp32wrover.menu.UploadSpeed.921600=921600
esp32wrover.menu.UploadSpeed.921600.upload.speed=921600
esp32wrover.menu.UploadSpeed.115200=115200
esp32wrover.menu.UploadSpeed.115200.upload.speed=115200
esp32wrover.menu.UploadSpeed.256000.windows=256000
esp32wrover.menu.UploadSpeed.256000.upload.speed=256000
esp32wrover.menu.UploadSpeed.230400.windows.upload.speed=256000
esp32wrover.menu.UploadSpeed.230400=230400
esp32wrover.menu.UploadSpeed.230400.upload.speed=230400
esp32wrover.menu.UploadSpeed.460800.linux=460800
esp32wrover.menu.UploadSpeed.460800.macosx=460800
esp32wrover.menu.UploadSpeed.460800.upload.speed=460800
esp32wrover.menu.UploadSpeed.512000.windows=512000
esp32wrover.menu.UploadSpeed.512000.upload.speed=512000

esp32wrover.menu.DebugLevel.none=None
esp32wrover.menu.DebugLevel.none.build.code_debug=0
esp32wrover.menu.DebugLevel.error=Error
esp32wrover.menu.DebugLevel.error.build.code_debug=1
esp32wrover.menu.DebugLevel.warn=Warn
esp32wrover.menu.DebugLevel.warn.build.code_debug=2
esp32wrover.menu.DebugLevel.info=Info
esp32wrover.menu.DebugLevel.info.build.code_debug=3
esp32wrover.menu.DebugLevel.debug=Debug
esp32wrover.menu.DebugLevel.debug.build.code_debug=4
esp32wrover.menu.DebugLevel.verbose=Verbose
esp32wrover.menu.DebugLevel.verbose.build.code_debug=5

```

# Answer
> 0 votes
As I guess you mean the preprocessor defines to distinguish between different boards and include/exclude based on this different code parts.
In ArduinoIDE except from

```
 #ifdef ESP32
 const uint8_t pinA = 12;
 #endif

```

no luck as of core 1.04, because there are no preproc macros defined (like in other architectures).
If you are using PlatformIO you can get the board type from the define ARDUINO\_BOARD.
On ArduinoIDE you only can write your own macros (but this only solves the problem for your dev environment) So as of core 1.04 you can only do it manually by un/commenting defines:

```
/** Choose the correct model to use and compile the right pin settings*/
#define AI_THINKER_KIT
//#define WROVER_DEV_KIT
//#define ESP_EYE_32
//#define M5STACK_PSRAM
//#define M5STACK_NO_PSRAM

```

As an example the build.board property for SAM Boards is:

```
adafruit_itsybitsy_m0.build.board=ITSYBITSY_M0

```

Then in the Adafruit SAMD Boards platform.txt file you can see where the macro is defined:

```
## Compile c files
recipe.c.o.pattern="{compiler.path}{compiler.c.cmd}" {compiler.c.flags} -DF_CPU={build.f_cpu} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DARDUINO_ARCH_{build.arch} {compiler.c.extra_flags} {build.extra_flags} {build.cache_flags} {compiler.arm.cmsis.c.flags} {includes} "{source_file}" -o "{object_file}"

## Compile c++ files
recipe.cpp.o.pattern="{compiler.path}{compiler.cpp.cmd}" {compiler.cpp.flags} -DF_CPU={build.f_cpu} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DARDUINO_ARCH_{build.arch} {compiler.cpp.extra_flags} {build.extra_flags} {build.cache_flags} {compiler.arm.cmsis.c.flags} {includes} "{source_file}" -o "{object_file}"

## Compile S files
recipe.S.o.pattern="{compiler.path}{compiler.S.cmd}" {compiler.S.flags} -DF_CPU={build.f_cpu} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DARDUINO_ARCH_{build.arch} {compiler.S.extra_flags} {build.extra_flags} {build.cache_flags} {compiler.arm.cmsis.c.flags} {includes} "{source_file}" -o "{object_file}"

```

If you want to dig intoit deeper: Arduino 3rd party hardware documantatuion

---
Tags: arduino-ide, esp32, compile
---


# Question
Title: How does code typed in Arduino IDE runs on a nodemcu?
I actually have a series of questions regarding Nodemcu and esp8266.

1. How does code typed in Arduino IDE run on Nodemcu?
2. What firmware is present on the nodemcu?
3. How do I upload the above firmware on esp8266-01 module?
4. I want my esp8266-01 module to work with a Lilypad Arduino. So this is the way I want it to work: Lilypad Ardiuno has acquires some data using a sensor. It wants to post this data to a server on internet. So to do the job it uses a ESP8266-01. Will the configuration work?

# Answer
> how does code typed in Arduino IDE runs on Nodemcu

The IDE runs the compiler which turns the C into assembly and then machine code. That is then uploaded to the ESP8266.

> what firmware is present on the nodemcu.

The code that you just wrote and uploaded.

> i want my esp8266-01 module to work with a Lilypad Arduino .So this is the way I want it to work Lilypad Ardiuno has acquires some data using a sensor it wants the post this data to a server on internet.So to do the job it uses a ESP8266-01.So will the configuration work?

Sure, if you program it to do that. Two choices:

1. Use the AT firmware on the ESP-01 (installed by default)
2. Write custom firmware (as above) for the ESP-01 to do what you want.
> 0 votes

---
Tags: arduino-uno, esp8266, nodemcu, iot, firmware
---


# Question
Title: Ethernet Shield Not Working With TFT Screen
I'm trying to stack up Arduino UNO, Ethernet Shield and Waveshare 2.8" TFT Shield. Since I'm new to this I'm mostly doing basic stuff.

I successfully manage to get ethernet shield and TFT shield to work individually. Then since TFT shield will not be able to use the ICSP interface I connected the jumpers as it says on wiki.

> **Hardware configuration**
>
> * When using the Arduino board with ICSP interface, the jumpers SB1, SB2 and SB3 on the LCD module should be kept open.
> * When using the Arduino board without ICSP interface, the jumpers SB1, SB2 and SB3 on the module should be connected with a 0R resistor, respectively.

After this I put everything together and try to get them working with the below code but for some reason I don't know, Ethernet shield stopped working. I get the error `Ethernet shield was not found. Sorry, can't run without hardware. :(`. Even though the error, my TFT screen lights up and runs demo. Probably I'm missing something simple. I'll appreciate any help or guidance.

```
#include <stdint.h>
#include <LCD.h>
#include <SPI.h>
#include <Ethernet.h>

IPAddress server(192, 168, 0, 107);
IPAddress ip(192, 168, 0, 177);
IPAddress myDns(192, 168, 0, 1);
IPAddress gateway(192, 168, 0, 1);
EthernetClient client;
byte mac[] = {0x90, 0xA2, 0xDA, 0x00, 0x23, 0x36};

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

  /*--------- TFT Init -------------*/
  SPI.setDataMode(SPI_MODE3);
  SPI.setBitOrder(MSBFIRST);
  SPI.setClockDivider(SPI_CLOCK_DIV4);
  SPI.begin();
  Tft.lcd_init();
  /*--------- TFT Init End -------------*/

  /*--------- Ethernet Setup -------------*/
  Serial.println("Initialize Ethernet with DHCP:");
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    if (Ethernet.hardwareStatus() == EthernetNoHardware) {
      Serial.println("Ethernet shield was not found.  Sorry, can't run without hardware. :(");
    } else if (Ethernet.linkStatus() == LinkOFF) {
      Serial.println("Ethernet cable is not connected.");
    }
    // no point in carrying on, so do nothing forevermore:
    // while (true) {
    //   delay(1);
    // }
  }
  // print your local IP address:
  Serial.print("My IP address: ");
  Serial.println(Ethernet.localIP());
  /*--------- Ethernet Setup End -------------*/

  /*--------- Ethernet Connection Demo Setup -------------*/
  if (client.connect(server, 3000)) {
    Serial.print("connected to ");
    Serial.println(client.remoteIP());
    // Make a HTTP request:
    client.println("GET / HTTP/1.1");
    client.println("Host: localhost");
    client.println("Connection: close");
    client.println();
  } else {
    // if you didn't get a connection to the server:
    Serial.println("connection failed");
  }
  beginMicros = micros();
  /*--------- Ethernet Connection Demo Setup End -------------*/
}

void loop()
{
  /*--------- TFT Demo -------------*/
  Tft.lcd_clear_screen(WHITE);
  for (int x = 1; x <= 240; x++) {
    for (int y = 1; y <= 320; y++) {
      Tft.lcd_draw_rect(x, y, 1, 1, RED);
      delay(1);
    }
  }
  /*--------- TFT Demo End -------------*/

  /*--------- Ethernet Check-Up ---------*/
  switch (Ethernet.maintain()) {
    case 1:
      //renewed fail
      Serial.println("Error: renewed fail");
      break;

    case 2:
      //renewed success
      Serial.println("Renewed success");
      //print your local IP address:
      Serial.print("My IP address: ");
      Serial.println(Ethernet.localIP());
      break;

    case 3:
      //rebind fail
      Serial.println("Error: rebind fail");
      break;

    case 4:
      //rebind success
      Serial.println("Rebind success");
      //print your local IP address:
      Serial.print("My IP address: ");
      Serial.println(Ethernet.localIP());
      break;

    default:
      //nothing happened
      break;
  }
  /*--------- Ethernet Check-Up End ---------*/

  /*--------- Ethernet Demo ---------*/
  int len = client.available();
  if (len > 0) {
    byte buffer[80];
    if (len > 80) len = 80;
    client.read(buffer, len);
    if (printWebData) {
      Serial.write(buffer, len); // show in the serial monitor (slows some boards)
    }
    byteCount = byteCount + len;
  }

  // if the server's disconnected, stop the client:
  if (!client.connected()) {
    endMicros = micros();
    Serial.println();
    Serial.println("disconnecting.");
    client.stop();
    Serial.print("Received ");
    Serial.print(byteCount);
    Serial.print(" bytes in ");
    float seconds = (float)(endMicros - beginMicros) / 1000000.0;
    Serial.print(seconds, 4);
    float rate = (float)byteCount / seconds / 1000.0;
    Serial.print(", rate = ");
    Serial.print(rate);
    Serial.print(" kbytes/second");
    Serial.println();

    // do nothing forevermore:
    // while (true) {
    //   delay(1);
    // }
  }
  /*--------- Ethernet Demo End ---------*/
}

```

# Answer
From examining the schematics of the Ethernet shield as well as the TFT shield, it looks like the Chip Select (CS) pin of the Ethernet shield uses the same pin (Arduino pin D4) as the Interrupt pin of the Touch Panel on your TFT shield (TP\_IRQ) in the schematic.

I don’t think you can solve this without modifying any hardware. Either the TFT shield or the Ethernet shield should be modified to use a different pin, and these modifications should be reflected in the underlying library.

My guess is the Ethernet shield would be easiest to modify as its PCB can be reached from two sides. You could also cut the D4 pin from the TFT shield and connect its PCB trace to an unused digital pin via a short wire.
> 2 votes

# Answer
The error message is from the ethernet library. As I do not have the sufficient hardware to test this indicates a pin conflict. So the ethernet shield v1 uses/needs one or more pins the LCD shield is using.
How to find out dig into the circuit documenation and look at the used pins.
Be aware that a lot of tuts/infos on the net are about **ethernet shield v2** which is hardware differnt from **v1**.

* Circuit schematics for Waveshare and Ethernet shield v1
* Check also for shorts between USB (Arduino) / Ethernet plug and the above shields, I isolate them normaly with a piece of isolation tape (to be safe than sorry).

**EDIT**
Ethernet shield: Arduino communicates with both the W5100 and SD card using the SPI bus (through the ICSP header). This is on digital pins 10, 11, 12, and 13 on the Uno. Pin 10 is used to select the W5100 and pin 4 for the SD card. These pins cannot be used for general I/O
The wave share uses CS=D10, RS=D7, RST=D9 and the SD CS can be defined on eg SD\_CS 5 with this library as the waveshare lib is not usable other than basic playing around.
This lib is Adafruit\_GFX compatible so a wide variety of programs and other libs work.
So your chance is

* to remap the SD CS by software if the other pins pose no conflict (you have to test it) or
* get an other Ethernet connector (not a shield because its more flexible) or
* remap manually with dupont wires the LCD shield (because it's the top most) and change the according pins in the libs header file.

Do not cut traces or solder around its not worth the effort and you might break things
> 1 votes

---
Tags: arduino-uno, shields, ethernet, tft, ethernet-shield
---


title: Arduino Turn Signals

text:
# Question
Title: Arduino Turn Signals
Could I use an Arduino to power run the following lights? Here I have a project in mind, and although I am new to electronics, I am a computer programmer (C, C++, C#, Java) by profession so the coding side doesn't worry me, what I am confused about is what power supply I need etc.

# Answer
> 1 votes
If you mean you want to power it directly from a GPIO pin from an Arduino: no, for two reasons:

* It doesn't show the current needed, but it's likely more than 20 or 40 mA which is maximum for a GPIO pin. So you need to use a transistor, which can be used to turn on something with higher current, with the current of a GPIO pin. Search for 'Transistor as a switch' for more info.
* Also, it's 12 V and the Arduino delivers 5 V.

What you need is a separate 12V adapter, with a current capability MORE than what that light needs. I cannot find the current (mA) in the link, so you might need to measure it (e.g. with a digital multimeter). If you don't have a digital multimeter, buy one, you need one anyway if you will do electronics. You can even buy a 3 euro one from China if you want (for now).

# Answer
> 1 votes
If you look at the specs of those lights, they draw 1 watt at 12 volts. That is both too much current and too much voltage for an Arduino. (You're only supposed to draw about 20 mA from a single pin, and somewhere between 500 mA and 1 amp from the 5V regulator. (It is heat limited, and typically not very well heat-sinked. Er, heat-sunk?)

An Arduino only puts out 3.3v and 5V.

If you're looking to drive these from a car/motorcycle, you should be able to power them directly from the 12V battery of the vehicle. Failing that, get a 12V power supply that can put out as much current as you need for ALL of the lights you need, plus 10%-20% extra, for "slop".

What you should do is to buy a MOSFET power transistor designed for switching logic level signals for each turn signal you need to control. These would work well: https://www.adafruit.com/product/355

You'd then use logic lines from the Arduino to control the gates of the transistors, and each transistor would switch the power for one of your turn signal lights.

---
Tags: power
---


# Question
Title: Several ESP8266 in wifi network should share information
I am currently working on a project for my home where several ESP8266 (each with a relay) control lights. I have developed an android for this where I find the ESP8266s via mdns but the problem is that sometimes one or two won't be found ever (depends on the position where I am trying it). So my idea was to make them talk to each other so everyone knows like an list of ip addresses from the others. This would give me the possibility to find every ESP as soon as i have found one.

# Answer
I guess you are asking if it is feasible: if this is the case, I would say yes, without too many troubles. Each ESP can launch MDNS discovery, so they can discover each other.
> 2 votes

# Answer
Waht you may be looking for is a mesh network, you can use the standerd lib ESP8266WiFiMesh. Mesh reduces the loading of smart devices on the router by forming a mesh between the smart devices.There are unluckely no examples ready to use but you can look at the provided example and modify it to your needs,

You find the lib in your core dir

```
C:\Users\Your_Username\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.6.3\libraries\ESP8266WiFiMesh

```

but be aware there are a lot of open issues and PRs (which means lot of trouble in a stable production)
**EDIT**
There is also the Arduino library painlessMesh. Its well documented and has lot of examples and can be combined with MQTT.
For MQTT there is one condition where you might consider this option, if you have deep sleeping nodes on battery (than mesh might be contra productive)
> 0 votes

---
Tags: esp8266, wifi
---


# Question
Title: How to code an arduino to execute a particular code using a slide switch
I’m pretty new to arduino. I need help concerning a project I’m making. I’m using a SPDT slide switch to switch between what code(method) should be executed.i.e when I shift the switch to the left, XXX method should be executed and when I move the switch to the right, YYYY method should be executed. The center pin of the switch is connected to arduino +5v while the left and right leg of the switch are connected like how a tactile switch is interfaces with the arduino. Please can anyone help me with the code, or at least how to program the arduino? Thank you

# Answer
Your switch wiring for D12 is wrong. You connect your inputs directly to ground and that can never change, regardless of the position of the switch.

You effectively have:

simulate this circuit – Schematic created using CircuitLab

However you are over complicating things. A SPDT switch is nothing more than two buttons, only one of which can be pressed at one time. If one is pressed the other *must* be released.

You can completely ignore half the switch and treat the other half as a button: if the "button" is pressed then the switch is in one position. If the "button" is released then it's in the other position.

Unless it's a "center off" switch, in which case it has 3 positions, not 2, and the middle one has nothing connected.

If it is a simple 2-position SPDT switch then just disconnect the D12 wire and remove the right-and resistor in your drawing. Then read D13 to determine the position: HIGH is one position and LOW is the other.

If it's a 3-position "center off" switch then move the D12 wire 4 holes to the left so that it connects to the switch-resistor junction, not ground. Then you will need to read both D12 and D13 - which ever one is HIGH is the one that is activated, and the switch is in that position.

Then it's a simple "if / else" (2 position) or "if / elseif / else" (3 position center-off) structure to decide which code to run.
> 0 votes

---
Tags: programming, switch, input
---


# Question
Title: problem using one function to blink different leds
I wrote a function to blink an led using millis and want to blink multiple leds with the same function but with different delay intervals. When I call this function thrice to blink 3 different leds, all the leds blink with the shortest delay. As far my understanding is, functions can be reused if you want to perform same task but why doesn't it work in this case? It works incase I rename the function before calling it again.

Is it wrong to call single function more than once to perform same task but on different pins? How would you call a function without renaming it?

```
const int redLed = 10;
const int yellowLed = 11;
const int greenLed = 12;

void setup() {
  pinMode(redLed, OUTPUT);
  pinMode(yellowLed, OUTPUT);
  pinMode(greenLed, OUTPUT);
}

void loop() {
blinkLed(redLed, 1000);
blinkLed(yellowLed, 4000);
blinkLed(greenLed, 8000);
}

void blinkLed(int led, unsigned long timePeriod) {
  static unsigned long oldTime = 0;
  unsigned long newTime = millis();
  static boolean ledState = LOW;

  if (newTime - oldTime >= timePeriod) {
    oldTime = newTime;
    ledState = !ledState;
  }
  digitalWrite(led, ledState);
}

```

Edit: I have modified the function to not have shared variables but it just blinks redLed. why doesn't it work now? Here is the code:

```
const int redLed = 10;
const int yellowLed = 11;
const int greenLed = 12;

void setup() {
  pinMode(redLed, OUTPUT);
  pinMode(yellowLed, OUTPUT);
  pinMode(greenLed, OUTPUT);
}

void loop() {

  blinkLed(redLed, 1000);
  blinkLed(yellowLed, 4000);
  blinkLed(greenLed, 8000);
}

void blinkLed(int led, unsigned long timePeriod) {

  switch (led) {
    case 10:
      static unsigned long oldTime1 = 0;
      unsigned long newTime1 = millis();
      static boolean redState = LOW;

      if (newTime1 - oldTime1 >= timePeriod) {
        oldTime1 = newTime1;
        redState = !redState;
      }
      digitalWrite(led, redState);
          break;

    case 11:
      static unsigned long oldTime2 = 0;
      unsigned long newTime2 = millis();
      static boolean yellowState = LOW;

      if (newTime2 - oldTime2 >= timePeriod) {
        oldTime2 = newTime2;
        yellowState = !yellowState;
      }
      digitalWrite(led, yellowState);
          break;

    case 12:
      static unsigned long oldTime3 = 0;
      unsigned long newTime3 = millis();
      static boolean greenState = LOW;

      if (newTime3 - oldTime3 >= timePeriod) {
        oldTime3 = newTime3;
        greenState = !greenState;
      }
      digitalWrite(led, greenState);
      break;
  }
}

```

# Answer
> 1 votes
You want to let the LEDs blink concurrently.
Your static variables oldTime, and ledState are shared between the three LEDs.
So there is ony ONE ledState in your program but you need that state for each one.
Same applies for oldTime.

Resolve the this issue and your LEDs will blink as expected.

btw. you don't need the ledState as you can read its current state.

# Answer
> 1 votes
Yes, functions can be re-used if you want to perform the same task in different places or at different times. But your problem is that you only have one set of "time" variables.

You would be better off learning to create this as a *class* which can not only contain the "blink" function but also the variables that define the state for a specific instance of the blinking.

For example here is a small library I wrote ages ago as a demonstration.

# Answer
> 0 votes
Just putting other peoples' suggestions together:

```
void blinkLed(int led, unsigned long timePeriod) {
  static unsigned long oldTime[42];
  unsigned long newTime = millis();
  boolean ledState = digitalRead(led);

  if (newTime - oldTime[led] >= timePeriod) {
    oldTime[led] = newTime;
    ledState = !ledState;
  }
  digitalWrite(led, ledState);
}

```

---
Tags: arduino-uno, functions
---


# Question
Title: How to get the free/used space on a SD card and transmit it
I'm using this block of code to read and sum up the bytes of all the text files I have on an SD card:

```
long get_sd_memory_taken() {
  File dir = SD.open("/");
  long sd_memory_taken;
  int c = 0;
  while (true) {
    File entry = dir.openNextFile();
    if (!entry) {
      return sd_memory_taken;
      break;
    }
    if(strcmp(entry.name(), "SYSTEM~1") == 0) {
      continue;
    }
    if(c > 15) {
      tft.println(entry.name());
      tft.println(entry.size());
    }
    sd_memory_taken += entry.size();
    entry.close();
    c++;
  }
}

```

The SD card is 8GB so the number won't be larger than 8,589,934,592. The function get\_sd\_memory\_taken() returns the number so it can be send to a phone using Bluetooth. I just checked that long can hold max 2,147,483,647, so if the SD card is filled more than that, I suppose errors are gonna appear. How can I prevent this? I was thinking of maybe using a double and put the comma maybe 5 digits to the left and send that or maybe divide the number into 10 smaller longs and send them to the phone separately. I think the former method is better but I'm not sure if it'll work. What's the best way to go about this problem where I'm trying to use as less memory as possible?

# Answer
As SD.h includes

```
  #include "utility/SdFat.h"
  #include "utility/SdFatUtil.h"

```

or if you use the SDfat library than this function is more efficient than going all over the place:

```
#include <SdFat.h>

SdFat SD;

void ShowFreeSpace() {
  // Calculate free space (volume free clusters * blocks per clusters / 2)
  long lFreeKB = SD.vol()->freeClusterCount();
  lFreeKB *= SD.vol()->blocksPerCluster()/2;

  // Display free space
  Serial.print("Free space: ");
  Serial.print(lFreeKB);
  Serial.println(" KB");
}

```
> 1 votes

---
Tags: arduino-ide, c++, sd-card, data
---


# Question
Title: i2c scanner stuck on scanning for my 0.96in OLED screen with my Arduino Nano
> My pins are connected as follows; vcc-3v3, gnd-gnd, sda-A4, scl-A5.

# Answer
Is it a 3.3 V only OLED? I suppose its vcc(OLED)-3v3(Nano).
Most OLEDs use 3.3V -5V where sometimes the 3.3V from the Arduino is not sufficient.
If its a 3.3V only OLED could you give the make of the OLED (does it have jumpers to change I2C address). Normaly the I2C scanner should return at least with nothing found.
> 1 votes

---
Tags: arduino-nano, i2c, display
---


# Question
Title: nodemcu doesnt response in at command mode
I want to sent AT command into node mcu esp8266 module with arduino IDE through serial monitor. I connect the node mcu to arduino uno board in following sequence: RX to pin 2 of arduino TX to pin 3 of arduino Vin of node mcu to 3.3V of arduino GND to GND EN of node mcu to 3.3V of arduino I send at commands in serial monitor but dont get any response. I also checked different baud rates. what is the problem? what thing I'm doing wrong?

```
    #include <SoftwareSerial.h>
SoftwareSerial esp8266(2,3); //2 -->rx  ,3 -->tx

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

void loop() {
  if (esp8266.available()>0)
  {
      char c = esp8266.read();
      Serial.write(c);
  }
  if (Serial.available()>0)
  {
    delay(1000);
    String cmd = "";
    while (Serial.available())
    {
      cmd += (char)Serial.read();
    }
    esp8266.println(cmd);
  }
}

```

# Answer
Some points to note:

* VIN should connect to 5V (it goes through the on-board 5V -\> 3.3V regulator). If you connect VIN to 3.3V you will be starving the device of power.
* The NodeMCU doesn't come with AT firmware installed. You will have to install it first before it will respond.
* If you have a NodeMCU why are you bothering with an Arduino? The NodeMCU can do everything (and more) that the Arduino can do (except it lacks IO).
> 0 votes

---
Tags: arduino-uno, esp8266, nodemcu, iot
---