text:
Generate a true analog signal using Arduino
I am looking for a way to create a true analog output with the arduino uno. I am constantly reading an analog input on a0 pin, all i want to do is send the same signal as output. I know arduino convert the signal into pwm so have can i convert it back to true analog signal.I have a dac too but not getting proper output.
secondly, i want to send same signal by converting it into bits through Ethernet so how do i send and receive the signal.
here is my code for dac.
#include "Wire.h"
#include "MCP4725.h"
MCP4725 MCP(0x60);
uint32_t microphonePin=A0;
uint32_t threshold=800;
const int ledPin=13;

void setup() {
    Serial.begin(115200);
    pinMode (ledPin, OUTPUT);
    Serial.print("MCP4725 test program: ");
    Serial.println(MCP4725_VERSION);
    if (MCP.begin() == false)
     {
       Serial.println("Could not find sensor");
     }

    MCP.begin();
 }

void loop() {
   uint32_t sensorValue=analogRead(microphonePin);
   MCP.writeDAC(sensorValue);
   Serial.println(MCP.getValue());
   if (MCP.getValue()>threshold)
    {
      digitalWrite (ledPin, HIGH);
    }
   else{ digitalWrite(ledPin, LOW); }

  }

here is my circuit for audio amplifier

and for the speaker it is connected on DAC out.
FYI:I am able to read the data on my serial monitor form mic and i am also able to so do some operation by just using mic and GUi. I just want to here what i am saying on speaker.

you cannot output the same signal as intput, because you are not reading all of the input signal ... you are reading only intermittent samples of the input signal

using those value i want to create if not the same signal then approximately same signal

Can you describe how the signal you get is different from the expected signal? What frequencies do you need to process?

i have connected mic with amplifier circuit on my analog pin a0 now i want that send that signal to the speaker which is connected with dac. DAC is connected With A4 and A5 pin.

Why are you connecting the speaker with the mic through the Arduino? Why not connecting the mic amplifier circuit directly to the speaker amplifier? The Uno is not really made for audio processing. You can do some, but the result is not very good. And you give it an unnecessary workload with also outputting the digitized signal as analog.

my end game is to connect mic to one arduino and speaker to another arduino then communicate between them as they will be kept far from each other. but problem is that its not able get output on one device two device is far fetched.

I see that MCP4725 uses Wire library with the default clock of 100,000 kb/sec.
At a rough estimation each call to MCP.writeDAC or MCP.getValue will be at least 32 bits long and you use three of them in each loop.
This one:
   Serial.println(MCP.getValue());
   if (MCP.getValue()>threshold)

is redundant, you should store the value in a temporary variable and use-it in both "print" and "if".
With 10us for each bit that means 1060 us for each loop. The analog read also takes 100us to complete. Over all 1160us minimum.  Is the MCP.getValue() really needed?
That means that your maximum sample frequency is 860hz and the maximum bandwidth of 430hz. I doubt that this is an acceptable bandwidth for a microphone.
Even so, the output signal will not look similar at all, you need a higher bandwidth or to limit,  if possible, the bandwidth of the input signal.
In some limits you can modify the MCP4725 library to use fast wire clock four times faster if it suits your requirements. If you also drop the two MCP.getValue() calls that will be again almost three times faster, up to 5khz.
Also you might search for faster ADC on Arduino.
Update after OP microphone amplifier schematic.
The ADC works only with positive voltages. Short the output capacitor of the amplifier!

Hey, thanks for reply i have removed those two line only difference is their is less high pitch noise but i am not getting desired output.

@eTollSystems Oh!!! Now I see the other big flaw in your design!!! The ADC is not working with negative voltages!!! See the updated answer.

If you want something simpler than the transistor version you can use the following as well, for the other options skip to the --here-- mark
Oldstyle analog out. this works like a vacuum tube and while I use a LDR you can also use heat or a actual vacuum tube.
You Will Need:

A low resistance LDR or multiple in parallel.
A cardboard box or other box to isolate it from outside interfearance.
A Led or light bulb.

How this works: while a led flashes, a LDR needs a certain time to just to values(often up to around a few ms), so this will stabilize your adc signal.
You send the desired amplitude as a pwm signal to the light source(you probably want to invert your pwm signal) which aims at the LDR. you send your sound frequency through the LDR which now works as a variable resistor.
!!Use low resistance LDR's and a bright light source to get a as low as possible resistance. with (weak)lasers, you can get a normal LDR down to around 1 to 0 ohm. but you will most likely use a led since that has more precise intensity control.

Another simple method is the inversed of analog read in an Arduino. you basically use multiple output ports with different resistances to get a different output when done right in this case you can get around 257 different volume levels with 8 pins for the amplitude and 1 for the frequency.
--here--
--added this here as a simple explaination/guide--
first start with getting your microphone working, see if analogread get's some high values. if it stays at 0, 1 or another low value, then you didn't include a transistor with your microphone to boost the signal.
-For your output start with a project without a microphone to see if it is working right.
you will need to use 2 pins to power your output(excluding ground, assuming single-channel audio).
-the first one you will need for your frequency signal output. the other one is for the amplitude/volume/gain.
-We will use any type of amplifier(transistor) to merge the signals, in this case, I assume a transistor since they are cheap, simple low power, have an easy dynamic range and you most likely have them already.
-this following part can be done in 2 ways I would suggest to try way 1 first since it is most simple, logic, and fast which is great on a slow which is great in a small microprocesssor. where method 2 might seem the exact different way around but is much more precise.
Method 1: connect the frequency output pin to the emmitor pin of the transistor where the + normally goes in.
Connect the amplitude output pin to the base pin of transistor(the trigger)
add a very small capacitor(or a bigger one for tests) between the base and ground this is to convert the adc in analog voltage instead of pulses.
the collector of the transistor which you would normally connect to ground is your output.
you might want to add a small resistor after it especially if you are using it for a audio cable. you can also directly connect a very small speaker to hear the sound
for a cable(be careful withconnection arduino IO to things like a pc) you connect the output as oudio signal and the ground as ground. but check what voltage the other devices audio port supports since arduino's IO pins generate 5v
method 2.
connect the frequency out pin to the base of the transistor,
connect the ADC of the amplitude pin to the emitter pin of the transistor,
connect a capacitor of larger capacity than described in method 1 between the emitter pin of the transistor and the ground of the Arduino.
the collector is again your output, you might to as a resistor to it.
connect a wire from an analog port to the emitter pin of the transistor to read out the voltage in the capacitor for precise voltage regulation.
tinker with the values of the capacitor size.
(you now have an energy pool in front of the transistor if you know the ampere on which you are outputting you can use this to regulate the pool, otherwise you can read it using the analog feedback loop).
important to know is that if you want precise volume you use a larger capacitor, if you want fast volume differences you use a small one and intentionally use more pins to charge it. for an Arduino Uno due to low analog read speeds, I would recommend a larger capacitor or this.
extra stuff when putting your complete system together you might run into speed issues. you should therefor connect the microphone to both a digital and a analog pin. the digital pin constantly monitors the frequency and the analog pin measures the amplitude sometimes(add a small capacitor get that average amplitude).
I would also recommend turning down the analog read precision to prevent checking for all 1024 possible voltages.
for method one you can also add a extra resistor from base to ground and from the amplitude pin to base so you can more precisely calculate the voltages.
--end of simple version--
You can try to use 2 pins for the output signal. one of them sends the frequency digital(3 pins if you also want negative polarity audio). this output signal should go to something like a transistor or a digitally controlled potentiometer or amplifier. I will assume you use a transistor since those are most common and quite fast.
the first digital output pin should go to the emitter pin of the transistor
the second pin is used for the volume and will go to the base of the transistor. you might want to add a very small capacitor between the base and ground to reduce frequency interference(to prevent the ADC frequency from showing up in your signal).
the Collector pin would be your analog output suitable for audio.
So in basic steps:

split  the signal into a digital frequency and volume. (the digital frequency can be made by seeing a signal above a certain value as high and the other as low, this works best when you use both the positive and the negative side of the soundwave otherwise you will need to chose a very low number)(the analog frequency is literally your analog value for the positive only audio, and value-512 (*-1 for negative numbers to get only positive numbers) for the full audio if you include the negative audio)
Send the frequency signal to the emitter pin of your diode.
Send the amplitude signal to the base pin of your diode.
Connect a small capacitance between the ground and the amplitude signal.

however What Dorian said are things you might want to keep track of as well since they often indeed tend to kill of such projects because you very easily run into speed limits(analog read in a arduino ar basically 1024 digital reads(literally)).
So some tips for your cirquit:

