body:
I am currently designing a device that will take measurements from a load cell that  is in tension. I am using a v1.0 NodeMCU device that features an HX711 load cell amplifier and is running off of battery power. In order to conserve that power, I am wanting to be able to put as many parts of the device as possible into a sleep of some level when there is not a load on the cell. Then, I would like the device to be a be able to wake up when a load is applied and it goes into use. Going into a sleep will be simple enough, if the device is getting a reading around zero for a period time, it can enter sleep. Other notable hardware involved on the device will be a real-time-clock and an accelerometer.

From what I have already tried to look up, there doesn't seem to be any good way to use the load cell to get this action. The only idea I have been able to come up with for how to activate the device without having to wake it up extremely often other than a manual switch or checks very often came from this [question][1]. It suggests using a vibration sensor like [this][2], which is how bathroom scales put themselves to sleep.

While I think it might be possible to use a vibration sensor to wake up the device, I am not sure if the loads involved and use case will disallow me from using one. Are there any other sensors or methods that could be used to achieve goals that I have for this device?

  [1]: https://electronics.stackexchange.com/questions/271385/how-does-a-bathroom-scale-automatically-power-on-when-i-step-on-it
  [2]: https://www.sunrom.com/p/vibration-sensor

title: Waking up a NodeMCU when force load is applied to device

Answers: 0


body:
I'm a beginner at Arduino.

I have a soil moisture sensor and I mapped the lowest and highest moisture value to a value in between 0 and 100.

What I was trying to do was if the value was less than 50, then the LED should turn on. But even when the value was less than 50 (e.g 25) the LED doesn't turn on.

The moisture detection or the value mapping works perfectly fine.

Does the issue lie on my code or my LED wiring?
[![enter image description here][1]][1]

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

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

    int mostMoist = 180;
    int leastMoist = 600;
    int percent;
    int raw;
    const int threshold = 50;

    void setup() {
      Serial.begin(9600);
      pinMode(LED_BUILTIN, OUTPUT);
    }

    void loop() {
      raw = analogRead(A0);
      percent = map(raw,leastMoist,mostMoist,0,100);

      if (percent < 0){
        percent = 0;
      }

      if (percent < threshold){
        digitalWrite(LED_BUILTIN,HIGH);
      } else {
        digitalWrite(LED_BUILTIN,LOW);
      }

      Serial.println(percent);
      delay(2);
    }

title: Problems with controlling LED with soil moisture sensor

Answers: 1

body:
A good way to start debugging this sort of problem is to print out debug statements that say what the hardware should be doing. If the debug statements print out as expected then it's probably hardware, if not, then it's probably your code, e.g.

```
if (percent < threshold){
  Serial.prinln("LED on.");
  digitalWrite(LED_BUILTIN,HIGH);
}
else {
  Serial.prinln("LED off.");
  digitalWrite(LED_BUILTIN,LOW);
}
```


body:
My LCD info is called from an IF statement but since it's clock and temperature info i don't want to just show the information but update the information constantly in real time.
i don't want to use (while) loop or any other "code-blocking".

Here's the whole code:

    #include <OneWire.h>
    #include <LiquidCrystal_I2C.h>
    #include <DS3231.h>
    #include <DallasTemperature.h>

    #define ONE_WIRE_BUS 2
    int Heater= 3;
    int Switch1= 4;

    Time t;
    LiquidCrystal_I2C lcd(0x27, 16, 2);
    DS3231  rtc(SDA, SCL);
    OneWire oneWire(ONE_WIRE_BUS);
    DallasTemperature sensors(&oneWire);

    // Push button

    boolean oldSwitchState = LOW;
    boolean newSwitchState = LOW;
    boolean lcdScroll = LOW;
    boolean lcdBacklight = LOW;
    boolean lcdWelcome = LOW;

    unsigned long previousMillis = 0;
    const long BacklightTime = 10000;

    void setup() {
      Serial.begin(115200);
      pinMode(Heater, OUTPUT);
      pinMode(Switch1, INPUT);
      lcd.begin();
      rtc.begin();
    }
    void loop() {
      float testTemp = sensors.getTempCByIndex(0);
      sensors.requestTemperatures();
      t = rtc.getTime();
      if(lcdWelcome == LOW){
          lcd.setCursor(0,0);
          lcd.print("Welcome, Admin!");
          lcd.setCursor(0,1);
          lcd.print("press Start");
      }

      // LCD
      newSwitchState = digitalRead(Switch1);
        if (millis() - previousMillis >= BacklightTime) {
          lcd.noBacklight();
          lcdBacklight = LOW;
        }
        else if ( lcdBacklight == LOW ){
          lcd.backlight();
          lcdBacklight = HIGH;
        }
        if ( newSwitchState != oldSwitchState ) {
           if ( newSwitchState == HIGH ){
           previousMillis = millis();
           lcdWelcome = HIGH;
           lcd.clear();
          if ( lcdScroll == LOW ){
            lcd.setCursor(0,0);
            lcd.print(testTemp);
            lcd.print("   ");
            lcd.print(rtc.getTimeStr());
            lcdScroll = HIGH;
          }
          else{
            lcd.setCursor(0,0);
            lcd.print(rtc.getDOWStr());
            lcd.print("   ");
            lcd.print(rtc.getDateStr());
            lcdScroll = LOW;
          }
           }
           oldSwitchState = newSwitchState;
        }
    }

How can i update the functions inside the `if(lcdScroll == LOW){}` and `else{}` statements constantly to show on display?

title: How to repeat an IF statement

Answers: 1

body:
Like you suggested in your comment, you can implement a state machine, but the simplest would probably be setting a flag `bool a_flag` in this `if(lcdScroll==LOW)` clause and checking `if(a_flag)` in the highest scope of the `loop()` section. This is where you `print("test");`.

In respect to your code this will look like:

    bool a_flag=false;
    void loop() {
      // some irrelevant stuff
      if ( newSwitchState != oldSwitchState) {
        // some stuff
        if ( lcdScroll == LOW ){
          // stuff you would handle here
          a_flag=true;
        }
        else {
          // stuff you would handle here
          a_flag=false;
        }
      }
      if (a_flag) Serial.println("lcdScroll is LOW");
      else Serial.println("lcdScroll is HIGH");
    }

Beside this general solution you could simply do the following in your specific case:

    loop(){

      // your actual code

      if (lcdScroll) Serial.println("lcdScroll is LOW");
      else Serial.println("lcdScroll is HIGH");
    }


body:
This question might be a little esoteric, but I cannot find any answer for it.

Situation:

I want to have more than 8 Analog sensors on a NodeMCU ESP32. Unfortunately due to SPECTACULARLY poor design choices you cannot do this and have WiFi active at the same time. This is a non-starter for my project so I need a workaround.

Thought:

What if I share the available pins I can use, by turning power on and off to the sensors in question? Easy enough using the digital GPIO's and just turning them on and off. The issue is that the sensors are at the end of long wires and so I need 5v power to ensure good readings. So what if I just use a relay, powered off the 5v pin on the ESP32, and switch them on and off?

My question is - can you even do this? Most of what I have seen would indicate I need a separate power supply for the relay itself, **and** the source being switched on and off, but I would like to avoid having another power supply, and build it as in the circuit diagram below.

A couple of notes:

 - ignore the V1/1 V label in the picture - the circuit tool is very nice, but freezes a lot and I forgot to change that to VIN/5V before the screenshot
 - I have also omitted the data connections from sensors and to the relays to switch them on and off - I know they need to exist, but they aren't the issue.
 - I am running this project plugged in to the wall so source power is not an issue - I am not worried about drain or having a full 5V from the VIN pin

[![Circuit diagram of two relays powered from the same 5v pin][1]][1]

Before I fry parts, I thought it would be good to ask if anyone has tried this or if it is even possible?

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

title: Can I use the NodeMCU ESP12 5v pin and control it with a relay?

Answers: 0


body:
ESP.getFullVersion() output:

    SDK:2.2.1(cfd48f3)/Core:2.5.2=20502000/lwIP:STABLE-2_1_2_RELEASE/glue:1.1-7-g82abda3/BearSSL:a143020Connecting to DO_231455

I upload sketches from the Arduino IDE. How do I update the SDK?

I have the flasher tool but I can't seem to find documentation on what to do from this point:
[![enter image description here][1]][1]

I've downloaded the [assets][2] from Github

  [1]: https://i.stack.imgur.com/E4KFS.png
  [2]: https://github.com/espressif/ESP8266_NONOS_SDK/releases/tag/v3.0

title: How to upgrade ESP8266 NodeMCU SDK from V2.5.2 to V3?

Answers: 2

body:
The SDK is linked into every Arduino application you flash to the ESP8266 - it's not flashed separately.

Presumably you've already followed the instructions to put the URL for the ESP8266 Arduino Core in the preferences for the Arduino IDE.

Once that's there, to update the ESP8266 Arduino SDK, go to the Tools menu, select Board, then select the Boards manager (the first item in the menu).

That will bring up a dialog listing all the board families your Arduino IDE knows how to build for. You can limit the list to those with updates available by selecting "Updatable" in the "Type" field. Or just scroll down or search till you find the ESP8266 entry. Click it and if there's an update available you'll see an "Update" button appear on it. You can also reinstall older versions by choosing a version and clicking the "Install" button.

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

However, there is no version 3 as yet. At the time that I'm writing this, 2.5.2 is the most recent release of the SDK.

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

body:
The SDK is linked into every Arduino application you flash to the ESP8266 - it's not flashed separately.

Choose it in Tools menu. It is available only if you select "Generic ESP8266 module".

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

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


body:
Is it considered possible to use the esp32 code on an esp32 cam board? Do they use the same hardware? I am having difficulty using this sketch https://gist.github.com/wybiral/2a96c1d1605af7efa11b690586c4b13e on my esp32 cam and I think it is because it was designed for an esp32 board.

Thanks,
Dave

title: esp32 and the esp32-cam (agoal)

Answers: 0


body:
I am having trouble making an Arduino Pro Mini send commands via USART to an STM32 chip. The serial communication protocol is currently set to 9600 baud rate with no flow control or stop bits. Is there anything special that has to be done to make these two devices communicate with each other? I'm using the standard RX/TX pins for this. The Arduino logic level is 3.3V. The STM32 logic level is 2.5V. They share a common ground. I should also note that there is a 1K ohm resistor in series with each data line. Here's the code that I'm trying to use:

```c++
#include <Arduino.h>

void setup()
{
  Serial.begin(9600);
  delay(4000);
  pinMode(LED_BUILTIN, OUTPUT);
}

void loop()
{
  digitalWrite(LED_BUILTIN, HIGH);
  delay(1000);
  digitalWrite(LED_BUILTIN, LOW);
  delay(1000);
  digitalWrite(LED_BUILTIN, HIGH);
  delay(1000);
  digitalWrite(LED_BUILTIN, LOW);
  delay(1000);
  String voltage = String("85 2 0 0 10 174 96"); //Command to set voltage output on STM32
  Serial.println(voltage);

  while (1) {
    digitalWrite(LED_BUILTIN, HIGH);
    delay(200);
    digitalWrite(LED_BUILTIN, LOW);
    delay(200);
  }
}
```

title: Sending commands to an STM32 chip via UART with Arduino Pro Mini

Answers: 0


