message:
How to Home a stepper and make it move 45 degree after that

I am trying to let a stepper find home (via microswitch) after power up. After that make it move 45 degrees (or the equivalent in steps) and wait for 3 seconds. Below is the code i found/adapted.

The setup part kind of works, but does not run smoothly.

The stepper1() part does not work at all (only jerking movements).

I would also like the motor to be disable when it waits which in my understanding should be achieved by `digitalWrite(M2en,HIGH);`but when I place this at the beginning and end (LOW, HIGH) of stepper1() it never worked. Any ideas would be great.

    #include "AccelStepper.h"

    int M2dirpin = 4;  //Motor Y direction pin
    int M2steppin = 5; //Motor Y step pin
    int M2en=12;  //Motor Y enable pin
    #define home_switch 9 // Pin 9 connected to Home Switch (MicroSwitch)

    // AccelStepper Setup
    AccelStepper stepperX(1, 5, 4);   // (1,2,3) = (Dedicated Board, STEP, DIR)
    // Stepper Travel Variables
    long initial_homing = -1; // Used to Home Stepper at startup

    void setup() {

      pinMode(home_switch, INPUT_PULLUP);
      pinMode(M2dirpin,OUTPUT);
      pinMode(M2steppin,OUTPUT);
      pinMode(M2en,OUTPUT);
      digitalWrite(M2en,LOW);
      Serial.begin(9600);  // Start the Serial monitor with speed of 9600 Bauds
      stepperX.setMaxSpeed(50.0);      // Set Max Speed of Stepper (Slower to get better accuracy)
      stepperX.setAcceleration(50.0);  // Set Acceleration of Stepper

      // Start Homing procedure of Stepper Motor at startup
      Serial.print("Stepper is Homing . . . . . . . . . . . ");

      while (digitalRead(home_switch)) {  // Make the Stepper move CCW until the switch is activated
        stepperX.moveTo(initial_homing);  // Set the position to move to
        initial_homing--;  // Decrease by 1 for next move if needed
        stepperX.run();  // Start moving the stepper
        delay(20);
      }

      stepperX.setCurrentPosition(0);  // Set the current position as zero for now
      stepperX.setMaxSpeed(50.0);      // Set Max Speed of Stepper (Slower to get better accuracy)
      stepperX.setAcceleration(50.0);  // Set Acceleration of Stepper
      initial_homing = 1;

      while (!digitalRead(home_switch)) { // Make the Stepper move CW until the switch is deactivated
        stepperX.moveTo(initial_homing);
        stepperX.run();
        initial_homing++;
        delay(20);
      }

      stepperX.setCurrentPosition(0);
      Serial.println("Homing Completed");
      Serial.println("");

     // Move 10 steps forward from the limit switch (to get out of the switch)
      while (stepperX.currentPosition() != 10)
      {
        stepperX.setSpeed(10);
        stepperX.run();

    }
    }
    void loop()
    {
    //stepper1();
    }

    void stepper1()
    {
      stepperX.move(22.5);
      stepperX.run();
      delay(3000);
    }