If your microphone doesn't have a transistor connected to boost the signal add it since otherwise the analog port of the arduino uno is not sensitive enough to measure the signal. you can and should fist test this using a project where you constantly analogread and print it. you can add a small capacitor between the analog port and the ground to just measure the voltage.
use diodes to rectify your microphone signal, your arduino can only read positive voltage, the microphone also sends negative voltage. redirect the negative voltage to the arduino ground (you can invert the negative voltage using a transistor or some other methods to read the negative voltages as well, but I would recommend just sending the negative signals to ground since this would give the near full range as well)
use 2 microphones one for frequency and one for amplitude. or connect the output of your microphone to both a analog and a digital port. you might in the last case want to use resistors to lower the current going to them this makes sure both get a accurate voltage.
avoid as manny analog reads as possible, storing it is better than calling it twice
use c/c++ bitmanipulations for IO, not only is it more easy to program larger systems when using them, they are also a lot faster( arduino uno has the PORTB, PORTD, PIND, PINB, DDRD, DDRB, and the a and c version(however you most often only use the D and B) predefined. bitmanipulations require very little knowledge compared to other programming methods as long as you know the port addresses, which again for the arduino uno are predefined search: arduino uno bit manipulations or arduino uno PORTB.
you can sample the sound frequency using a digital port at a higher frequency than the amplitude. since sound often doesn't jump to fast in amplitude in a way that you would clearly notice. this means you could read the sound with a IO pin and write it on another IO pin, additionally you could once every interval measure the amplitude to use which makes your code a lot faster.

there are way more ways but these are easy to do.
for sending it trough internet however you need to be careful that the module you use processes those things itself so that you do not just connect a internet port since that would slow your system down even more.
For those wanting a ms paint sketch:
version one:

version two:

note that I just used random images from the internet you can use any capacitor and transistor that works for this, I did not check if this transistor is right for this, but it had a nice layout description in the image. the capacitor doesn't need to be ceramic, but this way you see clear legs and I don't need to focus on polarity. in general, all cheap 5v compatible transistors should work and all capacitors if they are not way too big or too small for your load.
I used descriptions rather than logos, so anyone should be able to read it as long as they have software to tell the differences in colour if they are colourblind.
How it works
The transistor sends the voltage from the emittor to the collector(or the other way around based on the transistor you use). so in method 2 which also works for mosfets. we send a adc signal to the capacitor to charge it to a voltage, you should however also add a resistor to ground or a cable to a analog port, because otherwise the voltage can just build up to 5v. this capacitor which we charge becomes a analog power source. we connect it to the emmitor(or pin which you normally connect on the + side). so if we where to open up the transistor(close the cirquit) by putting a positive voltage on the base or trigger pin then you would get a output of the voltage that you put into it. so if you play the frequency digital on the base completely opening and closing the transistor then you get a voltage output similar to the voltage in the capacitor.
method one works more difficult but a transistor opens up relative to the current going from base to exit, so we use the pwm and a small capacitor to get a analog voltage on it only partly opening it, then we send the digital audio signal into the pin that you normally connect to 5v and you get that frequency payed with the transistor acting as a variable resistor
So method one uses a transistor as a variable resistor
And method two uses the transistor or fet as a switch which uses the voltage build up in the capacitor, doesn't actually need to use pwm if you use a feedback loop.

i will work on it to see if it give desire output.

mic is working fine. I am not able to understand what other frequency you are sending to the transistor. one will be mic output through arduino which will be pwm data.

@eTollSystems the pwm data is used for the amplitude/volume only. since pwm sends a digital frequency that would show up as sound as well and only does it X times a secon, we can't use pwm for the audio signal.

@eTollSystems the signal pin is used to mirror the frequency/sound the mic hears. so you send out the sound digital. and use the pwm for the volume.

@eTollSystems so if your mic would give these signals: 0,382,890,3,999,4,439,0
then you could for example say everything above 200 is high and all other  is low. if you use a digital pin to read the mic it will be a lot more easy that way you can just ask if it is high or low( you can connect the mic to both a analog and a digital port(just add a resistor towards the digital port))

so the mic's sound is send as a digital signal, and the loudnes can be send as pwm.

@eTollSystems I've added 2 new methods, the first is similar to the others but more simple and old-fashioned, so this should be much more easy to make. the other is quite different but needs no conversion since you can literally write a analog signal with that(it does however take more pins). I also added some clarification about the 2nd transistor method. your mic hardware seems good and you said it worked. however you can connect the + out to the analog port and through a resistor to a digital port to also get a digital signal, or manually convert analog to digital in code.

i will look into your suggestion and yes my mic signal is working fine. when i am connecting those two pin directly to the speaker i am getting the proper output. Now i want to separate  mic and speaker and communicate it via one arduino if that works then i will be separating  mic and speaker further more by connecting mic in one arduino and speaker in another arduino and communicate between the arduino. If you have any suggestion or alternative for that please provide. thax in advance

@eTollSystems if your second arduino is only to reduce load in the first one you can also just connect the mic with amplifier to the arduino and the speaker, you can add a extra transistor as extra amplifier if it needs to be louder. you should also first try the output using tone() and a some predefined amplitudes since the analogread samplerate is really low so reading a microphone with a arduino as a analog device often needs a lot of custom extensions to your arduino to still hear the propper sound.(without other code a arduino could theoretically perform 10.000 analogreads per second max)

hey, ted i have started receiving some desire output but their is still lot of noise. I will add more filter and transistor to make it proper.  and no i am not separating my mic and speaker because of load my end game is mic will be in one room and speaker in another and  i should be able to here that voice properly .

@eTollSystems To detect where the problem is can you check the sample frequency so we know for sure that is right, since that is the most likely to have problems.
also I haven't used that specific amplifier chip you use, but do you have the powersource+ connected to the arduino + and powersource - to the arduino- and not a powersource that delivers negative voltages relative to the arduino ground. In the chips I use there is a reference pin, most often this one is only for the voltage so you can put that to 2,5v using resistors.  this will make it output 0v to 5v

for this wave however you will need to split it in 2 sections. <2.5v would be one wave and >2.5v would be another wave. so you need to see if it is below or above. if above just subtract 2.5v and do the result *2. if it is below. than do it -2.5v again and *-2 you might want to enlagre the low area instead of only using exactly 2.5v for example  >2<3

@eTollSystems For the other noice. again not based on your specific chip, but I use medical amplifier chips which are made for low noice. yet when build wrong you still get nice. so what you should do with high amplification is : keep short cables, avoid static charges or areas with magnetic fields such as earthlines or transformers and electric cables/coils. a more simple approach is to use aluim foil to make a faraday cage around your amplifier cirquit. so put aluim around longer jumpercables to shield them. and put cardboard with aluim around the cirquit, connect the aluim to arduino grnd

for your case(audio) there also is https://github.com/connornishijima/arduino-volume1
or the volume library
to install it you can use the git to get the files, or if you use the arduino ide, you can open the arduino ide and in the software go to helptools(4thoptionoftopmenubar)->Manage Libraries-> {type volume in the search bar}-> install the library called volume. you can also chose volume 2 or volume 3, see the git for the differences.
this however still uses micro pwm, so it is not true analog, but for audio it works. also note that on low volume the audio will be affected. I recommend only using the volumes between 100 and 255.
this method requires no additional hardware, and works well for audio, to send the audio to other devices however I would just send the audio values and not the audio output.
NOT TRUE ANALOG, but it solves your problem, the methods I described in my other answer will work well for most other analog cases, or even adding a small capacitor at that ma output might work in many cases. however since audio needs the voltage to change really fast this method works well, also since the volume is read by your mind instead of a digital device it has a normalization filter built in and a low sampling speed as well as sensitivity to only low frequency(how human brains and ears work) which will make the volume sound natural.
If you have a separate arduino for the volume or a well optimized code you can also avoid interrupts to get a higher frequency, this method is harder and requires you to know what your code does but allows for better quality volume(speciffically at low volume levels)
alternatively you can use a shiftregister and connect resisters to the outputs, for example 12800, 6400,3200,1600,800,400,200,100. like a bit but reversed, since the audio gets louder with a lower resistance. you can use other values, just don't make them to low, since arduino outputs 5v and 3.3v, both are much higher than your average headphone connection, also turning on multiple parallel resistors at once gives a lower resistance. for example if we turn on the 100 ohm and the 200 ohm resistor we get a output of around 66,66666666 ohm since the output is 1/((1/Resistor1)+(1/Resistor2)+(1/ResistorETC)
like this a singe 8 bit shift register can deliver 256 different volume levels as true analog. if you have ports free on your ardruino you can also use those instead of a shift register, however be sure to use bitmanipulations and not digitalwrite, since the later one is slow.
1 pin = 2 volume levels
2 pin = 4 volume levels
3 pin = 8 volume levels
4 pin = 16 volume levels
5 pin = 32 volume levels
6 pin = 64 volume levels
7 pin = 128 volume levels
8 pin = 256 volume levels
etc.
this method can give true analog voltage if you know the resistance at the output, a speaker however differs in resistance based on many factors, but doing this will still give you good volume control like actual analog voltage, even though it is actually more analog amperage. to get voltage content the terminal connected to all the outputs of the resistors to another resistor to generate a voltage divider, this works for things like vga displays, however for things like audio, lights, etc. you should jus directly take the output of the resistors


text:
Need help with independent speed control on multiple steppers
I am a NOOB. I admit to a huge lack of understanding of programming. I just need my machine to work.
I cannot wrap my head around getting independent speed control of 2 steppers since it seems that controlling the speed is dependent upon adjusting the length of delay between sending pulses to the motors, however sketches only contain one Loop and any delay in that loop has a global effect.
Here is my code so far
// My sketch to control 1.8 degree stepper motors operating the Gizmoto V3 Braiding Machine
// One 10k Pot speed-controls 2 braiding steppers,
// Second Pot speed-controls 3rd stepper which operates the take-up capstan

// Rev 1.0  March 10 2021

// Defines pins numbers

const int braidStepPin = 3;
const int braidDirPin = 2;

const int capstanStepPin = 5;
const int capstanDirPin = 4;

//Define variables here

int braidDelay; // Controls the speed of the braiding drive according to braidSpeed function
int capstanDelay; // Controls the speed of the capstan drive according to capstanSpeed function

void setup() {
  // Sets the pins as Outputs
  pinMode(braidStepPin,OUTPUT);
  pinMode(braidDirPin,OUTPUT);
  pinMode(capstanStepPin,OUTPUT);
  pinMode(capstanDirPin,OUTPUT);

  digitalWrite(braidDirPin,HIGH); // Sets the braid motors' direction
  digitalWrite(capstanDirPin,HIGH); // Sets the capstan motor's direction
}
void loop() {

  digitalWrite(braidStepPin, HIGH); // Sends the braid motors one pulse
  digitalWrite(braidStepPin, LOW);
  delayMicroseconds(braidSpeed);

  digitalWrite(capstanStepPin, HIGH); //Sends the capstan motor one pulse
  digitalWrite(capstanStepPin, LOW);
  delayMicroseconds(capstanSpeed);
}
// Function for reading the Braiding Potentiometer
int braidSpeed() {
  int braidDelay = analogRead(A0); // Reads the potentiometer
  int newBraidDelay = map(braidDelay, 0, 1020, 200, 700); // Converts the read values of the potentiometer from 0 to 1023 into desired delay values
  return newBraidDelay;
}
// Function for reading the Capstan Potentiometer
int capstanSpeed() {
  int capstanDelay = analogRead(A1); // Reads the potentiometer
  int newCapstanDelay = map(capstanDelay, 0, 1020, 200, 700); // Converts the read values of the potentiometer from 0 to 1023 into desired delay values
  return newCapstanDelay;
}

your code is step braid ... pause ... step capstan ... pause ... do you see a problem with that? .... the code needs to be look at time ... if needed, step braid ... if needed, step capstan .... or this ... decrement braid counter ... if zero, reset braid counter and step braid ... decrement capstan counter ... if zero, reset capstan counter and step capstan

Thank you for taking the time to offer help. As I stated I am very inexperienced at coding. I am aware of the accumulative effects of multiple pauses in the loop.. Do you know of an example of the code which you described: using counters, decrements and resets.. once I see that, maybe I'll be able to work through it. Sorry to be a nuisance.

there is a lot of example code included with the Arduino IDE ... lots more code on the internet ... here is an example of a counter https://mechatrofice.com/arduino/arduino-counter-code-circuit-working .... look at the lines that deal with count_value ... remove all the code that deals with the button ... keep the delay just for testing ... you'll have increment count_value ... print count_value ... delay 100

next, change the increment to decrement ... next, add code that sets value of count_value if count_value == 0 .... it's all baby steps ... expand your code slowly

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
The same button with one click and double click
i hope to get some help with my code.
I am trying to distinguish between a single press and a quick double press of the button with debouncing.
I am making some silly mistake in my code and i can't find out the problem. If I double press the button, both 'single' and 'double' gets printed on the serial monitor.
Thanks in advance for some help.
const int buttonPin = 5;
unsigned long lastPressTime;
int buttonState = 0;
int singlePress = 0;

void setup() {
  pinMode(buttonPin, INPUT_PULLUP);

  lastPressTime = millis();
  Serial.begin(9600);
}

void loop() {
  if (!digitalRead(buttonPin) == HIGH && buttonState == 0) {
    unsigned long currentPressTime = millis();

    //two presses within 500ms
    if (currentPressTime - lastPressTime < 500) {
      singlePress = 0;
      //Do double press action
      Serial.println("double");
    } else {
      singlePress = 1;
    }

    //update the last pressed time
    lastPressTime = currentPressTime;
    buttonState = 1;
  } else if (!digitalRead(buttonPin) == LOW) {
    buttonState = 0;
  }

  //check if 500ms have passed with no second button press
  if (singlePress == 1 && lastPressTime  - millis() > 500) {
    singlePress = 0;
    //DO single press stuff
    Serial.println("single");
  }
}

why not use a library? for example Bounce2

@Juraj...I know there are some library's for this type of situations. I know the Bounce2 and generally I use the OneButton library. In this case I am trying to make it work without the use of a library.

both 'single' and 'double' gets printed on the serial monitor .... you are almost there ... add code to pick one, then print

This looks odd  lastPressTime  - millis() > 500  since lastPressTime will be less than millis() but I don't think that is your only problem. I restructured your solution as a more explicit finite state machine and put it in a simulator: https://wokwi.com/projects/347070000856564307

The problem is this statement:
lastPressTime  - millis() > 500

Because time is stored as an unsigned long, this test as it is written now is always true.
You want to measure the time since the last press, so you should subtract the timestamp of the last press from the current time. Replace it with:
millis() - lastPressTime > 500

And the code will run fine.

If your "answer" is derived 100% from someone else's previous comment pointing out an obvious error, it would be courteous to at least acknowledge it. Even better would be to wait until the originator has had a chance to correct his code and report the results before making a statement such as "And the code will run fine." . (I don't believe it does)

