text:
_delay_ms() is much slower than expected (by a factor of 6) on TinyAVR 0/1 (ATTiny1604)
I designed a custom AVR development board using the Atmel ATTiny1604 microcontroller. It belongs to the new Tiny-0 family, due to its recentness, some required changes to relevant toolchains have yet to be included into the stable version  (I prefer to use the original upstream toolchains instead of Atmel/Microchip's SDK). Thus, I compiled the latest versions of toolchains from source. They include...

AVR GCC 10.2.0

avr-libc, svn trunk, with patch avrxmega3-v10.diff applied

After I installed the toolchains, I wrote a LED blinking program to verify whether my toolchain was working properly. The program was built with avr-gcc -mmcu=attiny1604 -Wall -Os -o blink.elf blink.c -Wl,--section-start=.text=0x200 and uploaded via the Optiboot_X bootloader.
#define F_CPU 20000000UL
#include <avr/io.h>
#include <util/delay.h>

int main(void)
{
    PORTB.DIRSET = 0b00000001;

    while (1) {
        PORTB.OUTSET = 0b00000001;
        _delay_ms(500);
        PORTB.OUTCLR = 0b00000001;
        _delay_ms(500);
    }
}

However, I found that _delay_ms(500) doesn't work as expected. Instead of a 500-millisecond delay, the actual delay is closer to 3000 milliseconds as seen on the oscilloscope, it has been slowed down by a factor of 6.

I've double-checked my fuse settings.
$ pyupdi -d tiny1604 -c /dev/ttyUSB0 -fr
Device info: {'family': 'tinyAVR', 'nvm': 'P:0', 'ocd': 'D:0', 'osc': '3', 'device_id': '1E9425', 'device_rev': '0.0'}
Fuse:Value
0:0x00
1:0x00
2:0x02
3:0xFF
4:0x00
5:0xF6
6:0x07
7:0x00
8:0x02
9:0xFF
10:0xC5

I saw pyupdi reported that the fuse OSCCFG (No. 2) has been programmed to 0x02, which according to the datasheet, means "Run at 20 MHz with corresponding factory calibration". Why do I get incorrect delays even when the system clock is running at the correct speed? Is my toolchain broken?
Note: This is a question I already solved. But consider there are relatively few tutorials about the new TinyAVR 0/1 on the web, I posted the question and answer here to serve as a reference for the community.

Your toolchain is not broken. In the ATTiny804/1604 datasheet, page 77, it shows the CPU clock is divided from the 20/16 MHz oscillator by a prescaler (the ATTiny1614 datasheet shows the same clock prescaler in page 80. So it's a feature found in both tinyAVR 0/1 microcontrollers).

Source: Microchip ATTiny804/1604 datasheet, fair use.
The datasheet says...

10.3.3 Main Clock After Reset After any Reset, CLK_MAIN is provided by the 16/20 MHz Oscillator (OSC20M) and with a prescaler division factor of 6. Since the actual frequency of the OSC20M is determined by the Frequency Select bits (FREQSEL) of the Oscillator Configuration fuse (FUSE.OSCCFG), these frequencies are possible after Reset:

16 MHz ---> 2.66 MHz
20 MHz ---> 3.3 MHz

By default, the division factor is 6. It means the CPU is actually running at 3.333 MHz when the OSCCFG fuse is programmed to 20 MHz.
Solution
Use the correct F_CPU
If a slower CPU is not a problem to you, you can simply report the correct CPU frequency to the compiler by change #define F_CPU 20000000UL to #define F_CPU 3333333UL.
Or disable frequency division
Alternatively, you can disable the frequency division and run the CPU at its 20 MHz full speed.
#define F_CPU 20000000UL

int main(void)
{
    /* Set CPU clock to 20 MHz */
    _PROTECTED_WRITE(CLKCTRL_MCLKCTRLB, 0);

    /* your code */
}

But don't overclock the CPU
Nevertheless, you should note that 20 MHz operation is only guaranteed by Atmel at 4.5 V and above. If you are running the microcontroller at a lower voltage, such as 3.3 V, you are overclocking the CPU by putting it outside the safe operating area designated by Atmel. See datasheet page 473.

Source: Microchip ATTiny804/1604 datasheet, fair use.
Although an overclocked microcontroller will probably work, and in a hobby project, you are unlikely to see any issue. But still, at this point there is no guarantee of stability from the manufacturer. For example, the microcontroller is officially rated at 105°C, but an overclocked microcontroller may start crashing. Increased power consumption is also likely. The worst possible problem could be mysterious malfunction under certain rare conditions. Thus, if reliability and stability is important, you should not overclock the microcontroller.
At 3.3 V, given a 20 MHz system clock, the CPU should only operate at 10 MHz by setting the prescaler to 2x. And at 1.8 V, at 5 MHz with a 4x prescaler.
/* Set CPU clock to 10 MHz */
_PROTECTED_WRITE(CLKCTRL_MCLKCTRLB,
                 CLKCTRL_PDIV_2X_gc | CLKCTRL_PEN_bm);

/* Set CPU clock to 5 MHz */
_PROTECTED_WRITE(CLKCTRL_MCLKCTRLB,
                 CLKCTRL_PDIV_4X_gc | CLKCTRL_PEN_bm);


text:
Issue using micros() instead of millis()
I have two function implementations that I expected to work the same:
#define HEAD_STEP_DELAY 1000
unsigned long HeadLastMicros;
void HeadUpdate()
{
    if ((micros()>=HeadLastMicros) && ((micros()-HeadLastMicros)<HEAD_STEP_DELAY)) {
        return;
    }
    HeadLastMicros = micros();
    HeadStep(true);
}

and
#define HEAD_STEP_DELAY 1
unsigned long HeadLastMillis;
void HeadUpdate()
{
    if ((millis()>=HeadLastMillis) && ((millis()-HeadLastMillis)<HEAD_STEP_DELAY)) {
        return;
    }
    HeadLastMillis = millis();
    HeadStep(true);
}

I know that the resolution of micros() is limited to about 8us, but I figure given that I have a 1000us wait, both of the above ought to be relatively close to the same behavior. I'm driving a stepper motor from this code, and the stepper that used micros() was behaving erratically. I haven't put the scope on it yet, so I don't know for sure, but the torque was significantly less (motor stalled easily) and it sounded wonky.
I'm using an ATMEGA324A together with the MightyCore library.
Is there anything wrong with my approach? Thanks.
EDIT: I did put the scope on it after my initial post, and the period of the micros() code is approximately half the period of the millis() code.

First off, when dealing with a time system that wraps around, don't compare two times.  Compare the differences.
Second, cache your function call results if you are going to use it more than once.
Third, if you want a consistent time interval, ask for it.  Your current micros() based code could well take 1990µs on some iterations and 1001µs on others.
Fourth, don't use the current time more than once...
Do something like (not specifying millis() or micros()):
unsigned long HeadLast; /* This should be initialized somewhere (HeadStart()?),
                           as otherwise things could go weird.
                           On the Arduino platform, initializing to 0
                           may work.  On other systems, time can start anywhen.
                           This caused Microsoft Windows to have trouble after
                           being up for 49 days (started at 0), while X Windows
                           has no such issue (start anywhen).
                           */
void HeadUpdate()
{
    /* compile with -O and this will optimize to a register. */
    unsigned long now = get_time_function();

    /* We don't need to test now >= HeadLast, as time is monotonic. */
    if ((now-HeadLast)<HEAD_STEP_DELAY)) {
        return;
    }
    /* Select the time we consider this to have started at.
       This may well be before the current time. */
    HeadLast += HEAD_STEP_DELAY;
    HeadStep(true);
}

source: Stack Exchange

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

sort: votes


text:
SPI register read returns 0x00 or 0xff
I am trying to interface a Arduino Uno with an ASM330LHH using SPI. Whenever I try to read any register, I either get 0xff or 0x00 on the serial monitor
The code I am using:
#include <SPI.h>

#define LOOP_DELAY 1000 //ms
uint8_t data;

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

  /* Refer datasheet for ASM330LHH
   * SPI freq max 10MHz
   * MSB first
   * SPI mode 3
   */
  SPI.begin();
  SPI.beginTransaction(SPISettings(1000000, MSBFIRST, SPI_MODE3));

  pinMode(10, OUTPUT);
  digitalWrite(10, HIGH);
  Serial.println("Setup complete!");

}

void loop() {
  digitalWrite(10, LOW);
  byte masked_addr = 0x0F | 0x80;
  Serial.println(masked_addr, BIN);

  SPI.transfer(masked_addr);
  data = SPI.transfer(0x00);
  Serial.println(data, BIN);
  digitalWrite(10, HIGH);
  delay(LOOP_DELAY);
}

The output I get:
10001111
11111111
10001111
11111111
10001111
0
10001111
0

The expected output for the above code is 0x6B. What might have gone wrong?
Thanks in advance

add SPI.begin();

I'm not entirely sure it will matter in what you have currently, but SPI.begin() should happen before .beginTransaction()

begin must be called before beginTransfer and 10 MHz is to fast for an 16 MHz arduino. 1 MHz should be OK. It might be, that the library correct the 10 Mhz property to a suitable value.

Just as an aside, your data rate was probably fine.  The Arduino UNO's ATMega328P running 16 MHz, can't run the SPI clock faster than 8 MHz or slower than 125 kHz.  The rate will be clamped to this range, which most SPI devices will handle.  The slower rate is probably better while you're troubleshooting though.

Your ASM330LHH is a 3.3V device.  You should probably update the question to have a picture/diagram/schematic of however you're interfacing your 5.0V Arduino UNO to it.

I just connected the Arduino Uno to ADXL345 (Equivalent to ASM330LLH) to test the code. The code works fine. Maybe the ASM330LLH has gone bad. I need to check.

There is so much I can't see to have any confidence in that idea.  Just to drive the point home: You can't, in the general case, connect a 5V and a 3.3V device together and expect them to work or work reliably without /some/, however minor, consideration for the differences.  I'm just guessing you have breakout boards, and those boards may or may not being doing something helpful in interfacing the chip to the Arduino.  Beyond rearranging the pins I mean.

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


text:
Unreliable function of transistor, pump and ESP32
I have a 12 VDC pump, 8.5A, connected to a MOSFET transistor PSMN5R6-100PS,127.
The connection from the transistor to transformer, pump and a ESP32:
1    Gate   --> port to ESP32
2    Drain  --> (-) pump
3    Source --> Gnd ESP32, (-) transformer
(+) transformer to (+) pump
This is, as I understand it, how it ought to work. But with this configuration it doesn't...
But changing 3    Source --> (-) transformer, removing the Gnd connection to the ESP32, then it works. It, however, seems to be some kind of leakage in terms of current because the pump has a "clucking" sound, not fully activating, just making a sound. Sometimes it doesn't work at all, where a reset makes it work again. Any ideas how I can fix it reliably?

That transistor has Vgs(th) typical 3V if I read the datasheet correctly. ESP is at 3.3V? Might not be enough