body:
You need to call `run` more often. From the [documentation](http://www.airspayce.com/mikem/arduino/AccelStepper/classAccelStepper.html#a608b2395b64ac15451d16d0371fe13ce):

> You must call this as frequently as possible, but at least once per minimum step time interval, preferably in your main loop. Note that each call to run() will make at most one step, and then only when a step is due, based on the current speed and the time since the last step.

So a single `run` call and then a delay, will make the motor move only one step. So you need to rewrite for example:

    stepperX.run();
    delay(3000);

to

    unsigned long startMillis = millis();
    while( millis()-startMillis<3000 )
    {
      stepperX.run();
    }

Secondly, `move` only works on integers, `stepperX.move(22.5);` will actually become `stepperX.move(22);`

Lastly, why are you using a totally different method from the rest, to move the motor 10 steps? I'd use a moveTo(10), like you are using everywhere else.


sender: user

message:
DHT 11 temp. And hum. Sensor always 0 values

![DHT11](https://i.stack.imgur.com/eiCeu.jpg)

I am trying to get my DHT 11 from the official arduino store to work (https://store.arduino.cc/grove-temperature-humidity-sensor).

I am following this guide right here:
http://wiki.seeedstudio.com/Grove-TemperatureAndHumidity_Sensor/

But I'm only getting invalid output of 0 humidity and 0 degrees.

I hope the image helps in identifying my problem.

On a side note, my sensor looks like a part is missing which is very strange and makes me doubt the right product was sent to me.

Some more information:
- Black to GND
- Red to 5v
- White is wmpty
- Yellow to d2
- Using an arduino Uno
- Output does not change whether the sensor is actually connect or not.
- Total noob at this.

Help would be appreciated a lot!

![sensor detail](https://i.stack.imgur.com/MERWr.jpg)

sender: assistant

body:
You haven't bought a DHT11 module but the *Grove - Temperature&Humidity Sensor (High-Accuracy & Mini) / TH02* module.

![module](https://camo.githubusercontent.com/2d556d0497a63f9ecdab0cd23bc7a05eaa0bd43b/68747470733a2f2f73746174696373332e736565656473747564696f2e636f6d2f696d616765732f70726f647563742f47726f766525323054656d25323048756d25323041636375726163792532304d696e692e6a7067)

Thus you should use the example code [here](https://github.com/Seeed-Studio/Grove_Temper_Humidity_TH02) or follow the guide at [seedstudio wiki](http://wiki.seeedstudio.com/Grove-TemptureAndHumidity_Sensor-High-Accuracy_AndMini-v1.0/).

Datasheet of the sensor: https://www.silabs.com/documents/public/data-sheets/Si7005.pdf


message:
How to read a 25 kHZ PWM signal from PC fan header?

I would like to control a DC motor's speed using the PWM output from my motherboard header.

Here's the standard pinout for a 4-wire PC fan header:

```
╔═══╦════════╦═════════════════╦════════╗
║ # ║  Name  ║   Description   ║  Wire  ║
╠═══╬════════╬═════════════════╬════════╣
║ 1 ║ GND    ║ Ground          ║ black  ║
║ 2 ║ +12V   ║ Fan Power       ║ yellow ║
║ 3 ║ SIGNAL ║ Fan RPM         ║ green  ║
║ 4 ║ PWM    ║ Digital Control ║ blue   ║
╚═══╩════════╩═════════════════╩════════╝
```

Since my DC motor doesn't have a PWM input, I thought of using an `ATmega328P` in my custom board to read the PWM output of the fan header -- pin 4 -- so that I can use a motor driver to control my motor's speed.

However, I'm not sure how I should read the PWM signal from the motherboard.

1. What is the `HIGH` voltage level of PWM output?
   Do I need a voltage divider resistor for it?

   A source for the fan control specifies this to be **5.25V** at maximum, but since I haven't tested it out myself, I don't want to risk feeding a 12V signal to my microcontroller's input lines.

2. Should I use [`pulseIn()`][1] function for the 25kHZ (21~28kHZ range) PWM output?
   Can the ATmega328p handle this frequency range?

I prefer to use Arduino's bootloader with the wiring library, but if you have AVR-specific examples that I could follow, I'd appreciate it.

  [1]: https://www.arduino.cc/en/Reference.PulseIn

body:
> Should I use pulseIn() function for the 25kHZ (21~28kHZ range) PWM output?
Can the ATmega328p handle this frequency range?

No, and No; 1/25000 = .000040 or 40 microseconds (μS) and the [documentation][1] for pulseIn() says:

> Works on pulses from 10 microseconds to 3 minutes in length

However the PWM frequency is the maximum on time, at 50% you will have a square wave that is HIGH for 20 μS and low for 20 μS. pulseIn will not work if the PWM duty cycle goes below 25%

What you want to do is put an 'accumulator' (an RC filter) between the PWM output and an analog input pin, and read the voltage off of that.

However since you want to

> ... control a DC motor's speed using the PWM output from my motherboard header

and the fanspeed header is already designed to do this, you just use the PWM signal to drive a transistor that drives the motor, the motor itself will act as an accumulator here; no micro controller needed!

> ... so that I can use a motor driver to control my motor's speed.

you will need to generate an extremely similar, almost certainly identical, PWM signal to drive your motor controller/driver

> A source for the fan control specifies this to be 5.25V at maximum, but since I haven't tested it out myself, I don't want to risk feeding a 12V signal to my microcontroller's input lines.

Trust your documentation or test it if you don't trust the docs!

  [1]: https://www.arduino.cc/reference/en/language/functions/advanced-io/pulsein/


message:
No matching function call for timer?

I am using the Timer library here with the Adafruit feather m0:
https://github.com/JChristensen/Timer
https://playground.arduino.cc/code/timer
I cannot figure out why I am getting the error:

no matching function for call to 'Timer::every(int, void (&)())'

Here is that part of the code:

    void setup(){
          everyAlt = t.every(100, readAltimeter);
          everyLaunch = t.every(500, detectLaunch);
          t.oscillate(blueled, 500, HIGH);
        }

        void readAltimeter(){
          alts[altPlace] = bmp.readAltitude()-zeroAlt;
          altPlace++;
        }

        void detectLaunch(){
          tempSpeed = 0;
          int x = 0;
          while (x < 5){
            tempSpeed += abs((alts[x]-alts[x+1])*10);
          }
          if (tempSpeed/5 > 5){
            t.stop(everyLaunch);
          }
        }

I am pretty new to arduino so any help would be much appriciated!

body: Had the wrong version. Correct version downloaded from the current master: github.com/JChristensen/Timer


message:
Question on a car kit I bought

recently bought an UNIROI Smart Car kit.
(UNIROI Smart Robot Car Kit Arduino Robot Kit with 4 Wheel Drive, Arduino UNO R3 Board, Ultrasonic Sensor, Infrared Tracking Module (No Welding Required) https://www.amazon.co.uk/dp/B07CWS344R/ref=cm_sw_r_cp_tai_wQExCbHT0YM8K)

I bought some extra things with it to make it more interesting, but the problem is is that I need to connect more pins to the Arduino but they are all taken up by the car. What I have noticed is that there are these extra pins along the side of the Arduino board as you can see here: https://i.stack.imgur.com/7nhBO.jpg

I know you guys don’t have it in hand, but I thought I’d give it a shot to see if any of you know I can use those pins.
The description of the car also quotes
“Extended Pin Interface. The chassis is designed with
extended pin interface for Arduino UNO, only need to solder pins for using, more convenient to develop
and build your own robot car kit”

Appreciate any help you guys got.

body:
It seems that you'll have to do some extended modifications to the design. In fact, all Arduino Pins (D0 - D13, A0-A5) are connected to components on the board and thus in use.

Schematics and Code: https://mega.nz/#F!Xbg1FA5L!qGah_HlLFJ_NKxv7ILLY2g folder "5 SCH".

[![schem][1]][1]

This means that the only way that you'll get new components into this project are:

* removing components  and re-programming the firmware to not use them
 * e.g., the two tracking-sensors left&right -> A2 and A3 are free
 * e.g., the speaker pin (D13). Who needs a speaker?
* restructuring components
   * e.g. for the analog sensors: instead of using the Arduino's analog pins, throw a I2C ADC module (e.g. [ADS1115](https://www.adafruit.com/product/1085)) in the build and change the firmware to get the analog values via that new module; making this project use an I2C bus will free all analog pins and cost 2 pins (SCL + SDA). The I2C bus has the additional benefit of being able to connect more than one device to it -- you can e.g. put a I2C GPIO expander (e.g. MCP23017) on it to gain 16 more digital I/O -- more than the Uno had to begin with.

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


message:
Does Arduino Uno come with Virtual Pin support?

I want to recieve Data with Virtuino from my Arduino Uno 3 (Ethernet Shield) via Ethernet.

Does Arduino Uno 3 support virtual pin? If so - is there a link with the Syntax I need?

Thank you very much

body:
Virtual pins are, as the name gives away, *virtual*, thus not related to the hardware you are using. Imagine you have a board with 100 pins, you have 100 physical pins and can add 1 million virtual pins (memory permitting).
In other words, the question doesn't seem to make sense to me.

**UPDATE**
If you need a bootstrap on *how* virtual pins are defined and used you could give a look at the examples published by the authors, like [these][1]

If that's not enough, please provide additional information on what problem you are facing and which solutions you have already attempted.

  [1]: https://virtuino.com/downloads/examples/bluetooth_example_03_virtual_memory.zip


message:
nRF24L01 using sender as receiver and vice versa with RF24 library

I have two nRF24L01 modules (I tried 2 with antenna and 2 without antenna) paired with their power base module and connected to two different Arduino Mega 2560 boards.
I'm able to send from one module to another up to 32 byte of data and get the acknowledge without any problems. But when I switch them, when I try to send data from receiver and receive it on the sender I have nothing. No data received, no acknowledge sent as response.

As I said before, first part of this code works well, but when it comes to the second part, which is after `delay(1000);` there's silence...

my code is:

**Receiver**

    #include <RF24.h>
    #include <RF24_config.h>
    #include <SPI.h>
    #include "printf.h"

    // Set pipes
    const uint64_t pipe01_ = 0xE8E8F0F0A1LL;
    const uint64_t pipe02_ = 0xE8E8F0F0A2LL;
    const uint64_t pipe03_ = 0xA3LL;
    const uint64_t pipe04_ = 0xA4LL;
    const uint64_t pipe05_ = 0xA5LL;
    const uint64_t pipe06_ = 0xA6LL;

    RF24 radio(9, 53);

    void setup()
    {
        Serial.begin(115200);
     delay(250);
     radio.begin();
     radio.setChannel(0x57);
     radio.setPALevel(RF24_PA_LOW);
     radio.enableAckPayload();
     radio.openReadingPipe(1, pipe01_);
     radio.openWritingPipe(pipe02_);
     radio.enableDynamicPayloads();
     radio.startListening();
    }

    void loop()
    {
        if (radio.available())
        {
         char newMessage[33];
            memset(newMessage, 0, sizeof(byte) * 33);
            while (radio.available())
            {radio.read(newMessage, 32);}

            Serial.println("newMessage: " + String((const char*)newMessage));
            delay(1000);
            radio.stopListening();

            char response[32] = "1234567890qwertyuiopasdfghjklzxc";
            radio.write(response, 32);
         unsigned long ack = 0;
         if (radio.isAckPayloadAvailable())
         {
          radio.read(&ack, sizeof(ack));
                Serial.println("ack: " + String(ack));
         }
            radio.startListening();
        }
    }

**Sender**

    #include <RF24.h>
    #include <RF24_config.h>
    #include <SPI.h>
    #include "printf.h"
    // Set pipes
    const uint64_t pipe01_ = 0xE8E8F0F0A1LL;
    const uint64_t pipe02_ = 0xA2LL;
    const uint64_t pipe03_ = 0xA3LL;
    const uint64_t pipe04_ = 0xA4LL;
    const uint64_t pipe05_ = 0xA5LL;
    const uint64_t pipe06_ = 0xA6LL;

    RF24 radio(9, 53);

    void setup()
    {
        Serial.begin(115200);
        delay(250);
        radio.begin();
        radio.setChannel(0x57);
        radio.setPALevel(RF24_PA_LOW);
        radio.enableAckPayload();
        radio.openReadingPipe(2, pipe02_);
        radio.openWritingPipe(pipe01_);
        radio.enableDynamicPayloads();
        radio.stopListening();

        char message[32] = "qwertyuiopasdfghjklzxc1234567890";
        radio.write(message, 32);

        radio.startListening();
    }

    void loop()
    {
        if (radio.available())
        {
            char respMessage[33];
            memset(respMessage, 0, sizeof(byte) * 33);
            while (radio.available())
            {radio.read(respMessage, 32);}

            Serial.println("respMessage: " + String((const char*)respMessage));
        }
    }

Please help me.

body:
**Update:** It was working yesterday, but today... same thing as with "delay()". What's wrong with these radio-modules??

I have discovered that the `delay()` function was causing this abnormal behavior.

So I have implemented periods instead of `delay()` and now I'm able to switch operating mode between "receiver" and "transmitter". Moreover, I have discovered few additional conditions that must be met (read the comments for the code).

Below is working sample code where transmitter sends some large message. Receiver gets it, waits 2 secs, then responds with another large message and gets the acknowledge for this message:

**Sender**

    #include <RF24.h>
    #include <RF24_config.h>
    #include <SPI.h>
    #include "printf.h"
    const uint64_t pipe01_ = 0xE8E8F0F0A1LL; //Writing pipe must be full address if acknowledges will be used
    const uint64_t pipe02_ = 0xE8E8F0F0A2LL; //At least one of reading pipes must be full adress
    const uint64_t pipe03_ = 0xA3LL;
    const uint64_t pipe04_ = 0xA4LL;
    const uint64_t pipe05_ = 0xA5LL;
    const uint64_t pipe06_ = 0xA6LL;
    RF24 radio(9, 53);

    void setup()
    {
        Serial.begin(115200);
        delay(250);
        radio.begin();
        radio.setChannel(0x57); //not necessary. But must be equal at both sides
        radio.setPALevel(RF24_PA_LOW); //not necessary. But must be equal at both sides
        radio.enableAckPayload(); //For ability to change the Ack Payload with writeAckPayload()
        radio.openReadingPipe(2, pipe02_); //At least one of reading pipes must be full adress
        radio.openWritingPipe(pipe01_); //Writing pipe must be full address if acknowledges will be used
        radio.enableDynamicPayloads(); //If not set, size will be of fixed length. Default fixed length is 32 bytes

        /*Must run this if "startListening()" will be used anywhere in the code below.
        nRF24L01 remembers it's state even if Arduino was restarted*/
        radio.stopListening();
        Serial.println("Sending the message...");
        char message[32] = "qwertyuiopasdfghjklzxc1234567890"; //some test message
        radio.write(message, 32); //Send message over the predefined "writing pipe"

        Serial.println("Waiting for response...");
        radio.startListening(); //Resets TX buffer and switches radio module's mode to "receiver"

        uint16_t ack = 123;
        radio.writeAckPayload(2, &ack, sizeof(ack)); //Custom ACK payload must be set after "startListening()". Because "startListening()" resets TX buffer
    }

    void loop()
    {
        if (radio.available())
        {
            char respMessage[33];
            memset(respMessage, 0, sizeof(byte) * 33);
            while (radio.available())
            {radio.read(respMessage, 32);}

            Serial.println("respMessage: " + String((const char*)respMessage));
     }
    }

**Receiver**

    #include <RF24.h>
    #include <RF24_config.h>
    #include <SPI.h>
    #include "printf.h"

    #define period_  2000

    // Set pipes
    const uint64_t pipe01_ = 0xE8E8F0F0A1LL; //At least one of reading pipes must be full adress
    const uint64_t pipe02_ = 0xE8E8F0F0A2LL; //Writing pipe must be full address if acknowledges will be used
    const uint64_t pipe03_ = 0xA3LL;
    const uint64_t pipe04_ = 0xA4LL;
    const uint64_t pipe05_ = 0xA5LL;
    const uint64_t pipe06_ = 0xA6LL;

    unsigned long checkPoint = 0;
    bool messageReceived = false;
    RF24 radio(9, 53);

    void setup()
    {
     Serial.begin(115200);
     delay(250);
     radio.begin();
     radio.setChannel(0x57); //not necessary. But must be equal at both sides
     radio.setPALevel(RF24_PA_LOW); //not necessary. But must be equal at both sides
     radio.enableAckPayload(); //For ability to change the Ack Payload with writeAckPayload()
     radio.openReadingPipe(1, pipe01_); //At least one of reading pipes must be full adress
     radio.openWritingPipe(pipe02_); //Writing pipe must be full address if acknowledges will be used
     radio.enableDynamicPayloads(); //Writing pipe must be full address if acknowledges will be used
     radio.startListening(); //If not set, size will be of fixed length. Default fixed length is 32 bytes
    }

    void loop()
    {
     if (radio.available())
     {
      char newMessage[33];
      memset(newMessage, 0, sizeof(byte) * 33);
      while (radio.available())
      {radio.read(newMessage, 32);}

      Serial.println("newMessage: " + String((const char*)newMessage));
      checkPoint = millis();
      messageReceived = true;
     }

     unsigned long timePassed = millis() - checkPoint;

     //When it receives, controller waits for 2 seconds then sends the response just one time
     if (messageReceived && timePassed > period_)
     {
      messageReceived = false;
      checkPoint = millis();
      Serial.println("sending response...");

      //This must be called before sending anything (except acknowledges)
      radio.stopListening(); //Resets TX buffer and switches radio module's mode to transmitter

      char response[32] = "1234567890qwertyuiopasdfghjklzxc";
      radio.write(response, 32);

      unsigned long ack = 0;
      if (radio.isAckPayloadAvailable())
      {
       radio.read(&ack, sizeof(ack));
       Serial.println("ack received: " + String(ack));
      }

      radio.startListening(); //Resets TX buffer and switches radio module's mode to "receiver"
     }
    }


message:
I want to get incomming call number and compare it

Hello i want to get and compare incomming call number, it works but not as I want.
When im calling from good number it print that I was calling form saved number when the number is stop calling i need to do it on start. And `else` is printing when nobody is calling. How can i do it? Here is my code:

    String d = "";
    void setup()
    {
      Serial.begin(9600);
      Serial1.begin(9600);
      Serial1.println("AT");
      delay(500);
      Serial1.println("AT+CLIP=1");
      delay(1000);
      Serial1.println("AT+CPIN=1439");
    }
    void loop()
    {
     d = Serial1.readString();
     if(d.indexOf("xxxxxxxxx") >=0)
       {
     Serial.println("call is from saved number");
        } else {
           Serial.println("call is not from saved number");
          }
    }

body:
The Arduino Serial class member function [`readString()`][1] has a builtin timeout. The function will return on timeout. The default timeout period is 1000 ms. The timeout can be set with [`setTimeout()`][2].

The sketch needs to filter out empty lines (timeout). This can be done by adding a check of the string length. See below for an example of checking:

    void loop()
    {
      String d = Serial1.readString();
      if (d.length() == 0) return;
      Serial.print(d);
      if (d.indexOf("xxxxxxxxx") >= 0) {
        Serial.println(": call is from saved number");
      }
      else {
        Serial.println(": call is not from saved number");
      }
    }

Cheers!

  [1]: https://www.arduino.cc/en/Serial/ReadString
  [2]: https://www.arduino.cc/en/Serial/SetTimeout


message:
Use 2 DHT22 AND PASS THE DATA TO SD?

I have the code to pass the data from dht22 to sd but for only one and i want to pass the data from 1 dht22 with one file and the data from other sensor to other file and logging in to sd. Anyone can help me?

```
#include
#include
#include "DHT.h"
#define DHTPIN 8
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);
File data_file;

int CS_pin = 10;
long sec=00;
long mint=00;
long hr=00;

void setup() {
Serial.begin(9600);
pinMode(CS_pin, OUTPUT);
dht.begin(); //This command will start to receive the values from dht22
// SD Card Initialization
if (SD.begin())
{
Serial.println("SD card is initialized and it is ready to use");
} else
{
Serial.println("SD card is not initialized");
return;
}
}

void loop() {
data_file = SD.open("data.txt", FILE_WRITE);
if (data_file) {
getData();
}
// if the file didn't open, print an error:
else {
Serial.println("error opening data.txt");
}
delay(1000);
}

void getData(){
for(long sec = 00; sec < 60; sec=sec+2){
float temp = dht.readTemperature(); //Reading the temperature as Celsius and storing in temp
data_file.print(hr);
data_file.print(":");
data_file.print(mint);
data_file.print(":");
data_file.print(sec);
data_file.print(", ");
data_file.println(temp);
Serial.print(hr);
Serial.print(":");
Serial.print(mint);
Serial.print(":");
Serial.print(sec);
Serial.print(", ");
Serial.println(temp);
if(sec>=58){
mint= mint + 1;
}
if (mint>59){
hr = hr + 1;
mint = 0;
}
data_file.flush(); //saving the file
delay(2000);
}
data_file.close(); //closing the file
}
```

Thanks

body:
First you need to setup the second DHT sensor and a second file. Please replace the `X` by the number of the pin your second sensor is connected to after `#define DHTPIN2`

    #define DHTPIN 8
    #define DHTPIN2 X
    #define DHTTYPE DHT22
    DHT dht(DHTPIN, DHTTYPE);
    DHT dht2(DHTPIN2, DHTTYPE);
    File data_file, data_file2;

In `setup()` you need to also start the second dht sensor:

    dht.begin(); //This command will start to receive the values from dht22
    dht2.begin(); //This command will start to receive the values from dht22

In `loop()` you have to open the second data file in addition to the first one:

    data_file = SD.open("data.txt", FILE_WRITE);
    if (data_file) {
    getData();
    }
    // if the file didn't open, print an error:
    else {
    Serial.println("error opening data.txt");
    }
    data_file2 = SD.open("data2.txt", FILE_WRITE);
    if (data_file2) {
    getData2();
    }
    // if the file didn't open, print an error:
    else {
    Serial.println("error opening data2.txt");
    }

Although not the most efficient/elegant solution, this requires you to duplicate your `void getData()` function as `void getData2()` to work for the second sensor/file, by replacing `dht` by `dht2` and `data_file` with `data_file2`.
This would do the logging on the two sensors in sequence.
If you want the logging in parallel you need to add the measurement and writing of the second sensor/file into the `void getData()` function.


message:
Would a 100KΩ resistor connected to ground pull an open analog line down to 0

I have a project that has a photoresistor wired into a voltage divider and connected through a 3.5mm “stereo mini plug”. When nothing is in the mini plug, the analog line is an open circuit, and floats, creating jittery spurious readings.

I’d like to wire a pull-down resistor into the project box to tie it to ground so I get a zero reading when the light sensor is not connected, but want to alter the voltage reading from my photo sensor voltage divider circuit as little as possible.

If I connect a 100KΩ resistor between my analog input and ground, that would give me zero readings on the analog pin when the photo sensor is not plugged in, wouldn’t it? I can’t see how < 20 CM of 26 gauge wire would pick up enough interference to pull my analog pin up from 0 through a 100kΩ resistor.

What is the effective range of an analog pin on an Arduino? (A Mega 2560, if that matters) What’s the lowest voltage that will register above 0?

(The project box is getting crowded, so experimenting is getting tricky. I’d like to make a single change rather than trying different resistor values.)

body:
I would expect a 100K pulldown to quiet the A/D, but I'd have to actually try it. I'd think testing it on the bare board, outside of your project box would still give you useful information. But I would sketch up the schematic of the proposed voltage divider with the parallel pulldown and run the numbers to convince yourself of what effect it will have on your measurement. You may be able to ignore it, or you may want to correct for it.

> What is the effective range of an analog pin on an Arduino?

0 - (1023/1024)*Vref, whichever reference, 1.1v, 2.56v, or Vcc applied to the Vref pin, you have selected.

> (A Mega 2560, if that matters) What’s the lowest voltage that will
> register above 0?

Appx (Vref * 2^-11), i.e.,  1/2 an LSB of the 10-bit A/D range.

Update:

Is that a jumper selection?

No, it's programmable; the external Vref is reset default. See ch. 25 of the 2560 datasheet for the low-level details; Arduino.cc's function-reference, for the [`analogReference()`][1] function for the quick & dirty how-to. Remember to take and discard a measurement whenever you change the reference.

  [1]: https://www.arduino.cc/reference/en/language/functions/analog-io/analogreference/


body:
With a 100 kΩ resistor to GND, it is not guaranteed that the value will be zero. If a (servo)motor is connected, it might get some noise.

The pull down resistor can be any value, because it is possible to calculate the value of the photoresistor.

There is an alternative solution. I think that all the analog pins of the Arduino Mega 2560 are digital pins as well. You can do a `pinMode(A0,INPUT_PULLUP);` to pull the input high. When a photoresistor is connected, you can turn the internal pullup resistor off with `pinMode(A0,INPUT);`.


message:
Error: Does not name a type

I have made a class called subjects and I have then made a subject called math. I am trying to set a classroom for math but it is giving me the error 'math' doesn't name a type.

Code for the class

    class subject {
    public:
      char subjectname[];
      char classroom[];

    };

Code for the classroom and math

    subject math;
    math.classroom = "A1";

How can I set the classroom of math to A1?

body:
    class subject {
    public:
      char subjectname[];
      char classroom[];

    };

This creates a class `subject` which has two `char` arrays of unspecified size as its members. This will attempt to create an array of size 0 (see [here](https://stackoverflow.com/questions/9722632/what-happens-if-i-define-a-0-size-array-in-c-c)). This is not what you want. You can e.g. statically allocate the space with a maximum number of characters beforehand and then `strncpy()` your new string inside the buffer.

This would look like

    class subject {
    public:
      char subjectname[32];  //32 bytes buffer
      char classroom[32];
    };

And later

    subject math;
    strncpy(math.classroom, "A1", 31); //copy at max 31 bytes to not overwrite the NUL terminator
    Serial.print("Classroom is: ");
    Serial.println(math.classroom)

Or, just use the Arduino `String` class.  For example

    #include <Arduino.h>
    class subject {
    public:
      String subjectname;
      String classroom;
    };

Then your first usage code can be used unmodified.

Example

    #include <Arduino.h>

    class subject {
    public:
      String subjectname;
      String classroom;
    };

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

        subject math;
        math.classroom = "A1";

        Serial.print("Classroom is: ");
        Serial.println(math.classroom);
    }

    void loop() { }


message:
Weird behavior with char/uint8 arrays

So I'm trying to read an 8-byte character string from an I2C device and print it to the serial console. This raw 8-char array is *not* terminated when it comes from the device, so I'm pretty sure I need to manually terminate it. Unfortunately, when I go to print the resultant string, the serial monitor just fills up with line breaks. Could someone take a look at this code and tell me where I went wrong?

    uint8_t* HT_Controller::readMultiple(uint8_t reg, uint8_t num)
    {
        Wire.beginTransmission(i2cAddr);
        Wire.write(reg);
        Wire.endTransmission();

        Wire.requestFrom(i2cAddr, num);
        uint8_t* data = new uint8_t[num];

        for(int i = 0; i < num; i++)
        {
            data[i] = Wire.read();
        }

        return data;
    }

    char* HT_Controller::getManufacturer()
    {
        uint8_t* data = readMultiple(REGISTER_MFR, NUM_MFR_BYTES); //Read the bytes from the controller
        char* dataTerminated = new char[NUM_MFR_BYTES + 1]; //Our new array that will have a null char at the end
        memcpy(data, dataTerminated, NUM_MFR_BYTES); //Copy the bytes into the new array
        delete(data); //We're done with the original array, remove it from the heap
        dataTerminated[NUM_MFR_BYTES] = 0; //Add that null char. NB: we don't need to '+1' the index because arrays start at 0, not 1

        return dataTerminated;
    }

And here's how it's used in the main sketch:

    void loop()
    {
        char* data = mc1->getManufacturer();
        Serial.println(data);
        delete(data);
        delay(500);
    }

body:
Your memcpy is backwards.

    SYNOPSIS
       #include <string.h>

       void *memcpy(void *dest, const void *src, size_t n);

So the line:

    memcpy(data, dataTerminated, NUM_MFR_BYTES); //Copy the bytes into the new array

should be:

    memcpy(dataTerminated, data, NUM_MFR_BYTES); //Copy the bytes into the new array


message:
Storing hash values from SHA256

I am using this code and I can not save the output of the hash function to an array of `char`. Can you help me how to do that?

    #include "sha256.h"
    #include <Arduino.h>
    #include "./printf.h"

    void printHash(uint8_t* hash) {
      int i;
      for (i=0; i<32; i++) {
        Serial.print("0123456789abcdef"[hash[i]>>4]);
        Serial.print("0123456789abcdef"[hash[i]&0xf]);
      }
      Serial.println();
    }

    void setup()
    { String FinalStr="1234567890";
    Sha256.init();
      Sha256.print(FinalStr);
      printHash(Sha256.result());
    }
    void loop()
    {

    }

body:
Save to a character vector (64 characters + NULL):

    void copyHash(char* buf, uint8_t* hash) {
      int i, j = 0;
      for (i = 0; i < 32; i++) {
        buf[j++] = "0123456789abcdef"[hash[i]>>4];
        buf[j++] = "0123456789abcdef"[hash[i]&0xf];
      }
      buf[j] = 0;
    }

    void setup()
    {
      String FinalStr="1234567890";
      Sha256.init();
      Sha256.print(FinalStr);
      char buf[65];
      copyHash(buf, Sha256.result());
    }

Cheers!


body:
This is the code that worked for me:

    #include "sha256.h"
    void setup(void)
    {char encoded[64];
        Serial.begin(9600);

        // this is actually the RFC4231 4.3 test

        Sha256.init();
        Sha256.print("123");
        uint8_t * result = Sha256.result();

        Serial.println("Expect: 2d711642b726b04401627ca9fbac32f5c8530fb1903cc4db02258717921a4881");
        Serial.print(  "Got   : ");
        for (int i = 0; i < 32; i++) {
                Serial.print("0123456789abcdef"[result[i] >> 4]);
                Serial.print("0123456789abcdef"[result[i] & 0xf]);

                for(int i = 0; i < 64; i+=2)
                    {
                      encoded[i] = "0123456789abcdef"[result[i / 2] >> 4];
                      encoded[i + 1] = "0123456789abcdef"[result[i / 2] & 0xf];
                    }
        }
        Serial.print("\n");
                for(int z = 0; z < 64; z++)
                Serial.print(encoded[z]);
    }

    void loop(void)
    {}


message:
Recommendations for 24V to 5V AC/DC converter

I'm working on an ESP8266 thermostat that should be powered by the 24V AC from the furnace. I'm looking for a converter to 5V DC that would be small enough to fit in a smaller enclosure and not dissipate too much heat. Not fully sure about the current, but I'm planning for up to 500 mA for short periods of time. I found on ebay [this](https://www.ebay.com/itm/AC-DC-Power-Supply-Buck-Converter-Step-Down-Module-3-3V-5V-9V-12V-15V-24V-36V-US/122832954547), but it accepts input from 85V upwards. What would happen if I would feed 24V AC to it? Would it still work. Or alternatively doesn anyone have a link for something similar that would work with 24V?

body:
Transformers for furnaces are typically Class 2 transformers, energy limited. Unloaded, or lightly loaded, they produce a significantly higher output voltage than the rated output voltage, 24 volts in this case. 28 volts is typical, and it may be higher during high line situation. The 24 volt rating is a loaded voltage, with a resistive load.

28rms x 1.4 = 39.2 volts

You should be using a regulator with a voltage rating of at least 40 volts, and that is really marginal.

https://www.aliexpress.com/item/1pcs-2018-new-dc-dc-converter-12V-24V-36V-48V-60V-72V-to-5V-0-5A/32922897633.html

The AC-DC converter you linked to would not work. It has a low voltage cutout. It also would not be able to provide the power if it was able to work at the lower voltage. The input current would be much higher than the normal input current at a normal line voltage.


message:
Digital I/O threshold voltages for ATmega32u4

What are the voltages on a ATmega32u4 (eg Arduino Leonardo) such that a `HIGH` or `LOW` is read?

I want to ensure that I'm reading the [chip reference manual](http://ww1.microchip.com/downloads/en/devicedoc/atmel-7766-8-bit-avr-atmega16u4-32u4_datasheet.pdf) correctly, where Table 29-1 says:

----------

VIL: Input Low Voltage, Except XTAL1 and Reset pin

 * Min: -0.5
 * Max: 0.2VCC-0.1V (LVTTL)

VIH: Input High Voltage, Except XTAL1 and RESET pins

 * Min: 0.2VCC+0.9V (LVTTL)
 * Max: VCC + 0.5V

----
My questions:

1. What is LVTTL?
2. How do I interpret the VIL Max and VIH Min?
3. Is the input undefined between those two values?

body:
 1. LVTTL is Low Voltage Transistor-Transistor Logic. In general, the
    term "TTL" is used for a digital signal.
    The "Low Voltage" part is special,
    the ATmega32U4 switches from low to high (and vice versa)
    at low voltages.
 2. Just as it is written. For example, when the ATmega32U4 runs at 5V,
    then:
    VILmax = 0.2 * 5 - 0.1 = **0.9 V**.
    VIHmin = 0.2 * 5 + 0.9 = **1.9 V**.
 3. Between those values the input signal is seen as low or high,
    but the exact voltage when it switches from low to high may
    vary.
    When the microcontroller is running at 5.0 V and is used
    within the specifications of the datasheet, then a voltage
    below 0.9 V is always seen as low and
    a voltage above 1.9 V is always seen as high (guaranteed).
    Those voltages is what a electronics designer must consider.

In the [datasheet of the ATmega32U4][1] at page 403 is paragraph 30.7 "Pin Threshold and Hysteresis" with figure 30-22 and 30-23.
The figures show that at 25°C and 5V, the input switches from low to high typical at 1.55 V and it switched from high to low at maybe a slightly lower voltage.
The hysteresis is almost none and the voltage depends on VCC and the temperature.

[![pin input threshold voltage][2]][2]

(*Thanks to Edgar Bonet for the correction/addition*)

  [1]: http://ww1.microchip.com/downloads/en/devicedoc/atmel-7766-8-bit-avr-atmega16u4-32u4_datasheet.pdf
  [2]: https://i.stack.imgur.com/1rQ6V.png


message:
NodeMCU Ping working on one but not another

Update 2:
Have tested by pinging various devices on different subnets / vlans
and did a pcap on the wifi AP

I can see the icmp requests going through for each request except for ones on the 4.x subnet, almost like the arduino doesnt like that IP address and refuses to send those packets?

Update 1:

Have tested the following

Turned on logging on firewall and noticed the following actions:

 - Ping router from Arduino - See logs in firewall, arduino gets response. (Red line)

 - Send external web request from arduino - See logs in firewall, arduino gets response. (Orange Line)

 - Send web request to internal server - Arduino queries internal DNS and gets IP of web server, but no request send (Nothing in firewall logs) (Yellow and Blue)

 - Send ping to internal server - Arduino queries same dns server, gets ip, but no request sent (Firewall logs again) (Yellow and Green)

however, sending the ping and web request from desktop, shows both the firewall log blocking the ping request, and the rule allowing the web request.(Brown Purple Pink)

Have attached diagram again to help visualize whats going onAnd can attach router logs or rules if required

https://imgur.com/a/g4TipmZ

Also have set a windows PC with the same IP address, and can ping the web server, so I know it's something wrong with the arduino's requests to the web server in particular, and not the firewall?
###End Update###

I have two Node MCUs which I'm using for a project.
A while ago they were working fine, but i recently changed some network settings on my home network and found that it broke the script I had running on them.
I finally figured out where it went wrong and fixed it, but now I have another interesting problem.

One of my nodes runs this script fine, where as the other gets stuck on the ping stage.
I have uploaded the same script to both nodes and swapped over the IP address assigned and it follows the device not the IP.
So I know its not a networking issue.

I know the WiFi is working on the funny node, as it gets a IP address.
but it doesn't go any further

Any ideas?

Script attached below:

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

        // WiFi credentials.
        const char* WIFI_SSID = "SSID";
        const char* WIFI_PASS = "******";
        WiFiClientSecure wifiClient;
        bool connection = false;
        WiFiClient client;
        const char* dbServer = "webaddress";

        void setup() {
          //Open Serial
          Serial.begin(9600);
          Serial.setTimeout(2000);

        //Connect to Wifi
          bool pingtest = false;
          Serial.print("Connecting to WiFi");
          WiFi.begin(WIFI_SSID, WIFI_PASS);
          //Wait for connection
          int wificount = 0;
          while (WiFi.status() != WL_CONNECTED) {
            delay(500);
            Serial.print(".");
          }
          if (WiFi.status() == WL_CONNECTED) {
            connection = true;
            Serial.println("WiFi connected");
            Serial.println("IP address: ");
            Serial.println(WiFi.localIP());
            while(!pingtest){
              Serial.println("Pinging Server");
              if(Ping.ping(dbServer) == true){
                pingtest = true;
              }else{
                Serial.print(".");
                delay(1000);
              }
            }
          }

        }

    void loop() {
      Serial.println("Hello");
      delay(2000);
    }

Update (Cross posted from another forum):
I have an Arduino which pings a server on a different VLAN / subnet as part of its code.
It was working a while ago, but I changed some settings on my firewall to restrict stuff down, and that broke the Arduino code.
I found it was because I was blocking ICMP across VLANs.
So I created a rule to allow ping requests between the two VLANs
tested on my desktop (on same net as Arduino) and works fine.
Went to test on Arduino and wasn't getting any response.

So I put the router IP in and tested it on the Arduino, works fine. I can even ping the Arduino from my desktop, and ping my desktop from the Arduino

So I figured I must have some other firewall rule allowing my desktop to have special access. (not that I could find it)
so gave the arduino the same Ip address and no luck, yet can still ping the router

I have attached a crude drawing here. Hopefully it helps to visualize my problem.

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

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

body:
If a ping doesn't work over a routed connection it could be.

1. Default gateway on the Arduino device, add a `Serial.println(WiFi.gatewayIP().toString());` to print the default gateway.

2. DNS issue, I presume that the `const char* dbServer = "webaddress";` indicate a FQDN.

3. Firewall is blocking the ICMP on either the inbound or outbound path.


message:
Arduino library redeclaration error

This is my first time here and I hope someone can be of help!
I'll try to keep it as concise as possible.

So I have two sensors/modules, 1 is an LCD screen from elecrow and another is the DS1307. Both are connected through analog 4 and 5. I tried hooking them up with the help of my breadboard but I've stumbled upon the following issue with the libraries (I don't even know if what I'm trying to achieve is possible but I'm trying nevertheless(and failing horribly while at it))

    In file included from C:\Users\c\Documents\Arduino\Sketches\IC2_Checker\BME280_LCD_Time\BME280_LCD_Time.ino:22:0:

        C:\Users\c\Documents\Arduino\libraries\RTClib/RTClib.h:79:31: error: redeclaration of 'OFF'

         enum Ds1307SqwPinMode { OFF = 0x00, ON = 0x80, SquareWave1HZ = 0x10, SquareWave4kHz = 0x11, SquareWave8kHz = 0x12, SquareWave32kHz = 0x13 };

                                       ^
    In file included from C:\Users\c\Documents\Arduino\Sketches\IC2_Checker\BME280_LCD_Time\BME280_LCD_Time.ino:21:0:

        C:\Users\c\Documents\Arduino\libraries\I2C_LCD/I2C_LCD.h:457:5: note: previous declaration 'LCD_SwitchState OFF'
             OFF=0x00,

             ^
        In file included from C:\Users\c\Documents\Arduino\Sketches\IC2_Checker\BME280_LCD_Time\BME280_LCD_Time.ino:22:0:

        C:\Users\c\Documents\Arduino\libraries\RTClib/RTClib.h:79:42: error: redeclaration of 'ON'

         enum Ds1307SqwPinMode { OFF = 0x00, ON = 0x80, SquareWave1HZ = 0x10, SquareWave4kHz = 0x11, SquareWave8kHz = 0x12, SquareWave32kHz = 0x13 };

                                                  ^
    In file included from C:\Users\c\Documents\Arduino\Sketches\IC2_Checker\BME280_LCD_Time\BME280_LCD_Time.ino:21:0:

        C:\Users\c\Documents\Arduino\libraries\I2C_LCD/I2C_LCD.h:458:5: note: previous declaration 'LCD_SwitchState ON'

             ON=0x01

             ^

        exit status 1
        Error compiling for board Arduino/Genuino Uno.

What I make out of this, is that the libraries are conflicting with each other on the following:

 - OFF = 0x00
 - ON = 0x80
 - ON= 0x01

Is there anyway to fix this? I know that I have to edit the .h libraries but I don't know what to change and to what it should be changed, here's the library code on the module itself:

    // RTC based on the DS1307 chip connected via I2C and the Wire library
    enum Ds1307SqwPinMode { OFF = 0x00, ON = 0x80, SquareWave1HZ = 0x10, SquareWave4kHz = 0x11, SquareWave8kHz = 0x12, SquareWave32kHz = 0x13 };

    class RTC_DS1307 {
    public:
       boolean begin(void);
       static void adjust(const DateTime& dt);
       uint8_t isrunning(void);
       static DateTime now();
       static Ds1307SqwPinMode readSqwPinMode();
       static void writeSqwPinMode(Ds1307SqwPinMode mode);
       uint8_t readnvram(uint8_t address);
       void readnvram(uint8_t* buf, uint8_t size, uint8_t address);
       void writenvram(uint8_t address, uint8_t data);
       void writenvram(uint8_t address, uint8_t* buf, uint8_t size);
    };

Thank you for your help!

C.C

EDIT:
I think that I might have come a bit closer. I tried implementing one of the answers and that made me get the following error:

        C:\Users\c\Documents\Arduino\libraries\RTClib\RTClib.cpp:284:1: error: 'Ds1307SqwPinMode' does not name a type

     Ds1307SqwPinMode RTC_DS1307::readSqwPinMode() {

     ^

    exit status 1
    Error compiling for board Arduino/Genuino Uno.

That's a whole lot less than before. I will keep this updated!

EDIT 2:

Meanwhile, I tried something entirely else like changing the name of OFF and ON Throughout the RTClib concerning only the DS1307 module. That however gives me an entirely new line of errors such as:

    error: 'enum Ds1307SqwPinMode' is not a class or a namespace

      RTC_DS1307 Ds1307SqwPinMode::readSqwPinMode() {

                                                  ^

and:

    error: could not convert '(Ds1307SqwPinMode)mode' from 'Ds1307SqwPinMode' to 'RTC_DS1307'

       return static_cast<Ds1307SqwPinMode>(mode);

                                                ^
These errors in particular only take place in the .cpp library
This is where I am stuck now at the moment

body:
A general rule is to keep definitions such as enum's within the context of the class (library). Below is a possible refactoring:

    class RTC_DS1307 {
    public:
       enum SqwPinMode { OFF = 0x00, ON = 0x80, SquareWave1HZ = 0x10, SquareWave4kHz = 0x11, SquareWave8kHz = 0x12, SquareWave32kHz = 0x13 };

       ...
       static SqwPinMode readSqwPinMode();
       static void writeSqwPinMode(SqwPinMode mode);
       ...
    };

Cheers!


body:
**FINAL EDIT WITH SOLUTION:**

I finally stumbled upon the last wall of issues before getting it to work,

 1. I redownloaded all the libraries
 2. Went to the .h library file of RTClib
 3. Changed the variable names from OFF to OFF and on to ONN (it's stupid I know but bear with me)
 4. Encounter an entirely new error which seemingly occurs at board version 1.6.23

Error:
> In function 'global constructors keyed to
> BME280_LCD_TIME.o':
>
> lto1.exe: internal compiler error: Segmentation fault
>
> Please submit a full bug report,
>
> with preprocessed source if appropriate.
>
> See <http://gcc.gnu.org/bugs.html> for instructions.
>
> lto-wrapper.exe: fatal error: C:\Program
> Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.15.0_x86__mdqgnx93n4wtt\hardware\tools\avr/bin/avr-gcc
> returned 1 exit status
>
> compilation terminated.
>
> c:/program
> files/windowsapps/arduinollc.arduinoide_1.8.15.0_x86__mdqgnx93n4wtt/hardware/tools/avr/bin/../lib/gcc/avr/5.4.0/../../../../avr/bin/ld.exe:
> error: lto-wrapper failed
>
> collect2.exe: error: ld returned 1 exit status
>
> exit status 1 Error compiling for board Arduino/Genuino Uno.

  5. Go to Tools > Board > Boards manager
  6. I *personally* had to change "**Arduino AVR Boards** by **Arduino** version **1.6.23**"  to **version 1.6.21**
  7. Compile the code
And that should do the trick!


message:
How do I fill an empty array with the values from a sensor and compare it to another given array I filled before

I'm designing a safe lock of 4 digits, but the password is in terms of colors, I have 3 colors. we are obliged to use a grayscale sensor (SKU: SEN0147).

The assignment is as follows:

Write a program on Arduino that will be used as a safe lock.
Consider having 3 colors black white and grey. Black = 0, Red = 1 and White = 2.

• When the microcontroller is turned on, the safe is locked. The Serial Monitor should display:
“System is online.”

• The combination lock should be saved in an array of integers called arr_code.

• The user has 3 trials to open the safe

• The system will wait for the user to enter 4 colors. To enter a color, the grayscale sensor should be place on top of the desired color. Once ready the push button is pressed. Once released, the color is saved in another array called arr_user_code.

• Once 4 colors are entered, the system should test automatically if the code entered by
the user is equal to the code saved in arr_code.

• If the wrong code is entered, the serial monitor displays: “Wrong Code. Try Again.”

• If the user enters the wrong code 3 times in a row the system is locked and a message is
displayed: “System Locked.”

• If the correct code is inserted, the Led on pin 13 is turned on.

• The combinations entered by the user should be displayed on the Serial Monitor.
The Arduino program should be clear, separated into functions and documented.

The program I wrote is the following:

    char led_pin = 13;
    char pb_pin = 2;
    int gs_pin = A0;
    //the brightness of the flash light im using is giving 894 value so im using it for testing purpose
    int arr_code[4] = { 894, 894, 894, 894 };
    int arr_user_code[4];

    int counter;
    int Lock_Interval = 2500;

    char trigger = false;
    bool equal = true;
    char led_state = false;

    int Array_Compare(int *a, int *b) {
      for (int i = 0; i < 4; i++) {
        if (a[i] != b[i]) return 0;
        else return 1;
      }
    }

    void Button_Wait(int buttonPin) {//function to sense if button is pressed
      int curr_state;
      int prev_state;

      while (1) {
        prev_state = curr_state;
        curr_state = digitalRead(buttonPin);
        if (curr_state != prev_state) {
          if (curr_state == false) {
            delay(10);
            return;
          }
        }
      }
    }

    int GS_Value(int gsPin) {
      int gs_value = analogRead(gs_pin);
      return gs_value;
    }

    void setup() {
      // put your setup code here, to run once:
      pinMode(led_pin, OUTPUT);
      pinMode(pb_pin, INPUT);
      Serial.begin(9600);
      digitalWrite(led_pin, false);
    }

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

      Serial.println("System Online");
      Serial.println("Please Enter Passcode:");

      for (counter = 0; counter < 3; counter++) {
        for (int i = 0; i < 4; i++) {//uploading user array with gs values
          Button_Wait(pb_pin);
          arr_user_code[i] = analogRead(gs_pin);
          Serial.print(analogRead(gs_pin));//printing values on monitor
          Serial.print(" ");
        }

        Serial.println(" ");

        for (int i = 0; i < 4 && equal; i++) {//testing if passcode is true
          if (arr_user_code[i] != arr_code[i]) {
            equal = false;
          }
          else equal = true;
        }
        if (equal == true) {
          Serial.println("System Unlocked");
          digitalWrite(led_pin, true);
        }

        else if (equal == false) {
          Serial.println("Wrong Passcode. Try Again");
        }
      }

      /*Array_Compare( arr_user_code, arr_code);
      if (Array_Compare) Serial.println("System UNLOCKED");
      else Serial.println("Wrong Passcode. Try Again");
      */
      if (trigger == false) {//for locking the system
        Serial.println("System LOCKED!");
        while (1) {
          Lock_Interval = Lock_Interval * 2;//CHANGE TO MINUTES LATER ON!!
          delay(Lock_Interval);
          return;
        }
      }
      delay(100);
    }

I'm sorry for having a lot of functions not used and a lot of canceled algorithms by remarks but its my scratch. the issue is that my program is always giving me a wrong passcode even if its correct.
Can you help me find the problem please? Thank you in advance.

body:
Your program has a lot of issues, but the main problem revolves around

    if (trigger == false)

The code initializes this to false and the logic never alters the value, thus the program will always indicate "System LOCKED!"

It looks like you've mixed the variables **trigger** and **equal**.  Get rid of the trigger variable and use equal.

    if (equal == false) {//for locking the system
        Serial.println("System LOCKED!");
        while (1) {
          Lock_Interval = Lock_Interval * 2;//CHANGE TO MINUTES LATER ON!!
          delay(Lock_Interval);
          return;
        }
      }

I recommend a different variable name to equal, such as "unlock", as it makes clear the use of the variable.  Also, initialize variables such as "equal" at the beginning of loop().  Good luck.

EDIT

Your comparison check in loop() is valid.  However if you have to use Array_Compare, here is the fix.

    // returns 1 if equal, 0 otherwise.
    int Array_Compare(int *a, int *b) {
    for (int i = 0; i < 4; i++) {
        if (a[i] != b[i])
        return 0;
    }
    return 1;
    }

Then in loop, remove your local comparison loop with

    //for (int i = 0; i < 4 && equal; i++) {//testing if passcode is true
 // if (arr_user_code[i] != arr_code[i]) {
 //  equal = false;
 // }
 // else equal = true;
 //}

    equal = Array_Compare(arr_user_code, arr_code);

I'm not comfortable writing your program for you, this is not a coding service.


body:
Since you are trying to distinguish tree different colours, I assume you are using SEN0147 in analog mode. That means the sensor output is between 0-5V. I do not believe that this will always be exactly a value of 894.

I suggest to change your comparison check in a way not to check if values are identical but to check if values are in a certain range. (additionally to all the answers @RamblinRose already suggested)

Here is a modification of the comparison loop of @RamblinRose with the change I propose. Check with different values of `threshold`, starting from high to lower values.

    // returns 1 if equal, 0 otherwise.
    int Array_Compare(int *a, int *b) {

       int threshold = 500;
       int temp;
       for (int i = 0; i < 4; i++) {
           temp = a[i] - b[i];
           if (abs(temp) > threshold)
           return 0;
       }
       return 1;
    }


message:
Does baud rate for HC-05 Bluetooth module need to match the Serial Monitor?

I have this sketch that I got as a sample.  I have the two HC-05s connected.  What I type in one serial monitor shows up on the other, but as question marks.  The most common reason for this I find is baud rate doesn't match.   I didn't change the baud rate on the HC-05s when I got them, so I assume they are set to default.  I can put them in command mode and ensure the baud rate is set.

Does the baud rate of the HC-05s have to match the baud rate of the Serial monitor?  I would assume not.  I am also wondering if this is a problem with formatting a char[] when writing to the serial display.

    #include <SoftwareSerial.h>
    SoftwareSerial BTserial(7, 8); // RX | TX
    // Connect the HC-05 TX to Arduino pin 7 RX.
    // Connect the HC-05 RX to Arduino pin  8 TX through a voltage divider.
    //

    char c = ' ';

    void setup()
    {
    Serial.begin(9600);
    Serial.println("Arduino is ready");
    Serial.println("Remember to select Both NL & CR in the serial monitor");

    // HC-05 default serial speed for AT mode is 38400
    BTserial.begin(38400);
    }

    void loop()
    {

    // Keep reading from HC-05 and send to Arduino Serial Monitor
    if (BTserial.available())
    {
        c = BTserial.read();
        Serial.println(c);
    }

    // Keep reading from Arduino Serial Monitor and send to HC-05
    if (Serial.available())
    {
        c =  Serial.read();
        BTserial.write(c);
    }
    }

body:
No, they do not need to match.

You are talking about two separate serial port connections.

The baud rate between the HC-05 and the Arduino (BTserial) has to match.

The baud rate between the Arduino and your PC (Serial) has to match.

BTserial and Serial can use different baud rates.

An overflow problem can arise if a lot of data arrives from the HC-05 and there is not enough memory to store it until it can be forwarded to Serial.

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

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

<!-- End schematic -->


message:
Creating an array of structures which store bitmaps to work with u8glib

I've tried reading the documentations and I'm getting desperate because I can't find anything.

I need to create an array of structures, which contains a bitmap stored in `PROGMEM` space (because of issues with memory usage).

The bitmaps are created as follows:

    const uint8_t pat[] PROGMEM = {
    ...
    };

Then I need to create a structure like this:

    typedef struct{
        uint8_t bitmap[8];
    } chars;

    chars allChars[1];
but the compiler doesn't like that for some reason and spit out a bunch on invalid conversion from const to char so it was clear I couldn't use that!
My next attempt was to create a pointer to the pattern like so:

    typedef struct{
        const uint8_t *bitmap[8];
    } chars;

    chars allChars[1];

This time it again gave warnings about invalid conversion but at least compiled!
I then tried to write the entire code and run it:

    #include "U8glib.h"
    U8GLIB_SSD1306_128X64 u8g(U8G_I2C_OPT_NONE|U8G_I2C_OPT_DEV_0);

    typedef struct{
        const uint8_t *bitmap[8];
    } chars;

    chars allChars[1];

    const uint8_t pat[] PROGMEM = {
      0xff,
      0x00,
      0xff,
      0x00,
      0xff,
      0x00,
      0xff,
      0x66
    };

    void draw(void) {
      u8g.drawBitmapP( 37, 28, 1, 8, pat);
      u8g.drawBitmapP( 74, 28, 1, 8, (char*) allChars[0].bitmap);
    }

    void setup(void) {
      allChars[0]= (chars) {*pat};
    }

    void loop(void) {
      draw();
      while(true);
    }

the first line where I have used the pattern directly in the draw function, works perfectly fine, but the second line which retrieves the value from the pointer draws some weird noise shape (I'm guessing memory dump of an address or something)!

Is it even possible to create a struct with one of the variables being just a pointer to the constants that I have defined earlier? I'm pretty sure I'm doing something very wrong as I'm not familiar with using pointers and addresses and whatnot, so it would be great if someone could help with these issues!

body:
You're making it far too hard on yourself.

All you need is a single 2-dimensional array of data in PROGMEM:

    const uint8_t bitmaps[10][8] PROGMEM = {
      { 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x66 },
      { 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x66 },
      { 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x66 },
      { 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x66 },
      { 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x66 },
      { 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x66 },
      { 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x66 },
      { 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x66 },
      { 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x66 },
      { 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x66 },
    };

Each row is a bitmap, and there are 10 rows, so 10 bitmaps (I have them all the same at the moment).

Then you just reference the slice number you are interested in:

    u8g.drawBitmapP( 100, 30, 1, 8, bitmaps[3]);

Note: I haven't tested this.


body:
That still wouldn't solve the issue with struct!
I think I have found a glitch in GCC compiler where if you define your struct in dynamic memory rather than PROGMEM, even if you use a buffer and fetch the data using memcpy_P, it will return the correct value while printing, but when you copy it again to allChars[0].bitmap , the wrong value is copied! the thing that solved the issue was adding PROGMEM to the struct like below:

    typedef struct {
      unsigned int ascii;
      int size[2];
      const PROGMEM unsigned char *bitmap;
    } chars;

I have not yet encountered any compilers that are this specific and don't even allow transfer between memory spaces correctly. (Not to mention other issues with GCC linker that are brought up by david from eevblog like stack overflow without warning, etc). They really need to solve issues like this as this compiler is one of the most frequently used on different platforms.

anyways, here is the final code if anyone finds it useful (I will probably end up making a youtube video about it later):

    #include "U8glib.h"
    //U8GLIB_SH1106_128X64 u8g(U8G_I2C_OPT_NONE);
    U8GLIB_SSD1306_128X64 u8g(U8G_I2C_OPT_NONE|U8G_I2C_OPT_DEV_0);

    typedef struct {
      unsigned int ascii;
      int size[2];
      const PROGMEM unsigned char *bitmap;
    } chars;

    chars allChars[1];

    const unsigned char pat[] PROGMEM = {
      0x00, 0x00, 0x00,  //.....................
      0x00, 0x00, 0x00,  //.....................
      0x00, 0x00, 0x00,  //.....................
      0x00, 0x00, 0x00,  //.....................
      0x00, 0x00, 0x00,  //.....................
      0x00, 0x00, 0x00,  //.....................
      0x00, 0x00, 0x00,  //.....................
      0x00, 0x00, 0x00,  //.....................
      0x00, 0x00, 0x00,  //.....................
      0x01, 0xfc, 0x00,  //.......%%%%%%%.......
      0x0f, 0xff, 0x00,  //....%%%%%%%%%%%%.....
      0x1f, 0xff, 0xc0,  //...%%%%%%%%%%%%%%%...
      0x3f, 0xff, 0xe0,  //..%%%%%%%%%%%%%%%%%..
      0x3f, 0xff, 0xe0,  //..%%%%%%%%%%%%%%%%%..
      0x7f, 0xff, 0xf0,  //.%%%%%%%%%%%%%%%%%%%.
      0x7f, 0xdf, 0xf0,  //.%%%%%%%%%.%%%%%%%%%.
      0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
      0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
      0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
      0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
      0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
      0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
      0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
      0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
      0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
      0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
      0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
      0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
      0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
      0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
      0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
      0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
      0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
      0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
      0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
      0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
      0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
      0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
      0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
      0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
      0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
      0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
      0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
      0x7f, 0xdf, 0xf0,  //.%%%%%%%%%.%%%%%%%%%.
      0x7f, 0xff, 0xf0,  //.%%%%%%%%%%%%%%%%%%%.
      0x3f, 0xff, 0xe0,  //..%%%%%%%%%%%%%%%%%..
      0x3f, 0xff, 0xe0,  //..%%%%%%%%%%%%%%%%%..
      0x1f, 0xff, 0xc0,  //...%%%%%%%%%%%%%%%...
      0x0f, 0xff, 0x80,  //....%%%%%%%%%%%%%....
      0x01, 0xfc, 0x00,  //.......%%%%%%%.......
      0x00, 0x00, 0x00,  //.....................
      0x00, 0x00, 0x00,  //.....................
      0x00, 0x00, 0x00,  //.....................
      0x00, 0x00, 0x00,  //.....................
      0x00, 0x00, 0x00,  //.....................
    };

    void charToBitmap(int x, int y, char chr){
      for(unsigned int i=0; i<sizeof(allChars);i++){
        if (allChars[i].ascii=chr){
          u8g.drawBitmapP( x, y, allChars[i].size[0], allChars[i].size[1], allChars[i].bitmap);
          break;
        }
      }
    }

    void draw(void) {
      charToBitmap(0,0,'0');
    }

    void setup(void) {
      allChars[0] = (chars) {48,{3,54},pat};
    }

    void loop(void) {
        u8g.firstPage();
      do {
        draw();
      } while( u8g.nextPage() );
    }


message:
Weird problem with arduino

I wrote the code below and the result is not what I expected at all! I'm not sure why it's happening!

    void setup() {
      // put your setup code here, to run once:
      Serial.begin(9600);
    }

    const uint8_t pat[] PROGMEM = {
      0xff,
      0x00,
      0xff,
      0x00,
      0xff,
      0x00,
      0xff,
      0x66
    };

    void loop() {
      delay(100);
      Serial.println(sizeof(pat));
      for (int i=0; i<8; i++){
        Serial.print(pat[int(i)],HEX);
      }
      Serial.println("");
      Serial.print(pat[0],HEX);
      Serial.print(pat[1],HEX);
      Serial.print(pat[2],HEX);
      Serial.print(pat[3],HEX);
      Serial.print(pat[4],HEX);
      Serial.print(pat[5],HEX);
      Serial.print(pat[6],HEX);
      Serial.print(pat[7],HEX);
      Serial.println("");
      while(true);
    }
the output is surprisingly this:

> 8
>
>008000010
>
>FF0FF0FF0FF66

What is compiler doing in the background but it seems to be messing things up really bad! The loop should be doing the exact same thing as manually writing that code over and over but it's not! How can I fix the loop?

body:
If you want to get a value from PROGMEM you must read it with `pgm_read` functions. Read the [PROGMEM reference][1].

    for (int i = 0; i < 8; i++) {
      Serial.print(pgm_read_byte_near(pat + i),HEX);
    }

`pat[0]` in `Serial.print(pat[0],HEX);` is an item in a constant array `const uint8_t pat[]`. it can't change at runtime so the compiler uses the value 0xFF. that is why it is printed ok without `pgm_read_byte_near`

  [1]: https://www.arduino.cc/reference/en/language/variables/utilities/progmem/


message:
Is this a good way to filter noise due to vibration in limit switch?

I have a circuit connected as follows
[![enter image description here][1]][1]

my limit switches which are attached to my structure sometimes gets falsely triggered, so I wrote this code to address it. My motor is supposed to go down skip the up limit switch at first hit the down one then go back to the up one. is this a good way to implement it?
https://pastebin.com/qVU1Gp0q

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

```
//Switch pressed ->  reading HIGH
//Switch not pressed -> reading LOW
//Motor direction 0 is down, 1 is up

const int uplimit = 32;
const int downlimit = 34;
const int motorspeed = 9;
const int motordirection = 28;
//const int pumpspeed=5;
//const int pumpdirection=6;
const int motorenable = 26;
//const int pumpenable=;
int Finishedcleaning = 0;
int Reachedup = 0;
int Motorinitialsetup = 0;
int Motorsecondsetup = 0;
int downfiltered = 0;
int upfiltered = 0;
void setup() {
  // put your setup code here, to run once:

  pinMode(motorspeed, OUTPUT);
  pinMode(motordirection, OUTPUT);
  pinMode(motorenable, OUTPUT);
  //pinMode(pumpspeed, OUTPUT);
  //pinMode(pumpenable, OUTPUT);
  pinMode(uplimit, INPUT);
  pinMode(downlimit, INPUT);

}

void loop() {
  // put your main code here, to run repeatedly:
  int average1 = 0;
  int average2 = 0;
  if (Motorinitialsetup == 0 ) // to be run before hitting initial switch
  { digitalWrite(motorenable, HIGH);
    analogWrite(motorspeed, 190);
    digitalWrite(motordirection, 0); // Bring motor down
    //   digitalWrite(pumpenable,HIGH);
    //  digitalWrite(pumpdirection,1);
    // analogWrite(pumpspeed,240);
    Motorinitialsetup = 1; //so this if statement does not run again

  }

  for (int i = 1; i < 100; i++)
  { downfiltered = digitalRead(downlimit);
    average1 = average1 + downfiltered;
  }
  average1 = average1 / 100;

  if ((average1 > 0.9) && Finishedcleaning == 0 ) // Function after hitting down switch
  {
    delay(1000); // wait until motor cross switch
    analogWrite(motorspeed, 0); // stop motor
    Finishedcleaning = 1; //indicate cleaning is over for next loop
    delay(500); // wait until motor cross switch
  }

  if ( (Finishedcleaning == 1) &&   (Reachedup == 0)  && (Motorsecondsetup == 0))
  {
    digitalWrite(motordirection, 1); // reverse motor direction
    analogWrite(motorspeed, 190); // start motor again
    Motorsecondsetup = 1;
  }

  if ( Motorsecondsetup == 1) // only checks switch up switch after motors comes back
  {

    for (int i = 1; i < 300; i++)
    { upfiltered = digitalRead(downlimit);
      average2 = average2 + downfiltered;

    }
    average2 = average2 / 300;
    if ((average2 > 0.9) && (Finishedcleaning == 1)) // Stop Motor after returning
    { analogWrite(motorspeed, 0);
      delay(1000);
      Reachedup = 1; // indicate finished returning after cleaning cycle
    }
  }
}

```

body:
**Hardware:**

You have the switch at 5V with a pull down resistor.
When using longer wires or when everything is put into a box, it might be safer to have a GND wire to the switch (with a pull up resistor) instead of a 5V wire. When a switch or button is connected with a shielded cable, it can also be better to connect one pin of the switch to GND.

If you change the switch and connect one pin to GND with pullup resistor, then you have to change the sketch as well, because the pin will become LOW when the switch is pressed.

You may add a capacitor of 1 nF to 100 nF between the digital input and GND. That will help against spikes and noise.

The pull down resistors of 4k7 is a high value for a noisy environment. I suggest to use 470 Ω or 1k resistors.

The **ground path** is very important. You have the GND of the motor driver connected to the breadboard and that is also where the switches are connected. That means the input (switches) and the output (motor driver) share a piece of ground wire. Always avoid such situations.
Breadboards have often bad contacts. If the GND to the breadboard is not very solid, then you are injecting the input pins with noise from the output pins of the Arduino board.
Use two seperate breadboards for input and output. Or connect the GND of the motor driver directly to the Arduino board.

**Software:**

An integer can not be 0.9, therefor your filter does not work.

The function `digitalRead()` returns HIGH or LOW. You add those values, but I prefer to stick with HIGH or LOW.

Taking multiple samples and have a threshold is a good idea. Do you really need 100 or 300 samples? A button may bounce for 10 ms, so I suggest to use about 20 samples during 20 ms.

    int digitalReadFiltered(int pin) {
      int result;
      const int n = 20;                // maximum 30
      int count = 0;                   // an integer can hold 30 analog samples

      for (int i = 0; i < n; i++) {
        if (digitalRead(pin) == HIGH) {
          count++;
        }
        delay(1);        // 1 ms for sampling during 20 ms with 20 samples
      }

      if (count > (n / 2)) {
        result = HIGH;   // counted enough HIGH values
      } else {
        result = LOW;
      }

      return(result);
    }

----------

In short, **a pull down (or pull up) resistor** with a low value makes the circuit low impedance, and the electrical noise will have less influence.

When a button is pressed, that connects the digital input pin of the Arduino board directly to 5V (or GND). Then it is almost impossible that electrical noise can get to that pin.

When a button is not pressed, then the resistor keeps the input pin low (or high). Then electrical noise can cause spikes.

A circuit with low impedance is less influenced by the electrical noise. The lower the value of the resistor, the less troubles with noise.

It is not something that can be calculated, see it as electrical/capacitive/electromagnetic/radio-noise combined with bad ground currents from a wrong ground path. What is the best way to receive that? With a high impedance circuit of course.

A pull down (or pull up) resistor with a value of 10k can be used when there are no wires connected to it that are going outside the circuit board. When there is a button with wires, then I would suggest a lower value, for example 2k2 or 4k7. Since you have troubles with noise, I suggest a value of 470 Ω or 1k.


message:
How to perform two tasks in one loop in Arduino?

I am trying to make a weather monitor using Arduino. I want my weather monitor to send me a message of the weather data every 5 hours using GSM sheild. Also, there is an LCD on my weather monitor which shows live weather conditions. The problem I am facing is that the delay of 5 hours in my code also applies to the LCD which updates the LCD every 5 hours and not every second as it should. Please tell me how to run these two functions simultaneously.

body:
Consider using a [finite state machine][1] to track multiple tasks.  Specifically, the state in which you send your message once every 5 hours.  And, the state you update your LCD, perhaps once every second.

As your tasks are associated with time, consider using the built in Arduino call to [millis()][2] to find how many milliseconds the Arduino program has been running.  This will not block your program.  Instead it will immediately return with a number you then need to manage.

To create a delay, use the above number from millis() and add the number of milliseconds for the desired delay.  Call millis() repeatedly until it returns the calculated number or a number greater than the calculated number.  Use this to drive your state machine.  Perhaps you only use millis() to count seconds and use software to count up to 5 hours (5 x 60 x 60 seconds).

Note, millis() will eventually roll over as it is of type "unsigned long".  That is, it will roll over once about every 50 days.  If you want to keep accurate timing when this happens, you will have to account for the roll over in your program.

  [1]: https://en.wikipedia.org/wiki/Finite-state_machine
  [2]: https://www.arduino.cc/reference/en/language/functions/time/millis/


body:
Something along the lines of this pseudocode should help you.

```
unsigned long weatherUpdate; // Use unsigned longs for millis times
unsigned long screenUpdate;  // You need to worry about wraparound less often
unsigned long timeNow;

setup {

  unsigned int interval1 = 0; // 0 Should be whatever delay you need
  unsigned int interval2 = 0; // 0 Should be whatever delay you need

  updateScreen();
  screenUpdate = millis();

  updateWeather();
  weatherUpdate = millis;

}

loop {

  timeNow = millis();

  /*
     These if statements are true when the interval between the current time
     and the last time the if ran is greater than the required interval. For
     organization purposes, maybe create separate functions for when you
     update your screen and weather functions instead of just replacing
     the function stubs I've included.
  */

  if((timeNow - screenUpdate) > interval1){

    updateScreen();  // Do what you need
    screenUpdate = millis();  // Update time since last run

  }

  if((timeNow - weatherUpdate) > interval2){

    updateWeather();  // Do what you need
    weatherUpdate = millis();  // Update time since last run

  }

}
```


message:
Arduino Code 'Bug'

I'm sharing my code.. The problem I am facing is that the code performs all the functions that are to be called except showing the MAX30100 (for heart rate) readings. I have tried this code using statement switches,cases, if-else but couldn't figure out.  Can anyone help me out regarding this?

        unsigned long runGSR() {

    total = total - readings[index];         // subtract the last reading:

     readings[index] = analogRead(inputPin);  // read from the sensor:

      delay(100);

      total = total + readings[index];       // add the reading to the total:

      index = index + 1;                     // advance to the next position in the

    array:

      if (index >= numReadings)               //when the end of the array is reached

        index = 0;                           // wrapped around to the beginning:

      average = total / numReadings;           // calculate the average:

      return average;       // send it to the computer as ASCII digits

        }
        void ambtemp()

        {

           reading = analogRead(A2);       //takes the reading from analogue pin 2

      tempVolts = reading * 5.0 / 1024.0;   //converts the readings to volts

      ambitemp = tempVolts / 0.01;        //output voltage /10 millivolts = 1 degree
    C

      Serial.print(",Ambient Temp:");      //prints ambient temperature in serial monitor

      Serial.println(ambitemp);

      delay(10);

        }

        void hbt()    //Function for heart rate (MAX30100) in which I am having problem
        {
            do
            {
                pox.update(); // Make sure to call update as fast as possible
                if (millis() - tsLastReport > REPORTING_PERIOD_MS) {   //the loop repeats every second
                lcd.clear();
                Serial.print("HR:");
                Serial.println(pox.getHeartRate()); //prints Heart rate on LCD
                delay(100);
                ambtemp();    //calls the ambient temperature function
                gsr = runGSR();   //calls the GSR sensor function
                delay(100);
                tsLastReport = millis();
            }

body:
I assume you use [this][1] as source for your code:

This means that:

    #include "MAX30100_PulseOximeter.h"
    PulseOximeter pox;

Your issue is that the line:

    Serial.println(pox.getHeartRate()); //prints Heart rate on LCD

Does not actually print anything on the LCD.
It only shows the value on the serial.

Try using [`lcd.print()`][2]

  [1]: https://github.com/oxullo/Arduino-MAX30100/blob/master/examples/MAX30100_Debug/MAX30100_Debug.ino
  [2]: https://www.arduino.cc/en/Reference/LiquidCrystalPrint


message:
Connecting NodeMCU through internet

I have a NodeMCU and a website (free website domain provided by [http://www.hpage.com][1]) and I have to send and receive some data (suppose a 8bit number) from the website to the NodeMCU via internet. The NodeMCU is connected to internet through WiFi hotspot of an Android phone.

- Can anyone provide an example code? How can I address the NodeMCU from the website?
- Does the NodeMCU need to be a server or just a client?

Thanks in advance for kind help.

  [1]: http://www.hpage.com

body:
> How can I address the NodeMCU from the website?

You can't. The NodeMcu is behind the phone, behind a router, behind a gateway of the operator etc. It can access the Internet over the infrastructure routing it out, but is not visible from the Internet.

> Does the NodeMCU need to be a server or just a client?

The device should be a client and open the communication to the server by sending a request and renewing the connection if it times out. You can use WebSockets or MQTT or similar framework.


message:
Control Stepper via Serial Monitor

I would like to control my stepper via serial monitor and unfortunatley the code below did not work. Serial monitor works (Serial.println()), but it does not execute the stepperOne() part. Any ideas why would be awesome.
Thank you.

    #include <AccelStepper.h>

    const int stepPin = 5;
    const int dirPin = 4;
    const int enPin = 12;

    String msg;

    unsigned int DEST = 800;
    unsigned int SPD = 1600;
    unsigned int ACCEL = 1600;
    const int TEST = 3;

    void setup() {

      pinMode(stepPin,OUTPUT);
      pinMode(dirPin,OUTPUT);
      pinMode(enPin,OUTPUT);
      digitalWrite(enPin,HIGH);
      Serial.begin(9600);  // Start Serial

    }

    void loop() {

    if (Serial.available()>0) {
        msg = "";
        while (Serial.available()) {
          delay(10);
          char tmp = Serial.read();
          // msg += tmp;
         if( tmp!='\r' && tmp!='\n' ) msg+=tmp; // Does not work either
        }
        msg.replace(" ","");
        if (msg=="G") {
          stepperOne();
          Serial.println("Stepper turned.");
        }
        Serial.flush();
      }
    }

    void stepperOne() {

      AccelStepper stepper(1,stepPin,dirPin);
      digitalWrite(enPin,LOW);
      stepper.setMaxSpeed(SPD);
      stepper.setAcceleration(ACCEL);
      stepper.move(DEST);
      if (DEST > 0) {
        while ( stepper.distanceToGo() > 0 ) {
          stepper.run();
          }
      digitalWrite(enPin,HIGH);
      }
     }

body: I found the solution, it was the Arduino, older version R2, the R3 works like a charm. I didn't know that the version could cause so much trouble. But in case someone encounters the same problem R3 did it for me.


message:
DFPlayer for Writing to SD Card

Can you use the DFPlayer to write to the SD card?
Link for DFPlayer: https://www.dfrobot.com/wiki/index.php/DFPlayer_Mini_SKU:DFR0299

Here's the goal of my project. I have a button that, when pressed, should a- play a song off an SD card that is hooked up to the DFPlayer and b- should log "button is pressed" to the SD card. Unfortunately, the DFPlayer library doesn't seem to have any functions for this, and I wasn't sure how to see whether the DFPlayer has the functionality to support writing onto an SD card. Are there modules that are Read-only for SD cards? If so, is the DFPlayer one of them?

PS - I'm using an Arduino Uno,
Thank you so much for your help! I am a complete novice for SD cards, so any help you give would be very much appreciated!

body:
Unfortunately the DFPlayer cant write that data to the SD card. The Arduino has some non volatile memory of its own built in though. Theres 1K of EEPROM for the UNO. Notes on how to use it here: https://www.arduino.cc/en/Reference/EEPROM
If you can get what you need to done in 1K and its not important to your project that you be able to unplug the SD card and put it in another reader, then perhaps thats a nice, simple solution...