Thank you all for your help...
Definitely the problem in my code, to get the one click and double click working like @mhopeng wrote, was this statement:
lastPressTime  - millis() > 500

changing it to this
millis() - lastPressTime > 500

maked it work.
But what i realize is that my approach is not enough responsive.
Using the approach of @6v6gt is much better than mine.
The reaction is much more responsive and smoother.
// note the simulation speed is about one third of real time
// adjust timings if using on real hardware.

const int buttonPin = 5;
unsigned long inStateAtMs = millis() ;
int buttonState ;  // 0 = waiting for press, 1= waiting for release 2= differentiate single or double 3= wait button release (double)

void setup() {
 pinMode(buttonPin, INPUT_PULLUP);
 Serial.begin(9600);
}

void loop() {

 if ( buttonState == 0 ) {
   // wait for button press
   if ( millis() - inStateAtMs > 100 ) {
     if (!digitalRead(buttonPin)) {
       buttonState = 1 ;
       inStateAtMs = millis();
     }
   }
 }
 else if ( buttonState == 1 ) {
   // wait for stable button release 1
   if ( millis() - inStateAtMs > 100 && digitalRead(buttonPin) ) {
     buttonState = 2 ;
     inStateAtMs = millis();
   }
 }
 else if ( buttonState == 2 ) {
   // differentiate between single and double press
   if ( millis() - inStateAtMs > 400 ) {
     // timeout - is a single press
     Serial.println("single");
     buttonState = 0 ;
     inStateAtMs = millis() ;
   }
   else if (  ( ! digitalRead(buttonPin) ) && (millis() - inStateAtMs > 100 ) ) {
     // got second press within timeout - double
     Serial.println("double");
     buttonState = 3 ;
     inStateAtMs = millis() ;
   }
 }
 else if ( buttonState == 3 ) {
   // wait for stable button release 2
   if ( millis() - inStateAtMs > 100 && digitalRead(buttonPin) ) {
     buttonState = 0 ;
     inStateAtMs = millis();
   }
 }
}

Thanks again all of you for the help

I'm glad you've got something which works for you. I put your original sketch, but with the correction, into the same simulator and it does not appear to work. However, it [the simulator] appears to implement an exaggerated button bounce which you may not encounter on a physical Arduino. It is here if you want to play with it: https://wokwi.com/projects/347070013621928531

I noticed that in the simulator my code does not work, but on the physical Arduino it does.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Problem using sequential loop
So I have created this project to have an LED blinking at a constant speed whenever the program is running. The first LED (green) will blink faster and faster the closer an object gets to the sensor. The second LED (Blue(is referenced in code as white)) should be blinking constantly. The LED (blue) is only blinking when my ultrasonic sensor has something in range. I would like to make it so it blinks no matter the circumstances.
This is probably something obvious Im missing - excuse my noob-ness
NOTE: if the picture of the circuit isnt correct (pins not being correct) know that it is correct in real life, this is what I get for doing a quick mock up and post at 1:00 AM
#include "DHT.h";

#define DHTTYPE DHT22   // DHT Type is DHT 22 (AM2302)
#define DHTPIN 7       // DHT-22 Output Pin connection
#define trigPin 5
#define echoPin 6
#define beepPin 12
#define scalingfactor 10
#define blueLed 11

#define ledPin2 10

float hum;    // Stores humidity value in percent
float temp;
float soundsp;
float soundum;
 DHT dht(DHTPIN, DHTTYPE);  // Initialize DHT sensor for normal 16mhz Arduino

int centi = 0;

const long erval = 500;

unsigned long previous = 0;
unsigned long lastduration = 0;
unsigned long duration = 0; //time it takes for sound to return
unsigned long maxtime = 2000;
unsigned long i = 1;  //variable to determine actual distance
unsigned long time2 = 0;
unsigned long time1 = 0;

void setup() {
  Serial.begin (9600);  //open monirot channel
  dht.begin();  //start temp and humidity sensor
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(beepPin, OUTPUT);
  pinMode(blueLed, OUTPUT);
}

void calculate(){
      // Calculate the Speed of Sound in M/S in accordance with temp
    soundsp = 331.4 + (0.606 * temp) + (0.0124 * hum);

    // Convert to cm/us
    soundum = soundsp / 10000;
}

void logdistance() {
  digitalWrite(trigPin, HIGH); // send sound signal
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);  // stop sound signal
  duration = pulseIn(echoPin, HIGH);  // listen for sound signal
  centi = (duration* soundum)/2;   // determine delay of sound signal in one direction
  maxtime = scalingfactor * centi;  // change max time in accordance to the distance of the previous object
}

void beep() {
  digitalWrite(beepPin, HIGH);   // turn on the beep pin (or LED pin)
  delay(60);
  logdistance();   // run the log distance function again so we get accurate data
  if (time2 - time1 < 30) {  // delay based on how close an object is
    delay((60 - (time2 - time1)));
  }
  digitalWrite(beepPin, LOW);  // turn off beeper (or LED)
  i = 1;
    while (1) {
    if (i % 60 == 0) {
      logdistance();  // run my log distance funciton
    }
    delay(1);
    ++i;  // add one to i to report that we have recorded the distance
    if (i >= maxtime) { // dont report distanc if sound took longer than max time to return
      break;
      }
    }
}

void BlinkBlue (int interval){
   static long prevMill = 0;
   if (((long)millis() - prevMill) >= interval){
    prevMill = millis();
    digitalWrite(blueLed, !digitalRead(blueLed));
   }
}

void temps(){
  hum = dht.readHumidity();  // Get Humidity value
  temp= dht.readTemperature();  // Get Temperature value
}

void loop() {
  BlinkBlue(500);
  beep();

  temps();
  calculate();

  //print results
  Serial.print (duration);
  Serial.print("c. ");
  Serial.print(centi);
  Serial.print(" ");
  Serial.print(temp);
  Serial.println(" ");
}

Start with the BlinkWithoutDelay example and go from there.

are you saying I need to save a log of my led blinks? The LED's blink based off when an object is detected. would that interfere with the process of it measuring distance?

sorry again- definitely new to this: im probably not picking up what youre putting down

In the IDE look at the File -> Examples menu. In there somewhere is one called "BlinkWithoutDelay". That will teach you how to do your LED blinking in a "non-blocking" manner so they don't interfere with each other.

okay so Ive made a few changes to the project. Ive updated the problem itself.

Look at “BlinkWithoutDelay” and apply that logic to both LEDs.


text:
Arduino Uno I2C two sensor connection Issues
I have been working on trying to get the MAXREFDES#117 PPG and the LIS3DH Accelerometer to run together. I am modifying the sample code found here to do so:
https://github.com/MaximIntegratedRefDesTeam/RD117_ARDUINO
However, when I add the line lis.begin(0x18) to the PPG code the code stops running correctly. There is no error and the only thing that will print to the Serial Monitor is “LIS”. I have gotten the accelerometer to run using acceldemo and the PPG sensor running using the code from GitHub (above), so I do not think it is a connection issue. I am not quite sure what the problem is and would greatly appreciate help.
//PPG

#include <Arduino.h>
#include "algorithm.h"
#include "max30102.h"

//Accelerometer

#include <Wire.h>
#include <SPI.h>
#include <Adafruit_LIS3DH.h>
#include <Adafruit_Sensor.h>

#define MAX_BRIGHTNESS 255

#if defined(ARDUINO_AVR_UNO)
//Arduino Uno doesn't have enough SRAM to store 100 samples of IR led data and red led data in 32-bit format
//To solve this problem, 16-bit MSB of the sampled data will be truncated.  Samples become 16-bit data.
uint16_t aun_ir_buffer[100]; //infrared LED sensor data
uint16_t aun_red_buffer[100];  //red LED sensor data
#else
uint32_t aun_ir_buffer[100]; //infrared LED sensor data
uint32_t aun_red_buffer[100];  //red LED sensor data
#endif
int32_t n_ir_buffer_length; //data length
int32_t n_spo2;  //SPO2 value
int8_t ch_spo2_valid;  //indicator to show if the SPO2 calculation is valid
int32_t n_heart_rate; //heart rate value
int8_t  ch_hr_valid;  //indicator to show if the heart rate calculation is valid
uint8_t uch_dummy;

Adafruit_LIS3DH lis = Adafruit_LIS3DH();