This is not a question about Arduino. 2) Removing the common GND connection from the transformer (-) to the ESP32 will almost certainly lead to problems. 3) My guess is your MOSFET does not fully conduct at the ESP32 port output voltage (3.3V). You need to increase the gate voltage. Did you add a flyback diode across the pump to protect the MOSFET?

(2) Yes, I suspected this...What kinds of problems could occur?  (3) Yes, this has been my hypothesis previously, especially when considering that when connecting this same transistor to LEDs the light intensity is significantly lower that if the LEDs are directly connected to the transformer. No flyback diod has been added. Would it be best to just look for another transistor with a lower requirement in terms of gate voltage? Any ideas?

As can be seen from the datasheet for the PSNB5R6 (Fig 7) at 3.3V the MOSFET is barely even beginning to switch on.
You need to select a more suitable MOSFET that switches on fully at a voltage well below 3.3V, such as the STP40NF04L.

Will purchase this transistor and will have a look if it works!

When you're looking at them, you may want to look at the "safe operating area."  I don't know if I was reading it correctly, but in the datasheet for your PSMN5R6-100PS, the graph seems to suggest that at continuous (DC) operation at 12V about 6 AMP would be maximum.  So even if it had been able to turn on fully, it's not clear that you'd be able to use it unless you were pulsing 8.5 amps to the pump.

Looks more like 9A to me on that graph.

I struck lines over it to double check just now.  Though, I don't see a way to insert an image into a comment.  As long as they're aware of this aspect to picking one out, I'm content.


text:
how can I stop my Arduino code after 1 second?
I want to send message NRF24L01 to NRF24L01. I want to see if I can send just one second. How can I stop code after 1 second?

study the example code that is included with the arduino IDE

