text:
Libraries not included correctly
I stumbled upon the following unexpected behaviour and am curious about its cause.
header.h:
#include <Time.h>
[...]

main.ino:
#include "header.h"
#include <Time.h>
[...]

My code is working correctly with this setup. However, if I comment out the Time.h library in my main.ino, my code is working not correctly anymore:
#include "header.h"
//#include <Time.h>
[...]

I can still access the functions of Time.h, but they are returning garbage time.
Why do I have to include the library in my *.ino, although I am already including it in my header file?
Is there a best practice, on where to include libraries? Shall I simply always include all libraries in my *.h and *.ino file?

you want time.h or TimeLib.h? Time.h is ambiguous

Firstly you should be including TimeLib.h not Time.h - the library header name has been changed to avoid conflicts on case-insensitive systems (Windows) and the internal time.h header in many compilers.
Secondly you should always include all your libraries in your INO file directly.  This is because the IDE parses the INO file before compiling looking for any included libraries. It then adds these found libraries to the list of libraries that need to be compiled. Without this you won't get the source code for your libraries compiled properly.

Yes! This (Secondly) also often applies to #include <Wire.h>, if another library uses I2C.

@DataFiddler And SPI, etc.

I don't include includes of libraries. the Arduino builder can handle it. I use Ethernet.h without SPI.h in sketch, UnoWiFiDevEdSerial1.h without Wire.h in sketch, ...

@Juraj As long as you're using a version of the IDE that uses Arduino Builder - or UECIDE of course which does it natively. For everyone else in the world (like those fools that apt-get install arduino, or idiots that use plugins to eclipse or VS ;) ) it won't work. So best to include them anyway since there's no down side, only up sides.  Of course, if no one else uses your code that's fine...


text:
Rounding float number
I want to enable user to change the duration of PWM from 0 to 255, the number should be in minute and increase/decrease with two push buttons.
(X) x 255 / 60000 = minute

In above example each time plus button pressed value (X) will multiple by the numbers of button pressed.
if (plusButton == HIGH) {
    PWMduration += (X);
}

The nearest number i found is 235.29 which equals to almost 1 minute:
235.29 x 255 / 60000 = 0.9999

How can i round that number to 1? or is there any other alternative solution to calculate this?

Use 235.294117647?

@Majenko equals 0.99999999999975

In float terms that's 1. I don't think you can actually represent 1 in a float.

so what's the solution? can i convert it to int?

What's the problem with such a tiny difference from 1?

i'm gonna lcd.print() it!

I think you're tackling the whole thing backwards. Also, what use is PWM that has a period of minutes?

turns the light on slowly during a period of time.

So you want to fade the PWM? That's different to defining a PWM period. It has little to no relationship to the PWM. All you want is a delay.

take a look at this question

What you want to do is calculate the delay based on the number of minutes. Not change the delay depending on the number of button presses. Keep the minutes as an integer. Then use that integer to calculate how long each delay interval should be.

You can cast it to an integer after adding an offset.
Casting to an int will lower the value to the lowest integer value (e.g. 0.9975 will become 0). However, if you want an accuracy of 0.5 (e.g. all values from 0.5 <= x < 1.5 should be 1.0), than add 0.5, thus:
int roundedValue = (int)(0.9975 + 0.5);

If you use constants and want to calculate with it, either add .0 to it, or use a f(loat) or d(ouble) postfix, e.g.:
float f = 12.0 / 3.0;

or
float f = 12f / 3f;

Than calculate the rounded value:
int roundedValue = (int)(f + 0.5);

source: Stack Exchange

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

sort: votes


text:
how does c++ understand which function must to use?
in this code:
    void AdptSendReply(const char* str)
{
    string s(strlen(str) + 2);
    s = str;
    AdptSendReply(s);
}

void AdptSendReply(const string& str)
{
    string s(str.length() + 2);
    AdptSendReply(s); // use the next one
}

void AdptSendReply(string& str)
{
    if (AdapterConfig::instance()->getBoolProperty(PAR_LINEFEED)) {
        str += "\r\n";
        AdptSendString(str);
    }
    else {
        str += "\r";
        AdptSendString(str);
    }
}

i think c++ use of overloading ability.but how it can recognize which of the two functions "void AdptSendReply(string& str)" or "void AdptSendReply(const string& str)" must use?!

You know the first and the second aren't same. Second one passes empty string. Also the first is possibly unnecessary, as const string reference can be initialized by "c-string" (const char *) - temporary object is created with implicit conversion.

this may answer your question  https://arduino.stackexchange.com/questions/3079/how-to-retrieve-the-data-type-of-a-variable#3080 ......... the compiler tests the argument of the function in a similar way

This is offtopic here you should ask it elsewhere, the main stackoverflow maybe? But yes this is overloading, and the compiler has rules to resolve which function to use; you can check the C++ manual, or a C++ Primer/tutorial for more information.

What is string? Why is this information missing from your question?

It's probably std::string judging by the code, however this isn't really an Arduino question but a C++ question which might be better asked at Stack Overflow. I see people are voting to close this question, and if it gets closed just ask at Stack Overflow. They are experts on C++. :)

Calling overloading function triggers a process called overload resolution, which uses argument types to select the proper function to call

If you supply an lvalue argument of type string, the compiler will call void AdptSendReply(string& str) version.
string s = "hello";
AdptSendReply(s); // calls 'string& str' version

If you supply an lvalue argument of type const string, the compiler will call void AdptSendReply(const string& str) version.
const string s = "hello";
AdptSendReply(s); // calls 'const string& str' version

If you supply an rvalue argument, the compiler will call void AdptSendReply(const string& str) version.
AdptSendReply(string("hello")); // calls 'const string& str' version

And so on. The full set of rules that govern overload resolution is quite extensive, especially when the context involves implicit conversions.

It is not clear what you mean by "must use". Normally, overloaded functions will do the same thing (functionality-wise), meaning that you are not supposed to worry about which function to use. Just call it with the argument you have available and the compiler will select the proper function to call.
Also, what is string? How are we supposed to know that? Without knowing it, your question make little sense.

The compiler decides which function to use based on the variable type information. Imagine you write
str += "test";

If you declare str as a constant, the above line will throw an error. So if you write AdptSendReply(str) instead, the compiler will call the const function. Likewise, if you declare str as a mutable variable, the above line will compile fine, and, should you call AdptSendReply(str), the compiler will use the non-const function.

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


text:
PIR sensor and hex inverter open collector
the M7404 Hex inverter is used to send an active low signal from a PIR sensor to a microcntroller pin
However the reset is being constantly sent some signal keeping it set to on. You can tell because the reset light is on in the picture
Thanks to ST2000 I was able to figure out I need a hex inverter open collector to change the high signal from high to low because the reset pin on the microcontroller is active low. However, Whenever I use the active low reset pin (number 3 on the esp32) it goes into a state of holding down the reset button. Or constantly being high. Here is the thread where ST2000 was able to provide me the solution I am working on: esp32 cam and PIR sensor

My question is: how do i get the pir sensor to send an active low signal to the microcontroller?
here is a schematic of the esp32 board
https://i.redd.it/yv050peu22p21.png

Ok i tried my best to make a schematic and updated to include a question sry. @jsotola

That schematic makes no sense.

The data line from the pir sensor goes through the inverter and then into the microcontroller that is supposed to accept an active low to trigger reset on the board. I know it doesnt make sense but please bear with me or provide another site that is easier to make schematics.

Edit your question then press the schematic button.

Your inverter is backwards in that schematic. Is it backwards in reality?

No its not. I am not at home atm but if you look closely at the camera picture it appears with the text and output oriented right. At least when I was wiring it up I was looking at a tutorial. Also I have updated my schematic to hopefully make more sense.

If you want to turn your active high output into an active low one all you need is a transistor and a resistor. The transistor makes it active low and open collector, and the resistor pulls it up to 3.3V.

it needs to be .7v active low to activate reset. But in my case it seems to be inactive all the time. regardless of the PIR state even w/o the inverter

Let us continue this discussion in chat.

See my edit. ...

@DavidGraff, thanks for adding the schematic .... now it makes sense .... why are you connecting the PIR to the reset pin? .... use one of the other data pins instead .... use a pullup resistor

I wouldn't have chosen a hex inverter for this job. I'd have just used a transistor and a resistor:

simulate this circuit – Schematic created using CircuitLab
When OUT is HIGH, M1 is ON, which connects D3 to GND.  When OUT is LOW, M1 is OFF, which allows R1 to pull D3 up to 3.3V.

As to why you have a boot loop, now you have shown a slightly (though still confusing) clearer schematic I can tell you that it is because you are using pin D3.
Don't use pin D3.
D3 is the RX pin and is held HIGH at boot. That means that when the board resets D3 goes HIGH which then pulls reset LOW through your inverter, which then lets D3 float, so RESET goes HIGH, and that makes D3 then go HIGH which means the RESET is pulled LOW... ad infinitum.
You should read this page and choose a different GPIO pin that isn't going be doing things at bootup.


text:
Serial monitor garbage output on both MacOS and Windows devices, output used to make sense
Baud rate is set to 115200 in both the serial monitor and in the setup() portion of the code. The output to the serial monitor just looks like a bunch of reverse question marks on MacOS and on Windows it's a bunch of gibberish characters. Any idea how to fix this and why it would have changed when the output used to be what I expected? Weird thing is the program on the board is still working because I'm seeing the proper output on my server but I want the serial monitor working for debugging if it's not making it to the server.

what else has changed?

Nothing that I've noticed. I don't think I even changed the code since this started happening.

plain esp8266 doesn't have USB. how do you connect it to Serial Monitor?

I have this board with a built on micro USB port.


text:
SPI - different implementation / timing
I'm a little bit confused. I'm running the same code on a ESP32 (Adafruit Huzzah32) and an Arduino (SparkFun Pro Micro). It works on the ESP32 but not on the Arduino.
Are there different API implementations?
It seems that the timings are not the same. The Arduino does not have the gaps between the bytes.

Maybe the other side you didn't mention is a problem. There is possibility it needs more time to prepare result (before you start sending dummy bytes). But as you didn't mention what is the other side, nobody knows.