// the setup routine runs once when you press reset:
void setup() {
   // initialize serial communication at 115200 bits per second:
   Serial.begin(115200);
   while (!Serial) delay(10);     // will pause Zero, Leonardo, etc until      serial console open

   Serial.println("LIS3DH initializing");
   lis.begin(0x18);
   Serial.println("LIS3DH initialized!");

   maxim_max30102_reset(); //resets the MAX30102
   pinMode(10, INPUT);  //pin D10 connects to the interrupt output pin of the MAX30102

   delay(1000);
   maxim_max30102_read_reg(REG_INTR_STATUS_1,&uch_dummy);  //Reads/clears  the interrupt status register

   while(Serial.available()==0)  //wait until user presses a key
   {

      Serial.write(27);       // ESC command
      Serial.print(F("[2J"));    // clear screen command
      Serial.println(F("Press any key to start conversion"));
      delay(1000);

   }

   uch_dummy=Serial.read();
   maxim_max30102_init();  //initialize the MAX30102
}

// the loop routine runs over and over again forever:

void loop() {
  uint32_t un_min, un_max, un_prev_data, un_brightness;  //variables to calculate the on-board LED brightness that reflects the heartbeats
  int32_t i;
  float f_temp;

  un_brightness=0;
  un_min=0x3FFFF;
  un_max=0;

  n_ir_buffer_length=100;  //buffer length of 100 stores 4 seconds of samples running at 25sps

  //read the first 100 samples, and determine the signal range
  for(i=0;i<n_ir_buffer_length;i++)
  {
    while(digitalRead(10)==1);  //wait until the interrupt pin asserts
    maxim_max30102_read_fifo((aun_red_buffer+i), (aun_ir_buffer+i));  //read from MAX30102 FIFO

    if(un_min>aun_red_buffer[i])
      un_min=aun_red_buffer[i];  //update signal min
    if(un_max<aun_red_buffer[i])
      un_max=aun_red_buffer[i];  //update signal max
    Serial.print(F("red="));
    Serial.print(aun_red_buffer[i], DEC);
    Serial.print(F(", ir="));
    Serial.println(aun_ir_buffer[i], DEC);
  }

  un_prev_data=aun_red_buffer[i];

  //calculate heart rate and SpO2 after first 100 samples (first 4 seconds of samples)
  maxim_heart_rate_and_oxygen_saturation(aun_ir_buffer, n_ir_buffer_length, aun_red_buffer, &n_spo2, &ch_spo2_valid, &n_heart_rate, &ch_hr_valid);

  //Continuously taking samples from MAX30102.  Heart rate and SpO2 are calculated every 1 second
  while(1)
  {
    i=0;
    un_min=0x3FFFF;
    un_max=0;

    //dumping the first 25 sets of samples in the memory and shift the last 75 sets of samples to the top
    for(i=25;i<100;i++)
    {
      aun_red_buffer[i-25]=aun_red_buffer[i];
      aun_ir_buffer[i-25]=aun_ir_buffer[i];

      //update the signal min and max
      if(un_min>aun_red_buffer[i])
        un_min=aun_red_buffer[i];
      if(un_max<aun_red_buffer[i])
        un_max=aun_red_buffer[i];
    }

    //take 25 sets of samples before calculating the heart rate.
    for(i=75;i<100;i++)
    {
      un_prev_data=aun_red_buffer[i-1];
      while(digitalRead(10)==1);
      digitalWrite(9, !digitalRead(9));
      maxim_max30102_read_fifo((aun_red_buffer+i), (aun_ir_buffer+i));

      //calculate the brightness of the LED
      if(aun_red_buffer[i]>un_prev_data)
      {
        f_temp=aun_red_buffer[i]-un_prev_data;
        f_temp/=(un_max-un_min);
        f_temp*=MAX_BRIGHTNESS;
        f_temp=un_brightness-f_temp;
        if(f_temp<0)
          un_brightness=0;
        else
          un_brightness=(int)f_temp;
      }
      else
      {
        f_temp=un_prev_data-aun_red_buffer[i];
        f_temp/=(un_max-un_min);
        f_temp*=MAX_BRIGHTNESS;
        un_brightness+=(int)f_temp;
        if(un_brightness>MAX_BRIGHTNESS)
          un_brightness=MAX_BRIGHTNESS;
      }
#if defined(ARDUINO_AVR_LILYPAD_USB)
      analogWrite(13, un_brightness);
#endif

#if defined(ARDUINO_AVR_FLORA8)
      LED.setPixelColor(0, un_brightness/BRIGHTNESS_DIVISOR, 0, 0);
      LED.show();
#endif

      //send samples and calculation result to terminal program through UART
      Serial.print(F("red="));
      Serial.print(aun_red_buffer[i], DEC);
      Serial.print(F(", ir="));
      Serial.print(aun_ir_buffer[i], DEC);

      Serial.print(F(", HR="));
      Serial.print(n_heart_rate, DEC);

      Serial.print(F(", HRvalid="));
      Serial.print(ch_hr_valid, DEC);

      Serial.print(F(", SPO2="));
      Serial.print(n_spo2, DEC);

      Serial.print(F(", SPO2Valid="));
      Serial.println(ch_spo2_valid, DEC);
    }
    maxim_heart_rate_and_oxygen_saturation(aun_ir_buffer, n_ir_buffer_length, aun_red_buffer, &n_spo2, &ch_spo2_valid, &n_heart_rate, &ch_hr_valid);
  }
}

Here is a picture of how the two sensors are wired:

You may find that if you Serial.flush(); after the message, but before the lis.begin(), that the entire message makes it out through serial and then it locks up.  I'm interested to know how it's wired.  You should run the I2C scanner and see if it doesn't also lock up in that as well, in which case you can at least temporarily not be concerned about your project or accelerator specific code.

Serial.flush(); did fix that line of output. I ran the I2C_Scanner and it picked up two sensors (0x18 and 0x57). Do you think that there is an issue with the wiring then? Before running the code with the combined sensors, I run the code for just the PPG and just the accelerometer to make sure both are wired correctly.

You need to solder those connections.  Otherwise you're going to go insane debugging this.


text:
How to completely clear everything from an arduino and print something new?
I'm in progress of making a stickman rush game, Until I hit a bug that I have been stuck on. I want to make a if statement that states "If the stickman and the object are in the same place, clear everything and print "Game over." But when i do this, the object is still there. I tried using "lcd.clear()" but it doesnt seem to affect anything. Is there another way to fix this?
Code:
#include <LiquidCrystal.h>

LiquidCrystal lcd(2, 3, 4, 5, 6, 7);

byte customChar[] = {
  B01110,
  B01110,
  B01110,
  B00100,
  B01110,
  B10101,
  B00100,
  B01010
};

byte gameObstical[] = {
  B11111,
  B11111,
  B11111,
  B11111,
  B11111,
  B11111,
  B11111,
  B11111
};

int vX = A0;
int vY = A1;
int sw = 8;

int xPosition = 0;
int yPosition = 0;
int SW_state = 0;
int mapX = 0;
int mapY = 0;

int screenWidth = 16;
int screenHeight = 2;

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

  pinMode(vX, INPUT);
  pinMode(vY, INPUT);
  pinMode(sw, INPUT_PULLUP);

  lcd.begin(16, 2);
  lcd.createChar(0, customChar);
  lcd.home();
  lcd.write(byte(0));

  lcd.createChar(1, gameObstical);

}

void loop() {

  int stickManPosition = 0;
  int obsticalPosition = 0;
  int stickManRow = 0;
  int obsticalRow = 0;

  int obsticalPosition2 = 0;
  int obsticalRow2 = 0;

  for (obsticalPosition = 15; obsticalPosition >= 0; obsticalPosition--) {
    lcd.setCursor(obsticalPosition, obsticalRow);
    lcd.write(byte(1));
    lcd.print(" ");
    delay(150);

    xPosition = analogRead(vX);
    yPosition = analogRead(vY);
    SW_state = digitalRead(sw);
    mapX = map(xPosition, 20, 1003, -500, 500);

    Serial.println("-----------");
    Serial.println(mapX);
    Serial.println(SW_state);
    Serial.println("-----------");

    if (mapX > 200) {

      lcd.clear();
      lcd.setCursor(stickManPosition, stickManRow);
      lcd.write(byte(0));

    } else if (mapX < -200) {

      stickManRow = 1;

      lcd.clear();
      lcd.setCursor(stickManPosition, stickManRow);
      lcd.write(byte(0));
    }

    if (stickManPosition == obsticalPosition) {
      if (stickManRow == obsticalRow) {

        lcd.clear()
        lcd.print("Game Over...");
        delay(150);

      }

      if (obsticalPosition == 12) {

        for (obsticalPosition2 = 11; obsticalPosition2 >= 0; obsticalPosition2--) {
          obsticalRow2 = 1;

          lcd.setCursor(obsticalPosition2, obsticalRow2);
          lcd.write(byte(1));
          lcd.print(" ");
          delay(150);
        }
      }
    }
  }
}

Any ideas? Thanks for reading.

You could just make setCursor(0,0);, print sixteen spaces and repeat it for the second row... But I'm sure there's a better way.

I've not intensively looked over your sketch. But, is it possible that the screen is really cleared with lcd.clear(). "Game over" is visible for less than 150 milliseconds and then other code in the loop function overwrites it with the stickman again. 150 ms is a very short time. Would you please change the delay(150) after the clear to let's say delay(3000);. To see if my guess is true?

You need to distinguish between someone actively playing a game and the game being over. You really need to implement a finite state machine.

you should create a condition to write objects, If game is over then dont draw objects else draw objects. or after your game is over create an infinite loop and get button push for break loop.


text:
How can I share one power supply between an arduino and servos?
I'm trying to power an arduino and a few modules (RF receiver, two servos, and a laser diode) through one power supply.
I get jittery/unresponsive servos when hooked up in the following configuration:

power supply goes to usb breakout, joins with top + and - rails, powers everything (tried
all grounds go to top - rail
black/grey/white wires going off right side are power/ground for the servos
red, green, yellow wires going off left/top side are signals to the servos/laser
purple wire going off left/top is ground for the laser

If I remove the orange wire (usb breakout to + rail) and plug another power supply into the Arduino, the poor performance disappears and everything works nicely.
Since my power supply is 2.5A, I doubt that I don't have enough power for this setup. This leads me to believe that the Arduino/receiver side of the circuit is making the voltage unstable so the servos misbehave. Is there a way I can isolate these two parts of the circuit (diode, capacitor?) so that I can power the whole setup with one cable?
Components:

Arduino pro micro (5v)
RF Link Receiver (WRL-10532, 434 MHz)
Servo (ROB-09065, sub-micro)
Laser diode (5V, 20mA)
Micro USB breakout (1A)
USB Micro power supply (5.1V, 2.5A)

Sorry, that image does not show up. And when I follow its link, I'm required to log into google. If you save the image on your PC and then drag and drop it into the image field, the image will be uploaded correctly.

What USB breakout board do you have exactly? It might not be able to provide the needed current.

Interesting--I tested in incognito and the picture still loaded.. guess there's some interesting access caching going on. Should be visible now?

Good call--it looks like the breakout says 1A (edited it into the post). That still feels high enough for these components, but maybe they are trying to pull more than this?

Yes, I can see the image now. How are you powering the Arduino? I don't see a wire from the USB breakout Vcc to the red rail (where Vcc of the Arduino is connected)

My mistake, ended up with the wrong photo. Corrected now.

You're not feeding the +5V into the USB port of the Arduino, are you, and then trying to power everything through the Arduino's +5V lines?

You need to figure out your total current requirements. Don't guess, figure it out. What is the peak current draw of the servos? of the other components? Add everything up. If the total is within 20% of your power supply current, that may be the problem.
Also, servos tend to draw spikes of current. You might need to add a filter capacitor to the +5V rail on the Arduino to even out dips as the servos cause sags in current before the voltage regulator in your power supply can compensate. (Put the cap between +5V and ground right at the Arduino.)

Fair. I estimated 0.2 + 0.25 * 2 ≈ 0.7A peak, but I'll measure to confirm. I wasn't considering that large a margin either. I'll also try the filter capacitor. Thanks!

The closer you get to the power supply's limits, the more its voltage is likely to "bobble" as the load varies, and motors loads are usually quite "spiky".

I too have found the servo driving of the Arduino ie UNO to be jittery. The problem is that the Arduino uses a timer, interrupts and software to terminate the pulse so if the processor is busy servicing another interrupt then the pulse gets extended by up to 10us. Modern servos, even the cheap ones, respond to this delay as if it were noise.
The servo library was dependent on clock frequency, and limited to pins 9 & 10, at one point in time, although that might have been fixed in updated versions. out of curiosity, what pins are you attaching your servos to? (9 or 10?)
you might try updating your version of the ardunio IDE/Libraries.
another thought, is that many servos are rated at 6V (not 5v), and while they will work, they may also be jittery. you might find it best to use a separate power supply. Be sure to connect the grounds of the Arduino and external power supply together.
From Servo.h:
...
    //attach(pin )  - Attaches a servo motor to an i/o pin.
    //attach(pin, min, max  ) - Attaches to a pin setting min and max values in microseconds
    //default min is 544, max is 2400
...

#define MIN_PULSE_WIDTH       544     // the shortest pulse sent to a servo
#define MAX_PULSE_WIDTH      2400     // the longest pulse sent to a servo
#define DEFAULT_PULSE_WIDTH  1500     // default pulse width when servo is attached
#define REFRESH_INTERVAL    20000     // minumim time to refresh servos in microseconds
...

you might try tweaking the min, max, and default settings, or check your code against the settings provided by Servo.h.


text:
How to avoid two arduino components using the same digital PIN
I'm trying to build an Arduino project where it involves a TFT and an ethernet W5500 component.
Here's the project I want to build to learn Arduino. However I wanted to change the board that already has an ethernet PoE here. The TFT I plan to use is a shield. It seems that pin D10 are being used by both components.
Is it possible through software to use a different Digital pin through software for either the board or the TFT display?  I have read where users are cutting traces and using jumper wires - would that be required in my case? I am planning on using SPI pins if possible. Thanks!

Sorry - let me edit.  I forgot to mention the TFT I plan on using is a shield. The W5500 mention in my link is built-in to the board and uses CS10.

Yes you can, but you will need to modify your TFT screen shield to disconnect pin 10 and route it to an unused pin.

Just connect the pin that would go into D10 to an unused pin with a cable. When defining TFT_CS, change the 10 simply to the pin you used.


text:
Endurance of Arduino UNO during 24/7 operations and mild power fluctuations
I am designing an automation system for my research project and planning on using Arduino Uno to do the same. The program is to execute simple instructions based on few input parameters and does not need large computational powers. It is estimated it would take 26 minutes to run the program (26-minute cycle*) and it is expected that it would take anywhere from 3 weeks to 2 months to complete the project (1160 - 3300 cycles before reboot)
My question is as follows:

Is the Arduino Uno capable of surviving the extended service expectancy and execute the program correctly?
What is the influence of small voltage fluctuations on the endurance of electronics on the board?
Is a heat sink needed for this application? How to determine the power draw to choose heat sink size?
Is there any fatigue rating for the cyclic running of the program?

I am planning to power the entire system via a regulated 12V 600-watt battery bank and this bank would be periodically recharged.
*By cycle duration I mean the real word time required for completion of one batch. It is estimated that it's required to complete 1160-3300 cycles/batches for the research

Can your application tolerate the MCU resetting via the use of a watchdog timer?

Is the Arduino Uno capable of surviving the extended service expectancy and execute the program correctly?

Yes, it is. Though your program and wiring needs to be stable and correct.

What is the influence of small voltage fluctuations on the endurance of electronics on the board?

Depends on what you call small. As long as you don't enter the brown-out region (where the voltage is so low, that the Arduino goes into reset for safety) or giving a too high voltage to it (See the specifications for that), you should be fine.

Is a heat sink needed for this application? How to determine the power draw to choose heat sink size?

The power draw of the Arduino depends on what you are doing with it. The best way would be to just measure the current of your application. Then you get the power by multiplying current and voltage. Normally you don't need a heatsink with an Arduino. The only part, that can get hot, is the linear voltage regulator. Depending on what you are interfacing with the Arduino, you might need to put a small heat sink on that (12V is a bit on the high side of input voltage for the regulator. It will dissipate the excess 7V as heat, so 7V multiplied by the used current). The microcontroller on the Arduino will not get hot (unless you are doing something terribly wrong).
And you should make sure, that the current for extra peripherals in your project doesn't flow through the Arduino, since that will place an extra burden on the voltage regulator. It should flow past it (means you connect them in parallel to the voltage source).

Is there any fatigue rating for the cyclic running of the program?

No, not really. I think the flash memory (where the program is stored) has a data retention failure rate of less then 1ppm (parts per million) over 20 years. So the program will not be lost, until you plan to run your application a hundret years. Also there is no read limit on the flash memory, only a write limit.

Since the Arduino itself uses a linear regulator, the OP might get nearly twice as much work out of their 12V battery with a switching power supply (even if only stepping down to 6 or 7V to feed the input side of the linear regulator, not bypassing it with a 5V switcher.)  I'm assuming the Arduino draws enough current to make an efficient SMPS possible, and the linear regulator only needs a volt or two of dropout range.

Connecting up their batteries in parallel instead of series to form a 6V bank with twice the mAh capacity would be good in theory, but only if they don't droop much below 6V as they discharge.  (I don't know what kind of low-dropout linear regulator Arduino Uno uses.)  If the battery geometry allows it, 9V or 8V that can droop down to 6V would probably be good.

You are right with your first comment, though I  didn't talk about it in my answer, since the OP didn't ask about the regulator or power supply. For the second comment: It is correct, but we don't know, if the OP uses individual batteries, which would be able to form a 6V bank. He didn't specify what power bank he uses. Only that its 12V

Yeah, I only mentioned it in case it was possible.  Thought you might want to mention something in your answer about selecting a DC->DC converter IC to avoid wasting half the energy in your batteries if that's worth the trouble, and what the minimum dropout for an arduino's linear regulator is, but if not then at least it's in comments.

I see no problems in that. Given the program you write is stable and correct, the Arduino UNO will certainly work without any problems for months. It has an integrated voltage regulator, so you can attach a 12V battery directly and it automatically regulates voltage changes. The CPU and/or flash do not have any "fatigue" problems as long as the program is only read or executed. The program flash has a limited number of write cycles, but that also is far beyond where you'll get problems.
Where I do see a problem is in your use case. You seem to be doing quite complex mathematics with quite a lot of data, when one cycle takes 26 Minutes. You might not have enough RAM on the UNO to do this. It has only 2.5k (that is around 2500 bytes) of RAM. Where do you store the results?

It's actually 2 K of RAM.

@PFM Kindly refer to the edit in the question clarifying the run time.

How much data do you collect per cycle? And how do you intend to store that data (copy it to a PC?)

I have Arduino here powered over year long, still working (running the same loop() again and again) without a glitch and it is not even hand-temperature hot in my living room - I expect it to run flawlessly for lot more years, until I will switch it off :)


text:
Can internal and external pull up/pull down resisters be used together?
What happens if a sketch uses code like pinMode(18,INPUT_PULLDOWN) to configure internal pull-down (or pull-up) resistors, but is used in a circuit where external resistors are also present?
Are there likely to be any problems, conflicts or unexpected behaviour, e.g. if software sets a pull-down, but there is an external pull-up, or visa versa?
I am using an ESP32 (which has both internal pull-ups and pull-downs available on most GPIO pins), but I would appreciate a general answer. To clarify, I am not after the pros and cons of using external resistors (which is discussed in other questions), but the potential pitfalls of using both, especially if they are pulling in opposite directions.

The main risk if you use both internal and external pullup/down resistors working in opposite directions is that the input will be left at an intermediate voltage that is not guaranteed to be read as high or low. Furthermore a little noise on the input might flip a read from high to low or vice versa. There is no risk of damaging the input however

It is dependent on the value of the resistors. The "resistors" in microprocessors are generally of a high value and have a large value tolerance. Sometimes it is desirable to hold a pin in a specific state until the system initializes it to possibly a different state.

When you add the external resistor it will be connected to the internal pull resistor (up or down) depending on configuration. The pull resistor will either be series or parallel with the external resistor. In series it will behave as a voltage divider, in parallel it will increase the current required to cause the pin to change state. Mixing will not harm the computer as the pull resistor is designed to be connected to the opposite polarity externally. With the data sheet and the value of your resistor you can calculate the current and or voltage. You do not want to use external pull up and pull down resistors on the same pin. It may work but it is best to do the calculations to see if it will give you a viable value.

It is actually beneficial for the chip to have an additional pull-up or pull-down. It can help to reduce noise and to protect from ESD on the pin coming in. The internal resistors can only take a very small amount of current and an external can take some of the current in case an ESD event is happening.
The downsides of an external resistor are (not complete list):

space requirements
cost (although very low cost)
slightly increased power consumption

If these are not a problem for you, an external resistor is a good idea.
Here is a video (not me), that explains the ESD-part it in more detail.
EDIT:
I just re-read your question and saw that you asked about mixing pull-up and pull-down. That you should normally not do as jksemple said.

pinMode(18,INPUT_PULLDOWN) ? There is no such thing! you use a resistor for that. only pullup internal available_

it is. some Arduino platforms use MCU with internal pulldown


text:
Multiple MQTT topics
I have 3 nodemcu's(ESP32) each connected with a sensor, from which I get data and send it to aws IoT-core. How can I send all 3 sensor's data by a single MQTT subscription? The below code is for a single MQTT using one nodemcu.
#include "SPIFFS.h"
#include <WiFiClientSecure.h>
#include <Wire.h>
#include <PubSubClient.h>

float V_0 = 5.0; // supply voltage to the pressure sensor
float rho = 1.204; // density of air