You can use different ways:
Use setup only
Instead of putting code in the loop function,  put it in setup, which is only executed once (use a for loop to send around 1 second.
millis() excluding setup
It is better to use the millis function and compare it against the start of sending; when 1 second is reached, don't send anything or use an infinite while loop.
Use something like:
unsigned long time_start;

void setup()
{
    // Your normal code

    time_start = millis();
}

void setup()
{
    if (millis() - time_start >= 1000)
    {
        while(1) {};
    }

    // your normal code (which should not take many ms,
    // otherwise the above code is not reached.

millis() including saetup (Thanks to Edgar Bonnet):
 void loop()
 {
     if (millis() >= 1000)
     {
        while(1) {};
     }
 }

This will stop exactly after 1 s  after startup (excluding the setup). It will start counting after millis start counting, which is before the setup function.
Actually, in none of the above the Arduino 'stops', it just is doing endlessly nothing (well internally endlessly checking against the true condition which never changes).

Or even if (millis >= 1000) exit();.

@EdgarBonet Thanks, I added it to the answer.


text:
How can I add a potentiometer and more buttons to my custom game controller?
I'm new to using Arduino, and know next to nothing about programming. I'm currently trying to add a potentiometer, and possibly a few more button inputs to my 3D-printed guitar controller project
It uses an Arduino Pro Micro, the code is just an example file from this joystick library that I mostly just played around with using trial and error, and this pinout diagram from Sparkfun, with this being what I ended up with:
#include <Joystick.h>

Joystick_ Joystick;

void setup() {
  // Initialize Button Pins
  pinMode(0, INPUT_PULLUP);
  pinMode(1, INPUT_PULLUP);
  pinMode(2, INPUT_PULLUP);
  pinMode(3, INPUT_PULLUP);
  pinMode(4, INPUT_PULLUP);
  pinMode(5, INPUT_PULLUP);
  pinMode(6, INPUT_PULLUP);
  pinMode(7, INPUT_PULLUP);
  pinMode(8, INPUT_PULLUP);
  pinMode(9, INPUT_PULLUP);
  pinMode(10, INPUT_PULLUP);

  // Initialize Joystick Library
  Joystick.begin();
}

// Constant that maps the phyical pin to the joystick button.
const int pinToButtonMap = 0;

// Last state of the button
int lastButtonState[11] = {0,0,0,0,0,0,0,0,0,0,0};

void loop() {

  // Read pin values
  for (int index = 0; index <= 10; index++)
  {
    int currentButtonState = !digitalRead(index + pinToButtonMap);
    if (currentButtonState != lastButtonState[index])
    {
      Joystick.setButton(index, currentButtonState);
      lastButtonState[index] = currentButtonState;
    }
  }

  delay(10);
}

This is the original example code that I used:
// Simple example application that shows how to read four Arduino
// digital pins and map them to the USB Joystick library.
//
// Ground digital pins 9, 10, 11, and 12 to press the joystick
// buttons 0, 1, 2, and 3.
//
// NOTE: This sketch file is for use with Arduino Leonardo and
//       Arduino Micro only.
//
// by Matthew Heironimus
// 2015-11-20
//--------------------------------------------------------------------

#include <Joystick.h>

Joystick_ Joystick;

void setup() {
  // Initialize Button Pins
  pinMode(9, INPUT_PULLUP);
  pinMode(10, INPUT_PULLUP);
  pinMode(11, INPUT_PULLUP);
  pinMode(12, INPUT_PULLUP);

  // Initialize Joystick Library
  Joystick.begin();
}

// Constant that maps the phyical pin to the joystick button.
const int pinToButtonMap = 9;

// Last state of the button
int lastButtonState[4] = {0,0,0,0};

void loop() {

  // Read pin values
  for (int index = 0; index < 4; index++)
  {
    int currentButtonState = !digitalRead(index + pinToButtonMap);
    if (currentButtonState != lastButtonState[index])
    {
      Joystick.setButton(index, currentButtonState);
      lastButtonState[index] = currentButtonState;
    }
  }

  delay(50);
}

I started this project in late February/early March, but only got to the Arduino part recently. I've had my v1 working for a little over a month using this code, and I've been working on the v2 design (adding a whammy bar and repositioning the start and select buttons) since then. I only just got to the point where I need to change the code last week.
From the comments in the example and some trial and error, I figured out that "const int pinToButtonMap = 9" is the lowest-numbered pin that it will use, and "for (int index = 0; index < 4; index++)" seems to determine the rest of the pins, so I changed 9 to 0, and "< 4" to "< 18" (the number of usable pins), and it kind of worked. Pins 0-10 and 14-16 now worked as button inputs, but button 14 (which would've been on pin 13, which doesn't exist on the Pro Micro) reads as constantly pressed, and pins A0-A3 (digital pins 18-21) don't read anything. If instead, I change it to "< 19", "< 20", etc. It just stops working completely, and if I change it to "< 11" or "<= 10" (my current code), all the pins from 0-10 work, and there are no phantom button presses
Also, I'm honestly not planning on learning any kind of real programming anytime soon. Maybe in the future, but for now, I just need enough to get this working with a 10k potentiometer (the same type that official Guitar Hero controllers use for their whammy bars) and possibly a few more button inputs (I might add a tilt sensor and maybe a D-pad in a future version)

Beautiful work with the 3D-printed guitar!  You have already spent a lot of time and effort with the physical design and construction of the controller, so I recommend you plan on spending some quality time with basic Arduino programming, including the basic pin layout for the Pro Micro and the basics of programming in the Arduino language (basically C++)
You can find all you need to know in the example programs that come with the Arduino IDE (File -> Examples - 01.Basics) and with the many available tutorials (search for Arduino tutorial).  Here's one that seems to be pretty clear https://www.youtube.com/watch?v=QO_Jlz1qpDw
You'll also need to look at one of the many Arduino pinout diagrams for the Pro Micro, like this one https://learn.sparkfun.com/tutorials/pro-micro--fio-v3-hookup-guide/hardware-overview-pro-micro
From the diagram, it appears you can use pins 2-10 and 16-21 for digital I/0 (for your buttons), but you'll need to use one of 10, 18-21 for your potentiometer input.  So, as one other poster already noted, you should use an array of pin numbers and then read each pin by indexing into the array.
For the potentiometer interface, one of the supplied examples in '01.Basics' is the 'AnalogReadSerial' program, which should get you started.  To use this program, connect the center pin of a potientiometer to pin 18(A0), and the other two to VCC & GND. Upload the program to the Pro Micro, and you should get some console printouts that vary when you change the potientiometer setting.
Make your programs very small to start with - think of them as disposable snippets that will later be incorporated into the final program.  One snippet just for the potentiometer, and another snippet just for, say, 4 buttons that connect to pins 2, 9, 16 & 21 just to make sure your array indexing scheme works.  Then when all is working, the snippets can be combined into a 'final' (nothing is ever really final in the Arduino world).
And lastly, use serial 'print' statements liberally for test & debug; they will save you no end of trouble & frustration.  You can comment them out after all testing has been done, or just leave them in.  In most projects the Serial.print statements don't take up enough time or memory to matter.
Welcome to the Arduino world!  You'll love it!
Frank

It seems pins 11, 12 and 13 do not exist as input pins and pins 0 and 1 are used for RX/TX which you don't want to use neither probably.
So instead of using a for loop iterating over indices, you should create an array with pin numbers and use that instead, something like:
Create globally:
int input_pins = { 2, 3, 4, 5, 6, 7, 8, 9, 10, 14, 15, 16, ... };

Use in loop:
for (int index = 0; index < sizeof(input_pins) / sizeof(int); index++)
{
    int currentButtonState = digitalRead(input_pins[index]);

You can use the same for to set the pin modes in the setup:
for (int index = 0; index < sizeof(input_pins) / sizeof(int); index++)
{
    pinMode(input_pins[index], INPUT_PULLUP);
}

sizeof(input_pins) / sizeof(int) will give the amount of items within the array. You can now easily change it depending on the pin numbers.
I suggest you learn a bit of coding to at least understand what you change, it will make your life much easier as you progress.
In case you want more pins beyond the actual existing pins, you need to use a multiplexer like 74HC595; there are plenty examples how to use this.

Don't you mean digitalRead(input_pins[index]) instead of just digitalRead(index)?

@chrisl Of course, thanks for the fix (I updated my answer).

I suggest you learn a bit of coding to at least understand what you change, it will make your life much easier as you progress

I do eventually want to learn to code, but that's just not something I'm interested in doing (or have time for) in the immediate future. For now, I just want to get this working, so I have more time for other 3D printing projects I'm working on

In case you want more pins beyond the actual existing pins

That won't be a problem for this project. At the absolute most, I need 15 input pins out of the 18 available

@taj1994 Ok clear for both. About the number of pins, of course you shouldn't add something complicated when you know beforehand it will be never needed. Good luck with your project.


text:
Input state is stuck HIGH when function called using input also uses same input to call another function
I'm writing a choose-your-own-adventure style project for a class project. My Arduino Uno is set up with a 16-digit LCD display and two pushbuttons with pulldown resistors. I'm wanting each function to display text on the LCD and then take two user inputs, Yes or No, from the pushbuttons, and then call another function respective of which input is pressed. Each successive function will also take the two inputs to then call the next function in the series, and so on.
My issue is that after the first time a pushbutton is pressed, its state does not change. When question1() is called, and the user presses button1, question2 is called. However, the function runs and never waits for user input, and question4 is called right away because the state of button1 seemingly stays HIGH after the first time it is pressed.
What am I missing? Is there a better way to be gathering the user input? My pushbuttons are properly wired with the resistor pulling down to ground so my issue must be with my code.
Thanks in advance for any help.
void loop()
{
  question1();
}

void question1()
{
  button1State = digitalRead(9);
  button2State = digitalRead(8);
  if (q1 == false)
  {
    text1();
  }

  if (button1State == HIGH)
  {
    question2();
  }

  if (button2State == HIGH)
  {
    question3();
  }
}

void question2()
{
  button1State = digitalRead(9);
  button2State = digitalRead(8);
  if (q2 == false)
  {
    text2();
  }

  if (button1State == HIGH)
  {
    question4();
  }

  if (button2State == HIGH)
  {
    question5();
  }
}

You're reading the (physical) button states in one location, inside loop() with button1State = digitalRead(9); .... Once you call question1() from loop(), the values of buttonState1 and buttonState2 are fixed and will not change until your code returns to loop() to re-read the physical button state into buttonState1 and buttonState2.

I was reading the button state at the beginning of each function and that wasn't seeming to do anything. Let me retry that though, thank you

Yeah the behavior is still the same. Since the state of the button is the condition of my if statement, perhaps that's what is holding this up?

think about this .... how do you detect two presses of one button?

@jsotola Yeah that's kind of what I'm trying to figure out

what is the sequence of events when you press a button twice?

If it's pressed twice nothing should happen unless the textX() function has ran, at which time it's time for user input again and the button press call the next function

You have to wait for the button to be released. Currently you wait for a button to be pressed in question1, which is fine. Once a button1 is pressed you go to question2, but since the button is still pressed it immediately goes on to question 4.

Do you suggest using the state of the button to assign a value to a variable, and then using that variable to call the respective function?

You want to count each button press once. So you don't want to look for the button pin being HIGH (as it will stay high for quite some time, like tens of milliseconds, ages for a microcontroller), you want to look for the transition from LOW to HIGH. Also you need to consider the button bounce, thus you need debouncing (you can google that). I suggest you have a look at the Bounce2 library, which will help a lot with reading mechanical buttons. Try the examples to understand, how the library is used

This answer might also help you. There are sure many more questions about reading buttons on this site. You can just search for them.

reading a button is not so simple as it seams. and for multiple buttons and long press detection etc, the code in sketch gets complicated. I use a library. Bounce2 maintained by Thomas O Fredericks

There needs to be a delay() after the button state is read to allow time for it to return LOW, dumba**.
You already have enough delay() in your textN() functions, just check the button state after calling that function, not before. Code should be as follows:
void loop()
{
  question1();
}

void question1()
{
  if (q1 == false)
  {
    text1();
  }

  button1State = digitalRead(9);
  button2State = digitalRead(8);

  if (button1State == HIGH)
  {
    question2();
  }

  if (button2State == HIGH)
  {
    question3();
  }
}

void question2()
{
  if (q2 == false)
  {
    text2();
  }

  button1State = digitalRead(9);
  button2State = digitalRead(8);

  if (button1State == HIGH)
  {
    question4();
  }

  if (button2State == HIGH)
  {
    question5();
  }
}

This solves the issue completely.


text:
DIY CNC Machine Power Requirements
I want to make a CNC machine that uses 5 NEMA 17 rated for 2A and a RAMPS 1.4 to control it all. I have a power supply that can deliver 1.5A at 12V. Is it enough? I am worried that when all 5 motors are under load, the amperage will get distributed and there will be very low amperage per motor.

5x2 is 10. You need at least that and more.

So I need at least 10 amps!

Is there any cheap place I can get that type of power supply? Also how much can an ATX power supply give out?

Yes, and more than that - here's an example https://cpc.farnell.com/unbranded/500w-builder-black/500w-black-12cm-psu-pfc/dp/CS32144?mckv=saBqmjUHB_dm|pcrid|395592567287|kword||match||plid||slid||product|CS32144|pgrid|83089512472|ptaid|pla-781001870297|&CMP=KNC-GUK-CPC-SHOPPING&gclid=Cj0KCQiA7qP9BRCLARIsABDaZzj6FBitKJ-pzTDlGUG-ci5LeuKl5bZcNUPqsTcVxTOlGW2Q3VvgLxoaArTlEALw_wcB

You can limit the current on some stepper driver modules by adjusting a potentiometer. But that results in less torque in the stepper motor. Not ideal, but it might be useful, so you can move forward while waiting for a proper power supply.

PS on ATX power supplies to need to connect the green wire (PS_ON) to GND (black wire), to enable it.

Some also need a load on the 3.3v or 5v to operate.

Is there near the 5-10 USD range?

Here's one that's $14.50. I'm personally not a fan of using ATX power supplies as general power supplies. Mornsun isn't a very known brand
but we using them for all our power supplies at my company and they are just as good for the faction of the cost. https://store.nacsemi.com/products/detail?part=LM150-20B12&stock=MS000000009106

Figuring out your current needs is simply a matter of adding everything up. If you have 5 2 amp motors, you'll need 5 x 2, or 10 amps just to drive the motors.
You should probably have at least 20% extra capacity, so I'd suggest having a 12V power supply that can put out at least 12A.
15A would be better.
The stiffer your power supply the less it will "bobble" as the load varies.

That's not really how stepper motors behave in practice, since their rated currents occur at much lower voltages than Vcc under use.
5A should be fine for five such steppers.


text:
Reading and Writing to a JSON File on the Desktop from Arduino?
I'm fairly new to Arduino. I'm working on a project where I'm making HTTP requests using a python code and this lets me read and write to a JSON file on my desktop. I have an Arduino with sensors that records values and I want to take those recorded values and update them to the JSON file on my desktop in real-time. I looked online and many suggested using some Arduino library, but it was only for reading. I'm still confused about reading and writing to the JSON file on my desktop. I appreciate any help to guide me in the right direction. Thank you.

The Arduino cannot just write to your PCs storage. There must be some kind of program on the PC to do the writing. Thus you don't need an Arduino JSON library. You could let your python code, that already writes to the JSON file, also read data from the Arduino (for example over serial) and put that data into the file

@chrisl is there a reliable resource you recommend that demonstrates how the python code can read data from the Arduino. From a quick search, I was able to find some examples of communication over serial.

The way the PC and the Arduino communicate depends on the used interface. If you connect the Arduino via USB, then it will be Serial. If you have a Wifi Arduino or an Ethernet shield, you could also send data via network connection. But it seems, you want serial here. I have no source, but you can google it. Probably you also should read Majenkos take on Serial on the Arduino.

When googling you can separate the Arduino from the PC, meaning, that you can google for something like "python reading serial" and then "Arduino serial" individually, instead of googling it together. Though you might find good resources with that too

Thank you, I'll check it out.

The Arduino cannot access files on a desktop computer.
However you can write software on your computer (you already use Python, so why not use that?) to accept information over Serial, process it, and store it in any way you like (including JSON), or return data from the computer to the Arduino if needed.

These were links I was looking at, thank you. I'm not too familiar with the coding to do this so I'm relying on sample codes that I can modify for my needs.


text:
Where to store critical data in power outage situation on ESP8266
I want to store a counter that is always changing, but I want it to remain and be able to retrieve it on after a power loss.
It's only one long number data, but as it is always changing, I don't know where to store it to not over wear the memory space.
I'm aware that writing to much on ESP's EEPROM or SPIFFS would damage it. I've seen that post, but it doesn't help in my case.
The data to be saved is the volume of water pumped with a water pump during it's entire life.
Of course I could save it only once a while to reduce the number of writes, but I would lose some acccuracy.

As far as I can see SPIFFS does wear leveling. To get a ballpark number of counter updates you can do before you have to think about wear. Get the size of the SPIFFS volume. Divide that by the sector size of the SPI flash (see datasheet). Multiply that by the number of cycles the datasheet specifies for it's endurance. My guess is, your pump has to run for millennia before you can expect problems with the flash.

you could save it to rtc memory each read, and to spiffs (which is wear-leveled) every 10 reads. That would let you lossless-ly resume from brief power interruptions, and balance long-term precision with reliability.

If you worry about the maximum number of write cycles, you could write the data to an SD card or some FRAM connected to the ESP8266, or you could send the data to a (web) server (if you have access to one) using WiFi. The server can then store the data.
If you really care about the data, you could do both. Having a backup is the only protection against catastrophic failure.

A local solution would be to use EERAM.  This is an EEPROM and an SRAM coupled together with some intelligent power management circuitry - writes get stored in SRAM until the power goes (or an instruction to save is sent) when the contents of SRAM get copied into EEPROM using the power stored in a large capacitor.
A good choice is the 47C16 (5V) or 47L16 (3.3V).


text:
Cannot compile F() macro with R"string"
I am trying to compile the following code:
logger.log_info(F(R"(some text here that may take
    multiple lines
    and here it is done.)"));

But the compiler exists with the following error:

error: unterminated raw string

I am able to use either R or F, but not both together. How should I be able to use them together?

Have you tried terminating the string manually, by adding \0 to the end? Maybe that helps, as the error message complains about the string not being terminated

@chrisl because I am using R, how should \0 be evaluated as string termination?

@chrisl, I tried it, but I am not able to compile because the whole remaining file is now evaluated as part of the string. So this did not work.

There were some bugs with raw string literals and the preprocessor in GCC a while back. What version are you using?

@Mat, Arduino libraries 2.7.4; GCC: 7.3.0

If you put:
    #define DO_NOTHING(s) (s)

    DO_NOTHING(R"xyz(Hello
    World)xyz")

you can see g++ choke on preprocessing the raw string literal in the macro invocation with the latest esp8266 board package as of writing (version 2.7.4).  This comes with g++ 4.8.2 for xtensa.
    ~/.arduino15/packages/esp8266/tools/xtensa-lx106-elf-gcc/2.5.0-4-b40a506/bin/xtensa-lx106-elf-g++ -E  donothing.h

You may need to adjust the command-line for your system.  donothing.h is just the macro and invocation described above.
Result:
# 1 "donothing.h"
# 1 "<command-line>"
# 1 "donothing.h"

donothing.h:3:13: warning: missing terminating " character [enabled by default]
 DO_NOTHING(R"xyz(Hello
             ^
(R"xyz(Hello World)
donothing.h:4:10: warning: missing terminating " character [enabled by default]
 World)xyz")
          ^
      xyz")

This does not happen with g++ 9.3.0 on an amd64 Linux target.
As a workaround you can reconstruct (more or less) what the F() macro does with the following:
    void setup() {
      Serial.begin(9600);
    }

    void loop() {
      static const char pgm_str[] PROGMEM = (R"xyz(Hello
    World)xyz");

      Serial.println(FPSTR(pgm_str));
      delay(4000);
    }

May I ask you why would you write something outside of the parenthesis of the literal? (namely xyz in your example)? If this is not gonna be shown anyway

Do you have any suggestion to convert the output of the FPSTR(pgm_str) to std::string? because the is the type of the argument I am using. This is the error I get now: no known conversion for argument 1 from 'const __FlashStringHelper*' to 'const string& {aka const std::basic_string<char>&}

std::string works by allocating from dynamic memory, except maybe for small strings, so in order to wind up with one you'd need to copy into it.  In other words, at some point you'll have a second copy in RAM.  What are you ultimately doing with the string?  BTW: the arduino String class usually accepts const __FlashStringHelper *, but this inn't what your ultimately want and it would be a little nuts to load it into one and then the other.

You are right, thanks for that point. That means, using const char * instead of String or std::string should be fine in this case, as no copying will happen and I will be fine to use this string for logging. Right?

I'm not sure I understand.  Where does logger.log_info come from?  Is this a published library you can point me to?  I ask, because if it was made with the Arduino in mind, it is likely that there is some support in it already for reading strings out of "PROGMEM".

No, actually it is not, it is written somewhen by myself, logging data are simply some strings that will be built in runtime. For example: logger.log_info("Current time " + time);. And the argument its takes is std::string, I can simply change it of course to const char *. However, now after changing the argument type, the compiler still complaining about the type: error: no matching function for call to 'Logger::log_info(const __FlashStringHelper*) const'.
Could you keep trying helping me please to solve this? I will accept anyway the answer cuz the main question has been solved!

Heh, unfortunately this is a horrible medium to try to hold a conversation on.  There's probably some policy against suggesting this, but you can find me on irc.freenode.net in #arduino      I can try to edit the answer to include a routine to load std::string from __FlashStringHelper if you like.  Or, I suppose it could just go into a comment, since it's not part of the actual answer to the question.

Let us continue this discussion in chat.


text:
'Servo_Pointer' was not declared in this scope
I can't seem to find the error I made; can anyone help me?
The error message: 'Servo_Pointer' was not declared in this scope
I get the error at the end of the code with the line: Servo_Pointer.write(servo_pos)
The code:
const int photo_left = A0;    // select the input pins for the photoresistor
const int photo_right = A1;
const int ledPin_1 = 2; // These leds will be used for the testing of the pointing of the servo motor
const int ledPin_2 = 4;
const int ledPin_3 = 7;
const int ledPin_4 = 8;
const int ledPin_5 = 12;
const int photoValue = 0;  // variable to store the value coming from the photoresistor
const int numReadings = 10;
int readings[numReadings];      // the readings from the analog input
int readIndex = 0;              // the index of the current reading
int total = 0;                  // the running total
int average = 0;                // the average

void setup() {
  // declare the ledPin as an OUTPUT:
  pinMode(ledPin_1, OUTPUT);
  pinMode(ledPin_2, OUTPUT);
  pinMode(ledPin_3, OUTPUT);
  pinMode(ledPin_4, OUTPUT);
  pinMode(ledPin_5, OUTPUT);
  Serial.begin(9600);
  #include <Servo.h>
  Servo Servo_Pointer;
  Servo_Pointer.attach(9);
  int servo_pos = 0;
  // initialize serial communication with computer:
  Serial.begin(9600);
  // initialize all the readings to 0:
  for (int thisReading = 0; thisReading < numReadings; thisReading  ) {
    readings[thisReading] = 0;
  }
}

void loop() {
  Servo_Pointer.write(servo_pos); // tell servomotor to go to position in variable 'servo_pos'
  delay(15);          // waits 15ms for the servo to reach the position
  // turn the ledPin on
  delay(15);
}

Please don't make more work for other people by vandalizing your posts. By posting on the Stack Exchange (SE) network, you've granted a non-revocable right, under the CC BY-SA 4.0 license for SE to distribute that content. By SE policy, any vandalism will be reverted. If you want to know more about deleting a post, consider taking a look at: How does deleting work?

You should make Servo Servo_Pointer; global, i.e. place it outside the setupfunction, e.g. after the line int average = 0;.
In your code, it is a local variable within the setup function. When this function ends, the local variables within this function (such as Servo_Pointer ) do not exist anymore.
By making the variable global, you can use it anywhere. However, it's not a good coding practice to use global variables when not needed.
A benefit of making the variable global is that you can see the memory consumption of the instance of Servo_Pointer when compiling.
Also see the comment of timemage below: Don't put #include statements in the middle of your code, put them in the beginning of your code.

Might be worth adding that it's at least unconventional to have an #include directive in the middle of your function.

@timemage Good catch, I did a search on Servo_Pointer missing that line.

You need to place the decleration outside of your setup() function. In other words, you need to move the following 3 lines and place then above your setup() function:
#include <Servo.h>
Servo Servo_Pointer;
int servo_pos = 0;

Your code should look like this:
#include <Servo.h>

const int photo_left = A0;    // select the input pins for the photoresistor
const int photo_right = A1;
const int ledPin_1 = 2; // These leds will be used for the testing of the pointing of the servo motor
const int ledPin_2 = 4;
const int ledPin_3 = 7;
const int ledPin_4 = 8;
const int ledPin_5 = 12;
const int photoValue = 0;  // variable to store the value coming from the photoresistor
const int numReadings = 10;
int readings[numReadings];      // the readings from the analog input
int readIndex = 0;              // the index of the current reading
int total = 0;                  // the running total
int average = 0;                // the average
int servo_pos = 0;

Servo Servo_Pointer;

void setup() {
  // declare the ledPin as an OUTPUT:
  pinMode(ledPin_1, OUTPUT);
  pinMode(ledPin_2, OUTPUT);
  pinMode(ledPin_3, OUTPUT);
  pinMode(ledPin_4, OUTPUT);
  pinMode(ledPin_5, OUTPUT);
  Serial.begin(9600);
  Servo_Pointer.attach(9);
  // initialize serial communication with computer:
  Serial.begin(9600);
  // initialize all the readings to 0:
  for (int thisReading = 0; thisReading < numReadings; thisReading  ) {
    readings[thisReading] = 0;
  }
}

void loop() {
  Servo_Pointer.write(servo_pos); // tell servomotor to go to position in variable 'servo_pos'
  delay(15);          // waits 15ms for the servo to reach the position
  // turn the ledPin on
  delay(15);
}


text:
Multiple external power sources and one Arduino
really noob question..
I am thinking of using a 12v power source and a 5v power source as an external power supply for my 5v relay (and some other stuff that I might add up to my project that will need 5V) and the 12v is for my 12V solenoids.
Is it right to connect all ground wires to the ground of the Arduino?
I am really sorry that I have to ask this question cause all tutorials I see online are only connecting one external power supply to their Arduino.
Any form of correction is highly appreciated. Thank you so much

First make sure the voltages are stable enough even under any and all expected changes in current load - solenoids take quite a bit of juice and have interesting magnetic field effects.  No sense subjecting your arduino to potential overvoltage in AC from an accidentally bucking inductor.

Yes, in general all grounds need to be connected

Besides connecting all the grounds, a "good idea" whenever working with solenoids or magnetic (as opposed to solid state) relays is to add protection against inductive kickback, which can create really high voltages (hundreds of volts) when the current through an inductor changes suddenly. (The voltage is the product of the inductance and the rate-of-change of the current.)  The protection is simple:  Put a rectifier diode across each coil, with the arrow pointing to positive (reverse-biased).  The rectifier has to handle a big spike of current as well as the high voltage, so use something like 1N4004.
This protection will reduce the likelihood of spikes causing mysterious state changes in your circuits.

Hi, correct me, but a snubber diode is like a safety precaution to avoid frying your relays right? so it should work for DC Motors too cause its an inductive load right? thanks

Correct.  Google for "snubber diode on DC motor"

thanks a lot! I wish you a happy day :)


text:
utility/spi_com.h error when compiling Marlin for Arduino mega with Ramps 1.4
I am using win 8.1 and trying to load Marlin 2.0.x onto Arduino Mega with an attached Ramps 1.4 board fitted with 3 8825 Drivers. Unfortunately everytime I try to compile It concludes with the following error. Can anyone please help.
Alternatives for utility/spi_com.h:
[]ResolveLibrary(utility/spi_com.h)  -> candidates: []In file included from C:\Users\Dad\AppData\Local\Temp\arduino_build_750275\sketch\src\HAL\STM32\MarlinSPI.cpp:23:0:C:\Users\Dad\AppData\Local\Temp\arduino_build_750275\sketch\src\HAL\STM32\MarlinSPI.h:28:12: fatal error: utility/spi_com.h:
No such file or directory   #include <utility/spi_com.h>

compilation terminated.
Using library SPI at version 1.0 in folder: C:\Users\Dad\Downloads\arduino-1.8.13-windows\arduino-1.8.13\hardware\arduino\avr\libraries\SPI
exit status 1
Error compiling for board Arduino Mega or Mega 2560.

trying to load Marlin 2.0.x onto Arduino Mega

I have no specific knowledge of Marlin.
For the moment, I'm ignoring the fact that it seems to be looking for STM32 files which would seem to play no role on an Arduino Mega.
I cloned the Marlin github repo and found no mention of a file "MarlinSPI.h" in the 2.0.x branch.  There is however a MarlinSPI.h in tag 1.1.9.1
You appear to be working with the code for the wrong version (or branch) of Marlin.


text:
Help using uint32_t? Trying to feed arduino serial from raspberry pi. Any help is very very much appreciated
So I don't know C so I'm just trying to get some very very basic code running on my arduino to send it commands over serial.
I'm feeding serial into buf
irsend.sendNEC(0x210704FB, 32)
this works but I need to read from buf instead of hardcoding for one code.
irsend.sendNEC(buf, 32) won't compile but irsend.sendNEC((uint32_t) buf, 32) will. It just doesn't do anything.
When I use
serial.print((uint32_t) buf, 32);
it prints just seemingly random letters?
I'm trying to just feed it a serial code with a language I know a little better. I can send the hex code over serial with python but I don't know the first thing about C. I don't understand why I can't just feed it a variable and have it read it as is.
here's my code
#include <IRremote.h>

char buf[80];

int readline(int readch, char *buffer, int len) {
  static int pos = 0;
  int rpos;

  if (readch > 0) {
    switch (readch) {
      case '\r': // Ignore CR
        break;
      case '\n': // Return on new-line
        rpos = pos;
        pos = 0; // Reset position index ready for next time
        return rpos;
      default:
        if (pos < len-1) {
          buffer[pos++] = readch;
          buffer[pos] = 0;
        }
    }
  }
  return 0;
}

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

IRsend irsend;

void loop() {
  if (readline(Serial.read(), buf, 80) > 0) {
    //tried to set up code to show what the arduino received and tried ways to send
    //Serial.print("You entered: >");
    //Serial.print(buf);
    //Serial.println("<");
    //doesn't seem to do anything irsend.sendNEC((uint32_t) buf, 32);
    //works but only for this one button irsend.sendNEC(0x210704FB, 32);
    //want to use irsend.sendNEC(buf, 32);
    //me trying to figure out what irsend is being fed through buf Serial.print((uint32_t) buf, 32);

  }
}

What is buf? The first two sendNEC in your question are identical but you say one compiles and one doesn't - probably a wrong copy/paste. Please [edit] your question to clarify.

serial.print(...., 32). "32" is not a valid second parameter for the serial.print() function when printing an integer value. Just leave it out or replace it with either "BIN", "DEC", "OCT" or "HEX". BTW, what is your question exactly?

I updated my post yesterday to add some clarity and show my entire code instead of just the specific function I was having a problem with. Any help is very much appreciated.

Same issue for me, but this is my solution.
Mapping beween python struct (packed data) and arduino struct is as follows:
Python              Arduino
?                   boolean
i                   int32_t or uint32_t
f                   float

Arduino Code:
// The struct we want to send over the serial connection
struct Data {
  int32_t timer;
  float value2;
  uint32_t sensor1;
  uint32_t datasize;
};
 Data data;
void setup() {
  // Initialize the serial connection
  Serial.begin(115200);
}

void loop() {
  // Create an instance of the Data struct

  data.timer = micros();
  data.value2 = 3.14;
  // read the input on analog pin 0:
  data.sensor1 = analogRead(A0);

  // Calculate the size of the struct in bytes
  size_t size = sizeof(data);
  data.datasize = size;
  // Allocate a buffer for the packed data
  uint8_t *buf = (uint8_t*)malloc(size);

  // Pack the data into the buffer
  memcpy(buf, &data, size);

  // Send the packed data over the serial connection
  Serial.write(buf, size);

  // Free the buffer
  free(buf);

  // Wait before sending the data again
  delay(10);

}

Python Code:
#
# read struct from arduino / sample code above
#

import serial
import struct

# Open the serial port
ser = serial.Serial('/dev/ttyUSB0', 115200)

# The struct we expect to receive from the Arduino
#struct Data {
#  int32_t value1;
#  float value2;
#  uint32_t value3;
#}
expFormat = "i f i i"         # Format to match arduino struct
structDataLength = struct.calcsize(expFormat)
print(structDataLength)       # RESULT IS 12

while True:
# Read the data from the serial port
# We read until we have received all the bytes for the struct

    data = b''
    while len(data) < structDataLength:
        data += ser.read(structDataLength - len(data))
    # Unpack the data into an instance of the Data struct
    val = struct.unpack('i f i i', data)

# Print the values
    print(val)

# Close the serial port
ser.close()


text:
Brushless ESC Recommendations
I've got a project in which I'll be controlling 8 24V/10A brushless DC motors with an Arduino Due on a quadrupedal robot. I've been having trouble finding ESCs that would work well for this application and was wondering if anyone could provide recommendations. My ideal ESC would be one with on-board PID control given an encoder. In looking around, I've only been able to find one ESC with this capability but lacked the power output these motors want.
A secondary question would be if it's reasonable to run 8 PID loops on the Due alongside its other tasks (primarily serial data receiving/transmitting). I feel like it might be too much for the Due to handle, but I wanted to get other's opinions on this.
Sidenote: I have enough of a gear reduction between motor and output shaft that fine movements should not be an issue.


text:
Programming multiple arduino at once
I actually made a prototype with multiplexing Chip select pin on Arduino, which connects to RESET pin of target board to program. When I am connecting one target board at once I am able to program it but when I am connecting multiple target boards then not able to program ICs.
I am using Nick gammon's code for programming the target Arduino using the master Arduino
https://github.com/nickgammon/arduino_sketches/tree/master/Atmega_Hex_Uploader_Fixed_Filename
This is rough block diagram of multiplexing chip select pin -

I also tried connecting RESET pin of target Arduino to its chip select pin but that is also not working.

Which pin on the targets are you multiplexing too?
I don't think they even need CS for being programmed - just a RESET, followed by the SPI communication.
I'd try multiplexing the RESET pin instead, but since that is active low, it depends on your multiplexer IC.

Also other Arduinos must have SPI pins disabled (= inputs), so it won't affects selected one. Otherwise you'll need 74HC(T)125 per arduino or 74HC(T)244 per two of them

@towe MOSI, MISO, SCK pins are common between the master and all other target arduinos. The Chip select pin on master arduino (which is responsible for programming all targets) is multiplexed using 74HC4067 mux. And the output of the mux is connected to RESET of target ICs. Now the target ICs will either be programmed for the first time when the do not have any bootloader. Or reprogrammed/firmware update. In any case the hex file is firmware+bootloader file. This setup is not working.

I searched for SPI multiplexing and found out that the master's chip select pin should be connected to target's CS pin which should be pulled up. Now as RESET on target side is needed for programming mode to initialize, I connected RESET and CS pin on target. But this setup also doesnt work.

Isnt it that RESET is normally pulled up and to initiate programming its given LOW signal?

You're right, I thought it only had to be pulsed to enable programming.

But I actually tried what you said. When I connected 2 target boards with the master IC, normally it was not working. But when I connected RESET pin of one of the target board to ground the other one was successfully programmed. Have to find a way to automate the grounding of RESET pin and program ICs sequentially one after the other.

But there is still some weird behaviour. When I replicated the same by connecting RESET of the now programmed IC to gnd and tried programming the other one, that works. But the already programmed one wont work. Basically I uploaded Blink program. So when I uploaded blink on 2nd one the 1st one was not blinking. But thanks this gives me some idea to work with.

Technically you are using ICSP to program the MCU, not SPI. So the the CS pin terminology doesn't really apply. Since the MISO MOSI and CSK pins are all tied together, you have to make sure that any code running on the target MCUs will never use those pins (as outputs), or they will interfere with the ICSP programming process, and possibly cause damage. Also, the 74HC4067 needs 2 inputs to select between 4 outputs.

You last two comments are strange. From the datasheet To enter and stay in Serial Programming mode, the AVR microcontroller reset line has to be kept active(low).

Can the 74HC4067 even work. Doesn't the 74HC4067 set only one of it's outputs HIGH, while the reset is LOW? To program one MCU you'd need one (reset-)pin to be LOW, but the reset HIGH.

you don't do SPI so you don't have to connect CS. you can use any pin of programmer board to do a reset of the target board. what for is the multi target setup? it has no practical use. how do you decide which target you reset to program? you can"t program them simultanously

@Gerben So in previous comments someone suggested to pull RESET pin down of all other targets when programming one target. It worked but I observed some issues. Trying to work on it. 74HC4067 is 16:1 MUX so there are 4 selection pins to select the output.

@Juraj So I am trying to implement multiple ic programming for mass production purpose. And yes one cannot program them sumiltaneously but what I am trying to implement is that connect like 16 ICs to one master programmer and then click a button and then everyting will be taken care of and a person who is responsible for IC programming in production cycle will then can focus on other things as well, And then when all the ICs are programmed will the check error messages to debug if any IC was not programmed successfully. Trying to improve productivity.

RESET should be LOW while ICSP flashing.


text:
variable name standards, e.g best method to send motion_detect=true
I am working with some sensors and sending data to a public web server via http, I was thinking this server can be possibly used by more people to send their data and server displays a chart.
I was wondering if there is a IOT industry standard when sending certain type of data, so that in future I don't need to rename this or change documentation to be more compatible or more intuitive.
For example when sending a "motion detected" ping, do I go with pir=true, pir=1, motion_detect=true ?
Then for example when sending temperature, it would be much better temp_celsius=30 then just temp=30.
It should also make developers job much easier if there is a certain standard. Is there one ?

No, there is no "industry standard". You are free to choose what you like.
If you want to be completely generic you could choose to do something like:
p1name=Temperature&p1units=celcius&p1value=23.4&p2name=Humidity&p2units=%25&p2value=43.8

(%25 is a % when URL encoded)
Or you could use:
p1=Temperature/Celcius/23.4&p2=Humidity/%25/43.8

That's just two examples. There is no end to how you could do it.

I don't think there is. It also kind of depends on how you are going to store the data.
I'd go with motion=true instead of pir=true, as it describes what you are detecting, instead of what sensor type you used. What if you decide to change the PIR sensor to a radar-based sensor. Now the variable name doesn't make sense.
Secondly, what happens if you add a second motion sensor somewhere else? I'd add something unique to the request. Something like a node-id. That way, you can differentiate between the two. Something like ?nodeid=1&motion=1. You can that also add additional info like the battery voltage for that node; ?nodeid=1&motion=1&voltage=3.1.
I don't think differentiating between C and F makes a lot of sense. But if it does you'd store this somewhere on the server, as it should never really change. Something like; the temperature value coming from nodeid 6, is the temperature in the "livingroom", and is specified in "C", and should be shown on a graph with Y-axis of "10 C" to "30 C".

Regarding nodeid I made it automatically generate a random serial number that is saved to EEPROM so each new node will send an unique ID.

For motion, to cover both situations (adding / replacing sensors and types) I might go with pir[1], pir2, radar[1], radar2 and user can associate friendly names on server.

On my own system I had every arduino have a nodeid. The each sensor has an id (unique for that node). Every sensor value was just a number. This made the packet data really compact (send via NRF24). The other upside was that I could just store this data directly to the database, without any preprocessing, as it does have to have idea what the data is. New nodes and/or sensors could be added with zero server changes. The web application showing the data did the heavy lifting, in turning the raw numbers to the real word data. This worked pretty okay for me. Maybe some part of it is useful to you

yes, that helps a lot, it is mostly how I do it now. And the NRF24 is nice, the one with external antenna goes 1 KM

Yes, there are systems designed to continuously receive such data and the data exchange is standardized, even some Units are standardized.
OPC DA
An example is OPC Data Access for real time values. It seems you want to build a graph, so OPC Historical Data Access is more what you're looking for.
One would set up the data points on the server side once, i.e. configure the type and unit that you're gonna receive on that "channel" or "port" or whatever you call it.
Unfortunately, OPC DA and OPC HDA use XML and building XML is not trivial. It's not very suitable for IoT devices.
Lessons learned: configure the unit on server side and let the client send data only. Do not use XML for data transfer.
OPC UA
Then there is OPC Unified Architecture. They also learned their lesson and removed XML and added security. They now use a binary protocol. The specification is more than 1000 pages, so understanding it will be difficult and is in fact so difficult that even OPC UA implementations of different companies do not work together well.
OPC UA defines 25 data types and ways of defining other data types.
The address space in OPC UA is hierarchical - and probably a device can exist in multiple hierarchies, e.g. physical topology like floors and rooms or logical topology that fits into the structure of the machine.
Lessons learned: make the protocol simple and think about security, i.e. if you want to do URL encoding (GET), then use HTTPS at least. AFAIK, devices ESP32 support encryption, so it's no longer a problem for tiny devices. People will use very strange data types, like 18 bit integers. Also, do not only provide a flat list of devices, but let them arrange stuff as needed.
MQTT and NodeRed
Now these were quite heavy protocols and models driven by companies. Of course there are also protocols better suited for IoT, like MQTT. MQTT is widely known and uses the also well known Node Red software for handling it. You can define workflows how the data should be handled, converted, stored and whether alarms shall be triggered above or below thresholds.
They already think of connection loss, reconnect and how to send all the data that was already recorded but could not be sent.
Lessons learned: People want more than just data storage and a graphics.
Units
openHAB tries to come up with a List of units. I am a radio amateur. I am measuring electromagnetic fields. I am still missing

SWR (standing wave ratio)
dBu (dB µW)
dBc (dB relative to the strongest signal)
dBV, dBmV (dB for Volts instead of Watts)

Personal experience
I was working for a company that made software for industry. There are devices that send a measurement value every 100 ms. Let's say this is a simple temperature value of just 1 byte, that's still 315'000'000 records per year.
How do you display such data? On a Full HD screen you would still need to combine 150'000 measurement values on a single column of pixels.
Lessons learned: you need sophisticated data crunching skills to generate the graphics. The users probably want some control over the time span they are viewing. They want zooming and panning.
Conclusion

I was thinking this server can be possibly used by more people to send their data and server displays a chart.

IMHO, sorry, it's hardly needed. People do not want to send their data to a random HTTP server. Some want to set it up at home only, so that no data ever reaches the Internet. Some people want to do more than just displaying a grpahics (especially alarms). MQTT and Node Red runs locally, on a Raspberry, on a server and even in the cloud, whatever you want.
You do not only need pir=true, pir=1, motion_detect=true, you also need

an ID for the device,
a timestamp when the data was recorded
potentially a way to send bulk data after the server was offline for an hour of maintenance
a system for units
encryption

That's quite an effort. Node Red has > 4000 commits.


text:
3 pin ethernet module?
So basically I'm working on a project that uses an Atmega328 like on the Arduino Uno. I need to receive both DMX (with max485) and E131 (Not both at the same time, I'll decide which with a boolean in the sketch) and then use that to control 16 channels. I need the TX and RX pins (UART) for the max485 (DMX), 16 outputs for the triacs, and 1 pin for zero-cross detection. If I use the Analog pins as digital outputs, that lets 3 pins to connect the ethernet module. Most of them use 4 pins, I believe it's SPI. I only have 3 available. Is this possible? Also, I may need a second zero-cross detector, so is it possible with 2 pins then?
Thanks!

Sounds like you need either an MCU with more pins or a second MCU for the ethernet.

Are there ethernet modules that use, say, i2c?

did you try to add Ethernet library to your sketch? don't you run out of flash?

you could use some UART module. esp8266 WiFi module uses Serial.

No, I havent actually made a sketch yet. Just trying to figure out the hardware side first.

And what do you mean by uart module and esp8266? I specifically need it to be ethernet, not wifi.

https://www.waveshare.com/uart-to-eth.htm it uses an MCU

I haven't heard of any I2C Ethernet modules, no, but that doesn't mean there aren't any. But then it wouldn't be too hard to write a sketch for an Arduino that has an Ethernet card on it and communicates over I2C with your existing setup.

Yes, your right I could use a uart ethernet module and then put a physical switch or jumper to connect one or the other. Those are kinda expensive tho, not sure why.

Also I don't need cs because I only have 1 chip connected to SPI bus right? That would get me down to 3 pins. And then do I need a tx for E131? Does the arduino need to send something to say that the packet was received, or to help connect it to a pc? Or can I just use RX only? If so, that would get me down to the 2 pins I need.

the W5x00 don't work without switching CS input

Could it just be constantly pulled high or low?

no. the logic in chip reads the CS signal edges


text:
Running an Arduino without the computer
I am having trouble getting my Arduino Uno to run my code when I disconnect it from my computer.
I have a 9V battery to power it and it is turning on, however, it is not doing anything at all. What can I do to make it run the code when it is using the battery and not connected to the computer?

You should probably give some indication in the question on how you know it is behaving differently between battery power and usb power.  Also given that 9v are not particularly good batteries beyond their ability to produce 9v, you may want to say what else you have connected to the board.

If you use a 9V block battery, recycle it and buy better batteries. You could use a series of AA batteries

how do you know that the arduino is doing nothing?

Please provide more information. What is the schematics? What is the code?

What components do you have in your project? Specifically, what are you connecting to the 5V line?

I have four DC motors connected to the Arduino. They each have a basic circuit with one transistor, resistor, and a diode for each. As of right now the objective is just to get the motors to run while its not connected to the computer. They run perfectly when connected to the computer but when I try to connect the battery so that it doesn't have to be connected to the computer, which it need to be able to be, the Arduino is on but nothing is happening. Do you have any better batteries that you recommend over the 9V?

To get a useful answer on a power source, you'd need to say more about the motors themselves.  You may find it instructive to put a voltmeter on the 5V line and alternately the VIN pin (or battery directly) and watch what is happening to their voltages when you attempt to operate the motors.

Use a fresh 9V battery, or better, a proper power supply or some AA batteries in series, just to make sure the power supply isn't the problem.
BTW on some Arduinos (though probably not yours) it often pays off to check if there is a while (!Serial); or some such in the code. If there is, it is blocking code execution until the USB is connected and the serial monitor is opened.

A battery a day keeps the environment decay.

"For testing only". I never use primary cells myself.

while (!Serial); would have no effect on an UNO.

@timemage: People with different Arduinos will also read this Q&A without looking at the tag, so I thought it would be a good idea to include it.

@ocrdu: I was looking at more as UNO having been in the question, the while loop is thing is a more of a rabbit hole.  I suppose you could mark it as "for some boards this is also a problem."  I don't have really strong feeling about it really.  In case you're wondering, I didn't vote down your answer.

@ocrdu, Heh, I'd had a follow on this and saw your change come in.  I'm going to upvote this just to cancel out the -1 that, in my opinion, should not have been there anyway.

And Arduino should run the last program installed to it when you apply power to the barrel connector. IT powers up, does a reset, and begins executing the sketch that's installed.
As others have mentioned, the small rectangular 9V batteries have very low current output and total power storage. You will run a fresh 9V battery down to nothing in a short time with just an Arduino, and with other components also drawing power it will happen even faster. I suggest getting a ≥ 1 amp 7V - 9V DC transformer and plugging that into the barrel connector.
You need to tell us what components you are using in your project and their current requirements.
If you are just running a "bare" arduino and very little else then you should get like 24 hours out of a fresh 9V battery, as mentioned by @ocrdu

All pins together can't source more than 150mA. Why should he use a 1000mA power supply?

@Duncan-C: Could be it, but power consumption is not THAT bad; 500mAh will run some Arduinos that aren't doing too much for about 24 hours.

I did find some that are 9V 1200mA batteries would these suffice?

You mean 1200 mAh? (that stands for milliamp-hours. It tells you the total power storage capability of the battery. A 1200 mAh battery can put out 1200 milliamps for an hour. (Or 120 milliamps for 10 hours. You just multiply current by time).


text:
Change/declare a constant in setup and use it in loop
I want to change or declare a constant in the setup() and then, I want to access it in the loop().
I have searched a lot, but the only questions I found could be solved by declaring the constant in the beginning of the program. That doesn't work for me because I am using the Adafruit BMP388 and I can't use the pressure before setup().
I also tried declaring the variable before setup() and changing it inside setup(), but it didn't change when I used it in loop().
How can I solve this?

how are we to know that you actually changed it in loop()?

I didn't change it in loop(), I have to access it there. I want to change it in setup()

look at the fade sketch in arduino IDE example sketches

how are we to know that you actually changed it in setup()?

I want to use it in loop(): I need the startpressure (declared in setup()) and compare it to the current pressure

the title of your post does not match the content of your post ... title asks about a variable, content asks about a constant ... i suggest that you research the difference

Constants cannot, by definition, be changed. Do you mean variables?

I also tried declaring the variable before the setup() and changing it inside the setup(), but it didn't change when I used it in the loop(). - Can you show this code? A variable, changed in setup, would stay changed. Unless you declared it twice (shadowed it).

You are not going to get good answers without showing your code, but maybe this is a good guess of what you want:
why not try something roughly like this (untested and incomplete)?
Adafruit_BMP3XX bmp;
float startPressure;
float difference;

void setup() {
  bmp.begin_I2C();
  startPressure = bmp.readPressure();
}

void loop() {
  difference = startPressure - bmp.readPressure();
}

Or, better:
Adafruit_BMP3XX bmp;

void setup() {
  bmp.begin_I2C();
}

void loop() {
  static const float startPressure = bmp.readPressure();
  static float difference;
  difference = startPressure - bmp.readPressure();
}

I'm not entirely sure this is the direction he's going in.  But if he is, you could move float startPressure; into the loop(), perform startPressure = bmp.readPressure(); as part of its initialization, and make it static and const.
As in: static const float startPressure = bmp.readPressure();
This would behave as what you have but would limit startPressure to the only scope it's used in.

@timemage: True, and better, but it would require an explanation of "static", and I don't feel up to it 8-). I will add it though.

difference does not need to be static.

Yeah, and it technically isn't "constant" in C++ terms.  But it seems to be in the spirit of the question so far as I understand the question.

@Edgar-Bonet: No, doesn't have to be in the example, but who knows if he wants it to remain the same over several loops in his code.


text:
Alternatives to Nextion display
I am wanting to have a display where I can design the GUI on a program and then somehow transfer it to the display. For the graphics I want to make, it would be really hard to manually write the code. I heard that the Nextion displays do this but they are quite costly. Is there some cheaper alternative? If not, can you make a normal display do all of that?

The only other make I know are 4D Systems, and they are just as much, if not more, than Nextion.

We work with Proculus displays, and we are a distributor of this display here in Brazil (Victor Vision). The display is great, very professional. Used in medical equipments, and cheaper than Nextion.
They are starting now in the web and selling in Alibaba.


text:
Why is my buzzer always on?
I wanted to make a buzzer go off when the distance measured by the ultrasonic sensor becomes more than 100cm. The things used in this project are a 4x4 keypad, an hc-sr04 ultrasonic sensor, and a passive buzzer all connected to a keyestudio mega 2560.
What happens is that the moment I upload the code/turn on the Arduino, the buzzer turns on despite a solid object being within a 100cm range. And the buzzer almost randomly stops for a couple of seconds and continues. It won't turn off, even when I press the appropriate key on the keypad.
This is the code I have written, thanks
    #include <Key.h>
    #include <Keypad.h>

    const int trigPin = 11;    //output to sensor
    const int echoPin = 12;    //input from sensor
    const int buzzPin = 13;    //output to buzzer

    const byte ROWS = 4;
    const byte COLS = 4;

    long duration;    //travel time of sound waves
    int distance;    //distance at which an object is

    char hexaKeys[ROWS][COLS] = {
      {'1', '2', '3', 'A'},
      {'4', '5', '6', 'B'},
      {'7', '8', '9', 'C'},
      {'*', '0', '#', 'D'}
    };

    byte rowPins[ROWS] = {9,8,7,6};
    byte colPins[COLS] = {5,4,3,2};

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

    void setup() {
      // put your setup code here, to run once:
      pinMode(trigPin, OUTPUT);
      pinMode(echoPin, INPUT);
      pinMode(buzzPin, OUTPUT);
      Serial.begin(9600);
    }

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

      char customKey = customKeypad.getKey(); // gets key values from keypad

      if(customKey) {
        Serial.println(customKey);
       }

      digitalWrite(trigPin, LOW);    //reset the sensor by turning it off for 2 microseconds
      delayMicroseconds(5);

      digitalWrite(trigPin, HIGH);    //generate ultrasound wave by turning it on for 10 microseconds
      delayMicroseconds(50);
      digitalWrite(trigPin, LOW);

      duration = pulseIn(echoPin, HIGH);    //time it takes for sound to get back
      distance = duration*0.034/2;    //plug into formula for distance

      Serial.println(distance);

    if (distance <= 100){
     digitalWrite(buzzPin, LOW);
      }
    if (distance >= 100){
      digitalWrite(buzzPin, HIGH);
      if (customKey != 7){
        digitalWrite(buzzPin, HIGH);
        delay(2000);
        digitalWrite(buzzPin, LOW);
        delay(1000);
      if (customKey == 7){
        digitalWrite(buzzPin, LOW);
}
}
}
 }

indent the braces at the end of your program properly ... you may notice that they are in the wrong places

what is printing in serial monitor?


text:
esp-01 with rf receiver keeps crashing
SOLVED:
after may hours of testing i have solved the problem.
it turned out to not be a software issue. the power supply i was using did not have a flyback diode and thus caused large voltage spikes that would crash the esp. the solution was to add a diode on the inductive load to remove those voltage spikes.
I have an esp-01 running some code that checks for a rf remote signal using the rc-switch library, it is also running some blynk and ota code.
when i press one of the buttons on my rf remote the buzzer pin keeps being triggered but will not shut off, eventually the esp will crash..
the device is in a permanent location thus the reason for the ota updates and i cant easily hookup a serial monitor to see what the esp crash code is.
the troublesome code is,

    void newloop() {
      if (mySwitch.available()) {
        // int recieved = mySwitch.getReceivedValue();
        if (mySwitch.getReceivedValue() == 5099665) {
          digitalWrite(buzzer, LOW);
          delay(200);
          digitalWrite(buzzer, HIGH);
          mySwitch.resetAvailable();
        }
        else if (mySwitch.getReceivedValue() == 5099666) {
          digitalWrite(buzzer, LOW);
          delay(2000);
          digitalWrite(buzzer, HIGH);
          mySwitch.resetAvailable();
        }
      }
      // Blynk.run();
    }

the full code, with redacted passwords/keys is,
#include <ESP8266WiFi.h>
#include <ESP8266mDNS.h>
#include <WiFiUdp.h>
#include <ArduinoOTA.h>
#include <ESP8266WebServer.h>

#define BLYNK_PRINT Serial
#include <RCSwitch.h>
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
#define buzzer 2
char auth[] = "<blynk auth>";
RCSwitch mySwitch = RCSwitch();

const char* ssid = "HansenHome";
const char* password = "<wifi password>";
ESP8266WebServer server;

bool ready = false;
bool ota_flag = true;
uint16_t time_elapsed = 0;

void setup() {

  Serial.begin(115200);
  Serial.println("Booting");
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);

  pinMode(buzzer, OUTPUT);
  digitalWrite(buzzer, HIGH);
  Blynk.begin(auth, ssid, password);
  mySwitch.enableReceive(0);

  while (WiFi.waitForConnectResult() != WL_CONNECTED) {
    Serial.println("Connection Failed! Rebooting...");
    delay(5000);
    ESP.restart();
  }

  // Hostname defaults to esp8266-[ChipID]
  ArduinoOTA.setHostname("lock");

  // No authentication by default
  ArduinoOTA.setPassword("<uploading password>");

  ArduinoOTA.onStart([]() {
    String type;
    if (ArduinoOTA.getCommand() == U_FLASH) {
      type = "sketch";
    } else { // U_SPIFFS
      type = "filesystem";
    }

    // NOTE: if updating SPIFFS this would be the place to unmount SPIFFS using SPIFFS.end()
    Serial.println("Start updating " + type);
  });
  ArduinoOTA.onEnd([]() {
    Serial.println("\nEnd");
  });
  ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
    Serial.printf("Progress: %u%%\r", (progress / (total / 100)));
  });
  ArduinoOTA.onError([](ota_error_t error) {
    Serial.printf("Error[%u]: ", error);
    if (error == OTA_AUTH_ERROR) {
      Serial.println("Auth Failed");
    } else if (error == OTA_BEGIN_ERROR) {
      Serial.println("Begin Failed");
    } else if (error == OTA_CONNECT_ERROR) {
      Serial.println("Connect Failed");
    } else if (error == OTA_RECEIVE_ERROR) {
      Serial.println("Receive Failed");
    } else if (error == OTA_END_ERROR) {
      Serial.println("End Failed");
    }
  });
  ArduinoOTA.begin();
  Serial.println("Ready");
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());

  server.on("/restart",[](){
    server.send(200,"text/plain", "Restarting...");
    delay(1000);
    ESP.restart();
  });

  server.on("/setflag",[](){
    server.send(200,"text/plain", "Setting flag...");
    ota_flag = true;
    time_elapsed = 0;
  });

  server.begin();
}