Thanks for your answer. I'm not waiting for results. The 2 '0's are just attached to make it more clear. I'm asking because i'm wondering why there are no gaps between the bytes ...

should there be wider gaps? ... the logic analyzer doen not appear to need wider gaps

No, but my SPI module seems not to understand the commands if there are not any delays. The second picture shows the same command without any delays between the bytes. My main question is, why does the ESP32 have delays and the Arduino does not? and how can i fix this without rewrite the SPI commands?

the speed is not the same

I've checked the speeds. the arduino sends with 125MHz but i need 80kHz. I didn't look at it because i've set the spi settings SPISettings _spiSettings( 80000, MSBFIRST, SPI_MODE0 ).  I played around with SPI.setClockDivider() but i cant achieve such a low rate. Any suggestions?

https://www.arduino.cc/en/Reference/SPI


text:
How to start a dendrometry dimension build (Dimensions of Trees) for research?
I am looking to build a device that can measure the dendrometry fluctuations of trees (etc). I essentially want to build this https://publiclab.org/notes/kinasmith/09-09-2016/dendrometers to a t but I don't know where to start. I have admittedly pretty limited knowledge of arduino/microcontrollers and microcontroller kits and sensors.

The tension meter from that link does not measure the circumfence. I measures the force from displacing a small part of the string. Do you really want to measure the circumfence?

I don't care about the actual circumference measurements, but I do need to wrap the string around a circular object and measure tension changes. What sort of device would I use to get started or what should I read up on?

I don't really understand the whole setup, but you can build a tension meter like in the link yourself by using a load cell

I am attempting to measure dendrometry dimensions of trees if that helps and want to do a setup like this but I am a beginner at this https://blog.adafruit.com/2016/10/25/using-circuits-sensors-to-study-dendrometry-dimensions-of-trees-in-alaska-citizenscience/

edited question for clarity

design and contruction of any sensor is not related to arduino

try using a sewing tape measure for the sensor band ... sewing tape measure is usually made of fiberglass or something similar and does not stretch .... you can determine its suitability by using it to measure the circumference of a tree at intervals ... if found suitable, then proceed with the construction of the sensor itself

The measuring principle, that is describe in that link, is quite cool and simple.
The string is wrapped around the tree. One end is connected to a fixed point (here the casing of the sensor). The other end is connected to a spring, which in turn is again connected to a fixed point. As the tree get's bigger, it will pull at the string. At the first side of the string nothing happens (because it is a fixed point). But the end with the spring will move according to the force of the tree. Force and displacement have a linear relationship for a spring (as long as you don't overload it): F = k*x with the force F, the spring constant k and the displacement x.
The displacement of the springs end can be measured with a linear potentiometer. That is just a simple strip of resistive material with a glider, which can be set to any position at the strip. It will create a voltage divider, giving you an analog voltage depending on the position (most potentiometers are linear, but there are also others). Connect both ends of the potentiometer to Vcc (supply voltage) and ground respectively and the glider to an analog pin of the Arduino. Then you can measure the voltage with analogRead().
As jsotola mentioned in his comment: Be sure to use a string, that will not stretch too much, as this will make your measurement less precise.

thanks @chrisl, this is starting to make sense to me. The only part that i'm not understanding is why the spring is necessary and how to actually set up the potentiometer to measure the displacement of the spring.

get a string and a rubber band (spring) and a couple of small nails and try it out on a tree .... attach the string to the tree and then put your hand under  the string to simulate tree trunk expansion ... see how the end of the string moves .... now try it without the rubber band

Would you use a gliding potentiometer or a Softpot? Forgive me if this is the same thing, I may be confused here.


text:
can't return float value from function
I want to put a 2 seconds delay to temperature reading but the millis() delay is not applying.

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

#define ONE_WIRE_BUS 2

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

const int OnHour = 23;
const int OnMin = 42;
const int checkTemp = 2000;
const int checkTempinterval = 0;

void setup() {
  Serial.begin(115200);
  pinMode(3, OUTPUT);
  lcd.begin();
  lcd.backlight();
  rtc.begin();
}
void loop() {
  t = rtc.getTime();
  float testTemp;
  testTemp = temperature();
  lcd.setCursor(0,0);
  lcd.print(testTemp);
  lcd.print("   ");
  lcd.print(rtc.getTimeStr());
  lcd.setCursor(0,1);
  lcd.print(rtc.getDOWStr());
  lcd.print("   ");
  lcd.print(rtc.getDateStr());
  if(testTemp >= 28){
    digitalWrite(3,HIGH);
  }else{
    digitalWrite(3,LOW);
  }
//  if(t.hour == OnHour && t.min == OnMin){
//    digitalWrite(3,HIGH);
//  }else{
//    digitalWrite(3,LOW);
//  }
}
float temperature(){
  unsigned long currenttime = millis();
  if(currenttime - checkTempinterval >= checkTemp){
  sensors.requestTemperatures();
  float testTemp = sensors.getTempCByIndex(0);
  currenttime = checkTempinterval;
  return testTemp;
  }
}

First of all, not all execution paths are returning the value, second of all, why are you doing: currenttime = checkTempinterval;, it's pointless as it won't exist anymore after the return.

There is nothing called "minis" in your code example.

@KIIV so i can't return value from sensors.getTempCByIndex(0);? it's reading the temp but the delay is not applying...

You can, but code is not doing it in case the if condition fails.

@KIIV so what's the solution?

Delete it all, and start from a scratch. Enable all warnings! Don't use any branches in temperature(), maybe even forget about functions, until you don't understand concept of local variables and it's scope and existence. Just use delay(2000), read rtc, request temperature, print results

that's a question and by kindly answering it you can help me to "understand the concept of local variables" and i don't want to use delay!

Also asked here: https://forum.arduino.cc/index.php?topic=621590.0

@Jot "Detective achievement unlocked"!

Moreover what is the question?  I don't see one.

I see 2 problems with your code:

Returning a value from a function: If you want to return a value from a function, you will have to make sure, that in any case the return x statement is executed inside the function in the temperature() function you currently have this if statement:
if(currenttime - checkTempinterval >= checkTemp){

Inside of it is the only return statement. That means, if the function is called before the next measurement time, the function will not return anything. Normally the compiler gives you at least a warning about that (maybe you have to turn the warnings on in the settings of the Arduino IDE).
Here you also have to think about, what you want to return, if no measurement was actually executed. Do you want to return an error value (for example -300; the error value should not be found inside valid data)? Then do so after the if statement. Or do you want it to simply return the last measured value? Then declare a variable (either at global scope, meaning outside of any function, or at local scope, meaning inside the function, but static, which means that the value will be retained between the functions executions). Save the measured temperatures to this variable and return it after the if statement.
If you do this, also consider what that means for the rest of your code. For example, if you return an error value, currently it will also be displayed by your code.
Doing the millis() code correctly: What you are doing wrong here, it that you update the wrong variable inside the if statement. Currently you write the value of checkTempinterval (which is the time of the last measurement) to the variable currenttime. The variable currenttime was declared locally (meaning inside the function) by using
unsigned long currenttime = millis();

Local variables are only present during the execution of the function, that they are declared in. When the microcontroller has executed the return statement, it will throw all local variables away, making the RAM free for other variables. That means currently you are saving a value inside a variable, that get's thrown away directly after it.
What you actually meant to do, was to do it vice versa:
checkTempinterval = currenttime;

checkTempinterval is a global variable. It will stay in RAM during the whole program execution. Since it holds the last measurement time, you write the currenttime to it, when you measure.
Very important: Currently checkTempinterval is defined as const int meaning constant integer. This variable must not be constant, since we want to change the value (update the time of the last measurement). Also you should not use int here, because it's value range goes only up to 32767, which is 32 seconds when used with millis(). After that, it will overflow to negative values. Better use the type of millis() return value: unsigned long. It has 4 byte (instead of ints 2 byte) and will only overflow after 49 days. If you only use this variable type for things with millis(), even this overflow will not be a problem.

You can use the millis() function to create a "timer" that will get the sensor reading every 2 seconds. The sketch BlinkWithoutDelay.ino, should come with the Arduino IDE, but if not, you can find it here: BlinkWithoutDelay.
I've used that exact sketch with some modifications to display the results on the Serial Monitor instead of blinking an LED. When you are creating something, using the Serial Monitor can help you to De-bug your sketch.
Please read the code comments in the following sketch. Once you have this working with your code, then you could decide if you need a function or not.
// Store the last time you checked the sensor.
unsigned long previousMillis = 0;

// interval at which to checked the sensor (milliseconds)
const long interval = 2000;

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

void loop() {
  // here is where you'd put code that needs to be running all the time.

  // Get the current time.
  unsigned long currentMillis = millis();

  // Check to see if it's time to check the sensor reading.
  if (currentMillis - previousMillis >= interval) {
    // save the last time you checked the sensor.
    previousMillis = currentMillis;

    // This is where you add the code that checks the sensor.

    // Test output.
    Serial.println("Checking Sensor");
  }
}


text:
Constant ADC sampling rate on ESP8266 or ESP32
I want to sample Sound input with either an ESP8266 (preferred) or ESP32. As I'm using a low pass filter anyway, a sample rate of 1000-2000hz would be totally ok. What is more important, is that it is constant. Can I use DMA for that? If so: how? Or should i go via Timer interrupts?
I know about the wifi issue on the ESP8266, but I intend to just turn Wifi off as I don't need it for this project.

You have several options for controlling the sampling rate.
Software only
This is the simplest, and the previous answer got it almost right. Here
is my take:
const SAMPLE_INTERVAL = 500;  // 500 microseconds

void loop() {
    static unsigned long last_sample_time;
    if (micros() - last_sample_time >= SAMPLE_INTERVAL) {  // note 1
         last_sample_time += SAMPLE_INTERVAL;  // note 2
         // Take your sample here.
    }
}

Note 1: On the AVR-based boards, millis() is not accurate to the
millisecond. It tends to get late, then compensate for this by jumping
by two milliseconds at once. For controlling a process that should
happen every 1 ms exactly, millis() is very clearly not
suitable. I do not know how good is the ESP8266's millis(). It may
well be better than the AVR version. However, even a perfect millis()
will not be good for anything faster than 1 kHz.
The solution to this problem is pretty trivial: just count the time in
microseconds instead of milliseconds. The only drawback of using
micros() is that you cannot measure durations longer than about
71.6 minutes, which in turn means you cannot use it for sampling at
any rate slower than 233 µHz. Obviously this is not something you
should be concerned about. Note that the micros() rollover is not an
issue as long as you are sampling faster than the rollover period.
Note 2: It is impossible to have a steady sampling rate if it is
controlled by software. The best you can hope for is a tight control on
the average sampling period. This is accomplished by updating
last_sample_time as
last_sample_time += SAMPLE_INTERVAL;

Note that this variable holds the time when the last sample was supposed
to be taken, not the time it was actually taken. The sample was probably
taken a little bit behind schedule, as anything the CPU does takes time.
Updating last_sample_time this way means that these timing errors are
not cumulative. They would be cumulative if you did it in the “Blink
without delay” style, namely
previousMillis = currentMillis;

The drawback of this software method is that it inherently has a
significant amount of jitter. The program tests the current time only
once per loop iteration, and it may have other things to do within that
loop that adds to its execution time.
Software triggered by interrupts
I have never programmer an ESP timer but, if you can, it should provide
you better timings than the software-only version. Have the timer
deliver an interrupt at the desired sampling period, and use the ISR for
triggering the ADC. You may wait for the result inside the ISR, store it
in RAM, and set a flag to tell the main loop that a new sample is
available, as in
volatile int analog_sample;
volatile bool analog_sample_valid;

ISR(whatever_timer_interrupt)
{
    analog_sample = analogRead(ANALOG_PIN);
    analog_sample_valid = true;
}

void loop()
{
    if (analog_sample_valid) {
        int analog_sample_copy = analog_sample;  // note 1
        analog_sample_valid = false;
        // handle analog_sample_copy here
    }
}

Note 1: On an 8 bit Arduino, you would have to do this with
interrupts disabled. You shouldn't need to disable interrupts on a
32 bit platform.
This method should significantly reduce the jitter compared to the
software-only version. Now the sampling doesn't have to wait for the
program to run through the loop and reach the point when the time is
tested. Instead, whatever the program is doing, it will be immediately
interrupted for doing the sampling. Well... almost. From time to time it
will happen that the interrupt fires when the program is running with
interrupts disabled. This may be the case if it is already servicing
another interrupt. When this happens, the sampling will have to wait
until interrupts are enabled again. You end up with a jitter that is
most of the time a small fraction of a microsecond, and then
occasionally a sample is late by several microseconds.
Hardware only
On an AVR, you can configure the ADC to be automatically triggered by a
timer, or even to automatically trigger itself in the so called “free
running mode”. I do not know the specifics of the ADC in the ESP8266.
You may want to read the datasheet and see if it offer similar
functionality. If you can enable ADC auto-triggering, then you will have
cycle-accurate timings. The steadiness of your sampling will be just
as good as the quartz crystal clocking your MCU. No software solution
can ever come close to this level of perfection. The only drawback of
this method is that you will have to study the datasheet of your ESP in
order to implement it.

Have you looked "BlinkWithoutDelay" sample on Arduino? The most valuable part of it is the following:
void loop() {

    unsigned long currentMillis = millis();   // NOTE: 1

    if (currentMillis - previousMillis >= interval) {  // NOTE: 2
         // save the last time you blinked the LED
         previousMillis = currentMillis;  //NOTE: 3
         .. do your thing here ..
    }
}

Take into account the places from NOTE 1 to NOTE 3 I have marked in comments:
NOTE 1:
First thing in the loop where you mainly go is taking current time in millis. Should not take a lot of effort from Arduino to achieve.
NOTE 2:
Second thing is a comparison: is there enough time gone to make your thing ( = to take the sample) or not? If it is false, you make another round. If true, make it! Again, no big effort from computer.
NOTE 3:
Here you reset the timer, BEFORE doing anything else. So, your "sample interval clock" is quite precise, it consists of three little steps inside the computer and it should work in fractions of seconds accuracy (time estimate = (1 / Arduino clock speed) * some machine commands).
The other commands: taking sample, storing or sending it, should happen inside the one millisecond left from these commands. Do make a note, 1000 samples gives you 1ms time and 2000 samples 0.5ms time. This example fits perfectly to the 1000 samples case, as the accuracy of your clock is 1ms. I would go with that, if possible.
The time left, 1ms is quite long as a machine's executing time, but you have to make sure that some other components like a WiFi connection you mentioned, may be harmful for this approach. The other part of code inside the loop cannot take more than 1ms, otherwise it affects to the constant rate. Anything less than 1ms is ok, this algorithm makes no difference between 0.1ms or 0.9ms hard work inside the if, the accuracy of 1-10 machine words always holds.
(I don't know exactly how long command if is, nor how long is function millis(). If you want to be very precise, you may take these in account, but IMHO you can omit their importance in calculations: whether they take some time or not, anyways the execution of these may be quite well taking the same on every round - in constant time!)
SOURCE:
https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay

and how exactly do you want to get above 1000hz with "millis"? :P this is a highly imprecise solution.

This is accurate only for 1000hz, you are right.


text:
How to automatically reset the NRF24L01 module
For my home-automation project I'm using several arduino nano's with each a NRF24L01+ module. Each module is able to both receive and transmit with one another. Everything seemed to be flawless for a couple of hours, but after a couple of hours it either stops transmission (completely frozen) of receives the last data repeatedly. In my design I'm using the RF24 and RF24Network libraries, I was wondering whether someone managed to automatically reset the NRF24L01 module using code, when one of these errors occured, and could share his/her code?
I already found this form, but this is only using the standard RF24 library, whereas I'm also using the RF24Network library. Furthermore, in this form it is having a seperate TX and RX side, whereas I like to have each module to be able to both send and receive.
Some extra side information, I use a stable power supply with a capacitor connected to the module, also the wires are soldered to the module.
I hope somebody can help me with this,
Guido

Are you sure the problem isn't on the Nano? It might be better to reset the Nano. Resetting the Nano would also reinitialize the NRF24.

@Gerben It is a known problem, and is especially prevalent with Chinese clones. One make even has the entire ACK bit inverted ... such quality...

This is a known problem with those chips (especially Chinese clones). It is caused when a chip gets stuck in TX mode waiting for an ACK that never arrives back.
The chips don't have a "reset", but switching them into low power mode and then back on again, which doesn't affect any register settings, aborts the current TX operation.
RF24Network is merely a protocol layer on top of the RF24 library. That RF24 library has powerDown() and powerUp() methods. Simply call powerDown followed by powerUp on your RF24 driver object.

I have tried your suggestion. However, I didn't get it to work. I indeed use these so called Chinese clones. I gave an explanation of my code used in next answer. I hope you could give me some useful advise on improving it.

Same issue; Simple work-around did it for me: (1) supply +3.3V power the nRF24L01 from a digital pin, using a forward bias diode/LED (with Vf in range 1.7-2.3V) to reduce voltage to compliant range (2.7-3.3V), then (2) in setup say, switch the pin to OUT/HIGH
pinMode(NRFPIN, OUTPUT); digitalWrite(NRFPIN, HIGH);
Notes:
A) If you have 3.3V device then you can skip voltage reduction in (2)
B) nRF24L01 power consumption peaks at 13mA (quiescent is miniscule) so well within spec for output pin
C) Of course you can do (1) with a voltage divider, or a level converter chip, etc, but the appeal of the LED (I checked Vf across 100 ohm @5V to find a decent match) is that it is simple, passive and in-line and has the nice added advantage of a faint flash when transmitting or receiving!
Look here also nRF24L01 reset

@Majenko thank you for your suggestion, I have been playing around a little bit with the powerDown() and powerUp() functions but unfortunately I haven't got it to work yet. Again, it seemed to work for a couple of hours and then again seem to get stuck. Therefore, I also included my code to see if I maybe made some major mistakes.
Furthermore, I assume that I'm having such Chinese clones of the NRF24L01+, as I have bought mine on Aliexpress.
I have included several parts of my code, the following part resets the NRF24L01+ module once a failure is detected. In here I also included the suggested powerDown and powerUp functions.
void NetworkReconnect()
{
  pinMode(CE_PIN, OUTPUT); digitalWrite(CE_PIN, HIGH);
  pinMode(CS_PIN, OUTPUT); digitalWrite(CS_PIN, HIGH);

  radio.powerDown();

  radio.begin();

  radio.powerDown();

  Network.begin(90, thisNode);

  delay(100);

  radio.setPALevel(RF24_PA_MAX);
  radio.setDataRate(RF24_1MBPS);

  radio.powerUp();
}

The following code I have in my void.loop(), every 5 seconds I check the network connection, by calling NetworkCheckConnection() (see last part of included code). Which tries to figure out whether the module has crashed, I found this failure detection as a suggestion at a discussion form on the RF24 library on GitHub Discussion. Furthermore, the while loop is limited to only 500ms to avoid being in an infinite loop, if this is exceed, the function NetworkReconnect() is called again.
void loop()
{

  Network.update();

  if (millis() - Timer > 5000)
  {
    NetworkCheckConnection();
    Timer = millis();
  }

  if(radio.failureDetected){
    radio.failureDetected = false;
    delay(250);
    Serial.println("Radio failure detected, restarting radio");
    NetworkReconnect();
  }

  if (Network.available())
  {
    uint32_t failTimer = millis();
    while (Network.available())
    {
      if(millis() - failTimer > 500)
      {
        radio.failureDetected = true;
        Serial.println("Radio available failure detected");
        break;
      }

      ... The usual Network.read stuff ...

    }
  }

  ... Remainder of code ...

}

And lastly the NetworkCheckConnection() code, this code is based on the RF24 Failure handling example and the principles used for checking connectivity of the RF24Mesh network link (see line 140).
void NetworkCheckConnection()
{
  if (radio.getDataRate() != RF24_1MBPS)
  {
    radio.failureDetected = true;
    Serial.println("CheckConnection FailureDetected");
    return;
  }
  // see line 140 of: https://github.com/nRF24/RF24Mesh/blob/master/RF24Mesh.cpp
  bool ok = 0;
  if(radio.rxFifoFull() || (Network.networkFlags & 1))
  {
    return;
  }
  RF24NetworkHeader header(otherNode, NETWORK_PING);
  ok = Network.write(header,0,0);
  if(ok) { Serial.println("Network Connected");       return;}
  if(!ok){ radio.stopListening(); NetworkReconnect(); return;}
}