body:
I have a project with 9 servo, I want to make a function to control each separate. Only that he is not accepting the servo as a parameter.
Can someone tell me if it is possible to pass the servant as a parameter, and how? Thank you!!
Example:

    Servo s1,s2,s3;

    void toMove(Servo obj,int inPosition, int forPosition){
    var i = 0;
      for(i = inPosition; i<forPosition; i++){
       obj.write(i);
      }
    }

    void loop(){
      if(true){
         toMove(s1,0,180);
         toMove(s2,0,180);
      }
    }

title: Servo Motor in function

Answers: 2

body:
Yes, it is possible, and you've done it *almost* right. I made a minor correction in the `toMove()` function ("int" instead of "var"), and supplied the `setup()` function which you didn't show. It compiles without error. I didn't check it for correct operation as it looks like you had reduced your code to the minimum example necessary to demonstrate your question -- and thanks for that! Here is what I compiled:

    #include <Servo.h>

    #define SERVO1  9
    #define SERVO2  10

    /*****< External and Global Declarations >*****/
    Servo s1, s2;
    void toMove(Servo obj, int inPosition, int forPosition);

    /*****< Local Function Prototypes >*****/

    void toMove(Servo obj,int inPosition, int forPosition){
    int i = 0;
      for(i = inPosition; i<forPosition; i++){
        obj.write(i);
      }
    }

    void setup()
    {
     s1.attach(SERVO1);
     s2.attach(SERVO2);
    }

    void loop() {
       toMove(s1, 0, 180);
       toMove(s2, 0, 90);
    }

body:
You have not use attach() function:

     s1.attach(pin_1);
     s2.attach(pin_2);

See [how to use servo motor][1]

  [1]: https://arduinogetstarted.com/tutorials/arduino-servo-motor


body:
So I'm making a device that does 3 things,

1. Measures frequency of an audio signal through a microphone
2. Checks whether there is a weight placed on a pressure pad (my pressure sensor works through the resistance of the material changing when a weight is placed on it)
3. Measure ambient room temperature

I have coded each individual section and tested them individually to find them work great, here are the sketches.

Frequency sketch :

    // runs every time thru the loop
      setInputState();

      // count every transision HIGH<->LOW
      if (inputState != lastInputState) {
        count++;
        lastInputState = inputState;
      }

      if (millis() - previousCountMillis >= countMillis) {
        previousCountMillis += countMillis;

        // show Hz on Serial too if available
        Serial.print(count);
        Serial.println(" Hz");
        ledtest = count;
        // reset to zero for the next half second's sample
        count = 0L;
      }
      if (ledtest >= 400 && ledtest <= 850){
        digitalWrite(A2, HIGH);
      }
      else if (ledtest < 400 || ledtest > 850){
        digitalWrite(A2, LOW);
      }
    }

Here is the pressure sensor sketch

    int Vin = 5;
    float Vout = 0;
    float raw1 = 0;

    int R1 = 770;

    int R2old1 = 0;

    int R2new1 = 0;

    int R2avg1 = 0;

    int pressurelog = 0;

    void setup() {
      pinMode(A0, INPUT);             //Receive pressure voltage
      pinMode(A1, OUTPUT);            //Red led, PRESSURE PAD
    }

    void loop() {
      raw1 = analogRead(A0);
      Vout = raw1*5/1024;
      R2old1 = Vout*R1/(Vin-Vout);

      raw1 = analogRead(A0);
      Vout = raw1*5/1024;
      R2new1 = Vout*R1/(Vin-Vout);

      R2avg1 = (R2new1+R2old1)/2;

      Serial.print("Resistance: ");
      Serial.println(R2avg1);

      if (R2avg1 >= 1000){
        digitalWrite(A1, LOW);
        pressurelog = 0;
      }
      else if (R2avg1 <= 1000){
        digitalWrite(A1, HIGH);
        pressurelog = 1;
      }
    }

here is the temperature code

    float raw = 0;
    float tempC = 0;
    float tempF = 0;

    void setup() {
      pinMode(A5, INPUT);
      pinMode(A1, OUTPUT);
      Serial.begin(9600);
    }

    void loop() {
     raw = analogRead(A5) * 0.004882814;
     tempC = (raw - 0.5) * 100.0;
     tempF = (180.0/100.0)*tempC + 32.0;

     Serial.print("temp: ");
     Serial.println(tempF);
     delay(1000);
    }

I coupled the "void loop" of all three and defined everything and ran the code to give a peculiar output. It does the temp and pressure reporting just fine but seems to constantly skip the frequency measurement. It seems to like doing the pressure and temperature measurement like 50 times then do an audio measurement which doesn't make sense as it should do it sequentially.

I TRIED:

1. adding a delay between the frequency measurement and the other two. This didn't work as now the audio measurement work, as it relies on the millis () function
2. adding the 3 components in 3 different functions and calling them sequentially. This results in the exact same stupid output.

Does anyone have an idea or solution?

    Combined code:

    int Vin = 5;
    float Vout = 0;
    float raw1 = 0;

    int R1 = 770;

    int R2old1 = 0;

    int R2new1 = 0;

    int R2avg1 = 0;

    int pressurelog = 0;

    const byte inputPin = 2;

    boolean inputState = false;
    boolean lastInputState = false;
    long count = 0L;
    int ledtest = 0L;

    unsigned long previousCountMillis = millis();
    const long countMillis = 500L;

    void setInputState() {
      inputState = digitalRead(inputPin);
    }

    int crylog = 0;

    float raw = 0;
    float tempC = 0;
    float tempF = 0;

    int templog = 0;

    void setup() {
      pinMode(inputPin, INPUT);       //Receive microphone data
      pinMode(A0, INPUT);             //Receive pressure voltage
      pinMode(A1, OUTPUT);            //Red led, PRESSURE PAD
      pinMode(A2, OUTPUT);            //Blue led, FREQUENCY/CRYING
      pinMode(A3, OUTPUT);            //Green led, TEMPERATURE
      pinMode(A4, OUTPUT);            //Red led, MAX WARNING
      Serial.begin(115200);
    }

    void loop() {
      Serial.println("HI");
      Cryometer();
      delay(2);
      Serial.println("YO");
      Pressure();
      Temperature();

      // WARNING SETUP
      if (pressurelog == 1 && templog == 1){
        digitalWrite(A4, HIGH);
      }
      else {
        digitalWrite(A4, LOW);
      }
    }

    void Pressure() {
      raw1 = analogRead(A0);
      Vout = raw1*5/1024;
      R2old1 = Vout*R1/(Vin-Vout);

      raw1 = analogRead(A0);
      Vout = raw1*5/1024;
      R2new1 = Vout*R1/(Vin-Vout);

      R2avg1 = (R2new1+R2old1)/2;

      Serial.print("Resistance: ");
      Serial.println(R2avg1);

      if (R2avg1 >= 1000){
        digitalWrite(A1, LOW);
        pressurelog = 0;
      }
      else if (R2avg1 <= 1000){
        digitalWrite(A1, HIGH);
        pressurelog = 1;
      }
    }

    void Cryometer(){
      // runs every time thru the loop
      setInputState();

      // count every transision HIGH<->LOW
      if (inputState != lastInputState) {
        count++;
        lastInputState = inputState;
      }

      if (millis() - previousCountMillis >= countMillis) {
        previousCountMillis += countMillis;

        // show Hz on Serial too if available
        Serial.print("Frequency: ");
        Serial.print(count);
        Serial.println(" Hz");
        ledtest = count;
        // reset to zero for the next half second's sample
        count = 0L;
      }
      if (ledtest >= 400 && ledtest <= 850){
        digitalWrite(A2, HIGH);
        crylog = 1;
      }
      else if (ledtest < 400 || ledtest > 850){
        digitalWrite(A2, LOW);
        crylog = 0;
      }
    }

    void Temperature() {
       raw = analogRead(A5) * 0.004882814;
       tempC = (raw - 0.5) * 100.0;
       tempF = (180.0/100.0)*tempC + 32.0;

       Serial.print("Temperature (F): ");
       Serial.println(tempF);
       Serial.println();

      if (tempF >= 75 && ledtest <= 50){
        digitalWrite(A3, HIGH);
        templog = 1;
      }
      else if (ledtest < 50 || ledtest > 75){
        digitalWrite(A3, LOW);
        templog = 0;
      }
    }

title: Help combining digital and analog code in arduino programming

Answers: 1

body:
Your approach is globally sound. However, the code that measures the
input frequency is very time sensitive. Thus, you have to make sure this
piece of code is never delayed by anything else. This means that
everything in your sketch should be fast and _non-blocking_.

I see a few instances of blocking behaviour you should get rid of: the
call to `delay()` and the serial prints. The first is particularly
useless, so just remove it. Printing to the serial port is fine as long
as you do not try to print _too much_. If you try to print at every loop
iteration, you end up filling the output buffer. From there on every
print becomes a blocking call: the serial library has to wait for the
port to send out the data, until there is enough room in the buffer for
what you want to send. The solution is to throttle down the output rate
by only printing once in a while. You have done this brilliantly in the
frequency-meter code:

    if (millis() - previousCountMillis >= countMillis) {
      previousCountMillis += countMillis;
      Serial.print("Frequency: ");
      Serial.print(count);
      Serial.println(" Hz");
      // ...
    }

Now you just have to apply the same technique to _every_ instance of
`Serial.print()` and `Serial.println()`. Well, maybe the "HI" "YO" could
just be removed instead...

Once you remove these blocking behaviors from your sketch, it will
probably run fast enough for the frequency counting to perform
correctly. There is still something you may want to optimize though: the
computations in `Pressure()` are horribly inefficient, especially
considering that you have an 8-bit CPU with no hardware floating point
support. If you need to average, I suggest you average the analog
readings rather than computed resistances. Also note that computing the
voltage at the analog pin is completely useless:

    void Pressure() {
        int raw = analogRead(A0) + analogRead(A0);
        float R = (float) R1 * raw / (2048 - raw);
        // ...
    }

You may even replace `float` by `long` if you don't need a resolution
better than 1 Ω.


body:
This is my first manually typed code. I'm sure there may be some glaring "schoolboy errors" in it, so wondered if people could give it the 'once over' In particular, I have never used C++ arrays, storing binary data within, and then trying to read them bit by bit. In perl, much easier; you would simply use a multi-dimensional something like this:

    @code1=('10101010', '01010101');
    $bit=$code1[0][0] (..through to..) code1[0][7]
    $bit=$code1[1][0] ... code1[1][7]

So this is my Arduino code. Welcome to suggestions.

    int pinArray[]={2,3,4,5,6,7,8,9};
    int code1[]={B10101010, B01010101,B10101010, B01010101,B10101010, B01010101};
    int count=0;
    int split=0; // Counter for the bit loop
    int led; // Store bit data
    byte x;  // Used to store the binary data in code1

    void setup(){
     for (count=0; count<8; count++){
     pinMode(pinArray[count],OUTPUT); // Sets pinMode as output on pinArray pins
     ]
    }

    void loop(){
     for (count=0; count<6; count++){
     x=code1[count];
     ledDisplay(x);
     }
    }

    void ledDisplay(){
     for (split=7; split>=0; split--){
     led=bitRead(x,split);
      if (led == 1){
      digitalWrite(split+2,HIGH);
      }
      else{
      digitalWrite(split+2,LOW);
      }
     }
    }

Have just modified split as realised bit7 is the leftmost digit. In split, I am adding 2 to the value.  Does this need to be enclosed in brackets,ie (split+2) ?