void loop() {
  if(ota_flag)
  {
    uint16_t time_start = millis();
    while(time_elapsed < 10000)
    {
      ArduinoOTA.handle();
      time_elapsed = millis()-time_start;
      delay(10);
    }
    ota_flag = false;
  }
  if(ready == false) {
    ready = true;
    digitalWrite(buzzer, LOW);
    delay(20);
    digitalWrite(buzzer, HIGH);
    delay(20);
    digitalWrite(buzzer, LOW);
    delay(20);
    digitalWrite(buzzer, HIGH);
    delay(20);
    digitalWrite(buzzer, LOW);
    delay(20);
    digitalWrite(buzzer, HIGH);
    delay(20);
    digitalWrite(buzzer, LOW);
    delay(20);
    digitalWrite(buzzer, HIGH);
    ready = true;
  }
  server.handleClient();
  newloop();
}

BLYNK_WRITE(V1) {
  digitalWrite(buzzer, LOW);
  delay(200);
  digitalWrite(buzzer, HIGH);
}

void newloop() {
  if (mySwitch.available()) {
    // int recieved = mySwitch.getReceivedValue();
    if (mySwitch.getReceivedValue() == 5099665) {
      digitalWrite(buzzer, LOW);
      delay(200);
      digitalWrite(buzzer, HIGH);
      mySwitch.resetAvailable();
    }
    else if (mySwitch.getReceivedValue() == 5099666) {
      digitalWrite(buzzer, LOW);
      delay(2000);
      digitalWrite(buzzer, HIGH);
      mySwitch.resetAvailable();
    }
  }
  // Blynk.run();
}