Lastly, I also call the NetworkReconnect() function if any of my Network.write functions fails.
I hope that you can give me some suggestions on how to get this module to work more reliable, any suggestion is welcome!
Thanks in advance :)

If you encounter a radio failure, what do you get as the output of printDetails()?


text:
Connecting to WiFi on ESP32 using credentials from SD card
I'd like to use an SD card to provide the login credentials to an ESP32. I've already got the ESP32 reading the relative data from the SD card and storing it as a char array on the ESP, but when I use those arrays in the WiFi.begin function it never connects.
Is this something to do with the way arrays work or am I doing something else wrong?
Respective code:

if (dataFile) {
Serial.println("File is available");
while (dataFile.available()) {
  byte currbyte = dataFile.read();
  if (currbyte == 58) {
    reading = 1;    //Begin reading data
    i = 0;
  }
  while (reading == 1 and s == 0) {
    byte currbyte = dataFile.read();
    //Serial.print(currbyte);
    //Serial.println(char(currbyte));
    if (currbyte == 13) {
      s = 1;
      reading = 0 ;
    }
    ssid[i] = char(currbyte);
    i++;
    //Serial.println(ssid);
  }
  while (reading == 1 and s == 1) {
    byte currbyte = dataFile.read();
    //Serial.print(currbyte);
    //Serial.println(char(currbyte));
    if (currbyte == 13) {
      s = 2;
      reading = 0 ;
    }
    password[i] = char(currbyte);
    i++;
    //Serial.println(password);
  }
}
dataFile.close();
WiFi.begin(ssid, password);

while (WiFi.status() != WL_CONNECTED and count < 20) {
Serial.println("Connecting to WiFi..");
delay(1000);
count++;}

Hi I've got the data of the SD card without issues, howeverI can't connect to wifi with that data stored as arrays

Alright, well I know that the code works if I manually enter the SSID and Password. A serial print of the arrays shows that they visually appear to be correct, and are being called correctly for the function

that makes it clear ... one way to debug this issue is to write the data back to the SD card and examine the result (i am assuming that you used a mac or a pc to write the data to the SD card) .... perhaps use a separate filename for each data field .... also, update your question with the info in your last comment

Writing the arrays for the SSID and password to a file on the SD card returns the correct results. So like I asked, is this something to do with arrays or is it something else I'm doing?

do not write an array to the SD card ... write the content of the array .... the SSID and password strings ... check that there are no hidden characters in the strings

I used
dataFile.println(ssid);
dataFile.println(password);
Which when I checked the file on my computer afterwards showed the exact correct string of ASCII characters

you add the '\13' to the SSID and password string instead of the terminating zero

Where exactly do I add that? In my wifi.begin or when I finish reading the SSID from the SD card?

ssid[i] = char(currbyte); runs for  13 too

you add the '\13' to the SSID and password string instead of the terminating zero, because ssid[i] = char(currbyte); runs for 13 too
use readBytesUntil()
  char ssid[33];
  int l = file.readBytesUntil('\n', ssid, sizeof(ssid));
  if (l > 0 && ssid[l-1] == '\r') {
    l--;
  }
  ssid[l] = 0;


text:
Error conecting raspberry with my arduino in a serial port
Hi i am trying to make a comunication between theses device but when i am trying to run in my raspberry i have the follow error:

Traceback (most recent call last):
    File "serial.py", line 1, in
      import serial
    File "/home/pi/Desktop/serial.py", line 2, in
      ser = serial.Serial('/dev/ttyACM0', 9600)
  AttributeError: 'module' object has no attribute 'Serial'

i have the next code:
import serial

ser = serial.Serial('/dev/ttyACM0', 9600)

while 1:

    if(ser.in_waiting >0):
        line = ser.readline()
        print(line)

If any can help me, i will be thankfull

did you check if a function nsmed Serial actually exists in the serial library?

Don't name your files with the names of modules you're using. Also, why ask a Raspberry question on Arduino site when we have RPi.SE, where the exact same question was already answered?

What's almost certainly happening here is that you've named your file serial.py, so the import is trying to load the library from your file within the current working directory.
To fix this problem, simply rename your serial.py script to something else, for example serial_comms.py or whatever other useful name you want.

you are a genius, that was the problem thank you

@JesusMiguelHerrera You're most welcome. I ran into this when I had to learn Python for a previous job.


text:
How to create a wired ESP8266 range extender?
Context: I have a NETGEAR router on the first story of my home, the range doesn't extend to the ground floor. I do have a cable duct from my router(on the first story) to the ground floor.
Question:
Is it possible to wire a Keyes ESP8266 to my router to act as a WiFi range extender?
Note: The length of the cable would be 10 meters.

not with Arduino

@Juraj Do you mean "Not with ESP"?

not with esp8266 Arduino core and libraries. maybe with the Espressif SDK, but that is not Arduino

Check out this discussion. I believe your case is deemed off-topic.

There's a project that calls itself a "wifi repeater" at
https://github.com/martin-ger/esp_wifi_repeater
It includes support for an ENC28J60 ethernet adapter connected via SPI.
It has some serious limitations.
First, it's really a NAT (Network Address Translation) router, not a Wifi extender, though it can effectively extend wifi. However, devices being extended will not be able to communicate with devices on the original network via broadcast or multicast. This will break some applications and many IoT devices.
Also, devices on the original network will not be able to originate connections to devices on the extended network.
But if you just have some devices that only need to talk to the Internet and are a little too far for your router, this should work for them.
Also, the ESP8266 can only get about 5Mbps through it (I'm actually surprised it's that high). You probably won't be able to reliably stream video - definitely not 4K video. It's not a good choice for connecting a television and probably won't work well with security cameras.
Finally, as @Juraj mentioned, it's not an Arduino project. You'll need to install the NON-OS SDK and toolchain to build it. It does include a pre-built image and instructions on how to flash it.
I haven't used it and can't promise that it will work well, but it's the closest thing I'm aware of to what you're looking for.

Much appreciation. According to this documentation the Ethernet interface will support about 1 Mbps when the ESP is running at 160 MHz. that will reduce the speed of the connection to the stations connected to the NAT correct?

That sounds right to me.


text:
Garage door button with delay feature
I am working on an art project that involves a garage door opener.  I am very new to Arduino, and electronics.  I have a starter kit with a ton of accessories.
The garage door opener has 2 screws (terminals?) designed to connect a button.  If I touch a wire between them, the opener will start.  I connected a button to my bread board, and ran wires to those terminals on the opener to see if a simple switch would work, and it does.
I want to:

press a button, and the Arduino connects the terminals on the opener, and then it starts
button is then ignored (delayed) for a set amount of time (5 seconds for this example)
after the set amount of time, the button works as normal (like in step 1)

I ran through some tutorials on buttons, and I think I got ahead of myself.

I can turn on an LED from a switch on the bread board, and use a delay(5000) to ignore any other button presses.  I tried to connect the wires that were going to LED to the 2 terminals on the garage door opener, and it did not work
In code, I setup pin 5 as OUTPUT, and pin 6 as INPUT.  I used the button to send a HIGH on pin 5, to see if that signal would work when connected to the 2 terminals on the opener.  I tested this a bit in code by reading the state of pin 6, and it appears to have worked.  However, it did not work when I connected both pin 5 to one terminal, and pin 6 to the other.

I tried looking for a simple example, but searching for garage door openers and Arduino results in too many tutorials on how to do super fancy wireless stuff.  I just want to ignore a button press for 5 seconds after it has been pressed once.
I'm looking for a simple example that allows my button to tell the Arduino to make that connection on the garage door opener.  I guess I'm looking for my Arduino to act like a switch instead of my (physical) switch?
My Arduino kit comes with a bread board, wires, switches, Uno R3 and tons of other stuff I haven't gotten to yet.  I apologize in advance if I'm not thinking of something super-simple that would solve my problem.  I'm very new to this.
Thanks for your time!
Edited for spelling.  Elaborated on my attempts.  I'm going to read about what a relay is.

Why not search for "debounce circuit"? Hardware solution

Or on "arduino button debounce" software solution

The existing opener electronics should already have a de-bounce built-in, you shouldn't need to add one. The simplest control method is to use a relay, then you don't need to understand what is inside the existing opener. Or, a opto-coupled transistor should work, if you get the polarity correct.

Two things about your question are confusing, and an edit would be appreciated.  First, you use "beard board" and "bread board" interchangeably.  I believe you mean "bread board".  My apologies if dyslexia is one of the crosses you must bear.  Second, "debounce" is not the correct term for what you want to do -- "time delay" is a better term.  "Debounce" is specifically what you do to overcome the switch physics, not to create some desired behavior.

And, while I'm pestering you -- please edit your post to include a proposed schematic, or a block diagram if you're not comfortable with a schematic.  Detail how you're connecting the Arduino to the opener, and what "does not work" means (i.e., does it act like the switch is always unpushed, or always pushed, or something odder yet?).

why do you need to debounce the button? ... i am sure that the button on the garage door opener is not debounced

if you want the opener to only run between two limits, just put additional limit switches at the two limits, wire them in parallel. and wire the push-button in series with the switches.

Just a detail: check the voltage and if it's high you must use a relay.

Please share some details like what are the connection diagrams (schematic), the kind of switch or a block diagram and the expected behavior of the door opener (like for what is the minimum time you want it to operate, switch behavior during its operation, how switch should turn it ON, etc.)

I figure out a solution - I just needed to use a relay.
I didn't know what a relay was, and had a hard time figuring it out.  I've included some notes for anyone who finds this post in the future.

I can't determine if it took reading 3-4 articles on relays for it to sink in, or if one article was the best.  Anyway, for me this one helped the most: https://www.instructables.com/id/How-Electronic-Switches-Work-For-Noobs-Relays-and/
My relay looked different from most of the tutorials.  I figured it out by connecting a couple alligator clips to a 9v battery and listening for the click of the magnetic switch.  Then I used my volt meter to determine which leads were working with the relay.

Relay Setup:

I connected my ~5 to one lead on the relay, and 5v to the other
The Common (middle) lead connects to one terminal on the garage door opener
The N/C (Normally Closed) lead connects to the other terminal on the garage door opener

Button Setup:

The button setup was just like all the other button tutorials
When the button is pressed (LOW), I start and stop the relay to trigger a "button press" for the garage door opener (it starts)
I then run a delay for the set amount of time I want
All button presses are ignored until after the delay has finished

Now I can move on to the actual project.  Thanks!


text:
Arduino menu coding problem by Keypad and 128*64 graphic LCD
I am trying to modify on the menu code to be able to use a keypad shield and arduino for scrolling between lines. after uploading and trying the code the following has happened:
1- I can not scroll more than 2 lines.
2- If I press D, I can scroll to another 2 lines.
What is the problem in this code?
include "String.h"
include"AccelStepper.h"
include "Keypad.h"
include "U8glib.h"
U8GLIB_ST7920_128X64_1X u8g(12, 11, 10, 13);

//Keypad setup

const byte ROWS = 4;

const byte COLS = 4;

char hexaKeys [ROWS][COLS] = {

{'1', '2', '3', 'A'}, {'4', '5', '6', 'B'}, {'7', '8', '9', 'C'}, {'*', '0', '#', 'D'} };

byte rowPins [ROWS] = {5, 4, 3, 2};

byte colPins [COLS] = {9, 8, 7, 6};

Keypad customKeypad = Keypad (makeKeymap(hexaKeys), rowPins, colPins, ROWS, COLS);

define KEY_NONE 0
define KEY_PREV 1
define KEY_NEXT 2
define KEY_SELECT 3
define KEY_BACK 4
uint8_t keycode1 = KEY_NONE;

uint8_t keycode2 = KEY_NONE;

uint8_t keycode = KEY_NONE;

void keymode(void){

keycode2 = keycode1;

char keypressed = customKeypad.getKey();

if (keypressed != NO_KEY){

switch (keypressed){

case 'A':

keycode1 = KEY_PREV;

Serial.println("A");

break;

case'B':

keycode1 = KEY_NEXT;

Serial.println("B");

break;

case 'C':

keycode1 = KEY_SELECT;

Serial.println("C");

break;

case 'D':

keycode1 = KEY_BACK;

Serial.println("D");

break;

}

if (keypressed != 'A' && keypressed != 'B' && keypressed !='C' && keypressed != 'D')

keycode1 = KEY_NONE;

}

if (keycode2 == keycode1)

keycode = keycode1;

else

keycode = KEY_NONE;

}

define MENU_ITEMS 4
const char *menu_strings[MENU_ITEMS] = {"Start", "Hello", "Let's Go", "End"};

uint8_t menu_current = 0;

uint8_t menu_redraw = 0;

uint8_t Last_key_code = KEY_NONE;

void drawmenu(void){

uint8_t i, h;

u8g_uint_t w, d;

u8g.setFont(u8g_font_6x13);

u8g.setFontRefHeightText();

u8g.setFontPosTop();

h = u8g.getFontAscent()-u8g.getFontDescent();

w = u8g.getWidth();

for( i = 0; i < MENU_ITEMS; i++ ) {

d = (w-u8g.getStrWidth(menu_strings[i]))/2;

u8g.setDefaultForegroundColor();

if ( i == menu_current ) {

u8g.drawBox(0, ih+1, w, h);

u8g.setDefaultBackgroundColor();

} u8g.drawStr(d, ih, menu_strings[i]);

} }

void updatemenu(void){

if (keycode != KEY_NONE && Last_key_code == keycode) {

return; } Last_key_code = keycode;

switch(keycode){

case KEY_NEXT:

menu_current ++;

if (menu_current >= MENU_ITEMS)

menu_current =0;

menu_redraw = 1;

break;

case KEY_PREV:

if (menu_current ==0)

menu_current = MENU_ITEMS;

menu_current --;

menu_redraw = 1;

break;

} }

void setup (){

Serial.begin(9600);

menu_redraw = 1;

}

void loop (){

keymode();

if (menu_redraw !=0) {

u8g.firstPage();

do{

drawmenu();

}while(u8g.nextPage());

menu_redraw = 0;

} updatemenu();

}

it is unclear how you want the code to work ... you need to provide clear description of expected behavior  ... your question is unanswerable until you do so

I just want to make a clear menu and to be able to scroll down without problems,
after that i will move to the next part.

https://github.com/neu-rah/ArduinoMenu will handle IO for you


text:
5th Led wont turn on (ws2812)
I'm trying to re-use a piece of example code I found here:
https://howtomechatronics.com/tutorials/arduino/how-to-control-ws2812b-individually-addressable-leds-using-arduino/
And I only have 5 LEDs in my strip, so I changed the define NUM_LEDs to 5, but when compiling with that value, I get a compilation error. with the define at 6 it works tho, but the 5th LED wouldn't turn on. Here is my code:
#include <FastLED.h>
#define LED_PIN     7
#define NUM_LEDS    6
CRGB leds[NUM_LEDS];
void setup() {
  FastLED.addLeds<WS2812, LED_PIN, GRB>(leds, NUM_LEDS);

}
void loop() {

  leds[0] = CRGB(0, 10, 0);
  leds[1] = CRGB(10, 0, 0);
  leds[2] = CRGB(0, 10, 10);
  leds[3] = CRGB(10, 10, 0);
  leds[4] = CRGB(10, 10, 10);
  FastLED.show();
  delay(500);
  leds[0] = CRGB(0, 0, 0);
  leds[1] = CRGB(0, 0, 0);
  leds[2] = CRGB(0, 0, 0);
  leds[3] = CRGB(0, 0, 0);
  leds[4] = CRGB(0, 0, 0);
  FastLED.show();
  delay(500);

}

So in the code, I've set the first LED to green, seccond one to red, third one to blue, 4th one to yellow, and the 5th one to white. As you can see in the picture they all light up correctly but the 5th one which stays blank, and I don't know why. I have tested this LED individually and it works perfectly well so it's not a hardware problem. I would encourage anyone who wants to test this code on 5 LEDs and let me know if it works for them, I'd be surprised it it did, but if you have a better solution for me, I would appreciate it.
Thanks.

What is the compilation error you get when setting the number of LEDs to 5? Does the 5th LED turn on if you set it to another color, let’s say red? You said it works individually and, looking at the picture, it seems you have wired the LEDs yourself: have you checked the data line is soldered correctly and you don’t have a flickering connection?

Holly crap, I literaly did this earlier today and had a compilation error, but I just tried it now, and the error went away. no idea why. By the way I got these PCBs made and you're right, I did solder it myself

but the 5th LED still doesn't light up. It might be a problem with the circuit but I really think it's the code. If someone can test this code on a strip of 5 LEDs it would be nice if they could confirm if it's a hardware problem or the code.

Your code is non optimized but correct: all LEDs should light up but very dim for half a second and turn off for another half. Please note you are setting a value of 10 out of 255, meaning you are about at 5% power. Try replacing 10 with 255 and see the increased brightness, but take into consideration the increased power consumption as well: the power supply for the strip must be able to safely deliver that much current.

what happens if you code it for 10 LEDs, does the last one work then?


text:
Changing the light state
Can someone give me a solution to the following problem?
I have 1 IR remote, blynk app,some pushButtons and also 1 relay module.
(I set 1 pin of ATMega as input to be able to read what esp sends when I use the blynk app).
So basically what I want to do is this:
If I press btn1 from the IR Remote or PushBtn nr1, or I send 1 from blynk app
then relay 1 must turn on. For now that part works.
Anyway, what I want to do next is this:
If the relay is turned on (closed) I want to be able to turn it off using the same buttons (for which I have set a counter and I call that variable).
Now I can turn the relay off only if I use the same btn that previously I have used to turn it on. But I want to be able to turn it off the other way.
If I used the blynk app to turn it on then if I press the pushbtn second time - I want it to be off. Also if I don't press the pushbtn but I use the IR remote and press 1 2 times- the relay should be off.
if(cntbtn2 == 1 || cntPushbtn2 == 1)
      {
      digitalWrite(rel2,LOW);
      u8g.setFont(u8g_font_courB10);
      u8g.drawStr(32,10,"Interior");
      u8g.drawFrame(0,12,128,51);
      u8g.drawLine(64,12,64,62);

      if(cntbtn1 == 1 || cntPushbtn1 == 1)
          {
          u8g.setFont(u8g_font_5x8);
          u8g.drawStr(10,23,"Sufragerie");
          u8g.drawStr(15,60,"L.aprinsa");
          u8g.drawBitmapP( 20, 8, 16, 64, LightOn);
          }

      else if(cntbtn1 != 1)
          {
          u8g.setFont(u8g_font_5x8);
          u8g.drawStr(10,23,"Sufragerie");
          u8g.drawStr(15,60,"L.stinsa");
          u8g.drawBitmapP( 20, 8, 16, 64, LightOff);
          }

      u8g.drawStr(73,23,"Dormitor");
      u8g.drawStr(75,60,"L.aprinsa");
      u8g.drawBitmapP( 78, 7, 16, 64, LightOn);
      }

else if(cntbtn2 == 2)
    {
    if(cntbtn1 == 1 || cntPushbtn1 == 1)
        {
        u8g.setFont(u8g_font_courB10);
        u8g.drawStr(32,10,"Interior");
        u8g.drawFrame(0,12,128,51);
        u8g.drawLine(64,12,64,62);
        u8g.setFont(u8g_font_5x8);
        u8g.drawStr(10,23,"Sufragerie");
        u8g.drawStr(15,60,"L.aprinsa");
        u8g.drawBitmapP( 20, 8, 16, 64, LightOn);
        u8g.drawStr(73,23,"Dormitor");
        u8g.drawStr(75,60,"L.stinsa");
        u8g.drawBitmapP( 78, 7, 16, 64, LightOff);
        }
    else{
        digitalWrite(rel2,HIGH);
        u8g.setFont(u8g_font_courB10);
        u8g.drawStr(32,10,"Interior");
        u8g.drawFrame(0,12,128,51);
        u8g.drawLine(64,12,64,62);
        u8g.setFont(u8g_font_5x8);
        u8g.drawStr(10,23,"Sufragerie");
        u8g.drawStr(15,60,"L.stinsa");
        u8g.drawBitmapP( 20, 8, 16, 64, LightOff);
        u8g.drawStr(73,23,"Dormitor");
        u8g.drawStr(75,60,"L.stinsa");
        u8g.drawBitmapP( 78, 7, 16, 64, LightOff);
        }
    }

if(cntbtn2 == 1 && cntPushbtn2 == 2)
    {
    digitalWrite(rel2,HIGH);
    }

//ecran stanga
if(cntbtn1 == 1 || digitalRead(espPin) == 1 || cntPushbtn1 == 1)
    {
    digitalWrite(rel1,LOW);
    u8g.setFont(u8g_font_courB10);
    u8g.drawStr(32,10,"Interior");
    u8g.drawFrame(0,12,128,51);
    u8g.drawLine(64,12,64,62);
    u8g.setFont(u8g_font_5x8);
    u8g.drawStr(10,23,"Sufragerie");
    u8g.drawStr(15,60,"L.aprinsa");
    u8g.drawBitmapP( 20, 8, 16, 64, LightOn);
    if(cntbtn2 == 1 || cntPushbtn2 == 1)
        {
        u8g.drawStr(73,23,"Dormitor");
        u8g.drawStr(75,60,"L.aprinsa");
        u8g.drawBitmapP( 78, 7, 16, 64, LightOn);
        }
    else
        {
        u8g.drawStr(73,23,"Dormitor");
        u8g.drawStr(75,60,"L.stinsa");
        u8g.drawBitmapP( 78, 7, 16, 64, LightOff);
        }

   }

else if(cntbtn1 == 2)
    {
    digitalWrite(rel1,HIGH);
    u8g.setFont(u8g_font_courB10);
    u8g.drawStr(32,10,"Interior");
    u8g.drawFrame(0,12,128,51);
    u8g.drawLine(64,12,64,62);
    u8g.setFont(u8g_font_5x8);
    u8g.drawStr(10,23,"Sufragerie");
    u8g.drawStr(15,60,"L.stinsa");
    u8g.drawBitmapP( 20, 8, 16, 64, LightOff);
    if(cntbtn2 == 1 || cntPushbtn2 == 1)
        {
        u8g.drawStr(73,23,"Dormitor");
        u8g.drawStr(75,60,"L.aprinsa");
        u8g.drawBitmapP( 78, 7, 16, 64, LightOn);
        }
        if(cntbtn2 != 1)
            {
            u8g.drawStr(73,23,"Dormitor");
            u8g.drawStr(75,60,"L.stinsa");
            u8g.drawBitmapP( 78, 7, 16, 64, LightOff);
            }
        }
    else
        {
        digitalWrite(rel1,HIGH);
        digitalWrite(rel2,HIGH);
        u8g.setFont(u8g_font_courB10);
        u8g.drawStr(32,10,"Interior");
        u8g.drawFrame(0,12,128,51);
        u8g.drawLine(64,12,64,62);
        u8g.setFont(u8g_font_5x8);
        u8g.drawStr(10,23,"Sufragerie");
        u8g.drawStr(15,60,"L.stinsa");
        u8g.drawBitmapP( 20, 8, 16, 64, LightOff);
        u8g.drawStr(73,23,"Dormitor");
        u8g.drawStr(75,60,"L.stinsa");
        u8g.drawBitmapP( 78, 7, 16, 64, LightOff);
        }
   }