// parameters for averaging and offset
int offset = 0;
int offset_size = 10;
int veloc_mean_size = 20;
int zero_span = 2;

const char* ssid = ""; //Provide your SSID
const char* password = "";          // Provide Password
const char* mqtt_server = "a3mtl8k0aiowyx-ats.iot.us-east-2.amazonaws.com"; // Replace with your MQTT END point
const int mqtt_port = 8883;

String Read_rootca;
String Read_cert;
String Read_privatekey;
//=============================================================================================================================
#define BUFFER_LEN  256
long lastMsg = 0;
char msg[BUFFER_LEN];
int value = 0;
byte mac[6];
char mac_Id[18];
int count = 1;
int id=1;
//=============================================================================================================================

WiFiClientSecure espClient;
PubSubClient client(espClient);

void setup_wifi() {
  delay(10);
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

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

  randomSeed(micros());

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

void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }
  Serial.println();
}
void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Create a random client ID
    String clientId = "ESP32-";
    clientId += String(random(0xffff), HEX);
    // Attempt to connect
    if (client.connect(clientId.c_str())) {
      Serial.println("connected");
      // Once connected, publish an announcement...
      //client.publish("ei_out", "connection success");
      // ... and resubscribe
      client.subscribe("ei_in");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

void setup() {
  Serial.begin(115200);
    for (int ii=0;ii<offset_size;ii++){
    offset += analogRead(34)-(1023/2);
  }
  offset /= offset_size;
  Serial.setDebugOutput(true);
  // initialize digital pin LED_BUILTIN as an output.
  pinMode(2, OUTPUT);
  setup_wifi();
  delay(1000);
  //=============================================================
  if (!SPIFFS.begin(true)) {
    Serial.println("An Error has occurred while mounting SPIFFS");
    return;
  }
  //=======================================
  //Root CA File Reading.
  File file2 = SPIFFS.open("/AmazonRootCA1.pem", "r");
  if (!file2) {
    Serial.println("Failed to open file for reading");
    return;
  }
  Serial.println("Root CA File Content:");
  while (file2.available()) {
    Read_rootca = file2.readString();
    Serial.println(Read_rootca);
  }
  //=============================================
  // Cert file reading
  File file4 = SPIFFS.open("/9bcef01134-certificate.pem.crt", "r");
  if (!file4) {
    Serial.println("Failed to open file for reading");
    return;
  }
  Serial.println("Cert File Content:");
  while (file4.available()) {
    Read_cert = file4.readString();
    Serial.println(Read_cert);
  }
  //=================================================
  //Privatekey file reading
  File file6 = SPIFFS.open("/9bcef01134-private.pem.key", "r");
  if (!file6) {
    Serial.println("Failed to open file for reading");
    return;
  }
  Serial.println("privateKey File Content:");
  while (file6.available()) {
    Read_privatekey = file6.readString();
    Serial.println(Read_privatekey);
  }
  //=====================================================
  char* pRead_rootca;
  pRead_rootca = (char *)malloc(sizeof(char) * (Read_rootca.length() + 1));
  strcpy(pRead_rootca, Read_rootca.c_str());

  char* pRead_cert;
  pRead_cert = (char *)malloc(sizeof(char) * (Read_cert.length() + 1));
  strcpy(pRead_cert, Read_cert.c_str());

  char* pRead_privatekey;
  pRead_privatekey = (char *)malloc(sizeof(char) * (Read_privatekey.length() + 1));
  strcpy(pRead_privatekey, Read_privatekey.c_str());

  Serial.println("================================================================================================");
  Serial.println("Certificates that passing to espClient Method");
  Serial.println();
  Serial.println("Root CA:");
  Serial.write(pRead_rootca);
  Serial.println("================================================================================================");
  Serial.println();
  Serial.println("Cert:");
  Serial.write(pRead_cert);
  Serial.println("================================================================================================");
  Serial.println();
  Serial.println("privateKey:");
  Serial.write(pRead_privatekey);
  Serial.println("================================================================================================");

  espClient.setCACert(pRead_rootca);
  espClient.setCertificate(pRead_cert);
  espClient.setPrivateKey(pRead_privatekey);

  client.setServer(mqtt_server, mqtt_port);
  client.setCallback(callback);

  //====================================================================================================================
  WiFi.macAddress(mac);
  snprintf(mac_Id, sizeof(mac_Id), "%02x:%02x:%02x:%02x:%02x:%02x",
       mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
  Serial.print(mac_Id);
  //=====================================================================================================================
}

void loop() {
    float adc_avg = 0;
    float veloc = 0.0;

// average a few ADC readings for stability
  for (int ii=0;ii<veloc_mean_size;ii++){
    adc_avg+= analogRead(34)-offset;
  }
  adc_avg/=veloc_mean_size;

  // make sure if the ADC reads below 512, then we equate it to a negative velocity
  if (adc_avg>512-zero_span and adc_avg<512+zero_span){
  } else{
    if (adc_avg<512){
      veloc = -sqrt((-10000.0*((adc_avg/1023.0)-0.5))/rho);
    } else{
      veloc = sqrt((10000.0*((adc_avg/1023.0)-0.5))/rho);
    }
  }
//  Serial.println(veloc); // print velocity
//  delay(10); // delay for stability
  //===============================================

  if (!client.connected()) {
    reconnect();
  }
  client.loop();

  long now = millis();
  if (now - lastMsg > 5000) {
    lastMsg = now;
    //=============================================================================================
    //String macIdStr = mac_Id;
    String sensor_id=String(id);
    String Velocity = String(veloc);
    snprintf (msg, BUFFER_LEN, "{\"sensor_id\" : \"%s\", \"Velocity\" : \"%s\"}", sensor_id.c_str(), Velocity.c_str());
    //"{\"mac_Id\" : \"%s\", \"Velocity\" : %s, \"sensor_id\" : \"%s\"}"
    Serial.print("Publish message: ");
    Serial.print(count);
    Serial.println(msg);
    client.publish("ei_out", msg);
    count = count + 1;
    //================================================================================================
  }
  digitalWrite(2, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);                       // wait for a second
  digitalWrite(2, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);                       // wait for a second
}

ei_out is the topic I have subscribed in iot-core,
I wish to have one more ei_out_1 from another nodemcu

ei_out is the topic I have subscribed in iot-core, I wish to have one more ei_out_1 from another nodemcu -- So... have another called ei_out_1...? I don't understand what you're asking. If you want to send to a different topic then send to a different topic.

How can I send all 3 sensor's data by a single MQTT subscription? .... same way that you would place three words on one piece of paper? .... BTW, data is sent by publishing,  subscription is for receiving data

You're not subscribing to ei_out but only to a topic called ei_in (defined in reconnect()). What you want is to publish. At the moment, you're using only ei_out to publish (client.publish("ei_out") in loop()). You can freely create additional topics (with different names than "ei_out") to publish data from other sensors.

Publishing has to have an explicit topic. Subscribing has two wild cards # which means anything below this level in the hierarchy and + which means anything at the next level of the hierarchy. The division between hierarchical levels is the / character. So if sensor one publishes on sensor/1/out/temp1 and sensor two publishes on sensor/2/out/temp1 you can subscribe to sensor/+/out/temp1 to read from both sensors. You can subscribe on sensor/1/out/+ to read anything sent by sensor one. You can subscribe to sensor/# to read any output from any sensor.

change ei_out and ei_out_1 to ei/out and ei/out/1 to get the benefits of the hierarchical topic structure. The only hard part of this stuff is designing a sensible and coherent hierarchy for your topics.


text:
When it comes to UART to RS485 communication, what is the difference between the 'MAX485' and the 'HW-0519' module?
I recently found this model with the ID 'HW-0519' on it. It can be found online (HW-0519 in Aliexpress) and is sold for the purpose of converting UART to RS485 communication using Arduino devices. The MAX485 module (MAX485 in Banggood) is the more commonly used module for this purpose and has been used in many projects. The MAX485 has the following pins DI (data in), RO (receiver out), DE (Data Enable), RE (Receiver Enable), VCC, GND and the 'A' and 'B' pins for the RS485 device (Shown below).

The HW-0519 module, has a slightly different pin configuration, and I can't seem to wrap my head around it. It has Tx and Rx pins, which I am guessing match up with RO and DI respectively, but don't have enable pins. They have the VCC and GND pins along with the 'A' and 'B' pins, but also come with this pin marked in Chinese. I translated it using Google translate and it translates to something similar to 'Ground'. Which is not connected to the GND pin though (Shown below).

Does anyone know whether I can use the HW-0519 module in the same manner as the MAX485? If so, are there any libraries written for this module? I want to use the module for communication with a pH sensor like the one in this link.

Looks like the HW-0519 module implements automatic TX/RX mode switching for you.

@Majenko does that mean I need not concern myself with controlling the direction of the data when writing the code with this HW-0519?

@Majenko because, from what I understand, the DE and RE in the MAX485 module are usually connected together to one pin in the microcontroller and set to HIGH when transmitting and LOW when receiving.

Theoretically, though there may be baud rate considerations to take into account and pre/post send delays or something. I don't know how the module works, so YMMV with it.

I did a bit of research and found others who use this particular component for their RS485 communication purposes. It is difficult to get clear info because the device goes by different names and the most commonly used name is MAX485 (name of the IC), which is used interchangeably for both the components shown in the question.
It seems the more I search for the 'HW-0519', the more names I find for it. So far, it goes by the name 'MAX485', 'XY-017', and 'XY-K485'. A clear advantage for this 'HW-0519' is that it does not require D or R enabling, just straightforward Tx and Rx. It also has LEDs to show the data transfers. I found a project that used this module here. I am unsure about their pin connections from the ESP-32 though. It looks like they've connected the ESP-32's TX2 to the HW-0519's Tx, and the RX2 to the Rx. I thought it should be the other way around.

I confirm the module has to be connected like: Module TX--TX MCU and Module RX--RX MCU

I have the HW-0519 (bought as https://www.amazon.co.uk/gp/product/B0BCFLTLGJ/ at £9.98 for 8x in 2023-09) and it matches the picture above quite closely enough. It is a variant, and the first difference I see is the (?) polyfuses JK075 above are T010 on mine.
I picked this because it has protection components on the board which others don't have - including the MAX485 board from Banggood linked above.
Both boards lack mounting holes but the MAX485 board has pins which (if they align?) might assist breadboard usage. For me, the prototyping phase will start with epoxying HW-0519 to a Lego brick.
I found a circuit diagram at https://easyeda.com/modules/HW-0519-TTL-to-RS485-converter_c4836920e8ec45b3924add8ac2acbe57 for something similar which helped me work out what's what. I'm not going to steal a copy and upload here but it looks like https://web.archive.org/web/*/https://image.easyeda.com/components/c4836920e8ec45b3924add8ac2acbe57.png .

Starting at the A+ / B- lines,
fuses F1 and F2 of type "108L" (presumably polyfuse type),
120Ω bus termination R14 across,
then an SM712 asymmetric TVS protection chip https://www.semtech.com/products/circuit-protection/rs485/sm712 ,
finally the pull-up resistors 4k6 and MAX348 chip named U6.

My board is a cousin of the circuit diagram I found.

chips are named U2 (unmarked SOIC14, maybe 74HC04) and anon unmarked SOIC8,
its TVS protection is done as three chunky 2-pin diodes marked WK as in the HW-0519 above,
bus termination resistor is R9 and you have to short R0 to terminate the bus, so one at each end but not in the middle, in the usual way.
TVS protection comes to that third bus pin 球大(??) which I think is "earth big (something)"

Note that the bus ground is not connected to the logic ground GND on the 4-pin connector. You need to provide bus ground separately and maybe from a different source after considering fault currents.


text:
LILYGO TTGO T-Display cannot detect MPU 6050 Accelerometer, Gyroscope and Temperature Sensor
I've been trying to connect a MPU 6050 Accelerometer, Gyroscope and Temperature Sensor to a LILYGO TTGO T-Display to get readings displayed on the serial monitor (for starters). The wiring is pretty straightforward. I need to power up the MPU6050 with 3V, and connect the SDA and SCL. I followed this tutorial (https://randomnerdtutorials.com/esp32-mpu-6050-accelerometer-gyroscope-arduino/).
This is the code used:
#include <Adafruit_MPU6050.h>
#include <Adafruit_Sensor.h>
#include <Wire.h>

Adafruit_MPU6050 mpu;

void setup(void) {
  Serial.begin(115200);
  while (!Serial)
    delay(10); // will pause Zero, Leonardo, etc until serial console opens

  Serial.println("Adafruit MPU6050 test!");

  // Try to initialize!
  if (!mpu.begin()) {
    Serial.println("Failed to find MPU6050 chip");
    while (1) {
      delay(10);
    }
  }
  Serial.println("MPU6050 Found!");

  mpu.setAccelerometerRange(MPU6050_RANGE_8_G);
  Serial.print("Accelerometer range set to: ");
  switch (mpu.getAccelerometerRange()) {
  case MPU6050_RANGE_2_G:
    Serial.println("+-2G");
    break;
  case MPU6050_RANGE_4_G:
    Serial.println("+-4G");
    break;
  case MPU6050_RANGE_8_G:
    Serial.println("+-8G");
    break;
  case MPU6050_RANGE_16_G:
    Serial.println("+-16G");
    break;
  }
  mpu.setGyroRange(MPU6050_RANGE_500_DEG);
  Serial.print("Gyro range set to: ");
  switch (mpu.getGyroRange()) {
  case MPU6050_RANGE_250_DEG:
    Serial.println("+- 250 deg/s");
    break;
  case MPU6050_RANGE_500_DEG:
    Serial.println("+- 500 deg/s");
    break;
  case MPU6050_RANGE_1000_DEG:
    Serial.println("+- 1000 deg/s");
    break;
  case MPU6050_RANGE_2000_DEG:
    Serial.println("+- 2000 deg/s");
    break;
  }

  mpu.setFilterBandwidth(MPU6050_BAND_5_HZ);
  Serial.print("Filter bandwidth set to: ");
  switch (mpu.getFilterBandwidth()) {
  case MPU6050_BAND_260_HZ:
    Serial.println("260 Hz");
    break;
  case MPU6050_BAND_184_HZ:
    Serial.println("184 Hz");
    break;
  case MPU6050_BAND_94_HZ:
    Serial.println("94 Hz");
    break;
  case MPU6050_BAND_44_HZ:
    Serial.println("44 Hz");
    break;
  case MPU6050_BAND_21_HZ:
    Serial.println("21 Hz");
    break;
  case MPU6050_BAND_10_HZ:
    Serial.println("10 Hz");
    break;
  case MPU6050_BAND_5_HZ:
    Serial.println("5 Hz");
    break;
  }

  Serial.println("");
  delay(100);
}

void loop() {
  /* Get new sensor events with the readings */
  sensors_event_t a, g, temp;
  mpu.getEvent(&a, &g, &temp);

  /* Print out the values */
  Serial.print("Acceleration X: ");
  Serial.print(a.acceleration.x);
  Serial.print(", Y: ");
  Serial.print(a.acceleration.y);
  Serial.print(", Z: ");
  Serial.print(a.acceleration.z);
  Serial.println(" m/s^2");

  Serial.print("Rotation X: ");
  Serial.print(g.gyro.x);
  Serial.print(", Y: ");
  Serial.print(g.gyro.y);
  Serial.print(", Z: ");
  Serial.print(g.gyro.z);
  Serial.println(" rad/s");

  Serial.print("Temperature: ");
  Serial.print(temp.temperature);
  Serial.println(" degC");

  Serial.println("");
  delay(500);
}

The pinout config for the TTGO T Display is shown below:

I connected the pins based on this as follows:
TTGO        MPU6050
3V  ---->  Vcc
G   ---->  Gnd
22  ---->  SCL
21  ---->  SDA
But I keep getting the following error on the serial monitor.
ets Jul 29 2019 12:21:46

rst:0x1 (POWERON_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
configsip: 0, SPIWP:0xee
clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
mode:DIO, clock div:1
load:0x3fff0030,len:1324
ho 0 tail 12 room 4
load:0x40078000,len:13508
load:0x40080400,len:3604
entry 0x400805f0
Adafruit MPU6050 test!
Failed to find MPU6050 chip

What is strange is that the MPU 6050 works perfectly fine with the same pin connection on the normal Node MCU ESP 32 system. Any idea why it won't work on the TTGO?

I had exactly the same error (Failed to find MPU6050 chip)on the same program with the same tutorial. I thought it was this, that, and an act of nature. I hade proven the MPU6050 worked fine and the ESP32 worked fine. EVENTUALLY I realised it was dead simple, the ESP32 ( a cheapo one) had different pinout to the one in the tutorial, SCL,SDA and 3.3v were in the wrong place even though the red LED illuminated on my MPU6050 board. Anyway I wired it correctly and it works just fine and the Webserver one too. I did not do the display one! ( Don't take anything for granted). I do not know which incarnation of the MPU6050 you are using but when using mine (looked identical as the one in the tutorial) on an ESP8266 the I2C addressing was a bit finicky and I had to take the address connection hard to GND  with a wire to get it to run consistently, that too caused the same error (Failed to find MPU6050 chip).


text:
Issues with interrupts coming from RTC DS3231 and power supply interference
Several months ago I developed a device able to detect water flood in a closed space and do some operations in case (closing valves, issuing an acoustic and Bluetooth alarm etc.).
After 8 hours it tries to reopen the valves and restart the normal cycle. Arduino UNO is always in sleeping mode (this device remains active 7/24). It wakes up every minute (@ sec.00) to detect presence of water, checks for 4 cycles (4 minutes) the presence of water -if the sensors are on- and then, after have issued the alarms and closed the valves, it wakes up after 8 hours, in order to reopen the valves and come back in its normal check-mode.
It worked and works flawlessly, when left working on my table. I tried it for almost a month.  The problem raised when I installed it in place, because there is a water pump (an autoclave, of some 1,5Hp, 1 phase), connected on the same power supply line, that -of course- starts whenever somebody opens a water valve at home.
Whenever it starts, Arduino wakes up immediately and the 1 minute (or 8 hours waiting cycle) stops.

I tried to use several caps on the 12V power supply line (some 3000uF, 50Vl in total) and a EMI filter between the power supply line and my device, but nothing changed.

I made some mods on the software, checking if the wakeup hour and minute is compatible with the correctly wakeup time calculated and setted on Arduino, and storing an alarm flag with wakeup hour and minute in EEPROM, in order to manage the same check if Arduino undergoes a hardware reset or is turned off/on.

I suspect that the problem raises for the fact that the RTC interrupt is activated when the IRQ pin is lowered from the HIGH state.
There is a way to set the DS3231 to remain in LOW state always, and issue a HIGH level just for the interrupts?
Does anybody have any electrical suggestion? I use this 12V chinese switching UPS/power supply connected to a 12V-7Ah lead battery that assures no interruptions.

I don't know how to ask you clarifying questions about this without them also implicitly containing an answer: best attempt show the wiring and find out whether or not you're tripping the UNO's brownout detector.

Thank you very much for your answer.
I'm puzzled a little bit.
my power supply gives some 10A (@13,4V), and it's connected to a big 12V-7Amps (4,5lbs) brand new lead battery (*) to Arduino (on VIN pin+ground) + a 7805.
The 7805 feeds a couple of water sensors (less than 5mA each), the DS3231RTC, 3 LEDs plus the relais board (2 relais, some 55mA each when excited), of course all the grounds connected togheter.
(*)  https://www.amazon.it/gp/product/B071JMHMN6/ref=ppx_yo_dt_b_asin_title_o01_s00?ie=UTF8&psc=1
I did not draw the wiring diagram yet, but I will make it ASAP

It would probably help to see it diagrammed. In your setup() can you do something like blink an led with an easily recognizable pattern such that if your Arduino UNO resets, you will be able to tell very clearly?

yes. I normally do not write diagrams for very simple circuits, but its just a my fault, of course.
In the front of my device there are 3 main leds, I blink them all for 1/2 second in the setup function.
They don't light up during these strange "resets".
I believe that something different happens, like just a unexpected, wakeup that happens just when a transient noise happens in line power.
I prepared a new firmw. version (that I will try tomorrow) in which I always check datetime after the wakeup, reading it from the EEPROM, in which I write in case of flood, just before to go to sleep.

Today I've done other tests:

Arduino does not emit serial messags after those strange resets - it' clearly visible that continues to work by the blinking leds - to obtain messages it's needed to reset Arduino (close/reopen serial window in IDE or push reset);
changing power line does not change anything - I connected it to another power line, completely isolated from the original one and the problem persists;
leaving it powered just by the big battery does not change anything (!) when the pump starts Arduino wakes up!

...an EMI? I connected all the grounds to earth

Without compilable code and a diagram there's not much for me to ask, say, or do.

My guess would be EMI. Can you twist and shield the power lines from the big battery to the Arduino? Do you have a oscilloscope? You could try to see if there is a spike in the 5V power to the Arduino when the pump starts running.


text:
Data output , ds18b20 , lcd1602 , yl-69, dht11
Good afternoon, I wonder if you could help me. I have the code but the data from the sensors is not correct. Perhaps there are some errors, could you fix them?
I apologise for my inaccurate statement. I have the task of displaying data from three sensors on the screen. I've written a sketch, but it doesn't work correctly. That is, the data from two sensors (ds18b20, yl-69) is not displayed correctly. I think the problem is with the sketch.
The data from sensor ds18b20 is constantly displayed differently, and partly depends on the data from sensor yl-69, although it should not. All sensors should work separately from each other, but give their data to the arduino
#include <DallasTemperature.h>

#include <OneWire.h>
#include <DS18B20.h>

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

#include <DHT.h>

const uint8_t ds1Pin{7};            // DS18b20 будем подключать к пину D7
const uint32_t msRepTime {10000};   // DS18b20 будем опрашивать каждые 10 секунд (по факту каждые 11)
uint32_t msTemp {msRepTime};        // Объявляем счетчик для опроса DS18b20 и инициализируем его значением для моментального начала процедуры
const uint8_t simvol[8] = {B11100,B10100,B11100,B00000,B00000,B00000,B00000,B00000};
uint8_t ds1Qty {1};                 // Количество датчиков DS18b20 на пине (не более 3-х). Если больше одного, значения будут усредняться
int8_t  ds1Temp {0};                // Собственно, значение температуры по Цельсию от DS18b20
uint8_t ds1DS[3][8];                // Адреса положу пока здесь. Если кому не лень, их нужно убрать из глобальной ОВ, как и количество датчиков

const uint8_t DHTPin{8};            // DHT будем подключать к пину D8
float dhtTemp {0};                  // DHT значение температуры
float dhtHum {0};                   // DHT значение влажности
const uint32_t msDhtTime {5017};    // DHT будем опрашивать каждые 5+ секунд. "Кривое" значение, чтобы не пересекаться по времени с опросом DS
uint32_t msDht {msDhtTime};         // Объявляем счетчик для опроса DHT и инициализируем его значением для моментального начала процедуры

const uint8_t ylPin{14};            // YL будем подключать к пину A0(14). ВНИМАНИЕ: подключение аналогового выхода датчика!
uint16_t ylVal{0};                  // Переменная для показаний датчика влажности YL
const uint32_t msYlTime {100};      // YL будем опрашивать каждые 0.1 секунд, чтобы МК хоть чем-то был занят в цикле))
uint32_t msYl {0};                  // Объявляем счетчик для опроса YL-69

const uint32_t msPageExpo {5000};   // Устанавливаем по 5 секунд на отображение каждой страницы
uint32_t msPage {0};                // Объявили счетчик для экрана

LiquidCrystal_I2C lcd(0x27, 16, 2);
DHT dht(DHTPin, DHT11);
OneWire oneWire(DS18B20);

void setup() {
  Serial.begin(9600);     // Скорость должна соответствовать настройкам монитора порта
  lcd.init();
  lcd.backlight();
  dht.begin();
  searchSensors();          // Запускаем первоначальный поиск датчиков DS18b20 на пине
}

void loop() {

  if (millis() - msTemp > msRepTime)  updateTemp();       // Опрашиваем температуру DS18b20 с частотой msRepTime
  if (millis() - msDht > msDhtTime)   runDht();           // Опрашиваем DHT
  if (millis() - msYl > msYlTime)     runYl();            // Опрашиваем YL-69
  if (millis() - msPage > msPageExpo) updatePage();       // Листаем страницы

}

//**************  Секция экранчег  ****************************
void updatePage(){                       // Листаем страницы на экранчике
  static uint8_t page {0};
//  Первая страница
  if (page == 0){
    lcd.setCursor(0,0);
    lcd.print("temp water:    ");
    lcd.setCursor(0,1);
    lcd.print((int8_t)ds1Temp);
    lcd.setCursor(3,1);
    lcd.print("C   ");
    msPage = millis();
    page++;
    return;
  }
//  Вторая страница
  if (page == 1){
    lcd.setCursor(0,0);
    lcd.print("temp air:         ");
    lcd.setCursor(0,1);
    lcd.print((int8_t)dhtTemp);
    lcd.setCursor(2,1);
    lcd.print("C   ");
    msPage = millis();
    page++;
    return;
  }
//  Третья страница
  if (page == 2){
    lcd.setCursor(0,0);
    lcd.print("hum air:         ");
    lcd.setCursor(0,1);
    lcd.print((uint8_t)dhtHum);
    lcd.setCursor(2,1);
    lcd.print("%   ");
    msPage = millis();
    page++;
    return;
  }
// Последняя страница
  if (page == 3){
    lcd.setCursor(0,0);
    lcd.print("hum earth:         ");
    lcd.setCursor(0,1);
    lcd.print((uint16_t)ylVal);
    lcd.setCursor(3,1);
    lcd.print("%   ");
    msPage = millis();
    page = 0;
    return;
  }
}

//**************  Секция YL-69  ****************************
void runYl(void){
  ylVal = analogRead(ylPin);; //Измеряем влажность. Маппинг пишем сами, если надо
  msYl = millis();
}

//**************  Секция DHT  ****************************
void runDht(void){
  dhtHum = dht.readHumidity();          //Измеряем влажность
  dhtTemp = dht.readTemperature();      //Измеряем температуру
  msDht = millis();
}

//**************  Секция DS18b20  ****************************
void updateTemp(){                       // Основная процедура обновления температурных данных со всех датчиков
  static uint8_t stage {0};
//  Первый этап. Отправка запросов на конвертацию
  if (stage == 0){
    if (ds1Qty) requestSensor(ds1Pin);
    stage++;
    msTemp = millis() - msRepTime + 800;    // 0.75 секунды требуется датчику для осуществления конвертации на максимальном разрешении
    return;
  }
// Второй этап. Чтение показаний
  if (stage == 1){
    if (ds1Qty) readSensor(&ds1Temp, ds1Pin, ds1DS, ds1Qty);
    msTemp = millis();
    stage = 0;
    return;
  }
}

void readSensor(int8_t* t, uint8_t pin, void* buf, uint8_t qt){       // Чтение температуры с датчика ds18b20
  OneWire ds(pin);
  uint8_t addr[8];
  uint8_t data[9];
  float temp[3];
  uint8_t qty {0};
  for (uint8_t c {0}; c < qt; c++){
    for(uint8_t i {0}; i<8 ;i++) addr[i] = *((uint8_t*)buf+c*8+i);
    ds.reset(); ds.select(addr); ds.write(0xBE);
    for (uint8_t d {0}; d<9; d++) data[d] = ds.read();
    int16_t raw = (data[1] << 8) | data[0];
    raw = raw & ~1;
    temp[qty++] = raw / 16.0;
  }
  float tmp {0};
  for (uint8_t i {0}; i<qty; i++) tmp+= temp[i];
  *t = round(tmp/qty);
  Serial.print("Температура пин "); Serial.print(pin); Serial.print(" : "); Serial.println(*t);
}

void requestSensor(uint8_t pin){          // Отправка запроса на конвертацию ds18b20
  OneWire ds(pin);
  ds.reset();
  ds.skip();
  ds.write(0x44,0);
}

void searchSensors(){                          // Поиск датчиков на всех линиях
  ds1Qty =   src(ds1DS, ds1Pin);
}

uint8_t src(void * adr, uint8_t pin){      // Вспомогательная функция для поиска на одной шине. Возвращает количество найденных датчиков
  if (pin == 0) return 0;
  OneWire ds(pin);
  uint8_t newAddr[8]{0};
  uint8_t count {0};
  ds.reset_search();
  delay(5);
  while (ds.search(newAddr) && count <3){
    if (ds.crc8(newAddr, 7) == newAddr[7]){
       for (uint8_t i{0}; i<8; i++) *((uint8_t*)adr + count * 8 + i) = newAddr[i];
       count++;
    }
  }
  return count;
}

Is the compiler giving you any errors? Then you absolutely need to include them in your question. Or is the code having unexpectedly? Then you need to describe, what you expected and how the code actually behaves. I don't really want to read a long code and searching for errors, that might or might not be there. Please test yourself and then you can provide the needed information for us to help you

Please divide your program into small chunks and test them individually. If you have figured out, which part is not working as indended, I am happy to help on that small part. Also please read: https://arduino.stackexchange.com/help/how-to-ask

how do you know that data from sensors is not correct? ... what are you expecting to see? ... what are you seeing? .... which sensors are affected? .... how are the sensors connected? .... please add all information to your question ... do not put in comments


text:
Buttons pressed in correct order
I’m trying to figure out the best way of doing this, currently using a bunch messy if-statements which kind of work. I have an IR sensor and three buttons that all need to be activated in the right order. Each sensor/button will activate LEDs and sound effects. First, when sensor1 goes HIGH, button1 can be pressed momentarily, then button2, then button3. If sensor1 is LOW, then nothing should happen when the buttons are pressed. When sensor1 is HIGH then the buttons should be pressed in the right order to progress through the sequence. When sensor1 goes back to LOW it should reset everything and allow the sequence to be run again when HIGH. Should I look into case switches for this?
Thank you
Jason

what should happen when buttons are pushed in wrong order?

If sensor1 is LOW, then nothing should happen when the buttons are pressed. When sensor1 is HIGH then the buttons should be pressed in the right order to progess through the sequence.

what should happen when the sensor state goes low partway through the button sequence? .... please add the description to your question ... do NOT write a comment

Should I look into case switches for this? ... you can, if you want ... the switch/case  block is equivalent to if else if else if ... .... is that really the only question that you want to ask?

and some pointers to learn to code this. I'm still learning. thanks

This is a classic application for a state machine, in which you keep track of where your process currently is in the sequence of events that must take place. The 'state' is just a numeric variable whose value you change whenever a significant event takes place.
You would probably assign 0 - Initial state, waiting for an event (or the first event); 1 - Sensor is high, 2 - button-1 went high, 3 - button-1 went low; ... etc.
It always helps to sketch out your state machine on paper, drawing a circle for each state, and arrows from each state 'x' to whatever the next state should be if an event 'y' happens while in state 'x'. The events are sensors and buttons going HIGH or LOW. In a particular state, no arrow for some event means you want to ignore that event while you are in that state.
Once you have drawn the map you can code the state machine. A common way of coding it is with a switch-case block, one case per defined state. Inside each case block, you test only for those events for which there is an arrow leading from that state to another state.
As you add new conditions, (e.g. "What should happen if the sensor goes low after button-1 has been pressed?"), switch-case logic will be much easier to modify than if you had used a complex collection of if-then statements. And you will be adding new conditions & removing or fixing wrong ones as you discover ways the device fails or humans do things you didn't anticipate. (Ask me how I know this! :-)
It will be really helpful to be able to go back to your state map to visualize what should (or shouldn't) happen, and what to change (on the map) to make that behavior. From the updated map, it is usually easy to see what code needs to be added, deleted, or fixed in the switch-case block.

+1 for the finite state machine. For the details on how to implement this in code, I usually point people to Majenko's Finite State Machine tutorial, which I find quite good.