EDIT:
so after so further testing it appears to be a power supply issue, the power supply i was using was hooked up to a large inductive load. once that load is turned off there is a huge power spike and for some reason causing the esp to crash.
the board the esp is on has 2 voltage regulators and a few input caps
i added a large cap to the main supply and a 100uf to the 3.3v rail directly on the esp. it is still crashing..

try printing a message to serial, instead of buzzer and delay code

i cant get a proper serial output.. i may be able to move it around and get a monitor hooked up to it but it will take time

i changed the power supply while testing and it has not broke yet, so it may have to do with that

I believe you are allowed to post answers to your own questions as weird as that sounds.

By which I mean via "Post Your Answer" button rather than placing it into the question.  You could, if you wanted, have you edit say "I solved this myself, see my answer below" I suppose.


text:
esp8266 sending to both webserver and myphpadmin
I have tried to send all the variables to both the webpage and to myphpadmin. I seperated
the code into two functions and put the functions inside the void loop() function under the
impression that it will loop both but it seems if I put both then the device will only send
data to phpmyadmin. However, if I delete void logs() which is the function that sends data to
phpmyadmin then the void page() which sends the data to the webpage starts working. I can't find a solution for these two functions to work together, I really don't understand what I'm doing wrong, your guidance would be much appreciated
this is my code:
String header = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n";