your code is badly formatted ... the indentation is all over the place .... that makes it difficult to follow the program flow ... please fix the indentation

how should it be? is written in arduino ide. that editor identation is bad.

Re “that editor identation is bad”: the IDE is just a writing tool. It is not responsible for what you write. You are. It is willing to help though, if you ask nicely: “Tools → Auto Format”.

Split the logic and the buttons in separate parts and avoid code duplication.
First step is to determine what should control the relay state:
// pseudo code follows
if (pushButton.isPressed() || blinkApp.sentCommand() || conditionAlfa.isMet()) {
  // update condition is met, proceed to state change
  relayState = !relayState; // swap relay state
  updateRelay = true; // activate the part responsible for the change
}

Once the new desired state is set, act on the relay and update the screen accordingly:
// pseudo code again
if (updateRelay == true) {
  updateRelay = false; // we are now going to update, don’t do it again if not necessary
  relay.setState(relayState); // update the relay, no matter what was the event source
  screen.drawGraphics(); // update the screen, no matter what was the event source
}

If you split the two parts you start operating on logical conditions rather than on physical events, making your entire code cleaner and your task simpler.

i am new in programming and don't know so well many concepts. Also i have a question about the last part of the code you posted. if(updateRelay == true){updateRelay = false; } that will execute? i mean- the uC it looks at that condition and verify that is it true, but then when enter into the brackets, that condition not became false? and stop executing it?