title: USing arrays, binary data and bitRead

Answers: 1

body:
There are only two errors I can spot in your program:

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

1. A block of code should be delimited by curly braces:

        for (count=0; count<8; count++){
            pinMode(pinArray[count],OUTPUT);
        }  // ← ‘}’ instead of ‘]’

2. If a function expects to be passed arguments, these should be
   declared as parameters in the function prototype:

        void ledDisplay(byte x){  // ← mind the “byte x”
            // ...
        }

Other than that, here a few suggestions to make the code look nicer, and
hopefully more maintainable:

* indent consistently
* use `const` to qualify constants
* use named constants instead of magic numbers
* keep variables local if possible
* note that an int that is either 0 or 1 is equivalent to a boolean
* use `pinArray[]` for accessing the pins

Applying those suggestions, I get the following:

    const int PIN_COUNT = 8;
    const int pinArray[PIN_COUNT] = { 2, 3, 4, 5, 6, 7, 8, 9 };
    const int CODE_COUNT = 6;
    const int code1[CODE_COUNT] = {
        B10101010, B01010101, B10101010, B01010101, B10101010, B01010101
    };

    void setup() {
        for (int count = 0; count < PIN_COUNT; count++) {
            pinMode(pinArray[count], OUTPUT);
        }
    }

    void loop() {
        for (int count = 0; count < CODE_COUNT; count++) {
            ledDisplay(code1[count]);
        }
    }

    void ledDisplay(byte x) {
        for (int split = 7; split >= 0; split--) {
            if (bitRead(x, split)) {
                digitalWrite(pinArray[split], HIGH);
            } else {
                digitalWrite(pinArray[split], LOW);
            }
        }
    }


body:
I was testing out whether my 16x2 LCD works. I hooked it up to the arduino.

Some white box appeared which probably meant it works fine, but the box and the blue background looked very dim even when the potentiometer was turned to the maximum, and did not have the bright blue background which I saw on google.

FYI I soldered copper wire on the LCD and shoved them onto the breadboard since I did not have any pin headers. Would this be a cause of the problem?

[![My LCD][1]][1]

[![One from google][2]][2]

  [1]: https://i.stack.imgur.com/Brlt5.jpg
  [2]: https://i.stack.imgur.com/19TyJ.jpg

title: Arduino controlled LCD 16x2 is very very dim

Answers: 1

body:
I suggest you invest a dollar or so and get some proper wires. Those bare wires, which don't look soldered on, from the top view, just don't cut it. It also looks like the individual wires would short with each other (or are actually shorting).

It will light up when the backlight is correctly connected, which is impossible to tell from your photo.


body:
I have to arduino's which are communicate using rx/tx. Arduino1 (A1) send data over serial to Arduino2 (A2). My questions are:

1 - If A1 do Serial.print each 50ms and A2 reading serial each 100ms which value will get A2? For example A1 send "1" and after 50ms send "2". Considering A2 will read serial after 100+ ms it will get "2" ?

2 - If A1 send data each 100+ms and A2 read at 50ms which value will get A2 between? For example A1 send "1" and A2 read "1" when read at 50ms but when it read again after 50ms (during that time A1 didn t sent anything ) will read again "1" ?

Thank you

title: Serial communication questions

Answers: 1

body:
> 1 - If A1 do Serial.print each 50ms and A2 reading serial each 100ms which value will get A2? For example A1 send "1" and after 50ms send "2". Considering A2 will read serial after 100+ ms it will get "2" ?

The Arduino has a 64 byte (software) buffer.  You will get the numbers in sequence up until that buffer overflows. Then it's not easy to predict what the results will be.

Probably something like:

 121212121[...]2121212121212111111111111111

> 2 - If A1 send data each 100+ms and A2 read at 50ms which value will get A2 between? For example A1 send "1" and A2 read "1" when read at 50ms but when it read again after 50ms (during that time A1 didn t sent anything ) will read again "1" ?

If there is nothing in the buffer the read function returns -1.  That can be mapped (IIRC) into ASCII (depending on your software) as ÿ so you would get:

    1ÿ1ÿ1ÿ1ÿ1ÿ...

You should read [my tutorial on reading serial on the Arduino](https://majenko.co.uk/blog/reading-serial-arduino).


body:
I'd like to get a word of advice regarding the subject. Basically there's a COM port based device which I need to connect to an Android tablet via USB. The tablet will be exchanging data packages with the COM device, but a) Arduino may need to do same transformation of the packages b) the tablet should not leverage OTG feature and shouldn't be a master itself.

So, my questions are

1) Which Arduino board is the best fit?
2) Is it an option to use Chinese boards for the sake of cost optimization?
3) Do I need separate RS232 and USB shield or it's ok to leverage built in USB and data pins?

Apology for this quite a noob question but that's exactly who I am for Arduino platform. Appreciate any answers.

title: Arduino USB host + RS232

Answers: 1

body:
> 1) Which Arduino board is the best fit? 2) Is it an option to use Chinese boards for the sake of cost optimization? 3) Do I need separate RS232 and USB shield or it's ok to leverage built in USB and data pins?

When communicating with Android you need to make sure that there is software available for doing the communication. That's really down to the application more than the operating system, and because of that it can be quite restricted what boards will work and what won't.

Personally I would go for either an ATMega32U4 based board which provides a standard CDC/ACM interface. This also has the advantage that the (often single) UART on the board is *not* used by the USB communication.

Then you need to convert the UART into RS232 using (for example) a MAX232 board.