String html_1 = R"=====(
<!DOCTYPE html>

  <meta name='viewport' content='width=device-width, initial-scale=1.0'/>
  <meta charset='utf-8'>

  <title>Temperature & Humidy Monitor</title>

Temperature & Humidity Monitor

Time

Temperature

 -- ℃

Humidity

 -- %

Pressure

 -- hPs

Altitude

 -- m

)=====";

#ifdef ESP32
  #include <WiFi.h>
  #include <HTTPClient.h>
#else
  #include <ESP8266WiFi.h>
  #include <ESP8266HTTPClient.h>
  #include <WiFiClient.h>
#endif
#include <Wire.h>
#include "HTTPSRedirect.h"
#include "DebugMacros.h"
#include <Adafruit_Sensor.h>
#include <Adafruit_BME280.h>
#include <ESP8266WebServer.h>
#include <DHT.h>

#define SEALEVELPRESSURE_HPA (1013.25)
#define DHTPIN 2     // what digital pin we're connected to
#define DHTTYPE DHT11   // DHT 11

Adafruit_BME280 bme;

const char* ssid = "fl";  // Enter SSID (WiFi Name) here
const char* password = "99110233";  //Enter Password here
const char* serverName = "http://192.168.101.17/sensordata/post-esp-data.php";
ESP8266WebServer server(80);