updateRelay is just a "flag". It doesn't do anything by itself; it's a way to store the fact that the condition had been met. Once it has been tested (by if (updateRelay == true) { , its value is no longer needed; the following section will or won't be entered by if statement. So making it false again is just "housekeeping" for the next time around. You don't want to keep entering the if-clause after having seen the condition once; only when one of the conditions (button, blynk, etc.) becomes true again.

Thank you very much Robert.


text:
atmega328: external crystal oscillator and uart
I need an clearity about external crystal oscilator. I got communication between esp32 and atmega8/88/328 processor, I use atmega wih internal oscillator and looks like it have problem with serial communication (some time it lose data, or replace it with nonsences).
So i have read that should use extercal crystal oscillator to achieve stable uart communication.
Question is that, what frequency to choose, and how that gonna effect uart, and atmega processor lifetime. I know if choose 16mhz processor gonna run faster, but assume it life time will decrease compated with 1mhz or 8mhz.
What about uart, which one of those frequences are best for it, or it make no difference?

the lifetime of your atmega won't be affected. you just need to make sure if the atmega is meant to run at that frequency. Regarding your uart? you need to make sure that you adjust the prescaler so the baudrate remains correct.

There are some specific crystal oscillator frequencies named 'UART friendly'. Using these frequencies would lower % error in UART communications. Please refer to the table in the datasheet, in chapter named "BAUD rate settings" (datasheet of ATMega328: '24.11. Examples of Baud Rate Setting'). There are tables to show error percentage. What to look at is "Error" column. fosc is selected oscillator/crystal frequency. For succesful UART communication you aim for less than 3.5% Error.
 Your crystal speed should depend on your desired communication speed, for example for me the preferred ones are 11059200Hz or 1843200Hz.

or below:

With raising frequency you may expect power consumption and the chip's temperature rise, anyway I wouldn't worry too much about life shortening. More important here would be power consumption rise.
 Do you want the chip(device) to be battery powered? To save on energy you can also consider lower frequencies like 1.8432MHz or 3.6864MHz.

1.84mhz is uart friendly for almost all rates, but In arduino ide there is no such frequency to select


text:
The arduino can't seem to output correctly
i am a beginner at python and I am average at Arduino and I had the idea of using both of them together for a project. I have been trying to make a Arduino + Python car which I can control with my computer. I have used Pyfirmata and the code seems perfect to me. When I run the code from CMD i have a weird bug/issue.
I have uploaded Standard Firmata to the arduino UNO. I get no errors while uploading or running its just that its output is messed up.
Here's the Python Code:
from pyfirmata import Arduino, util
import time

board = Arduino("COM3")

MotorLeft = board.get_pin('d:10:o') # Assigning output to PIN
MotorRight = board.get_pin('d:11:o') # Assisging output to PIN

play = True

while play:
    control = input(
        print("Enter W, A or D to move forwards, left or right. Enter 0 to exit"))

    if control != 0:
        if control == "W" or "w":
            MotorRight.write(1)
            MotorLeft.write(1)
            time.sleep(1)
            MotorRight.write(0)
            MotorLeft.write(0)

        if control == "A" or "a":
            MotorLeft.write(1)
            time.sleep(1)
            MotorLeft.write(0)

        if control == "D" or "d":
            MotorRight.write(1)
            time.sleep(1)
            MotorRight.write(0)

        else:
            print("Invalid Commmand")

    else:
        print("Exited Succesfully")

    play = True

Currently I have not built the car, I am using a pair of LEDs to do what the motors function and to test out the code.
Heres the CMD response:

Here is the link for the output video. I entered "W" which should ideally turn on both of the LEDs however, both of them turn on then off and then turn on off one by one.
https://youtu.be/DjUkkpzF0so

Is it possible to see what is your Arduino code?

@smajli, Arduino code is PyFirmata

I cannot check it, but I guess you have to change the or commands like:
if control == "W" or "w":

Change to
if ((control == 'W') or (control == 'w'))

And similar for the other if statements.
Also, you can do not need to check for control == 0, since it will not be a character otherwise.
Besides that, the elif (else if) construct is normally used in Python, so instead of:
if control != 0:
    if control == "W" or "w":
        MotorRight.write(1)
        MotorLeft.write(1)
        time.sleep(1)
        MotorRight.write(0)
        MotorLeft.write(0)

    if control == "A" or "a":
        MotorLeft.write(1)
        time.sleep(1)
        MotorLeft.write(0)

    if control == "D" or "d":
        MotorRight.write(1)
        time.sleep(1)
        MotorRight.write(0)

    else:
        print("Invalid Commmand")

You can write:
if ((control == 'W') or (control == 'w')):
    MotorRight.write(1)
    MotorLeft.write(1)
    time.sleep(1)
    MotorRight.write(0)
    MotorLeft.write(0)

elif ((control == 'A') or (control == 'a')):
    MotorLeft.write(1)
    time.sleep(1)
    MotorLeft.write(0)

elif ((control == 'D') or (control == 'd')):
    MotorRight.write(1)
    time.sleep(1)
    MotorRight.write(0)

else:
    print("Invalid Commmand")

Also, you can combine the or in a list (but I cannot check it, no python compiler at hand), e.g.
if (control in ['W', 'w']):

Thank You. I will try to make these changes

Thank You! This project works now! Do you know what causes this problem? so I can avoid this problem in the future.

Great to hear, you can accept my answer than, to let others notify the problem has been solved.

if control=='W' or 'w'     since 'w' is not equal to 0, this will always be true, its the same as writing if control=='W' or True


text:
Dynamic Serial port selection and use without instantiating all Serialx objects
I have an arduino project that reads a config file from SD and then receives data on a serial port that is specifed in the config file.
I therefore need to instantiate the Serial (Serial0), Serial1,..2,3, etc based on dynamic data.
I am using a mega2560 with 4x HardwareSerial. Serial (also Serial0) is the USB. Serial 1, 2, 3 are on specific hardware pins.
I started with code something like:
uint8_t InitPort(uint8_t port) {
    switch (port) {
        case 0:
            if(Serial.begin(9600) return 1;
            break;
        case 1:
            if(Serial1.begin(9600) return 1;
            break;

        ... etc...

        default:
            return 0;
}

However, this instantiates all Serialx objects (using 157 bytes of data/bss each).
I've since written a class wrapper that takes a referece to the desired serial object as an initialising paramter, but this just pushes the problem up-stack to the calling code.
Is there a way that a Serial object can be instanitated dynamically with a port number passed in, to only end up with one instance connected to the desired port?

Do you speak about SoftwareSerial interfaces or the hardware interfaces?

they are all instanced, but optimized away if the code doesn't use it. the class of Serials depends on the board. on some boards Serial is USB and Setial1 is HardwareSerial. but on boards with 328p it is something like HardwareSerial Serial(&UBRRH, &UBRRL, &UCSRA, &UCSRB, &UCSRC, &UDR);

Post editied to clarify mega2560 - hardware serial.

@Juraj they are not optimised away by the linker in my appliction (which is the problem) becuase the linker does not know which one will be use at runtime - this is based on user config data read from the SD. So it includes all 4 with assoicated memory use which is the underlying problem.

all are used in your sketch in some case, so must be in the final build.

@TisteAndii, it is not so complicated. only the instances must be created dynamically as Edgar shows in the answer

but what is 3 times 157 bytes in 8 kB SRAM of the Mega? :-)

sometimes it really matters :-) https://forum.arduino.cc/index.php?topic=622002.msg4215655#msg4215655

You can create an instance of HardwareSerial referencing a hardware
port that depends on a function parameter, as in
void initPort(uint8_t port) {
    switch (port) {
        case 0: {
            HardwareSerial serial(&UBRR0H, &UBRR0L,
                     &UCSR0A, &UCSR0B, &UCSR0C, &UDR0);
            serial.begin(9600);
            break;
        }
        case 1:
            // etc...
    }
}

However, since only a local variable can be created in this manner, it
is not of much use. Ideally, you would want to have a global variable
for the serial port, and initialize it in initPort(), as
HardwareSerial serial;

void initPort(uint8_t port) {
    switch (port) {
        case 0:
            // Invoke fictional init() method.
            serial.init(&UBRR0H, &UBRR0L,
                     &UCSR0A, &UCSR0B, &UCSR0C, &UDR0);
            break;
        case 1:
            // etc...
    }
    serial.begin(9600);
}

Alas, this is not possible, as the HardwareSerial class has no default
constructor. This means that binding the object to the hardware port can
only be done when it is constructed.
Short of modifying the Arduino core (adding a default constructor and an
init() method), the only option I can see is to have the global
variable be a pointer. Then, in initPort() the object is
instantiated while initializing the pointer. I tried this approach in
the example program below. There was a slight technical difficulty
though: since the object files from the core defining Serial,
Serail1, etc. will hopefully not be linked to the program, the
interrupt service routines defined therein must be also defined in the
sketch itself. And since an ISR cannot be bound to an interrupt at run
time, the ISRs have to be defined for all the ports, even though only
one ends up being actually used.
Here is my test program:
#include <HardwareSerial_private.h>

HardwareSerial *serial;

ISR(USART0_RX_vect) { serial->_rx_complete_irq(); }
ISR(USART1_RX_vect, ISR_ALIASOF(USART0_RX_vect));
ISR(USART2_RX_vect, ISR_ALIASOF(USART0_RX_vect));
ISR(USART3_RX_vect, ISR_ALIASOF(USART0_RX_vect));
ISR(USART0_UDRE_vect) { serial->_tx_udr_empty_irq(); }
ISR(USART1_UDRE_vect, ISR_ALIASOF(USART0_UDRE_vect));
ISR(USART2_UDRE_vect, ISR_ALIASOF(USART0_UDRE_vect));
ISR(USART3_UDRE_vect, ISR_ALIASOF(USART0_UDRE_vect));

void initPort(uint8_t port)
{
    switch (port) {
        case 0:
            serial = new HardwareSerial(&UBRR0H, &UBRR0L,
                         &UCSR0A, &UCSR0B, &UCSR0C, &UDR0);
            break;
        case 1:
            serial = new HardwareSerial(&UBRR1H, &UBRR1L,
                         &UCSR1A, &UCSR1B, &UCSR1C, &UDR1);
            break;
        case 2:
            serial = new HardwareSerial(&UBRR2H, &UBRR2L,
                         &UCSR2A, &UCSR2B, &UCSR2C, &UDR2);
            break;
        case 3:
            serial = new HardwareSerial(&UBRR3H, &UBRR3L,
                         &UCSR3A, &UCSR3B, &UCSR3C, &UDR3);
            break;
    }
    serial->begin(9600);
}

void setup() {
    initPort(0);
    serial->println("Hello, World!");
}

void loop(){}

It should be noted that the ISRs do not take that mush flash space.
There are actually only two of them, even though each is referenced four
times in the interrupt vector table.

Excellent that you have shared your progression to the answer. Many thanks. Now for the next learning deep dive - understanding ISRs properly on arduino and getting accross all the U variables in the HardwareSerial class. I presume they are registers of some sort?

@BrendanMcL: If you want to dig deeper, you will have to read the chapter “USART” of the ATmega2560 datasheet, and the chapter “Interrupts” of the avr-libc documentation.

@BrendanMcL: The “U variables” are references to hardware I/O registers. For example, UBRR0H is a macro that expands to (*(uint8_t*)0xc5), where 0xc5 is the memory-mapped address of the “USART0 Baud Rate Register High Byte”.

@Edgar_Bonet many thanks. Understood. Having so many great libraries on the arduino platform is a great upside for working quickly. Downside being that it abstracts away so much detail making it a full learning curve to do something outside the spec.


text:
Waking up a NodeMCU when force load is applied to device
I am currently designing a device that will take measurements from a load cell that  is in tension. I am using a v1.0 NodeMCU device that features an HX711 load cell amplifier and is running off of battery power. In order to conserve that power, I am wanting to be able to put as many parts of the device as possible into a sleep of some level when there is not a load on the cell. Then, I would like the device to be a be able to wake up when a load is applied and it goes into use. Going into a sleep will be simple enough, if the device is getting a reading around zero for a period time, it can enter sleep. Other notable hardware involved on the device will be a real-time-clock and an accelerometer.
From what I have already tried to look up, there doesn't seem to be any good way to use the load cell to get this action. The only idea I have been able to come up with for how to activate the device without having to wake it up extremely often other than a manual switch or checks very often came from this question. It suggests using a vibration sensor like this, which is how bathroom scales put themselves to sleep.
While I think it might be possible to use a vibration sensor to wake up the device, I am not sure if the loads involved and use case will disallow me from using one. Are there any other sensors or methods that could be used to achieve goals that I have for this device?

use a switch that closes when the scale deck is loaded

use an ESP32 and a ULP processor routine to monitor the input.

@dandavis After doing some research, that does seem like a really good option. The only issues that I can see running into is that the HX711 uses digital inputs and I have no idea how I would use assembly code to measure off of the HX711. What are your thoughts?

well it does make it a lot more complicated. the latest arduino lib helps somewhat, giving you some macros for common situations, one of which is reading an input state. i've not used it though, so i can't really explain it, i'm just aware of the broad possibilities it provides.


text:
Problems with controlling LED with soil moisture sensor
I'm a beginner at Arduino.
I have a soil moisture sensor and I mapped the lowest and highest moisture value to a value in between 0 and 100.
What I was trying to do was if the value was less than 50, then the LED should turn on. But even when the value was less than 50 (e.g 25) the LED doesn't turn on.
The moisture detection or the value mapping works perfectly fine.
Does the issue lie on my code or my LED wiring?

Code:

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

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

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

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

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

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

load and run LED blink code to test the LED

problem aside: you should only switch on power to the sensor when you're about to do a reading; a constant charge will corrode the sensor's metal very quickly.

A good way to start debugging this sort of problem is to print out debug statements that say what the hardware should be doing. If the debug statements print out as expected then it's probably hardware, if not, then it's probably your code, e.g.
if (percent < threshold){
  Serial.prinln("LED on.");
  digitalWrite(LED_BUILTIN,HIGH);
}
else {
  Serial.prinln("LED off.");
  digitalWrite(LED_BUILTIN,LOW);
}

Thanks, everything's working fine after adding the debug statement, the LED's turning on at the right time!

You're welcome, glad to help. If that answers your question you may want to mark the answer as accepted: https://stackoverflow.com/help/someone-answers


text:
How to repeat an IF statement
My LCD info is called from an IF statement but since it's clock and temperature info i don't want to just show the information but update the information constantly in real time.
i don't want to use (while) loop or any other "code-blocking".
Here's the whole code:
#include <OneWire.h>
#include <LiquidCrystal_I2C.h>
#include <DS3231.h>
#include <DallasTemperature.h>

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

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

// Push button

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

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

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

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

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

please use true and false as boolean values

@Juraj thanks but does it make any difference?

I'm not clear on what your problem is - I don't see any blocking code here - you test the clock and the switches and either act on them or don't, which is appropriate. Also, what do you mean by "How to repeat an IF statement"?

Also, do not compare values with true, false, 1, 0, or HIGH or LOW, just write if (variable), by default all nonzero values will result in executing the if statement.

well your void loop() is already a while loop.....What is it that you are wanting to repeat that is not already happening?

@JRobert the problem is code inside if (lcdScroll == LOW){} only runs once but if i want to have the time to update in real time, time functions have to be in a loop not only run once.

Well, it runs once per loop(). If the rest of the code is implemented properly, loop() will be fast and you have everything you want. I don't see any blocking code like delays(), etc. So what was the problem again?

Maybe it is happening so fast OP can not see the scrolling - giving the appearance that it is only running once.???? What happens if you put some serial.println's in your code? Does the if statement get executed more than once then when you press "the button"???

@SimSon if we add a Serial.prinln("test"); to if (lcdScroll == LOW){} statement you'll see that when push button pressed the code inside that statement only runs once. i think what i need is a "state machine" to get this to work...

Ah, now I got it, see my answer

Like you suggested in your comment, you can implement a state machine, but the simplest would probably be setting a flag bool a_flag in this if(lcdScroll==LOW) clause and checking if(a_flag) in the highest scope of the loop() section. This is where you print("test");.
In respect to your code this will look like:
bool a_flag=false;
void loop() {
  // some irrelevant stuff
  if ( newSwitchState != oldSwitchState) {
    // some stuff
    if ( lcdScroll == LOW ){
      // stuff you would handle here
      a_flag=true;
    }
    else {
      // stuff you would handle here
      a_flag=false;
    }
  }
  if (a_flag) Serial.println("lcdScroll is LOW");
  else Serial.println("lcdScroll is HIGH");
}

Beside this general solution you could simply do the following in your specific case:
loop(){

  // your actual code

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

i'm very new to this can you please implant that in the code so i can get the whole idea?

@newbie You need to clear this flag somewhere and I'm not sure where (probably in the corresponding else{}). I'll add an implementation of this soon...

See my example implementation. This will continuously print the corresponding message. Note also that the backlight will behave erronuously when millis runs over!

i asked this question both in reddit and arduino forum and they didn't/couldn't give me an answer. you sir are a legend. thank you and god bless you.


text:
Can I use the NodeMCU ESP12 5v pin and control it with a relay?
This question might be a little esoteric, but I cannot find any answer for it.
Situation:
I want to have more than 8 Analog sensors on a NodeMCU ESP32. Unfortunately due to SPECTACULARLY poor design choices you cannot do this and have WiFi active at the same time. This is a non-starter for my project so I need a workaround.
Thought:
What if I share the available pins I can use, by turning power on and off to the sensors in question? Easy enough using the digital GPIO's and just turning them on and off. The issue is that the sensors are at the end of long wires and so I need 5v power to ensure good readings. So what if I just use a relay, powered off the 5v pin on the ESP32, and switch them on and off?
My question is - can you even do this? Most of what I have seen would indicate I need a separate power supply for the relay itself, and the source being switched on and off, but I would like to avoid having another power supply, and build it as in the circuit diagram below.
A couple of notes:

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

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

your setup could work as described. sharing power isn't the issue. the main concern would be the 3.3v HIGH being high enough to actuate the relay module.

You dont really need relays, you could switch power on/off using a transistor, use the same power supply, there would be no issue.  However, you would need to find out if having two sensors connected to the same input would skew the results even if one is not powered. You are still introducing an "unknown" circuit and it could mean that your output changes or even damages the other circuit, as you are now apply a voltage to an output of another device.  You could use diodes to ensure current is only flowing out of the device and not into the other device, but again this will effect the voltage

dandavis the 3.3 should work to activate it (I can get a 3.3 model as well so that's an option too)
@ChadG - I had thought of the diodes to protect the data lines from the sensors, but the voltage drop could be an issue. Given the length of wire involved between sensor and MCU, we are talking about pretty small amounts (sub 3 volt most likely although not tested with a multi yet). Would the diode be that much of a drop in that case?

voltage drop over a diode is pretty fixed, so it actually becomes a much higher percentage with lower voltages. The exact amount changes based on the diode, but 0.7V is common.

Yeah dropping almost a full 1v is probably a no go for the readings from the sensor since they are analog and thus voltage dependent. Oh well, guess I am stuck then.

oh, @ChadG, thanks for the idea on the transistor instead of the relay. Probably a much more efficient design for the PCB, given it has to fit in roughly 70 x 70 MM!

Now you could use double throw relays between the output lines of sensors and the input on the uC.  This way only one was connected to it at a time, and the two sensor outputs would not be connected this way.

Another option, and probably the cleanest, is to use adc IC's.  The ones I link are only a single channel, but they communicator over I2C so you can use a number of them off the same bus, now you actually have as many inputs as you need   https://www.mouser.com/ProductDetail/Analog-Devices/5962-9475501MPA?qs=sGAEpiMZZMvTvDTV69d2QgYdPJm2vkaBTxTWToXHJa8%3D

Just get an additional power supply that is capable of providing enough current. The relay-approach is much too complicate and will be more expensive than an ordinary PSU...

@SimSon the relays were not being considered because of power draw, but so that the sensors could be multiplexed to the inputs.(have one set on at a time)

@ChadG Doesn't the esp32 have enough pins that are multiplexed to the ADC internally? And if the OP really needs more pins than available then using an analog multiplexer IC would be the way to go in my opinion...

I am liking the ADC IC idea. It would eliminate both the power and " not enough pins" issue. I think it will fit in the confines of the PCB - just need to see. I have several on the bench, but it never occurred to me to go that route. DUH.


text:
How to upgrade ESP8266 NodeMCU SDK from V2.5.2 to V3?
ESP.getFullVersion() output:
SDK:2.2.1(cfd48f3)/Core:2.5.2=20502000/lwIP:STABLE-2_1_2_RELEASE/glue:1.1-7-g82abda3/BearSSL:a143020Connecting to DO_231455

I upload sketches from the Arduino IDE. How do I update the SDK?
I have the flasher tool but I can't seem to find documentation on what to do from this point:

I've downloaded the assets from Github

The SDK is linked into every Arduino application you flash to the ESP8266 - it's not flashed separately.
Choose it in Tools menu. It is available only if you select "Generic ESP8266 module".

The SDK is linked into every Arduino application you flash to the ESP8266 - it's not flashed separately.
Presumably you've already followed the instructions to put the URL for the ESP8266 Arduino Core in the preferences for the Arduino IDE.
Once that's there, to update the ESP8266 Arduino SDK, go to the Tools menu, select Board, then select the Boards manager (the first item in the menu).
That will bring up a dialog listing all the board families your Arduino IDE knows how to build for. You can limit the list to those with updates available by selecting "Updatable" in the "Type" field. Or just scroll down or search till you find the ESP8266 entry. Click it and if there's an update available you'll see an "Update" button appear on it. You can also reinstall older versions by choosing a version and clicking the "Install" button.

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

it is the Arduino core version in Boards Manager, not the Espressif SDK version


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

what difficulty?

are you implying they should be compatible? @Juraj I am having difficulty with the board locking up and not being able to program it anymore. That is another issue I am still dealing with. I am new to arduino and cant understand it. I explain that issue here: https://arduino.stackexchange.com/questions/66402/stuck-with-bad-sketch

StackExchange is not for troubleshooting. stop asking the same question again and again and discussing in comments. https://arduino.stackexchange.com/tour


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

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

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

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

Nothing special needs to be done. Beyond that, we can't really help you without seeing some code.

Do the chips share a common ground? Do they use the same logic voltage levels? Are they both powered? Did you connect the Arduino's TX to the STM32's RX? Do you have a scope?

Please see the edited post. They are both definitely powered and the RX/TX lines are wired correctly.

I see nothing wrong on the Arduino side. Are you sure the STM32 expects text rather than binary? Does it like the CRLF line termination? Is its RX 3.3V-tolerant?

According to the datasheet, the STM32 is 3.3V tolerant. I haven't tried binary. I will give that a go. Thank you for the quick response!

What is your stm code and why is it powered at 2.5V?

Just a quick note: confirm that the STM is 3.3V tolerant even when Vcc is 2.5V; this is because most of the times the upper value is Vcc+0.3V. Even though, I'm confident it is compatible with the voltage range.

Moreover, check with an oscilloscope on the serial line, so that you can detect whether the issue is with the arduino or the STM

Unfortunately, I don't have access to the STM code. I added a voltage divider to the Arduino TX to bring it down to 2.5V. I tried transmitting binary code with no luck. Is it possible that I need to convert the values in the string to ASCII characters since it's USART? I will take a look with an oscilloscope when I try again.

I finally figured it out! I ended up having to declare the values in the string as integers, and then I used serial.write() instead of serial.print(). Thank you everyone for your help!


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

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

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

Where is the rest of your sketch? The servo include is missing, setup is missing, and var i = 0; looks like JavaScript, not "Arduino code".

try void toMove(Servo& obj,int inPosition, int forPosition){

It doesn't make sense to write all values from inPosition to forPosition in increments to the servo. Since the period of the pulsed signal to the servo is much longer (multiple orders of magnitude) than the time the for-loop needs, the servo will (almost) never see any intermediate values. You can just write the forPosition to the servo.

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

#define SERVO1      9
#define SERVO2      10

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

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

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

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

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

a function prototype a line before the function definition? (and a line before the comment about it?)

As noted by Juraj in a comment to the original question, it would be better to pass a reference to the servo, rather than copying the whole object: void toMove(Servo &obj, int inPosition, int forPosition);.

Yeah, that was an editing 'oops'. Originally I'd put toMove() below loop(). Clearly, the declaration is no longer needed.

I am simulating in Tinkercad, I copied its code and set up the project, with the arduino and the servo, it continues giving error, the Servo is not identified as type of variable for the function.
Would you like to help me, the link to the project is: https://www.tinkercad.com/things/2w0xPqGEqI0-smooth-vihelmo/editel?tenant=circuits?sharecode=Asr_eiFyOe07v5aViePWyad3yNYuyASikZSkzwspaoU=
Anyway thank you!

Have you tried @juraj & @ EdgarBonet's suggestion of passing by reference ( '&obj' instead of 'obj' in the function parameter list)? The compiler will accept it either way (at a 58 byte code penalty for passing the whole object), but perhaps Tinkercad won't accept passing the entire object (I couldn't try it - the link fails for me).

You have not use attach() function:
 s1.attach(pin_1);
 s2.attach(pin_2);

See how to use servo motor