body:
I'm new Arduino and I would like you to help me. I would like to have a public IP so that anyone can get access to it, not only from domestic domain. What could I do?. I'm using Arduino Uno, Arduino Ethernet Shield w5500 and a RTC.
My code:

    #include <SPI.h>
    #include <Ethernet.h>
    #include "RTClib.h"
    #include <EEPROM.h>

    #define time 1
    // Enter a MAC address and IP address for your controller below.
    // The IP address will be dependent on your local network:
    byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
    IPAddress ip(192, 168, 0, 177);

    // Initialize the Ethernet server library
    // with the IP address and port you want to use
    // (port 80 is default for HTTP):
    EthernetServer server(80);
    //----------------------------------------------------------------------------------------------------------------
     int i=0;
    String hora="";
    String readString;

    RTC_DS1307 RTC;

    void setup() {

      pinMode(2,OUTPUT);
      // Open serial communications and wait for port to open:
      Serial.begin(9600);
    RTC.begin(); // Inicia la comunicaci¢n con el RTC

    RTC.adjust(DateTime(__DATE__, __TIME__)); // Establece la fecha y hora (Comentar una vez establecida la hora)

      while (!Serial) {
        ; // wait for serial port to connect. Needed for native USB port only
      }
      Serial.println("Sistemas Digitales");

      // start the Ethernet connection and the server:
      Ethernet.begin(mac, ip);

      // Check for Ethernet hardware present
      if (Ethernet.hardwareStatus() == EthernetNoHardware) {
        Serial.println("Ethernet shield no se encontro.  No se puede correr el programa sin el hardware. :(");
        while (true) {
          delay(1); // do nothing, no point running without Ethernet hardware
        }
      }
      if (Ethernet.linkStatus() == LinkOFF) {
        Serial.println("El cable Ethernet no esta onectado.");
      }

      // start the server
      server.begin();
      Serial.print("El servidor esta en: ");
      Serial.println(Ethernet.localIP());
    }

    void loop() {
      // listen for incoming clients

    delay(1000);
    DateTime now = RTC.now(); // Obtiene la fecha y hora del RTC

      EthernetClient client = server.available();
      if (client) {
        while (client.connected()) {
          if (client.available()) {
    //---------------------------------------------------------------------------------------------------------------------------------
            char c = client.read();

    if(i==11 || i==12 || i==16 || i==17){
     if(i==16){
      hora +=':';
     }
      hora += c;
    }

            if(readString.length()< 100){
              readString += c;
            }
            i++;
            //Este escribe el texto en pantalla letra por letra
            Serial.write(c);

            // if you've gotten to the end of the line (received a newline
            // character) and the line is blank, the http request has ended,
            // so you can send a reply
            if (c == '\n') {
                Serial.println("acabo lectura");

                Serial.println(hora);
                 Serial.println(readString);

    client.println("HTTP/1.1 200 OK"); // Enviar una respuesta tipica
                 client.println("Content-Type: text/html");
                 client.println("Connection: close");
                 client.println("Refresh: 10");
               client.println();
               client.println("<!DOCTYPE HTML>");
              client.println(" ");
              client.println("");
              client.println("<meta charset='UTF-8'><title>Sistemas Digitales</title>");
              client.println("");
              client.println("
");
    client.print("
Fecha y hora del servidor:");
    client.print(now.day(), DEC);
    client.print('/');
    client.print(now.month(), DEC);
    client.print('/');
    client.print(now.year(), DEC);
    client.print(' ');
    client.print(' ');
    int horini;
    horini=now.hour();
    String horartc = "0";
    if(horini<10){
      horartc += horini;
    }else{
    horartc= String(horini);
    }
    client.print(horartc);
    client.print(':');
    int minuto;
    minuto=now.minute();
    String mainut;
    if(minuto<10){
      mainut='0'+ String(minuto);
    }else{
    mainut= String(minuto);
    }
    client.print(mainut);
    client.println("
");
    client.println("<form method='get'>");
    client.println("

¿A que horas le quiere dar de comer al chucho?

");
    client.println("<input type='time' name='hora'>");
    client.println("

que dias lo quiere alimentar?

");
    //dias en checkbox
    //client.println("<input type='checkbox' name='cbox1' value='?LunesOn'>Lunes
<input type='checkbox' name='cbox2' value='?MartesOn'>Martes
<input type='checkbox' name='cbox3' value='?MiercolesOn'>Miercoles
<input type='checkbox' name='cbox4' value='?JuevesOn'>Jueves
<input type='checkbox' name='cbox5' value='?ViernesOn'>Viernes
<input type='checkbox' name='cbox6' value='?SabadoOn'>Sabado
<input type='checkbox' name='cbox7' value='?DomingoOn'>Domingo
");
    client.println("<input type='submit' value='Enviar' id='enviar'> ");
    client.println("</form>");
    if (readString.length() >0) {
    Serial.println("hora del rtc");
    String horiux = horartc +':'+ mainut;
    Serial.println(horiux);
    EEPROM.put(0, hora);

    if(EEPROM.get( 0, hora ) == horiux){
    digitalWrite(2, HIGH);
    delay(10000);
    digitalWrite(2, LOW);
    delay(60000);
    }
    readString="";
    i=0;
    hora="";

              client.println("");
              client.println("");

              delay(1);
        // close the connection:
        client.stop();

            }

          }
        }

      }

      }
    }

There it is  a part of the code:

    IPAddress ip(192, 168, 0, 177);

I would like to make that IPto be public domain so you can get access anywhere instead of neededing to be in the same ethernet connection.

Any help would be wonderful, thanks for your time.

title: Public IP for Arduino with Ethernet shield and Arduino Uno

Answers: 1

body:
There is a discussion about the same topic [in Arduino's Forum here](https://forum.arduino.cc/index.php?topic=333328.0). The most valuable comment was this:

> To get an internet static IP address, contact your ISP. You will probably have to pay extra for that. Most people use a dynamic IP service such as www.noip.com to forward traffic to your current internet IP address. You put your dynamic ip address url in your web page so the browser request get routed properly.

I assume (by the address) that you want to do something like this:

>The NAT device might have a port forwarding feature.
You can use that.
Assume the WAN ip is 198.51.100.1 and the server's ip is 10.1.1.1, the server is listening on port 80.
So the port forwarding configuration will be something like :
198.51.100.1 80 ---> 10.1.1.1 80
From the outside you connect to the public IP - 198.51.100.1 80
When the NAT device receives packet, it forwards it to 10.1.1.1.
**more info** [here](https://www.quora.com/How-to-connect-to-a-server-behind-NAT)

This is direct copy from source. So in your case WAN IP is the static IP (or another else) that is visible about you outside your network and the private one is that 192.168.0.177 which you used. Like stated in first yellow box, you can use dynamic ip service, too.


body:
last two days I am trying to program my blue pill with Arduino IDE, helplessly...
Actually, I managed to install simple blink program, but after that, all other attempts ended up with:

> Failed to init device.
stm32flash Arduino_STM32_0.9

> http://github.com/rogerclarkmelbourne/arduino_stm32

> Using Parser : Raw BINARY
Interface serial_posix: 115200 8E1

> An error occurred while uploading the sketch

I crawled internet but no help so far... I followed simply tutorial:
https://www.youtube.com/watch?v=K-jYSysmw9w just as this https://github.com/rogerclarkmelbourne/Arduino_STM32/wiki/Installation, and as I said, first time was problem but finally successfully upload it. However, after that when I wanted some real working program to install failed.
All mappings ftdi -> stm32 are correct, jumper booto is set to 1 mode, for programming, I have required files within /etc/udev/rules.d, stm32 library folder in sketch folder, and yet the error above is happening for a last 20 hours... (I am using Ubuntu 16.04)
Please, if anyone point me what is wrong (why first time worked and second wont), or to give me precise steps to perform in order to work, I appreciate.

EDIT: Blinking program works just fine when I move jumper to 0, and supply power via usb.

title: Using use the STM32F103C8T6 board with the Arduino

Answers: 1

body:
thanx for help... It turns out that I have been sold crappy additional pins to plugin into breadboard. Even STM32 blink, turns out that one of the tx/rx has no contact with board (probably for microns).
However, firmed them altogether without breadboard, and it works...I spent 15 hours with this issue...


body:
I'm just learning to code in Arduino.

The purpose is that first the sensor measures the moist level (I mapped the reading values from 0 to 100). If the value is less than threshold 70, then it will turn on a water pump. As soon as the value goes beyond 70, the pump stops pumping water.

The problem is that even when the value is less than 70, the pump doesn't work.

I tried replacing the pump with a LED, it turns on a the right moment. I tested the pump itself, and it also works perfectly.
<!-- language-all: lang-cpp -->

    //for mapping values
    int mostMoist = 100;
    int leastMoist = 600;
    int percent;

    //direct value from sensor
    int raw;

    //threshold for minimum percentage to turn on pump
    const int threshold = 70;

    //initial state of water pump
    bool dosomething = false;

    void setup() {
      Serial.begin(9600);
      pinMode(13, OUTPUT);
    }

    void loop() {
      //if it's not pumping water:
      while (dosomething == false){
      //check sensor value, map out of 100, and display on monitor
      raw = analogRead(A0);
      percent = map(raw,leastMoist,mostMoist,0,100);
      if (percent < 0){
        percent = 0;
      }
      Serial.println(percent);
      Serial.println("dosomething is set to false");

      //check if percentage moist is less than threshold. if so, set dosomething true, orelse, loop dosomething false
      if (percent<threshold){
        dosomething = true;
      } else{
        dosomething = false;
      }
      delay(2);
      }

      //if it's pumping water:
      while (dosomething==true){
      //check sensor value, map out of 100, and display on monitor
      raw = analogRead(A0);
      percent = map(raw,leastMoist,mostMoist,0,100);
      if (percent < 0){
        percent = 0;
      }
      //turn on pump
      digitalWrite(13,HIGH);
      Serial.println("dosomething is set to true");
      //check if percent moist is less than threshold value, if so, loop dosomething true, orelse, set dosomething false
        if (percent<threshold){
        dosomething = true;
      } else{
        dosomething = false;
      }
        Serial.println(percent);
      delay(2);
      }

    }

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

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

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

  [1]: https://i.stack.imgur.com/Yc6Qy.jpg
  [2]: https://i.stack.imgur.com/5yBr0.jpg
  [3]: https://i.stack.imgur.com/GVhYC.jpg

title: Water pump controlled by soil moisture sensor

Answers: 2

body:
I don't see a second power-supply in your photo. If you're trying to run the pump directly from an Arduino pin, it is highly likely that the pump needs way more current than the pin can supply.

It may be possible to power the motor from the USB but 1) the Uno board doesn't make that readily available, 2) it puts your PC at some risk (of back-EMF or of over-drawing the port's capability. But the ideal would be a separate power supply (don't forget to connect that supply's ground to the Uno's ground).

Also, if you tested the pump while dry it may have been able to run, yet with water in it, have been unable pull enough starting current to get going.

body:
To control the pump you will need either a transistor or a relay board to handle the current. The arduinos pins can only drive 20 mA which is not enough for most pumps, even very small ones.

If the pump can run on 5 V and with <400 mA a transistor (FET) may suffice an power could come from VCC or so. Otherwise an extra supply with a relay is one simple solution.

You [could start here](https://arduinogetstarted.com/tutorials/arduino-controls-pump) for instance.

Look for tutorials, there are so many out there to be found with search engine, it's worth :)


body:
How can I get my programmer board/windows computer to recognize my board again. I am using the esp32 cam and have put two boards in a state where I am unable to flash them anymore. here is the error:

    serial.serialutil.SerialException: could not open port 'COM5'WindowsError(2,'The system cannot find the file specified.')Failed to execute script esptoolthe selected serial port Failed to execute script esptool

I tried reinstalling the drivers and understand that the com port is a separate chip
https://gist.github.com/wybiral/2a96c1d1605af7efa11b690586c4b13e

Here is the sketch I used. I uploaded it using the dev module board setting as well as with 80mhz and 112500 speed. I uploaded with 3v and then provided 5v to the board to run the sketch. The sketch runs but prints out gibberish.

Edit:

Here is a schematic of the board
https://github.com/SeeedDocument/forum_doc/raw/master/reg/ESP32_CAM_V1.6.pdf

title: Stuck with bad sketch

Answers: 1

body:
This very much looks like the Serial-over-USB-Driver has chosen another port than COM5 on reconnecting the board. Assuming you are using the Arduino IDE, check whether COM5 still shows up in the Board -> Port menu -- or, in other words, go there and select the port that is listed there *while the board is plugged in*.

Usually, I'd expect this port to be COM3 on Windows, but that may change when you...

* physically disconnect and reconnect the board too fast (i.e. the driver has not yet shut down the old COM port when a "new device on USB!" event comes in)
* still have the Serial Monitor open when disconnecting and reconnecting (because the driver cannot remove the virtual COM port device while the Serial Monitor has it opened, in which case the driver creates another virtual COM port device on a different number)
* disconnect and reconnect while the esptool process is still working (same reason as above).

It also might help to enable verbose output for compiling and uploading (see preferences dialog in Arduino IDE).


body:
Hello guys I am beginner with micro controllers but I am trying to make a simple IoT with Arduino and NodeMCU as WiFi. I was using this tutorial and code https://www.electronicshub.org/wifi-controlled-led-using-esp8266-and-arduino/.

When I upload the code for the first time everything worked perfectly but every other time when I upload the same code my program is stuck in a loop.

Program is in infinite while loop ```while(!esp8266.find("OK"))``` because as far as i understand it didnt receive the OK status from ESP.

But in fact ```    esp8266Serial("AT+CWJAP=\"SSID\",\"Password\"\r\n", 5000, DEBUG);``` prints OK in my console so it means that it should work but it doesnt...

Do you guys have any idea whats the reason?

 Code looks as follows;

<!-- language-all: lang-cpp -->
```C
#include <SoftwareSerial.h>
SoftwareSerial esp8266(2,3); //Pin 2 & 3 of Arduino as RX and TX. Connect TX and RX of ESP8266 respectively.
#define DEBUG true
#define led_pin 11 //LED is connected to Pin 11 of Arduino

void setup()
  {
    pinMode(led_pin, OUTPUT);
    digitalWrite(led_pin, LOW);
    Serial.begin(9600);
    esp8266.begin(115200); //Baud rate for communicating with ESP8266. Your's might be different.
    esp8266Serial("AT+RST\r\n", 5000, DEBUG); // Reset the ESP8266
    esp8266Serial("AT+CWMODE=1\r\n", 5000, DEBUG); //Set station mode Operation
    esp8266Serial("AT+CWJAP=\"SSID\",\"Password\"\r\n", 5000, DEBUG);//Enter your WiFi network's SSID and Password.

    while(!esp8266.find("OK"))
    {
      }
    esp8266Serial("AT+CIFSR\r\n", 5000, DEBUG);//You will get the IP Address of the ESP8266 from this command.
    esp8266Serial("AT+CIPMUX=1\r\n", 5000, DEBUG);
    esp8266Serial("AT+CIPSERVER=1,80\r\n", 5000, DEBUG);
  }

void loop()
  {
    if (esp8266.available())
      {
        if (esp8266.find("+IPD,"))
          {
            String msg;
            esp8266.find("?");
            msg = esp8266.readStringUntil(' ');
            String command1 = msg.substring(0, 3);
            String command2 = msg.substring(4);

            if (DEBUG)
              {
                Serial.println(command1);//Must print "led"
                Serial.println(command2);//Must print "ON" or "OFF"
              }
            delay(100);

              if (command2 == "ON")
                    {
                      digitalWrite(led_pin, HIGH);
                    }
                   else
                     {
                       digitalWrite(led_pin, LOW);
                     }
          }
      }
  }

String esp8266Serial(String command, const int timeout, boolean debug)
  {
    String response = "";
    esp8266.print(command);
    long int time = millis();
    while ( (time + timeout) > millis())
      {
        while (esp8266.available())
          {
            char c = esp8266.read();
            response += c;
          }
      }
    if (debug)
      {
        Serial.print(response);
      }
    return response;
  }
 ```

title: Arduino and NodeMCU problem with wifi conecction

Answers: 0


body:
it's a [UGN3503][1] hall effect sensor, in some schematics they used a 100uf capacitors and data connected to analog pin and in some a pull up resistor and data connected to digital pin.

as someone new to both electronics and arduino i'm a bit confused on how to wire the sensor to the arduino.

what i want is just simply read the data from sensor and if the number is above or under defined value do something.

do i need a pull up resistor and/or capacitor?

what's the right and standard way to wire a UGN3503 to arduino?

  [1]: http://www.bristolwatch.com/hall_effect/ugn3503.pdf

title: How to wire a hall effect sensor to arduino?

Answers: 1

body:
The UGN3503 that you use gives out a analog voltage that changes when there's a magnetic field present. So this sensor needs to be connected to an analog pin.

If there is no field present the voltage is around 2.5Volt. If the south pole of a magnetic field is present the voltage will be higher that 2.5V. With a north pole the voltage will be lower that this 2.5Volt. The amount of higher/lower voltage is based on the strength of the field.

A capacitor near the sensor could help reduce, so called, noise. Though 100µF is too high. I think you mean 100nF (0.1µF).

The pull-up is for other types of hall-effect sensors. Some of these sensors just give a HIGH of LOW output, based on whether a magnetic field is present. Those you connect to a normal input pin.


body:
I need to operate 2 different sensors (gas and DHT11) simultaneously. I have managed to run each one of them separately and I don't know how to manipulate the code so they could work together.

Here are the sketches:

Gas sensor MQ2 code :

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

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

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

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

This is the DHT11 code :

    #include <SimpleDHT.h>

    int pinDHT11 = 7;
    SimpleDHT11 dht11(pinDHT11);

    void setup() {
        // start working...
      Serial.begin(9600);
      Serial.println("Temperature and Humidity Data");
    }

    void loop() {

      delay (250);
      // read without samples.
      byte temperature = 0;
      byte humidity = 0;
      int err = SimpleDHTErrSuccess;
      if ((err = dht11.read(&temperature, &humidity, NULL)) != SimpleDHTErrSuccess) {
        Serial.print("Read DHT11 failed, err="); Serial.println(err);delay(1000);
        return;
      }
      Serial.print((int)temperature); Serial.print(" *C, ");
      Serial.print((int)humidity); Serial.println(" H");

      // DHT11 sampling rate is 1HZ.
      delay(1500);
    }

title: Combining code for multiple sensors in one program (Arduino)

Answers: 1

body:
You need to combine the 3 major area's of the code, the include/declaration section where files are included and global variables are declared.  Then combine the setup() functions and then combine the loop() functions. Ends up looking something like below. However you may have to tweek the timing of your delays

    #include <SimpleDHT.h>
    int redLed = 12;
    int greenLed = 11;
    int buzzer = 10;
    int smokeA0 = A5;
    // threshold value
    int sensorThres = 400;
    int pinDHT11 = 7;
    SimpleDHT11 dht11(pinDHT11);

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

    void loop() {
      int analogSensor = analogRead(smokeA0);
      Serial.print("Concentration: ppm ");
      Serial.println(analogSensor);
      // Checks if it has reached the threshold value
      if (analogSensor > sensorThres)
      {
        digitalWrite(redLed, HIGH);
        digitalWrite(greenLed, LOW);
        tone(buzzer, 1000, 200);
      }
      else
      {
        digitalWrite(redLed, LOW);
        digitalWrite(greenLed, HIGH);
        noTone(buzzer);
      }
      delay(250);
      // read without samples.
      byte temperature = 0;
      byte humidity = 0;
      int err = SimpleDHTErrSuccess;
      if ((err = dht11.read(&temperature, &humidity, NULL)) != SimpleDHTErrSuccess) {
        Serial.print("Read DHT11 failed, err="); Serial.println(err);delay(1000);
        return;
      }
      Serial.print((int)temperature); Serial.print(" *C, ");
      Serial.print((int)humidity); Serial.println(" H");

      // DHT11 sampling rate is 1HZ.
      delay(1500);
    }

The other way you can do it, which keeps it easyer to read, is move the contents of each main loop into its own function, and then call the two functions from inside loop().  This allows you to easly comment out one of the functions to trouble shoot somthing, or even allow you to call one more often then the other depending upon your needs, (can look at the blink without delay example for how to manage timing)

    #include <SimpleDHT.h>
    int redLed = 12;
    int greenLed = 11;
    int buzzer = 10;
    int smokeA0 = A5;
    // threshold value
    int sensorThres = 400;
    int pinDHT11 = 7;
    SimpleDHT11 dht11(pinDHT11);

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

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

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

    void loop2(){
      delay (250);
      // read without samples.
      byte temperature = 0;
      byte humidity = 0;
      int err = SimpleDHTErrSuccess;
      if ((err = dht11.read(&temperature, &humidity, NULL)) != SimpleDHTErrSuccess) {
        Serial.print("Read DHT11 failed, err="); Serial.println(err);delay(1000);
        return;
      }
      Serial.print((int)temperature); Serial.print(" *C, ");
      Serial.print((int)humidity); Serial.println(" H");

      // DHT11 sampling rate is 1HZ.
      delay(1500);
    }

    void loop() {
      loop1();
      loop2();
    }


body:
I have a problem with my 16,2 with buttons lcd shield.(LCD Keypad Shield). It is connected on top of an SD dataloger. I came to the conclusion that every time the sd shield logs data and completes the loop it switches off and on,flickering the lcd, and moves on with the loop. Is there any way to stop the flickering while the sd shield logs??[![SD Loger][1]][1][![Side][2]][2][![Top][3]][3]

  [1]: https://i.stack.imgur.com/UlNRt.jpg
  [2]: https://i.stack.imgur.com/XJgnk.jpg
  [3]: https://i.stack.imgur.com/EQ0eo.jpg

title: LCD on top of SD datalogger flickers help!

Answers: 0


body:
I have created a `byte` for 16x2 LCD. It is basically a custom character which I will have to change later.
<!-- language-all: lang-cpp -->

    byte char[8]{
     B10000,
     B01000,
     B00100,
     B00010,
     B00001,
     B11000,
     B11100
    };

I want to edit the third number from fourth row. So, the fourth row will become `B00110` from `B00010`. Is this possible? Are there any alternatives for this?

title: How to modify a created byte?

Answers: 2

body:
Well first of all you are trying to name the variable char? which is already a keyword for the variable type of char.   But you can access it by the index of the array. Also not sure if you intended to make the array 8 bytes in length, and then only use 7, but thats what you had done in your example

    //define it all at once
    // byte byteArray[8] = {B10000,B01000,B00100,B00010,B00001,B11000,B11100};
    //or by index
    byte byteArray[8];
    byteArray[0]=B10000;
    byteArray[1]=B01000;
    byteArray[2]=B00100;
    byteArray[3]=B00010;
    byteArray[4]=B00001;
    byteArray[5]=B11000;
    byteArray[6]=B11100;

    //if you need to change one in the code elsewhere
    byteArray[3]=B00110;
    //or
    byteArray[3]=6;
    }

body:
You can use the following array initialization:

In the setup I shows how to set a bit. For this, the bit operator or (|) is used. To reset a bit, you can use &. You can set/reset multiple bits this way.

Also you can use 1 << 2 which means 1 (most right bit) shifted left two places (thus B100).

Btw, it is common practice to initialize all values.

    byte lcd[8] =
    {
      B10000,
      B01000,
      B00100,
      B00010,
      B00001,
      B11000,
      B11100,
      B00000  // Also initialize last element
    };

    void setup()
    {
       lcd[3] |= B100; // Set 4th row (element 3), 3th bit (from the right)
       lcd[3] |= 1 << 2; // Alternative
    }

    void loop()
    {
    }

Explanation about the `or` arithmetics: OR means: if at least one bit is 1, the result is 1, otherwise 0.

Truth table:

    A | B | A or B
    --+---+-------
    0 | 0 |   0
    0 | 1 |   1
    1 | 0 |   1
    1 | 1 |   1

For your example it means:

    Original value of lcd[3]: B00010
    Or mask (in setup):       B00100
                              ------ OR
    Result                    B00110


body:
Im working on a project with my addresible led strip and arduino uno
I need 3 leds on the strip to light for 24 hours and then the next 3 leds on the strip should light up for 24 hours and so on.
Can somone help me with the code

title: Addresible led delay for 24 hours with arduino uno

Answers: 0


body:
Alright, seems there is something wrong I am doing that I don't understand. Before I start explaining, my question is different than this [`white screen`][1] question.

First of all my `TFT ST7735` is working very well with the below code, let's name it, **code part 1**:

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

    #define USE_ARDUINO_INTERRUPTS true    // Set-up low-level interrupts for most acurate BPM math.
    #include <PulseSensorPlayground.h>     // Includes the PulseSensorPlayground Library.
    #include <Adafruit_GFX.h>    // Core graphics library
    #include <Adafruit_ST7735.h> // Hardware-specific library for ST7735
    #include <Adafruit_ST7789.h> // Hardware-specific library for ST7789
    #include <SPI.h>
    #include <SD.h>

      #define TFT_CS        10
      #define TFT_RST        9 // Or set to -1 and connect to Arduino RESET pin
      #define TFT_DC         8

    #define TFT_MOSI 11  // Data out
    #define TFT_SCLK 13  // Clock out

    Adafruit_ST7735 tft = Adafruit_ST7735(TFT_CS, TFT_DC, TFT_MOSI, TFT_SCLK, TFT_RST);
    float p = 3.1415926;
    int Variable1;
    int ledState = HIGH;
    //  Variables
    int PulseWire = 0;       // PulseSensor PURPLE WIRE connected to ANALOG PIN 0
    int myBPM = 0;
    const int LED13 = 13;          // The on-board Arduino LED, close to PIN 13.
    int Threshold = 550;           // Determine which Signal to "count as a beat" and which to ignore.
    // constants won't change:
    const long interval = 1000;

    unsigned long previousMillis = 0;
    static uint32_t tsLastReport = 0;

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

      Serial.print(F("Hello! ST77xx TFT Test"));

    #ifdef ADAFRUIT_HALLOWING

      tft.initR(INITR_HALLOWING);        // Initialize HalloWing-oriented screen
      pinMode(TFT_BACKLIGHT, OUTPUT);
      digitalWrite(TFT_BACKLIGHT, HIGH); // Backlight on
    #else

      tft.initR(INITR_144GREENTAB); // Init ST7735R chip, green tab

    #endif

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

      uint16_t time = millis();
      tft.fillScreen(ST77XX_BLACK);
      time = millis() - time;

      Serial.println(time, DEC);
      delay(500);

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

    }

    void loop() {

      testdrawtext(" BPM: ", ST77XX_WHITE);
      tft.setTextColor(ST77XX_RED);
      tft.setTextSize(2);

      int sensorValue = analogRead(A0);

      tft.print(sensorValue);
        delay(300);
      tft.fillScreen(ST77XX_BLACK);

    }

    void testdrawtext(char *text, uint16_t color) {
       tft.setCursor(0, 0);
     tft.fillScreen(ST77XX_BLACK);

      tft.setCursor(0, 0);
      //  tft.setCursor(10, 40);
      tft.setTextSize(2);
     // tft.setTextColor(color);
      tft.setTextColor(ST7735_YELLOW);
      tft.setTextWrap(true);
      tft.print(text);
       delay(200);
    }

Here is the [video][2] for **Part 1** running very good with a random analog number.

 Secondly, I have a simple `Heart Beat circuit` and it is working very well when I apply this `getting_BPM_to_Monitor` [code][3] into it. I don't have a photo for it but trust me it is working good so please, when I do attach the schematic don't focus too much on the hardware side, it might not be very perfectly stable but it is working fine for me.

Now, is the magic when I combine the **Heart Beat** which is `getting_BPM_to_Monitor` & TFT ST7735 `circuit` things don't seem alright and I think a code with a video is better explaining the issue than me. The below code, let's name it, **code part 2**:

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

    #define USE_ARDUINO_INTERRUPTS true    // Set-up low-level interrupts for most acurate BPM math.
    #include <PulseSensorPlayground.h>     // Includes the PulseSensorPlayground Library.
    #include <Adafruit_GFX.h>    // Core graphics library
    #include <Adafruit_ST7735.h> // Hardware-specific library for ST7735
    #include <Adafruit_ST7789.h> // Hardware-specific library for ST7789
    #include <SPI.h>
    #include <SD.h>

      #define TFT_CS        10
      #define TFT_RST        9 // Or set to -1 and connect to Arduino RESET pin
      #define TFT_DC         8
    .
    #define TFT_MOSI 11  // Data out
    #define TFT_SCLK 13  // Clock out

    Adafruit_ST7735 tft = Adafruit_ST7735(TFT_CS, TFT_DC, TFT_MOSI, TFT_SCLK, TFT_RST);
    float p = 3.1415926;
    int Variable1;
    int ledState = HIGH;
    //  Variables
    int PulseWire = 0;       // PulseSensor PURPLE WIRE connected to ANALOG PIN 0
    const int LED13 = 13;          // The on-board Arduino LED, close to PIN 13.
    int Threshold = 550;           // Determine which Signal to "count as a beat" and which to ignore.
    int myBPM = 0;
    PulseSensorPlayground pulseSensor;  // Creates an instance of the PulseSensorPlayground object called "pulseSensor"

    static uint32_t tsLastReport = 0;

    void setup(void) {
      Serial.begin(9600);
     // .  PulseWire = 3;
      pulseSensor.analogInput(PulseWire);
      pulseSensor.blinkOnPulse(LED13);       //auto-magically blink Arduino's LED with heartbeat.
      pulseSensor.setThreshold(Threshold);
      pulseSensor.begin();

      Serial.print(F("Hello! ST77xx TFT Test"));

    #ifdef ADAFRUIT_HALLOWING

      tft.initR(INITR_HALLOWING);        // Initialize HalloWing-oriented screen
      pinMode(TFT_BACKLIGHT, OUTPUT);
      digitalWrite(TFT_BACKLIGHT, HIGH); // Backlight on
    #else
      // Use this initializer if using a 1.8" TFT screen:
     // tft.initR(INITR_BLACKTAB);      // Init ST7735S chip, black tab

      // OR use this initializer (uncomment) if using a 1.44" TFT:
      tft.initR(INITR_144GREENTAB); // Init ST7735R chip, green tab

      // OR use this initializer (uncomment) if using a 0.96" 180x60 TFT:
      //tft.initR(INITR_MINI160x80);  // Init ST7735S mini display

      // OR use this initializer (uncomment) if using a 1.54" 240x240 TFT:
      //tft.init(240, 240);           // Init ST7789 240x240
    #endif

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

      uint16_t time = millis();
      tft.fillScreen(ST77XX_BLACK);
      time = millis() - time;

      Serial.println(time, DEC);
      delay(500);

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

      Variable1 = 90;

    }

    void loop() {

      testdrawtext(" BPM: ", ST77XX_WHITE);
      tft.setTextColor(ST77XX_RED);
      tft.setTextSize(3);

      myBPM = pulseSensor.getBeatsPerMinute();
    if (pulseSensor.sawStartOfBeat()) {
    }

      tft.print(myBPM);
          delay(300);
      tft.fillScreen(ST77XX_BLACK);

    }

    void testdrawtext(char *text, uint16_t color) {
       tft.setCursor(0, 0);
     tft.fillScreen(ST77XX_BLACK);

      tft.setCursor(0, 0);
      //  tft.setCursor(10, 40);
      tft.setTextSize(2);
     // tft.setTextColor(color);
      tft.setTextColor(ST7735_YELLOW);
      tft.setTextWrap(true);
      tft.print(text);
       delay(200);
    }

Here is the [video][4] or this [video][5] for **Part 2**

Lastly, I provided the schematic for more reasoning opinion and it was provided by Easyeda.com and you have to have an account to view my [schematic][6]

Things I have tried...

 - I have modified TFT pins since `Gtting_BPM_to_Monitor` uses Timer1 & Timer2
 - I have added/remove a lot of delays
 - I have inserted`noInterrupts();` and `interrupts();`

**Edit 1** :
Here is a `PNG` of the schematic if and hopefully, it is clear enough.
[![enter image description here][8]][8]

  [1]: https://arduino.stackexchange.com/questions/62308/what-am-i-missing-st7735-tft-white-screen
  [2]: https://i.stack.imgur.com/NgL3u.jpg
  [3]: https://github.com/WorldFamousElectronics/PulseSensorPlayground/tree/master/examples/Getting_BPM_to_Monitor
  [4]: https://i.stack.imgur.com/ZAX7r.jpg
  [5]: https://i.stack.imgur.com/yOYjn.jpg
  [6]: https://easyeda.com/account/project?project=fdf3ccc0e5194541a411e4c0c5a5020f
  [7]: https://github.com/WorldFamousElectronics/PulseSensor_Amped_Arduino
  [8]: https://i.stack.imgur.com/DcnqR.png

title: Why does my TFT keep turning white after moments?

Answers: 0


body:
I want to send a function generator's signal to an Arduino UNO Analog pin. Can I use an Oscilloscope probe connected to the function generator output BNC, set to 1x to connect to the Arduino headers using jumper wires? I did read through the manuals of the function generator, but couldn't find a solution.

The function generator available is Tenma 72-14110.

title: Connecting Function Generator to Arduino

Answers: 2

body:
Sure, you can connect the function generator to an analog pin of the Arduino. The probe and the jumper wires are just wires here, nothing special. You should also connect the function generators ground to the Arduinos ground (!).

But: Be sure to stay in the Arduinos voltage range (0 to 5V) with the function generators signal. If you apply a higher or negative voltage, you can destroy the Arduino. As long, as you stay inside that range, nothing bad will happen.

body:
As a complement to chrisl's answer, I would recommend putting a
10 kΩ series resistor in series between the function generator and
the Arduino.

This is just for safety: if the function generator accidentally goes out
of the  Arduino's safe voltage range, the resistor will limit the
current that flows through the input pin's protection diodes. These
diodes are rated to only 1 mA, and a 10 kΩ resistor should
greatly expand the range of voltages you can send without frying them.


body:
I have a string,

"id,port,password,ssid,delay,flag,class,category"

Please tell me how can stringtok this and find out the "flag" value(0 or 1)?

Here is what I tried:

```c++
void setup()
{
    char input[] = {"id,port,password,ssid,delay,flag,class,category"};
    char *ptr;
    Serial.begin(115200);
    ptr = strtok(input, ",");
    Serial.println(ptr);
    while (ptr != NULL) {
        ptr = strtok(NULL, ",");
        Serial.println(ptr);
    }
}

void loop(){}
```

title: How to stringtok this long string?

Answers: 1

body:
For strings with a fixed format like that (I assume it's a fixed format...) I normally just do a manual strtok of the whole thing into a set of pointers. No need for a loop.  You can then just test the last one to see if the whole thing tokenised properly, since if anything before that fails then all other subsequent ones will fail and the last one will have failed.

    void setup()
    {
        char input[] = {"id,port,password,ssid,delay,flag,class,category"};
        char *ptr;
        Serial.begin(115200);

        char *id = strtok(input, ",");
        char *port = strtok(NULL, ",");
        char *password = strtok(NULL, ",");
        char *ssid = strtok(NULL, ",");
        char *delay = strtok(NULL, ",");
        char *flag = strtok(NULL, ",");
        char *class = strtok(NULL, ",");
        char *category = strtok(NULL, ",");
        if (category != NULL) { // Everything up to and including category worked
            Serial.print("Flag: ");
            Serial.println(flag);
        }
    }

    void loop(){}

As an aside: if there is ever a chance any of the fields could be empty ("flag,,category" for example) then you should use `strsep()` instead of `strtok()` as I detail in my [tutorial on splitting strings in C](https://majenko.co.uk/blog/splitting-text-c).


body:
I am using an esp8266 01 module with the Arduino Uno to establish a communication between the Arduino and my web site. I actually don't know how to send Rest HTTP requests from the Arduino to get data from my web site. I have done research but all I got is codes using `nodemcu` so I was wondering will the code of nodeMCU work fine on the Arduino using ESP01 and if not then how can I send get and post request from the Arduino using esp01
this the code that I found

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

    const char* ssid = "SERVER NAME";
    const char* password = "SERVER PASSWORD";

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

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

    void loop()
    {
      if (WiFi.status() == WL_CONNECTED)
      {
        HTTPClient http; //Object of class HTTPClient
        http.begin("http://jsonplaceholder.typicode.com/users/1");
        int httpCode = http.GET();

        if (httpCode > 0)
        {
          const size_t bufferSize = JSON_OBJECT_SIZE(2) + JSON_OBJECT_SIZE(3) + JSON_OBJECT_SIZE(5) + JSON_OBJECT_SIZE(8) + 370;
          DynamicJsonBuffer jsonBuffer(bufferSize);
          JsonObject& root = jsonBuffer.parseObject(http.getString());

          int id = root["id"];
          const char* name = root["name"];
          const char* username = root["username"];
          const char* email = root["email"];

          Serial.print("Name:");
          Serial.println(name);
          Serial.print("Username:");
          Serial.println(username);
          Serial.print("Email:");
          Serial.println(email);
        }
        http.end(); //Close connection
      }
      delay(60000);
    }

title: how can i send get and post request from esp01 using arduino uno

Answers: 0


body:
I have a [Keyes Espressif ESP8266][1] NodeMCU, I have two LEDs that I want to control which are connected to the ESP. When I open the webpage `http://10.0.0.5/5` after uploading the sketch it works fine. If I don't open and close the website before ~ 02:30[mm:ss] the server becomes unreachable even if I close the existing connection and open a new connection in a new tab the same error yields: `ERR_CONNECTION_TIMED_OUT`

If I don't open a web page before ~ 02:30[mm:ss] I also receive error `ERR_CONNECTION_TIMED_OUT`

The web server is only made available when I hard reset the board then the same rules apply as above.

    ESP.getFullVersion() outputs:
    SDK:2.2.1(cfd48f3)/Core:2.5.1=20501000/lwIP:STABLE-2_1_2_RELEASE/glue:1.1-7-g82abda3/BearSSL:a143020

Question:

How can I make the web server accessible constantly?

With the help of @Juraj I tried changing to SDK V3 which made no difference I also tried:

 - All lwip variants

My Code:

    // Load Wi-Fi library
    #include <ESP8266WiFi.h>

    // Replace with your network credentials
    const char* ssid     = "DO_231455";
    const char* password = "0828842107";

    // Set web server port number to 80
    WiFiServer server(80);

    // Variable to store the HTTP request
    String header;

    // Auxiliar variables to store the current output state
    String output5State = "off";
    String output4State = "off";

    // Assign output variables to GPIO pins
    const int output5 = 16;
    const int output4 = 4;

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

      // Initialize the output variables as outputs
      pinMode(output5, OUTPUT);
      pinMode(output4, OUTPUT);
      // Set outputs to LOW
      digitalWrite(output5, LOW);
      digitalWrite(output4, LOW);

      Serial.print(ESP.getFullVersion());
      //WiFi.disconnect() ;
      //WiFi.persistent(false);
      //WiFi.setSleepMode(WIFI_NONE_SLEEP);
      // Connect to Wi-Fi network with SSID and password
      Serial.print("Connecting to ");
      Serial.println(ssid);
      WiFi.begin(ssid, password);
      while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
      }
      // Print local IP address and start web server
      Serial.println("");
      Serial.println("WiFi connected.");
      Serial.println("IP address: ");
      Serial.println(WiFi.localIP());
      server.begin();
    }

    void loop(){
      WiFiClient client = server.available();   // Listen for incoming clients
      if (client) {                             // If a new client connects,
        Serial.println("New Client.");          // print a message out in the serial port
        String currentLine = "";                // make a String to hold incoming data from the client
        while (client.connected()) {            // loop while the client's connected
          if (client.available()) {             // if there's bytes to read from the client,
            char c = client.read();             // read a byte, then
            Serial.write(c);                    // print it out the serial monitor
            header += c;
            if (c == '\n') {                    // if the byte is a newline character
              // if the current line is blank, you got two newline characters in a row.
              // that's the end of the client HTTP request, so send a response:
              if (currentLine.length() == 0) {
                // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
                // and a content-type so the client knows what's coming, then a blank line:
                client.println("HTTP/1.1 200 OK");
                client.println("Content-type:text/html");
                client.println("Connection: close");
                client.println();

                // turns the GPIOs on and off
                if (header.indexOf("GET /5/on") >= 0) {
                  Serial.println("GPIO 5 on");
                  output5State = "on";
                  digitalWrite(output5, HIGH);
                } else if (header.indexOf("GET /5/off") >= 0) {
                  Serial.println("GPIO 5 off");
                  output5State = "off";
                  digitalWrite(output5, LOW);
                } else if (header.indexOf("GET /4/on") >= 0) {
                  Serial.println("GPIO 4 on");
                  output4State = "on";
                  digitalWrite(output4, HIGH);
                } else if (header.indexOf("GET /4/off") >= 0) {
                  Serial.println("GPIO 4 off");
                  output4State = "off";
                  digitalWrite(output4, LOW);
                }

                // Display the HTML web page
                client.println("<!DOCTYPE html>");
                client.println("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">");
                client.println("<link rel=\"icon\" href=\"data:,\">");
                // CSS to style the on/off buttons
                // Feel free to change the background-color and font-size attributes to fit your preferences
                client.println("");

                // Web Page Heading
                client.println("
ESP8266 Web Server
");

                // Display current state, and ON/OFF buttons for GPIO 5
                client.println("
GPIO 5 - State " + output5State + "
");
                // If the output5State is off, it displays the ON button
                if (output5State=="off") {
                  client.println("
<button class=\"button\">ON</button>
");
                } else {
                  client.println("
<button class=\"button button2\">OFF</button>
");
                }

                // Display current state, and ON/OFF buttons for GPIO 4
                client.println("
GPIO 4 - State " + output4State + "
");
                // If the output4State is off, it displays the ON button
                if (output4State=="off") {
                  client.println("
<button class=\"button\">ON</button>
");
                } else {
                  client.println("
<button class=\"button button2\">OFF</button>
");
                }
                client.println("");

                // The HTTP response ends with another blank line
                client.println();
                // Break out of the while loop
                break;
              } else { // if you got a newline, then clear currentLine
                currentLine = "";
              }
            } else if (c != '\r') {  // if you got anything else but a carriage return character,
              currentLine += c;      // add it to the end of the currentLine
            }
          }
        }
        // Clear the header variable
        header = "";
        // Close the connection
        client.stop();
        Serial.println("Client disconnected.");
        Serial.println("");
      }
    }
Worth noting (while debugging):
The new client disconnects.

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

  [1]: https://wiki.keyestudio.com/KS0367_keyestudio_ESP8266_WiFi_Board
  [2]: https://i.stack.imgur.com/VTXEh.png

title: ESP8266 Webserver not reachable after 2 minutes from reset

Answers: 2

body:
**The short answer: Config a static IP!**

After looking at Git Issue [#2371][1] I found out that I need to create a static IP address to fix this issue. I can do this by inserting `WiFi.config(ip, gateway, subnet)` just before `WiFi.mode(WIFI_STA)` in the code above.

 - First I found the information `gateway` & `subnet` I needed by opening the command prompt on a computer that's connected to the access point(router) as the one connected to the ESP8266 which functions in station mode. I did this on Windows by searching `Command Prompt` then typing `ipconfig` to obtain the following information:

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

**Replace the points with commas!** See [this][3] references for more information regarding other parameters and DNS.

----------

 - To create an IP address you need to see your IP address in the red square in the picture above taken from the command prompt. The first three octects (numbers) of your router IP (probably `10.0.0.x`, `192.168.0.x`, or `192.168.1.x`) must match your chosen static IP. For my example the numbers to match would be `10.0.0`.

 - Next, I needed to obtain the DCHP range for my router. My router is a [Netgear Wireless ADSL2+ Modem Router DG834Gv5][4]. To obtain the range I needed to access my router settings. To access this I looked for an HTTP link under the router. For my router it was `http://10.0.0.2` along with the username and password which was `admin`, `admin` respectively. This is what it looks like:

[![enter image description here][5]][5]

This will vary according to your router - Then I went into Advanced settings and saw the DHCP range. **This is an error on my part noted by @djsfantasi. Please see his answer regarding DHCP range selection.**<strike>The new static IP needs to be within the DHCP range According to one of the comments `brendanmatkin` made in Git Issue [#2371][1] the last number of my static IP (which is `ZZ` in `WW.XX.YY.ZZ`) needs to be **outside** of this range. For me it didn't work, it worked when I used a value **inside** this range but `brendanmatkin` knows much more than me, I'm just a novice. There might be implications that I am not aware of so I think it's worth looking into.</strike> A DHCP range looks like this below:

[![enter image description here][6]][6]

My inserted code looks like this below:

    void setup(void) {
      .
      .
      .
      Serial.begin(115200);
      //WiFi.disconnect();  //Prevent connecting to wifi based on previous configuration
      IPAddress ip(10,0,0,15); // this 3 lines for a fix IP-address
      IPAddress gateway(10,0,0,2);
      IPAddress subnet(255,255,255,0);
      //WiFi.hostname("ESP8266");      // DHCP Hostname (useful for finding device for static lease)
      WiFi.config(ip, gateway, subnet);
      //Station mode:
      WiFi.mode(WIFI_STA);
      .
      .
      .
    }

Please comment for more info :)

**Additional information and changes I've made to IDE:**

OS : Windows 8.1

IDE : Arduino IDE V1.9.8

Board : [Keyes ESP8266][7]

Arduino IDE > Tools >Board (in boards manager) : Generic ESP8266 Board

Arduino IDE > Tools >lwip : V2 Low Memory

Arduino IDE > Tools >Esp FW:"nonos.." : nonos-sdk pr-3(known issues)*

Power Supply : USB COM from 300Watt desktop power supply. ~ 1.5A current output.

Much appreciation to @Juraj.  Juraj

  [1]: https://github.com/esp8266/Arduino/issues/2371
  [2]: https://i.stack.imgur.com/2iNxr.png
  [3]: https://arduino-esp8266.readthedocs.io/en/latest/esp8266wifi/station-class.html#config
  [4]: https://www.downloads.netgear.com/files/GDC/DG834GV5/DG834Gv5_UM_11Mar10.pdf
  [5]: https://i.stack.imgur.com/9EU2Q.png
  [6]: https://i.stack.imgur.com/r5l3W.png
  [7]: https://wiki.keyestudio.com/KS0367_keyestudio_ESP8266_WiFi_Board

body:
It worked when the IP was in the range because there are no valid IP addresses outside the range.

WW.XX.YY.0 and WW.XX.YY.255 are reserved. The router is using the .1 and .2 addresses. That leaves 3-254 available, which as we see are the addresses within the DHCP range.

You can assign a static IP address within the DHCP range, but you run the risk of disabling 1 or 2 devices. DHCP doesn’t know you’ve used one of it's addresses, so can assign it to another device. Boom! Two devices with the same address and both will not function.

The correct way to resolve this is to log into the router and change the DHCP range. For example, increase the lower limit of 3 to (random pick) 20. Now, DHCP won’t be disturbed and will happily give out addresses to your devices. But if you need a static IP address, you’ve defined a pool, from WW.XX.YY.3 to WW.XX.YY.19


body:
I am working on a final project called sound source localization using Arduino Uno. I want to use two sound sensor to capture a sound. The nature of the sound is clap or speech sound. I want to use the cross correlation method to estimate the time delay between the microphones then find the position and angle. My supervisor said to me you have to store the values on analogRead in two arrays then cross correlation the element of two arrays. But i am struggle the cross correlation part. I will appreciate any help from you guys.

```c++
#define LED_NORTH 2
#define LED_SOUTH 4

#define MIC_NORTH A0
#define MIC_SOUTH A2

/* let's said we want to read 100 samples */
const unsigned int numReadings = 100;
unsigned int analogVals[numReadings];
unsigned int i = 0;

void setup() {
  Serial.begin(115200);
  pinMode(LED_NORTH, OUTPUT);
  digitalWrite(LED_NORTH, LOW);
  pinMode(LED_SOUTH, OUTPUT);
  digitalWrite(LED_SOUTH, LOW);
}

void loop() {
  int north = analogRead(MIC_NORTH);
  Serial.println(north);
  int south = analogRead(MIC_SOUTH);
  Serial.println(south);
  /* take numReadings # of readings and store into array */
  for(unsigned int i = 0; i < numReadings; i++)
  {
    analogVals[i] = analogRead(A0);
    delay(1000);
  }
```

title: cross correlation of two analogread value on arduino?

Answers: 1

body:
I am not going to directly answer the question, as I think it is
ill-posed. Before posting a question here, you are supposed to have done
your research, and come with very _specific_ problems you cannot solve
by your own. I may be mistaken, but it looks to me like you are at a
very preliminary stage where you barely started to _think_ about the
project.

So, instead of trying to answer an overly broad question, I will try to
provide some guidance by asking questions back to you. Below is a list
of some problems and challenges you will have to consider for advancing
your project. It may not be complete: it's just what I can think off the
top of my head. This will hopefully help you tackle the right problems.

## Non-stereo sampling

Your Arduino is incapable of stereo sampling. Since it has only one ADC,
it can only sample one channel at a time. This means you will have to
alternatingly sample the left channel, then the right channel, then the
left channel... Since the left and right samples are not taken at the
same time, this will have an implication on how you interpret the
results from the cross-correlation. Did you think about how you will
handle this? Is this acceptable? Will you have to instead use external
ADC chips in order to have real stereo sampling?

## Slow sampling rate

If you `analogRead()` in a tight loop, you are taking at most one sample
every 112 µs. And since you are alternating between the channels,
on each channel you get one sample every 224 µs. This is a sampling
rate of 4.46 kHz, and a Nyquist frequency of 2.23 kHz. Is this
fast enough for your application?

In 224 µs, the sound travels about 76 mm, which is thus the
spatial resolution of your cross-correlation. How does this translate into
angular resolution? Is this resolution satisfactory? Do you plan to use
interpolation methods to try to improve it?

If the time resolution is not good enough, you can speed up the ADC by a
factor 2 or 4 at the cost of lowered accuracy. You will have to dig on
the MCU datasheet (or the Internet...) in order to learn how to do that.

## Inconsistent sampling rate

When you use `analogRead()`, the time between consecutive samples can
depend on the code you run between the consecutive calls to
`analogRead()`. It can also depend on how your code gets interrupted by,
say, the timer interrupt, or the UART interrupt if you are sending data
out. An inconsistent sampling rate is something you want to avoid when
doing cross-correlations.

You could try to mitigate this problem by running the acquisition with
interrupts disabled. However, the only way to guarantee periodic
sampling is by configuring the ADC to be triggered automatically, either
by a timer or by itself (free running mode). Walking this path will
require you to forego the comfort of the Arduino library (`analogRead()`
is just so easy to use...), and carefully study the datasheet, which
would be a very significant time investment.

Do you have the time and energy for this? If you end up learning all
this low-level details on the configuration of the ADC, will this
learning be relevant to the course for which this is a project?

## Finite data arrays

Mathematically, the cross-correlation is typically defined for infinite
series of samples. In your experiment, you will have to deal with finite
arrays, and this makes a subtle difference. Did you think about how you
will deal with the finiteness of the arrays? Are you going to zero-pad?
Remove the average before zero-padding? Apply a windowing function?

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

I hope it is clear by now that the “cross correlation part” is only one
of the many issues you will have to face. I suggest you discuss all
these questions with your supervisor. He might be able to advise you on
how to tackle them, whether it's worth it, where you may cut corners...


body:
There is a problem running a simple SPIFFS file system code on different versions of the Arduino IDE, as code shown below. In Arduino IDE version 1.8.4, works fine. No longer version 1.8.9, can not run.
ESP8266
IDE Arduino version 1.8.9

    #include <FS.h>

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

      // Always get ERROR on init SPIFFS
      if (!SPIFFS.begin()) {
        Serial.println("SPIFFS.begin error...");
      } else {
        Serial.println("SPIFFS.begin OK!");
      }
    }

title: Error Starting SPIFFS

Answers: 0


body:
I'm trying to make a Google Assistant controlled LED strip, but I'm stuck. I can control the on board LED of the nodemcu with Google Assistant, and I can control a LED strip too, but I can't combine the two. This is my code:
<!-- language-all: lang-cpp -->

    #define WIFI_NAME "****************"
    #define WIFI_PASSWORD "********"
    #define DEVICE_ID 1
    #define DEVICE_NAME "Google_ESP"
    #define TOKEN "************"

    #define FASTLED_ESP8266_NODEMCU_PIN_ORDER
    #include "FastLED.h"

    #include <RemoteMe.h>
    #include <RemoteMeSocketConnector.h>

    #include <ESP8266WiFi.h>

    #define ledpin D0

    RemoteMe& remoteMe = RemoteMe::getInstance(TOKEN, DEVICE_ID);

    //*************** CODE FOR CONFORTABLE VARIABLE SET *********************

    inline void setLedstrip(boolean b) {remoteMe.getVariables()->setBoolean("Ledstrip", b); }

    //*************** IMPLEMENT FUNCTIONS BELOW *********************

    // How many leds in your strip?
    #define NUM_LEDS 120

    // For led chips like Neopixels, which have a data line, ground, and power, you just
    // need to define DATA_PIN.  For led chipsets that are SPI based (four wires - data, clock,
    // ground, and power), like the LPD8806 define both DATA_PIN and CLOCK_PIN
    #define DATA_PIN D3

    CRGB leds[NUM_LEDS];

    boolean ledsOn = 0;

    void onLedstripChange(boolean b) {
        Serial.printf("onLedstripChange: b: %d\n",b);

        if(ledsOn != b){
            if(b == 1){
                turnLedsOn();
            }
            else{
                turnLedsOff();
            }

            ledsOn = b;
        }
    }

    void setup() {
        FastLED.addLeds<WS2812B, DATA_PIN, RGB>(leds, NUM_LEDS);

        Serial.begin(9600);

        WiFi.begin(WIFI_NAME, WIFI_PASSWORD);

        while (WiFi.status() != WL_CONNECTED) {
            delay(100);
        }

        remoteMe.getVariables()->observeBoolean("Ledstrip" ,onLedstripChange);

        remoteMe.setConnector(new RemoteMeSocketConnector());
        remoteMe.sendRegisterDeviceMessage(DEVICE_NAME);

        pinMode(ledpin, OUTPUT);
        digitalWrite(ledpin, HIGH);
    }

    void loop() {
      remoteMe.loop();
    }

    void turnLedsOn(){
      digitalWrite(ledpin, LOW);
      leds[0] = CHSV(0, 100, 100);
      FastLED.show();
    }

    void turnLedsOff(){
      digitalWrite(ledpin, HIGH);
      leds[0] = CHSV(0, 0, 0);
      FastLED.show();
    }

As you can see, it should turn on the on board LED and the first LED of the strip. It only does the on board one.

title: Can't get fastled.h and remoteme.h to work together

Answers: 0


body:
I am trying to combine the two sensors (pulse sensor using [this library][1] and LM35 temp)(on a Arduino UNO board),but there is a problem with them when is a noise at the pulse sensor .The values are fluctuates especially the LM35 it goes from 31 degrees (normal value ) to 25-50 and even the pulse one changes .

Here are the [results](https://i.stack.imgur.com/jG9ec.jpg) .

The code is this(I got the code form the  Getting_BPM_to_Monitor sketch ) :
```
#define USE_ARDUINO_INTERRUPTS true    // Set-up low-level interrupts for most acurate BPM math.
#include <PulseSensorPlayground.h>     // Includes the PulseSensorPlayground Library.

const int sensor = A5; // Assigning analog pin A5 to variable ‘sensor’
float tempc; //variable to store temperature in degree Celsius
float vout; //temporary variable to hold sensor reading
//  Variables
const int PulseWire = 0;       // PulseSensor PURPLE WIRE connected to ANALOG PIN 0
const int LED13 = 13;          // The on-board Arduino LED, close to PIN 13.
int Threshold = 550;           // Determine which Signal to "count as a beat" and which to ignore.
// Use the "Gettting Started Project" to fine-tune Threshold Value beyond default setting.
// Otherwise leave the default "550" value.

PulseSensorPlayground pulseSensor;  // Creates an instance of the PulseSensorPlayground object called "pulseSensor"
void setup() {
  Serial.begin(9600);          // For Serial Monitor
  // Configure the PulseSensor object, by assigning our variables to it.
  pulseSensor.analogInput(PulseWire);
  pulseSensor.blinkOnPulse(LED13);       //auto-magically blink Arduino's LED with heartbeat.
  pulseSensor.setThreshold(Threshold);
  // Double-check the "pulseSensor" object was created and "began" seeing a signal.
  if (pulseSensor.begin()) {
    Serial.println("We created a pulseSensor Object !");  //This prints one time at Arduino power-up,  or on Arduino reset.
  }
}

void loop() {
  int temp = analogTemp();
  Serial.print(temp);
  Serial.println("Temp");

  if (pulseSensor.sawStartOfBeat()) {            // Constantly test to see if "a beat happened".
    // Serial.println("♥  A HeartBeat Happened ! "); // If test is "true", print a message "a heartbeat happened".
    int myBPM = pulseSensor.getBeatsPerMinute();  // Calls function on our pulseSensor object that returns BPM as an "int".
    // "myBPM" hold this BPM value now.
    Serial.print("BPM: ");                        // Print phrase "BPM: "
    Serial.print(myBPM);                        // Print the value inside of myBPM.
    Serial.println(" A HeartBeat Happened ! ");
  }
  delay(20);                    // considered best practice in a simple sketch.
}
float analogTemp() {
  vout = analogRead(sensor);
  vout = (vout * 500) / 1023;
  return vout; // Storing value in Degree Celsius

}
```

  [1]: https://github.com/WorldFamousElectronics/PulseSensorPlayground

title: Can't get the right values with the pulse sensor and the LM35 temperature sensor . Reading 2 anolog sesnors

Answers: 0


body:
I have successfully installed "Eclipse C++ IDE for Arduino" and the Plugin works fine. Now I installed a custom board (ESP32) by adding package_index.json URL in windows>prefrences>C/C++>Arduino. The board installed and also work fine.
The only problem I'm facing is that I'm unable to import platform SDKs and libraries.(e.g. #include "driver/adc.h") which are present in the path: G:\program\eclipse\.arduinocdt\packages\esp32\hardware\esp32\1.0.2\tools\sdk\include
I just want to import files just like in the Arduino IDE.

Eclispse version :
Eclipse IDE for C/C++ Developers
Version: 2019-03 (4.11.0)
Build id: 20190314-1200

Thank You

title: Cannot import library file from ESP32 sdk library in "Eclipse C++ IDE for Arduino" project

Answers: 0


body:
I need help with my LCD. I have a 20x4 LCD and it shows up as 20x2. The LCD address said "// Set the LCD address to 0x27 for a 16 chars and 2 line display". I changed it which says "// Set the LCD address to 0x27 for a 20 chars and 4 line display" and uploaded it, thinking it would show up as 20x4 as it should. But it didn't work:

[![Photo of the issue][1]][1]

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

title: 20x4 LCD shows up as 20x2

Answers: 1

body:
Nori, just ignore every code that's after the //, they are just comments and the compiler will just discard them.

Look at the LCD rear, you should see your I2C chip, search google typing
["chip's code"  20x4 arduino]. You'll see which I2C address you most likely need to use. For instance, the PCF8574 has addresses fromm 0x20 to 0x27, the PCF8574A has addresses from 0x38 to 0x3F...

Without this info you are only shooting blindfolded, the 0x27 it's only the "standard" address of the most common PCF8574 module but there are plenty of modules.

Another way to find the address is to upload [this code][1], it's an I2C scanner that will write on the serial monitor any I2C device that replies a "ping" signal.

If you find the address and still it doesn't work or if you can't find the address, check and double and triple check the wiring, especially the false contact.

  [1]: https://playground.arduino.cc/Main/I2cScanner/


body:
I have a problem similar to these questions:

https://arduino.stackexchange.com/questions/52945/wemos-d1-doesnt-drive-relay

https://arduino.stackexchange.com/questions/65941/wemos-d1-is-not-triggering-relay

I got this BC548B transistor from an old apparatus I scratched. The transistor saturation voltage is 0.6V  according to the datasheet:

https://alltransistors.com/pdfdatasheet_fairchild_semi/bc548_bc548a_bc548b_bc548c.pdf

When I set up my circuit the wemos d1 inboard leds dim and the board resets so I guess something is going really wrong. Can someone advise if my design makes sense?

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

UPDATE
======

I replaced the 12V relay with a 5V one but still can't get it to work. Basically, the 3.3V signal seems to be too low to activate the solenoid. How can I raise the 3V3 signal to 5V? What was wrong with my idea of using a transistor to do it?

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

  [1]: https://i.stack.imgur.com/zA0i3.png
  [2]: https://i.stack.imgur.com/WqbGB.png

title: Activating a Relay with Wemos D1

Answers: 1

body:
That appears to be a 12 "solid state" relay. That means that it is designed to be both powered by and switched by 12V. You're trying to drive it with slightly more than 1/3 of its rated voltage. Don't do that.

## Edit:
Note that none of the relays being discussed are true solid state relays. These are are all conventional coil relays that include cicuitry that allows them to be driven by CMOS logic signals. A true solid state relay does not have any moving parts, but uses solid state components to do the job of a relay. Those cost significantly more money however.)

----
It might be that you can get away with driving a 5V solid state relay with 3.3V, or 12V relay with 5V, but you shouldn't do those things either.

Also note that even if you are using the correct relay, your relay almost certainly takes more current than the 5V pin on an Arduino can provide (When driven from USB, the entire system is limited to 500 mA, including the power needed to the Arduino.)

## Edit:

These solid state relays come in 12V, 5V, and 3V flavors. Get a 3V one: https://www.adafruit.com/product/3191?gclid=EAIaIQobChMIyY_dxM344gIVELbICh1ufwivEAQYBSABEgI3wPD_BwE