String apiKeyValue = "tPmAT5Ab3nnn9";
String sensorName = "BME280";
String sensorLocation = "Office";

float Temperature;
float Humidity;
float Pressure;
float Altitude;
String request = "";
int pin = 2;

void setup() {
  // initialize GPIO 2 as an output.
  pinMode(pin, OUTPUT);

  Serial.begin(115200);

  if (!bme.begin(0x76)) {
    Serial.println("Could not find a valid BME280 sensor, check wiring!");
    while (1);
  }

  Serial.println("Connecting to ");
  Serial.println(ssid);

  //connect to your local wi-fi network
  WiFi.begin(ssid, password);

  //check wi-fi is connected to wi-fi network
  while (WiFi.status() != WL_CONNECTED) {
  delay(10);
  Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected..!");
  Serial.print("Got IP: ");  Serial.println(WiFi.localIP());

  server.on("/", handle_OnConnect);
  server.onNotFound(handle_NotFound);

  server.begin();
  Serial.println("HTTP server started");

}

void loop() {

  page();
  logs();

}

void page(){
  //sends data to webpage
  server.handleClient();

  WiFiClient client = server.client();     // Check if a client has connected
    if (!client)  {  return;  }

    request = client.readStringUntil('\r');     // Read the first line of the request

    Serial.println(request);
    Serial.println("");

    if ( request.indexOf("getTemp") > 0 )
     {
          Serial.println("getTemp received");

          // Reading temperature or humidity takes about 250 milliseconds!

         Temperature = bme.readTemperature();
         Pressure = bme.readPressure() / 100.0F;
         Altitude = bme.readAltitude(SEALEVELPRESSURE_HPA);
         Humidity = bme.readHumidity();    // Read temperature as Fahrenheit (isFahrenheit = true)

          if ( !isnan(Temperature) && !isnan(Humidity) && !isnan(Pressure) && !isnan(Altitude) )
          {
              client.print( header );
              client.print( Temperature );   client.print( "|" );
              client.print( Humidity );   client.print( "|" );
              client.print( Pressure ); client.print( "|" );
              client.print( Altitude ); client.print( "|" );
              Serial.println("data sent");
          }
          else
          {
              Serial.println("Error reading the sensor");
          }
     }

     else
     {
        client.flush();
        client.print( header );
        client.print( html_1 );
        Serial.println("New page served");
     }

    delay(5);

    if (Temperature > 20.0){
    digitalWrite(pin, HIGH);   // turn the LED on (HIGH is the voltage level)
    delay(50);               // wait for a second
    digitalWrite(pin, LOW);    // turn the LED off by making the voltage LOW
    delay(1);
  }
}

void logs(){
  //sending to database
  //Check WiFi connection status
  if(WiFi.status()== WL_CONNECTED){
    HTTPClient http;

    // Takes Domain name with URL path or IP address with path
    http.begin(serverName);

    // Specifies content-type header
    http.addHeader("Content-Type", "application/x-www-form-urlencoded");

    // Prepare HTTP POST request data
    String httpRequestData = "api_key=" + apiKeyValue + "&sensor=" + sensorName
                          + "&location=" + sensorLocation + "&value1=" + String(bme.readTemperature())
                          + "&value2=" + String(bme.readHumidity()) + "&value3=" + String(bme.readPressure()/100.0F) + "";
    Serial.print("httpRequestData: ");
    Serial.println(httpRequestData);

    //String httpRequestData = "api_key=tPmAT5Ab3nnn9&sensor=BME280&location=Office&value1=24.75&value2=49.54&value3=1005.14";

    // Send HTTP POST request
    int httpResponseCode = http.POST(httpRequestData);

    if (httpResponseCode>0) {
      Serial.print("HTTP Response code: ");
      Serial.println(httpResponseCode);
    }
    else {
      Serial.print("Error code: ");
      Serial.println(httpResponseCode);
    }

    http.end();
  }
  else {
    Serial.println("WiFi Disconnected");
  }
  //Send an HTTP POST request every 30 seconds
  delay(30000);
}

void handle_OnConnect(){

  Temperature = bme.readTemperature();
  Pressure = bme.readPressure() / 100.0F;
  Altitude = bme.readAltitude(SEALEVELPRESSURE_HPA);
  Humidity = bme.readHumidity();

}

void handle_NotFound(){
  server.send(404, "text/plain", "Not found");
}

https://github.com/esp8266/Arduino/issues/7613#issuecomment-700869953


text:
Onboard led HIGH and LOW seems reversed
On an ESP32 board I am trying this simple code to control the onboard led.
But if I set it to HIGH, led is OFF, if I set it to LOW, led is ON (fully bright).
What could cause this ?
The board has one red and one blue leds, the blue one is the one that can be controlled.
#define onboard_led 2

void setup() {
  pinMode(onboard_led, OUTPUT);
}

void loop() {
    digitalWrite(onboard_led, HIGH);
    // digitalWrite(onboard_led, LOW);
}

Edit: it was a board like this ("Geekcreit" I think):

To know for sure, you'd need to show the design of the board.  But it's not uncommon for leds to be arranged in circuit such that to turn them on you sink current through the chip.  As in, LED is wired something like  3.3V --- RESISTOR --- LED --- GPIO_PIN.  When GPIO goes LOW (toward ground), your current flows and the LED turns on.   It's also possible that the MCU's pin is connected to a transistor that inverts the logic in addition to offloading the current handling onto the transistor.

There’s nothing wrong with your board. Your confusion is caused by how the onboard LED is wired as explained by @timemage. Many ESP boards have this arrangement for the onboard LED and you might also find other (external) hardware that has active-low controls. If you measure the I/O pin that is connected to the internal LED you will see that when it’s “HIGH” it’s at 3.3V (or close to it) just like it’s supposed to be.

I know it sound weird as a beginner, but it's not that unusual. Certain chips are better at sinking current (connecting to ground), than sourcing current (connecting to Vcc). A similar inverted logic is often used with buttons, where the input pin has a pull-up resistor. Resulting in reading a LOW when the button is pressed, and HIGH when not pressed. If this messes with your head a bit you could invert the value in code, which might make it more intuitive to read. Like digitalWrite(onboard_led, !HIGH);, where the HIGH indicates you want it to turn on, and the ! inverts it automagically.

OK, so I understand this is common. I don't have detailed schematics of the board, but I added a photo and name of board.

@adrianTNT, unfortunately there are a lot of boards /like/ that.  To the extent that a picture would be helpful, it would need to be either a picture of your board or one that you are certain is identical.  Otherwise it's just another variable.

@timemage I found that it is not uncommon for leds to be lit both ways (HIGH/LOW) so that is good enough of an answer for me :)

As this image from Okdo Page on LED Driving shows, there are two ways to drive an LED from a GPIO output pin:

In the Active HIGH case, a HIGH output on the GPIO will turn the LED on since that will source current out of the pin and through the LED into ground.
In the Active LOW case, a LOW output on the GPIO will sink current from the +V supply into the pin.
In your case the LED is hooked up in the Active LOW configuration and so to turn it ON you must set the pin to LOW.
I'll add that these ESP32 boards are made by many different manufacturers and they are not all identical.


text:
Count specific range of output as 1 single output
The LDR sensor gives a range of values to show whether a LED is OFF/ON, let's say above LDR range 400, the led is ON. When a LED is ON, after reading the sensor values it shows above LDR range 800, because the LDR sensor measuring in ms, a single LED blink shows six LDR 800+ values. Is there any way to count all the six  LDR 800+ values to increase counter by 1?
Here's my output in serial monitor. 314 to 322 is led OFF state and 816 to 851 is led ON state.
LED : 314
LED : 314
LED : 314
LED : 321
LED : 322
LED : 322
LED : 816
LED : 817
LED : 818
LED : 817
LED : 817
LED : 815
LED : 351
LED : 329
LED : 323
LED : 327
LED : 326
LED : 339

what is the problem?

what do you observe when you are counting flashes of a light? ... write your program to do the same

There are two distinct problems here.
The first problem is to convert the analog reading into a binary value.
You measure a value between 314 and 856, and you want to know whether
the LED is ON or OFF. The simplest solution is to compare the reading to
a threshold that is roughly in the middle of the range you measure. You
could say, for example, that the LED of OFF if the reading is below 580,
and is ON otherwise:
bool led_is_on = analogRead(ldr_pin) >= 580;

If the readings are noisy while they cross the threshold (does not seem
to be the case in the short span of data you show), you may want to use
some noise cancelling techniques. You could, as suggested by Michel
Keijzers, require multiple consecutive “ON” reading before deciding the
LED is actually ON. Or you may research the technique of using
hysteresis, which would be my favorite solution, as it is extremely
simple. However, if your readings are always as clean as what you are
showing us (never fluctuating mid-range), you can stick with the simple
threshold solution shown above.
The second problem is called edge detection. You want to count the
blinks. For this, you need to count how many times the LED turns ON,
which is not the same as how many times the LED is ON. You know that
the LED turned ON if you just detected it is ON and, on the previous
iteration it was OFF. So you have to remember whether the LED was ON
last time you looked at it. This means you have to store this
information (whether the LED was ON) in a static (or, if you prefer,
global) variable. Which leads to the following program:
int blink_count;

void loop() {
    static bool led_was_on = false;
    bool led_is_on = analogRead(ldr_pin) >= 580;
    if (!led_was_on && led_is_on) {
        blink_count++;
    }
    led_was_on = led_is_on;
}

Note the condition: !led_was_on && led_is_on means “The LED was not
ON and now it is ON”.

I'm not sure what the value 400 is used for exactly, but the code below is for increasing the counter when at least 6 consecutive values above 800 are occurred.
The key is to use a state machine.
I don't have a compiler at hand so forgive possible syntax errors.
First we define a state. In your case, there are only two possibilities, so a boolean (bool) is used, normally an enum is used.
bool _counting = FALSE;

We also need a constant (or define) and a counter to see how many ON values are needed before incrementing the counter, which counts downwards to 0 (and can go negative when more ON values occur).
const int MIN_FLASH_LENGTH = 6;
int _onBeforeIncrementing = MIN_FLASH_LENGTH;

However, we can use the last variable to see if counting is occurring, so we do not have to use the boolean above.
Then we need a counter for the amount of flashes itself:
int _amountOfFlashes = 0;

Both of these are global variables.
Furthermore, in the loop, we need to check for the LED value.
Thus the entire code will be:
const int MIN_FLASH_LENGTH = 6;

int _onBeforeIncrementing = MIN_FLASH_LENGTH;
int _amountOfFlashes = 0;

void loop()
{
    int ledValue = getLedValue(); // Use your code here
    if (ledValue >= 800)
    {
        _onBeforeIncrementing --;
        if (_onBeforeIncrementing == 0)  // Flash of enough length occurred
        {
            _amountOfFlashes++;
        }
    }
    else // Restart counting
    {
        _onBeforeIncrementing = MIN_FLASH_LENGTH;
    }
}

The code fragment
if (_onBeforeIncrementing == 0)
{
    _amountOfFlashes++;
}

can be reduced to:
 _amountOfFlashes += (_onBeforeIncrementing == 0) : 1 : 0;

Also note if you have more code to add, to use the name LED or LDR into the global variables for clearity.

For a single blink in LED, I'm getting multiple 800+ values. I want them to count as a single value until it drops below 800. So, the counter will increase by 1 if the values cross 800 until it drops below 800 again. So, I wanted to know if there is any way to make this as a range code where all the values will count as 1.

I appreciate your help, although I do have multiple LDR and LEDs to count, so I wanted to have something unified.

In that case use arrays for each led (global variable). This will cost 800 bytes if you make it a single (signed) byte.

By my understanding you want to count the values where your LED is on (800+ values in your case).
For this you can simply create an if condition where in you say if the value is greater than 800 increase counter by 1
int count = 0;

if(value>=800):
    count++

Here the variable value is the data you are printing on your serial monitor and count is your counter.
Also add the if condition inside the loop function and the declare the variable count = 0 outside the loop function

For a single blink in LED, I'm getting multiple 800+ values. I want them to count as a single value until it drops below 800. So, the counter will increase by 1  if the values cross 800 until it drops below 800 again.  So, I wanted to know if there is any way to make this as a range code where all the values will count as 1.

Exactly what I did above if you print count on the serial monitor you will see that count increases each time your value goes above 800. If you want to reset it just add else: count = 0 and count will reset to zero as soon as your value goes below 800

look, for a single blink i'm getting multiple 800+ values. if i , use  for ( values >800){ counter++;} my counter increases by 6-7 at a time for a single blink. using this condition because of multiple 800+ values it increases counter by a lot for a single blink. and I don't want that. i want to increase that by 1. i couldn't think about anything that would solve this.  you can refer to my question. i have added serial monitor output.