text:
L293D driver DC motors need help to start rotating
I set up this circuit which uses L293D motor driver IC to control two DC motors.

+6V input is connected to unregulated power supply. It's current rating is 500 mA.
There is a connection between Arduino's ground line and power supplies ground line. There is a parallel 0.1 uF capacitor connected between motor terminal pins.
There is a wheel at the end of the motors but they don't have a gearbox. The wheels are suspended so that they can rotate freely.
The source code of the software is as follows.
#include <Arduino.h>

unsigned int firstMotorPositive = 8;
unsigned int firstMotorNegative = 7;
unsigned int enableFirstMotor = 9;
unsigned int secondMotorPositive = 5;
unsigned int secondMotorNegative = 4;
unsigned int enableSecondMotor = 3;

void setup()
{
    pinMode(firstMotorPositive, OUTPUT);
    /*  I've changed this part as shown by @timemage  */
    //pinMode(secondMotorPositive, OUTPUT); // <------
    pinMode(firstMotorNegative, OUTPUT);
    pinMode(enableFirstMotor, OUTPUT);
    pinMode(secondMotorPositive, OUTPUT);
    pinMode(secondMotorNegative, OUTPUT);
    pinMode(enableSecondMotor, OUTPUT);

    // All motors are off
    digitalWrite(firstMotorPositive, LOW);
    digitalWrite(firstMotorNegative, LOW);
    digitalWrite(secondMotorPositive, LOW);
    digitalWrite(secondMotorNegative, LOW);
}

void turnOnMotors()
{
    // Set motors to maximum speed
    // For PWM maximum possible values are 0 to 255
    analogWrite(enableFirstMotor, 255);
    analogWrite(enableSecondMotor, 255);

    // Turn on motor A & B
    digitalWrite(firstMotorPositive, HIGH);
    digitalWrite(firstMotorNegative, LOW);
    digitalWrite(secondMotorPositive, HIGH);
    digitalWrite(secondMotorNegative, LOW);
    delay(2000);

    // Turn off motors
    digitalWrite(firstMotorPositive, LOW);
    digitalWrite(firstMotorNegative, LOW);
    digitalWrite(secondMotorPositive, LOW);
    digitalWrite(secondMotorNegative, LOW);

    analogWrite(enableFirstMotor, 0);
    analogWrite(enableSecondMotor, 0);

}

void speedControl()
{
    digitalWrite(firstMotorPositive, HIGH);
    digitalWrite(firstMotorNegative, LOW);
    digitalWrite(secondMotorPositive, HIGH);
    digitalWrite(secondMotorNegative, LOW);

    analogWrite(enableFirstMotor, 63);
    analogWrite(enableSecondMotor, 63);

    delay(3000);

    analogWrite(enableFirstMotor, 127);
    analogWrite(enableSecondMotor, 127);
    delay(3000);

    analogWrite(enableFirstMotor, 191);
    analogWrite(enableSecondMotor, 191);
    delay(3000);
/*
    analogWrite(enableFirstMotor, 255);
    analogWrite(enableSecondMotor, 255);
    delay(3000);
*/

    // All motors are off
    digitalWrite(firstMotorPositive, LOW);
    digitalWrite(firstMotorNegative, LOW);
    digitalWrite(secondMotorPositive, LOW);
    digitalWrite(secondMotorNegative, LOW);
    analogWrite(enableFirstMotor, 0);
    analogWrite(enableSecondMotor, 0);
}

void loop()
{

    /*
      turnOnMotors();
      delay(1000);
    */

    speedControl();
    delay(1000);
}

The problem is they need help to start rotating. They will only start rotating if I physically twist the shaft with my fingers first.
As far as I know the motors used in this circuit are two 6 volt DC motors.
When I measure the maximum voltage between motor terminals I read about 0.5 volts. If I twist the shaft I read about 4.5 volts.

does the motor spin when connected directly to the power supply?

Yes. If I connect motors to simple 1.5 volts battery it spins.

I've already tried that but it doesn't help either.

It is also possible that there are physical problems in the wiring.  A clear picture of your actual wiring end to end may help someone spot something.

The L2978D is a terrible motor driver (I really wish people wouldn't use it!). It is "bipolar" which means that both the high and low side switches of the H-bridge are Bipolar Junction Transistors. This means that you get about 1.4V voltage drop in total between the inputs and outputs.
To counter that you must provide at least 1.4V more than your motors need for them to operate properly.

I switched to unregulated power supply to 7.5 volts. I measured unregulated voltage with a DIMM. It was about 12.8 volts. Still, motors don't start. I've also tried with 9 volts. They don't also start with 9 volts.

no pinMode(firstMotorNegative, OUTPUT)
Well, here's a start at least:
pinMode(firstMotorPositive, OUTPUT);
pinMode(secondMotorPositive, OUTPUT); // <------
pinMode(enableFirstMotor, OUTPUT);
pinMode(secondMotorPositive, OUTPUT);
pinMode(secondMotorNegative, OUTPUT);
pinMode(enableSecondMotor, OUTPUT);

You are never setting firstMotorNegative to OUTPUT and probably intended to on the second line of this excerpt.
firstMotorNegative floating or pulled high
The AVR GPIO pins are INPUT on power-up.  Writing to the PORT register, which is what digitalWrite does, takes on a different meaning when the pin's mode is INPUT.  That is, it enables or disables the pull-up internal resistors.  In other words, your     digitalWrite(firstMotorNegative, HIGH); and digitalWrite(firstMotorNegative, LOW); are effectively toggling between pinMode(firstMotorNegative, INPUT_PULLUP) and  pinMode(firstMotorNegative, INPUT) respectively.
So your L293D is seeing either this signal being weakly pulled up or floating.  During the floating condition in particular maybe a problem when you're doing:
// Turn on motor A & B
digitalWrite(firstMotorPositive, HIGH);
digitalWrite(firstMotorNegative, LOW);

... because you're disabling the pull-up here, the "negative" pin is INPUT/floating rather than reliably LOW.  So, it may be being intermittently interpreted as HIGH at the L293D, in which case there is no movement while that's happening.

Thanks I've edited the code as you suggested. But practically there is no difference.

@Erdem I will look for more problems again later and update this if I find anything I'm reasonably certain is a problem.

That is operating as expected. Take a look at the data sheet. You can lose 1.8 volt on each output pin. Since you are in bridge configuration you now lose 3.6 Volts.  Now assume your power is 6VDC with 1 volt ripple. That adds to the voltage drop through the driver so rounding it out you lose 4 volts from your supply (not counting wiring loses) before you start, that is assuming the voltage does not droop. Two simple solutions, use a power supply with more voltage or go to a MOSFET bridge device.

Thanks for the suggestions. I have an adjustable DC adapter which provides unregulated 1.5 V, 3 V, 4,5 V, 6 V, 7.5 V, 9 V and 12 V with up to 500 mA of current. I graudually switched from 6 volts to 12 volts. But motors don't spin. This confuses me since one of the motor with a small wheel attached starts spinning with only 1.5 volts battery but doesn't spins with an external DC adapter. I switched DC adapter to 6 V and measured unregulated voltage with a DIMM. It was about 17 volts. Isn't it a huge voltage for for such a small toy DC motor?

Your best bet is to use a regulated power supply with enough power to drive your load with some spair. An unregulated power supply has ripple, the amount depending on the design and components chosen. Not knowing your DMM and your adapter I can only guess but try measuring the output voltage in the AC range, it should be almost nothing. If you get a value it is a rough approximation of your AC content.

I use pen type Mastech MS8211D  multimeter. I switched unregulated DC adapter to 6 volts setting. I selected AC and used max function to measure maximum voltage. This is quite interesting because it reads maximum voltage as 5.1 volts AC. Also DC voltage was about 10.5 volts.

I think we need to go back to the beginning and have you go to this link https://www.electronics-tutorials.ws/ It is teaches the basics of electronics. While you are studying that get a regulated 10 or 12 volt power source rated at 2 amps or more. If you are in this for the long hall get a Lab Power supply, that runs about $60 on ebay, possibly a Christmas present. The only common thread is the power supply you are using. Also get an Arduino motor shield with FET outputs. This should get rid of the unknowns and get you started.


text:
Comparing a String after reading it from Serial fails
I have bought an Arduino starter kit online. Everything seem to work, but when I try for example to use ifs (and other conditional statements), the LEDs do not turn on. Here is the code for a little project I am currently working on:
int redpin = 3;
int greenpin = 2;
int bluepin = 4;
String color;
String msg = "Insert color: ";

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

void loop() {
  // put your main code here, to run repeatedly:
  Serial.println(msg);
  while (Serial.available() == 0) {}
  color = Serial.readString();

  if (color == "red") {
    digitalWrite(redpin, HIGH);
    digitalWrite(greenpin, LOW);
    digitalWrite(bluepin, LOW);
  }
  if (color == "green") {
    digitalWrite(greenpin, HIGH);
    digitalWrite(redpin, LOW);
    digitalWrite(bluepin, LOW);
  }
  if (color == "blue") {
    digitalWrite(greenpin, LOW);
    digitalWrite(redpin, LOW);
    digitalWrite(bluepin, HIGH);
  }

  if (color == "off") {
    digitalWrite(greenpin, LOW);
    digitalWrite(redpin, LOW);
    digitalWrite(bluepin, LOW);
  }
}

I tried turning on the RGB LED with single digitalWrite() functions and it works. I think that the if statements in the code are the problem.
I`m using an Arduino Mega 2560 BTW.

You should print the variable color out to the Serial monitor, to make sure, that you really received, what you send. Also you shouldn't use Serial.readString(), but Serial.readStringUntil('\n') and set your Serial Monitor to a line ending of newline only. Then try again. If that works, I will formulate an answer around that.

After color = Serial.readString(); color also contains a newline character.
You can remove that by adding the line color.trim();, or even better, avoid the newline altogether by using Serial.readStringUntil('\n'); which discards the terminating newline character.
Also, you could, and maybe should, avoid using the String class and use:
char color[10]; // char array as buffer for reading from Serial

int number = Serial.readBytesUntil('\n', color, 10); //Read input and length
color[number] = '\0'; //Terminate the string by adding '\0' at its end

if (strcmp(color, "red") == 0) //Use strcmp(), not ==

respectively.

source: Stack Exchange

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

sort: votes


text:
DHTNEW library not working with ATTiny85 + DHT11
I tried to make a simple project with Attiny85 chip and DHT11 sensor. After 2 days of struggle, made it finally work, but not quite as expected. TinyDHT library does work, while DHTNEW does not.
I wonder,

what can be changed to make any of the libraries work at lower clock rate?
how to make DHTNew work?

My results so far:
with TinyDHT:

@ 16 MHz works nominally, showing valid T/H values (if I breathe on the sensor, it shows 95-99% humidity)
@ 8 MHz, shows nothing (either nan, or zeros)
@ 1 MHz, shows temp/hum as 5, 5 (or 50, 50, can't tell)

with DHTNEW:

@ 16 MHz returns SENSOR_NOT_READY
@ 16 MHz with mySensor.setDisableIRQ(true); -> WAITING_FOR_READ at first, then nothing (nan or 0)
@ 8 MHz WAITING_FOR_READ at first, then TIMEOUT_C
@ 8 MHz with setDisableIRQ -> always TIMEOUT_C
@ 1 MHz always TIMEOUT_A

Here's the setup on photo and as a scheme. Arduino UNO works as a programmator for Attiny chip, as shown in this tutorial. After I upload the code to Attiny85, the chip starts working normally, and there's no need to disconnect the Arduino board. (For actual work, I disconnect it, connect 5V power, and it works the same way.)
Settings in the IDE:

Board: Attiny25/45/85
Processor: Attiny85
Clock: Internal from 1 to 16 MHz
Programmer: Arduino as ISP

How I test this:

change clock frequency
run Tools -> Burn bootloader
run Sketch -> Upload
wait till upload ends (RX/TX diodes stop blinking)
the LED on breadboard blinks me the numbers

Code for TinyDHT
Code for DHTNEW

Reading the measurements requires somewhat accurate timings (i.e. millis() needs to work). Did you check that a blink sketch blinks at the expected frequency when you change your clock settings?

@Mat It blinks somewhat correctly, but I need to check that to tell more exactly. It may be some % off, indeed.

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


text:
SIM800L module on Arduino nano
I am trying to get Arduino nano and SIM800L module working together. I provided the module with the recommended external voltage of 4.0V (documentation states 3.6V - 4.2V) transformed via LM2596. The original source is 5V 3A.
LED on SIM800L blink once a second as stated in documentation when in an unconnected state.
The schema is the following:
                  Antena
                   \_/
                    |
Arduino    SIM800L  |  External 4.0V
             NET ---/
             VCC ----- +4.0V
D2 --------- RST
D3 --------- RX
D4 --------- TX
             GND ----- GND

I have already tried 3 different libraries for AT communication and also sending raw AT commands using writing to serial manually. I also tried another SIM800L module because I thought the module is faulty.
Here is the dump from serial communication:
[551135] ### TinyGSM Version: 0.10.9
[551139] ### TinyGSM Compiled Module:  TinyGsmClientSIM800
AT
��AT
�AT
H�j���[552012] ### Unhandled: Hj
AT
AT-���[552317] ### Unhandled: AT-
AT
��AT
��AT
�Z5
[553228] ### Unhandled: Z5
AT
␚)O���[553532] ### Unhandled: ␚)O
AT
AT���[553836] ### Unhandled: AT
AT
��AT
��AT
�)OK��[554748] ### Unhandled: )OK
AT
���[555053] ### Unhandled: 5
AT
���AT
��AT
��AT
�j�H�[556266] ### Unhandled: jH
AT
CC����[556570] ### Unhandled: CC
AT
AT���[556875] ### Unhandled: AT
AT
��AT
AT
���[557787] ### Unhandled: T
AT
�H����[558091] ### Unhandled: H
AT
AT���[558395] ### Unhandled: AT
AT
��AT
��AT
AT
jRO���[559610] ### Unhandled: jRO
AT
AT���[559915] ### Unhandled: AT
AT
��AT
��AT
AT
�
OK��[561128] ### Unhandled: OK
Failed to initialize SIM800L

As you can see the module is trying to negotiate the baudrate. By default, I use speed 9600 as stated in the documentation. When I use a different baudrate the module does not respond at all.
It seems the module replies and sometimes even correctly. Response to AT command should be OK.
Do you know how do I successfully negotiate the speed and establish reliable serial communication with the module? Do I miss any electrical components in my circuit like a capacitor or resistor? I tried to use capacitor 35V / 3300µF but without any difference. I think my power source is strong enough.
The source code is the following:
#define PIN_GSM_RST             2
#define PIN_GSM_TX              3
#define PIN_GSM_RX              4
#define GSM_BAUDRATE            9600

#define TINY_GSM_MODEM_SIM800
#define TINY_GSM_DEBUG          Serial
#define TINY_GSM_USE_GPRS       true
#define TINY_GSM_USE_WIFI       false

#include <Arduino.h>
#include <SoftwareSerial.h>
#include <TinyGsmClient.h>
#include <StreamDebugger.h>

SoftwareSerial serial_SIM800L(PIN_GSM_RX, PIN_GSM_TX);
StreamDebugger debugger(serial_SIM800L, Serial);
TinyGsm modem(debugger);
TinyGsmClient client(modem);

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

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

    serial_SIM800L.begin(GSM_BAUDRATE);
    delay(5000);

    while (!modem.init()) {
        Serial.println("Failed to initialize SIM800L");
    }
}

void loop() {
    //
}

Did you connect the GND of the Arduino with the GND of the SIM800L? I can not see a connection in the schematics.

@PeterPaulKiefer No, I only connected the SIM800L to the ground of the external source. Might that be the problem?

Of cause; All voltages that come from the arduino to the SIM800L must have a reference GND. You need a common potential. If you have none the Arduino is not able to communicate with the module. The GND of all modules and external Powersuplies must be connected. Only if you use a separate circuit, eg. behind a relais, the GND must not be connected.

One additional thing. The Nano is usally  a 5 Volt board. Are you sure the SIM800L pins are 5 Volt tolerant. If you connect GND, they might be faced by 5V. That could kill them, if they are not 5V tolerant.

Max working voltage of SIM800L is 4.2V. If the voltage is higher than 4.4V the module turns off. What schema to use so the module is not exposed to 5V via GND then?

Probably level shifter; or if you have a 3.3 Volt controller (Arduino Due, Micro, 3.3V Nano). As you are not familiar with electronics (I assume), search for arduino projects with SIM800L in the internet. And don't trust all the videos that say it is save to use a SIM 800L with 5V Arduinos. The following might be interesting for you: https://lastminuteengineers.com/sim800l-gsm-module-arduino-tutorial/

I used LM2596 to convert 5V to 4V eventually. I tried resistor level shifter as well before. Many articles I found simply did not use external power but diode voltage drop so board 5V pin could be used and I did not realize that. Your suggestion of connecting GNDs worked. Thank you.

You're welcome. Just to mention it: The Arduino pins that are connected to the SIM Module are 5 Volts. If your Module version has internal protection for these pins, all is fine. But, if the pins are connected without level shifting, the Module might work for a time, but there is a hight possibility that it get's destroyed. Cheers.

Thanks to @PeterPaulKiefer here is the answer.
External power for SIM800L module GND pin needs to be connected to both SIM800L module GND pin and Arduino nano GND pin. (e.g between RST and R2 pin on Arduino nano)
In order for the calling function to work, you also need to use a capacitor on SIM800L VCC and GND pins. I used 35V, 3300µF.
Schema:
                  Antena
                   \_/
                    |
Arduino    SIM800L  |  External 4.0V
             NET ---/
             VCC ----- +4.0V
 D2 --------- RST   |
 D3 ---------  RX  === Capacitor (35V, 3300µF)
 D4 ---------  TX   |
GND --------- GND ----- GND


text:
Recommend an Arduino Uno shield to monitor the state of 5 DPDT electrical switches
I have a project where I need to monitor the state of 5 DPDT electrical switches with Arduino Uno. Also, the Arduino board will be measuring the output from 3 thermocouples on 3 of the analogue pins as input and sending signals to open and close 3 relays for heaters on the 3 of the digital pins as output. The data with the state of the microswitches and the measurements from the thermocouples will be send over a serial connection to a PC.
I think I need a shield with at least 20 inputs for monitoring the 5 DPDT electrical switches (5 x 2 x 2). The common of the switches will be connected to a common rail. Can I use an I2C extension shield for this purpose? Is this going to create an issue with the serial connection? Any specific shield recommendations?

It is unclear what you are asking. Do you have 5 switches that you want to wire to an Arduino, or do you have some existing system which has 5 switches and you need to monitor the state of those switches?

Hi, the system is not yet built it is something that is being planned. I will have 5 DPDT switches that I want to wire to an Arduino. My question is on monitoring the state of the switches, because there are not enough pins on the Arduino Uno, and I do not have much experience with extensions shields. I wrote about the TC and the relays, so that it is clear that I will be using also 3 analogue and 3 digital pins on the board for another purpose.

Unless they are on-off-on switches you only need one input per switch - so 5 inputs.

1 DPDT switch has 2 NC, 2 NO and 2 COM pins, I think I need 4 pins for the 2 NC and 2 NO, the 2 COM are going to be connected to a common rail.

Just because there are two switches ganged together it doesn't mean you have to read them both. If you know the switch is in one position you also know it isn't in the other. Thus you only need one input. Common to ground, one side of the switch to input. Input to Vcc through resistor (or internal pullup). Just like any other switch. You're over-complicating it. Ignore 4 of the 6 connections - they are completely meaningless.

Have you found a way to make the two Poles of a DPDT switch be in different states? Or have you found a way for the direction that a DPDT switch to be Thrown in to be more than two choices?

Hi, I want to check the state on the 2 NC and 2 NO, I know that if DPDT switch is turned this changes the state for both circuits from one to another. However the reallity is that sometimes DPDT get a faulty circuit, the DPDT turns but only one of the circuits switches, because the other is faulty. Also there are cases of open circuit in switch connections, so if a i.e. NC is turned to NO, the NC circuits opens, but the NO is not closed and the other way around. I want to get the state of all contacts, so that I am sure the switches turned and that they do not have faulty circuits.

Those kind of failures only really happen from contact arcing - something you will never see with an Arduino.

what will the relays switch? (voltage, current, ac/dc)

The relays are SRD-05VDC-SL-C and will switch 230 AC voltage. They are on a board with other components. The board is powered by 12 V adapter and has input pins for the Arduino. The DPDT switches will switch low current signal.

If you're really set on measuring the state of every single connection of every single switch (though I still don't see the need) then yes, you'll need 20 IO connections.
You could create those with IO expanders (MCP23017 for example), or you could use multiplexing.
Instead of 4x5 (20) IO pins you'd instead need 2+10 (12) IO pins.
Treat all the "Common" connections as the rows of a keypad and all the NC and NO connections as the columns of a keypad. Add a smattering of diodes to isolate everything, and you can then scan through the switches one at a time checking each of the two switch states.
You can read more about keypad matrices here.

Thank you, I will try with MCP23017.

@Iliya They provide 16 IO, so you will need two of them. They can be chained together though.

Consider posting your schematic, not a frizzy thing showing all connections. On the switches just show a few of them so we understand what is happening.


text:
unable to modify NTPClient to use static IP address
I tried the example  File > Examples > ESP8266WiFi > NTPClient which requests the current time and it worked fine.  Then I tried to modify it so that the ESP8266 would have a static IP address on my home network.  I added the following lines before  void setup()
IPAddress staticIP(192, 168,   0, 159);
IPAddress  gateway(192, 168,   0,   1);
IPAddress   subnet(255, 255, 255,   0);

Then, in  void setup()     I added a line and commented out the original line like this
//  WiFi.mode(WIFI_STA);
WiFi.config(staticIP, gateway, subnet);

After running the sketch after I did this, it connected to my home network without any problems (as it did before).  But this time, after it prints the message sending NTP packet... to the serial monitor, it just says no packet yet.  This process is repeated every 10 seconds, but it never comes back with the time.
My troubleshooting efforts have been to uncomment the original line and comment out the line I added above.  This restores the sketch to its working condition.  I have done this several times over the past three days and the same thing always happens.
If I subscribed to conspiracy theories, I might think that some DHCP zealots are behind this.  Unfortunately, I can't come up with a better explanation.  So to ask just one question, "How can I get my ESP8266-01, flashed with Arduino 1.8.10, running on a Windows 8.1 laptop, to have a static IP on my home network and fetch current NTP timestamps from the internet?
(for reference, this is the sketch in question)
/*

  Udp NTP Client

  Get the time from a Network Time Protocol (NTP) time server
  Demonstrates use of UDP sendPacket and ReceivePacket
  For more on NTP time servers and the messages needed to communicate with them,
  see http://en.wikipedia.org/wiki/Network_Time_Protocol

  created 4 Sep 2010
  by Michael Margolis
  modified 9 Apr 2012
  by Tom Igoe
  updated for the ESP8266 12 Apr 2015
  by Ivan Grokhotkov

  This code is in the public domain.

*/

#include <ESP8266WiFi.h>
#include <WiFiUdp.h>

#ifndef STASSID
#define STASSID "peopleMightFreakIfIuseMyRealInfo"
#define STAPSK  "dontHaveAsecurityPanicAttack"
#endif

const char * ssid = STASSID; // your network SSID (name)
const char * pass = STAPSK;  // your network password

IPAddress staticIP(192, 168,   0, 159);
IPAddress  gateway(192, 168,   0,   1);
IPAddress   subnet(255, 255, 255,   0);

unsigned int localPort = 2390;      // local port to listen for UDP packets

/* Don't hardwire the IP address or we won't get the benefits of the pool.
    Lookup the IP address for the host name instead */
//IPAddress timeServer(129, 6, 15, 28); // time.nist.gov NTP server
IPAddress timeServerIP; // time.nist.gov NTP server address
const char* ntpServerName = "time.nist.gov";

const int NTP_PACKET_SIZE = 48; // NTP time stamp is in the first 48 bytes of the message

byte packetBuffer[ NTP_PACKET_SIZE]; //buffer to hold incoming and outgoing packets

// A UDP instance to let us send and receive packets over UDP
WiFiUDP udp;

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

  // We start by connecting to a WiFi network
  Serial.print("Connecting to ");
  Serial.println(ssid);
//  WiFi.mode(WIFI_STA);
  WiFi.config(staticIP, gateway, subnet);
  WiFi.begin(ssid, pass);

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

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

  Serial.println("Starting UDP");
  udp.begin(localPort);
  Serial.print("Local port: ");
  Serial.println(udp.localPort());
}

void loop() {
  //get a random server from the pool
  WiFi.hostByName(ntpServerName, timeServerIP);

  sendNTPpacket(timeServerIP); // send an NTP packet to a time server
  // wait to see if a reply is available
  delay(1000);

  int cb = udp.parsePacket();
  if (!cb) {
    Serial.println("no packet yet");
  } else {
    Serial.print("packet received, length=");
    Serial.println(cb);
    // We've received a packet, read the data from it
    udp.read(packetBuffer, NTP_PACKET_SIZE); // read the packet into the buffer

    //the timestamp starts at byte 40 of the received packet and is four bytes,
    // or two words, long. First, esxtract the two words:

    unsigned long highWord = word(packetBuffer[40], packetBuffer[41]);
    unsigned long lowWord = word(packetBuffer[42], packetBuffer[43]);
    // combine the four bytes (two words) into a long integer
    // this is NTP time (seconds since Jan 1 1900):
    unsigned long secsSince1900 = highWord << 16 | lowWord;
    Serial.print("Seconds since Jan 1 1900 = ");
    Serial.println(secsSince1900);

    // now convert NTP time into everyday time:
    Serial.print("Unix time = ");
    // Unix time starts on Jan 1 1970. In seconds, that's 2208988800:
    const unsigned long seventyYears = 2208988800UL;
    // subtract seventy years:
    unsigned long epoch = secsSince1900 - seventyYears;
    // print Unix time:
    Serial.println(epoch);

    // print the hour, minute and second:
    Serial.print("The UTC time is ");       // UTC is the time at Greenwich Meridian (GMT)
    Serial.print((epoch  % 86400L) / 3600); // print the hour (86400 equals secs per day)
    Serial.print(':');
    if (((epoch % 3600) / 60) < 10) {
      // In the first 10 minutes of each hour, we'll want a leading '0'
      Serial.print('0');
    }
    Serial.print((epoch  % 3600) / 60); // print the minute (3600 equals secs per minute)
    Serial.print(':');
    if ((epoch % 60) < 10) {
      // In the first 10 seconds of each minute, we'll want a leading '0'
      Serial.print('0');
    }
    Serial.println(epoch % 60); // print the second
  }
  // wait ten seconds before asking for the time again
  delay(10000);
}

// send an NTP request to the time server at the given address
void sendNTPpacket(IPAddress& address) {
  Serial.println("sending NTP packet...");
  // set all bytes in the buffer to 0
  memset(packetBuffer, 0, NTP_PACKET_SIZE);
  // Initialize values needed to form NTP request
  // (see URL above for details on the packets)
  packetBuffer[0] = 0b11100011;   // LI, Version, Mode
  packetBuffer[1] = 0;     // Stratum, or type of clock
  packetBuffer[2] = 6;     // Polling Interval
  packetBuffer[3] = 0xEC;  // Peer Clock Precision
  // 8 bytes of zero for Root Delay & Root Dispersion
  packetBuffer[12]  = 49;
  packetBuffer[13]  = 0x4E;
  packetBuffer[14]  = 49;
  packetBuffer[15]  = 52;

  // all NTP fields have been given values, now
  // you can send a packet requesting a timestamp:
  udp.beginPacket(address, 123); //NTP requests are to port 123
  udp.write(packetBuffer, NTP_PACKET_SIZE);
  udp.endPacket();
}

I suspect you also need to specify your DNS server (usually the same as your gateway, or use 8.8.8.8 or 8.8.4.4 for the google public DNS servers)

@Majenko  THANK YOU!!! THANK YOU!!! THANK YOU!!! THANK YOU!!!                 That did the trick!  I added the gateway as dns1 and used 8.8.8.8 as dns2   Do you want to post your comment as an answer?  I'll accept it for sure, If not, should I add [SOLVED] to my question or answer my own question?

As well as specifying your IP address and gateway you also have to provide DNS server addresses. These are normally provided by DHCP, and the ESP8266 doesn't assume that it's the same as your gateway address when using a static IP address.
Normally you would use your router's IP address as your DNS server address, but you can also use the Google public DNS servers on 8.8.8.8 and 8.8.4.4.
The full format of the config function is:
  WiFi.config(staticIP, gateway, subnet, dns);

where dns is, like the other parameters, an IPAddress.

If you use Arduino IDE with <ESP8266WiFi.h> there is a different order for the arguments in the config-statement See the comment in the source code: //ESP argument order is: ip, gateway, subnet, dns1
//Arduino arg order is: ip, dns, gateway, subnet.
So after lots of trouble i changed my config in WiFi.config(STATICIP, DNS1, GATEWAY, SUBNET) and everything works smooth now. The comment means that if you use ESP-IDE (?) the argument order is: ip, gateway, subnet, dns1. When you use Aduino IDE (for ESP8266) the argument order is: ip, dns, gateway, subnet._

ESP-IDE? ESP WiFi library! the esp8266 WiFi library has the order of config parameters different than all other WiFi libraries and Ethernet libraries. but the esp8266 WiFi library's config function can detect the parameters and works with the common ordering too


text:
How do I set up communication between the "Seeeduino Xiao" and the "Adafruit Bluefruit LE UART Friend - Bluetooth Low Energy (BLE)"?
I've seen normal Arduino boards connecting to it no problem (Uno, Nano, etc.). I'm trying to connect it to my Seeeduino Xiao. It has UART compatible pins, so I'm fairly certain wiring isn't an issue. I think I'm having a hard time with the coding.

Nevermind, I figured it out. For anyone that has this problem to:
First, use the "blueart_cmdmode" example file. Then, follow these steps:
HOW TO GET THE SEEEDUINO XIAO TO WORK WITH THIS

Make sure the "Adafruit_BluefruitLE_UART ble(Serial1, BLUEFRUIT_UART_MODE_PIN);"
line of text above the "void error" line is UNCOMMENTED. Everything else in that
block is to still be commented.

Define the pins in "BluefruitConfig.h" as such:
#define BLUEFRUIT_SWUART_RXD_PIN       6    // Required for software serial!
#define BLUEFRUIT_SWUART_TXD_PIN       7    // Required for software serial!
#define BLUEFRUIT_UART_CTS_PIN         0    // Required for software serial!
#define BLUEFRUIT_UART_RTS_PIN         -1   // Optional, set to -1 if unused

Wire the pins as defined above.

Make sure the Bluefruit is switched to "CMD" mode.


text:
16 by 2 lcd display is not showing any character
I am trying to interface 16by2 lcd with msp432p401m controller but my 16 by 2 lcd is not showing any character. I have attached schematic and code for reference. By using same schematic and code 20 by 4 lcd is working properly.
please help me...

why do you believe that the same code would work for both displays? ... what is your question? ... you did not ask any

Do you realize that the MSP432P401M is not a 5V device and might not be able to interface reliably with a 5V device like your LCD? Do you get anything on the screen (for example: dark rectangles)? Your schematic does not show E, RS, 5V and GND connected to the display. Are they connected? Have you tried to adjust the contrast?

Your use of (P4OUT & 0x00) | seems pointless but harmless.  Otherwise nothing really jumps out that's worth mentioning.

@StarCat, EN and RS are labeled nodes at both the MCU and display. They're logically connected despite not having a graphic line running from one to the other.  Similar thing going on with DGND and 5VD; somewhere else in the schematic they're more than likely labeled at a regulator. They've hardwired RW at LCD pin 5 into write mode.  Voting up with regard to other parts of your comment though.  All that said, hopefully the backlight has some current limiting on the module; I don't know that they all do.

@timemage, I mentioned EN and RS because they were not explicitly connected in the schematic and the question is clearly by someone inexperienced with this kind of material. There was a lot of information missing about the physical setup and I addressed some of that.


text:
Is it safe to connect VCC to a data pin on Attiny chips?
I'm trying to make a compact prototype with Attiny2313A, and want to connect VCC to pin 18 with a push button as in the picture. Is it safe? Or do I need a resistor there?

As long as the pin is configured as input, its save. Though you need a pulldown resistor in that case, or your pin will be floating, when the button is not pressed

As mentioned by @chrisl, here you would need a pull-down resistor to make sure that pin was not high when the button was not pushed.
It is more typical to connect the button between the IO pin and ground since then you can use the built-in pull-up resistors to make sure the pin is high when the button is not pushed. (This chip only has built-in pull-ups, although some chips have pull-downs).

In some cases I'll series something like 150 Ohms with the I/O pin.  It's not enough resistance to negatively affect the function of the circuit (it is small fraction of the pullup resistance value), but it's enough to limit current to a reasonably safe level in case something goes wrong in software and the pin becomes configured to output high.

@timemage In practice, this is almost never necessary in ATTINY chips. If you were to somehow accidentally set the button pin to an OUTPUT pin and drive it high, and then press the button so that pin was shorted to ground, then the chip would quickly undervoltage reset, which would set the pin back to an input.


text:
sim 900a mini status led glowing constantly instead of blinking
I am using sim 900a module for the first time(sim900a). Initially when i powered it with the arduino 5v supply, the power led of the board glow but the network status led never glow. After searching online for answers they showed to use external power supply with 5v 2A, then i used the specified power supply. It worked actually now the status led started to glow but it does not blink for ever 1sec or 3sec instead it glows continuously. I connected the module with the tx and rx of arduino and called the inserted sim the serial monitor detected the call and gave the output, but i cannot make a call or send sms from the module to other numbers. Pls help me out.

I am facing same problem... anybody found solution? Please help.


text:
Code For Lighting RGB Led
I am doing this simple introductory exercise to light an RGB Led, but I am confused about the code in the exercise. The following is the code:
/* Adafruit Arduino - Lesson 3. RGB LED
*/

int redPin = 11;
int greenPin = 10;
int bluePin = 9;

 //uncomment this line if using a Common Anode LED //#define
 COMMON_ANODE

void setup() {
pinMode(redPin, OUTPUT);
pinMode(greenPin, OUTPUT);
pinMode(bluePin, OUTPUT);   }

void loop() {
  setColor(255, 0, 0);  // red
  delay(1000);
  setColor(0, 255, 0);  // green
  delay(1000);
  setColor(0, 0, 255); // blue
  delay(1000);
  setColor(255, 255, 0);  // yellow
  delay(1000);
  setColor(80, 0, 80);  // purple
  delay(1000);
  setColor(0, 255, 255);  // aqua
  delay(1000); }

void setColor(int red, int green, int blue) {
#ifdef COMMON_ANODE
     red = 255 - red;
     green = 255 - green;
     blue = 255 - blue;
#endif
  analogWrite(redPin, red);
  analogWrite(greenPin, green);
  analogWrite(bluePin, blue);   }

In this code, why were they able to carry out setColor before expanding upon what it means later through void setColor(int red, int green, int blue)? Should that portion of the code come earlier or does it matter? Also I don't quite understand how the definition of the colors red, green, and blue were defined towards the bottom. I know what 255 would indicate maximum brightness, but why do you have to subtract the color from 255? Any help would be much appreciated.

why were they able to carry out setColor before expanding upon what it means later

You are correct in C that is the case. However the Arduino IDE adds "function prototypes" to the top of your code automatically. That means you no longer have to abide by the "define before use" of C and C++.

I know what 255 would indicate maximum brightness, but why do you have to subtract the color from 255?

This is for if your LED is "common anode" instead of "common cathode". With a common anode LED you write a LOW to turn it on and a HIGH to turn it off - this is the exact opposite of a common cathode.
So to set the brightness of a common anode LED you need to use the opposite value, and since PWM goes from 0-255 the opposite is 255-0: 255 is off, and 0 is fully on.


text:
Customizing system settings with defines?
I have written a library that contains a statically allocated buffer (f.g. struct taskList proc[TBL_SIZE];)
TBL_SIZE is a macro currently defined in my .h file.
I have heard that there's a way to set or reset the define statement inside the .ino file to customize this setting for some libraries, but I don't know how to do this myself, and by the time I realized that this was a problem I had forgotten what library allowed this setting.
This would be extremely useful as currently I have to edit my library every time I build a new project (or worse, am working on several at once with different settings).
My guess was a variant on an include guard, like this
#ifndef TBL_SIZE
#define TBL_SIZE 16 /*(or whatever)*/
#endif

block, but that failed to work. I tried it during a final project, so my memory is fuzzy from lack of sleep (and time, now), but I'm fairly sure I got an "undefined" error.
I don't know what this is called to search for it otherwise, so I'm hoping someone can help.

Here is more information about my specific issue:
In my .h (at the top, after the regular include guard):
#ifndef TBL_SIZE
#define TBL_SIZE 16
#endif

(Note that everything works if I just set this directly without the defines)
Further down the .h, inside my class:
struct task processes[TBL_SIZE];

In the main .ino file before the library includes:
#define TBL_SIZE 6
#include <CoRTOS.h>

Debug output of the build (I know from experience it built with 16 instead of 6 entries in that table from the memory size. The low memory warning is another big clue.)
Linking everything together...
"C:\\Users\\rdrag\\AppData\\Local\\Arduino15\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/bin/avr-gcc" -w -Os -g -flto -fuse-linker-plugin -Wl,--gc-sections -mmcu=atmega328p -o "C:\\Users\\rdrag\\AppData\\Local\\Temp\\arduino_build_258761/ECE554_ASP.ino.elf" "C:\\Users\\rdrag\\AppData\\Local\\Temp\\arduino_build_258761\\sketch\\ECE554_ASP.ino.cpp.o" "C:\\Users\\rdrag\\AppData\\Local\\Temp\\arduino_build_258761\\libraries\\CoRTOS\\CoRTOS.cpp.o" "C:\\Users\\rdrag\\AppData\\Local\\Temp\\arduino_build_258761\\libraries\\Adafruit_GFX_Library\\glcdfont.c.o" "C:\\Users\\rdrag\\AppData\\Local\\Temp\\arduino_build_258761\\libraries\\Adafruit_GFX_Library\\Adafruit_GFX.cpp.o" "C:\\Users\\rdrag\\AppData\\Local\\Temp\\arduino_build_258761\\libraries\\Adafruit_GFX_Library\\Adafruit_GrayOLED.cpp.o" "C:\\Users\\rdrag\\AppData\\Local\\Temp\\arduino_build_258761\\libraries\\Adafruit_GFX_Library\\Adafruit_SPITFT.cpp.o" "C:\\Users\\rdrag\\AppData\\Local\\Temp\\arduino_build_258761\\libraries\\Adafruit_BusIO\\Adafruit_BusIO_Register.cpp.o" "C:\\Users\\rdrag\\AppData\\Local\\Temp\\arduino_build_258761\\libraries\\Adafruit_BusIO\\Adafruit_I2CDevice.cpp.o" "C:\\Users\\rdrag\\AppData\\Local\\Temp\\arduino_build_258761\\libraries\\Adafruit_BusIO\\Adafruit_SPIDevice.cpp.o" "C:\\Users\\rdrag\\AppData\\Local\\Temp\\arduino_build_258761\\libraries\\Wire\\Wire.cpp.o" "C:\\Users\\rdrag\\AppData\\Local\\Temp\\arduino_build_258761\\libraries\\Wire\\utility\\twi.c.o" "C:\\Users\\rdrag\\AppData\\Local\\Temp\\arduino_build_258761\\libraries\\Adafruit_SSD1306\\Adafruit_SSD1306.cpp.o" "C:\\Users\\rdrag\\AppData\\Local\\Temp\\arduino_build_258761\\libraries\\SPI\\SPI.cpp.o" "C:\\Users\\rdrag\\AppData\\Local\\Temp\\arduino_build_258761\\libraries\\SparkFun_BME280_Arduino_Library-master\\SparkFunBME280.cpp.o" "C:\\Users\\rdrag\\AppData\\Local\\Temp\\arduino_build_258761/core\\core.a" "-LC:\\Users\\rdrag\\AppData\\Local\\Temp\\arduino_build_258761" -lm
C:\Users\rdrag\Documents\Arduino\libraries\CoRTOS\src/CoRTOS.h:38:7: note: array types have different bounds
 class cortos_class {
       ^
"C:\\Users\\rdrag\\AppData\\Local\\Arduino15\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/bin/avr-objcopy" -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 "C:\\Users\\rdrag\\AppData\\Local\\Temp\\arduino_build_258761/ECE554_ASP.ino.elf" "C:\\Users\\rdrag\\AppData\\Local\\Temp\\arduino_build_258761/ECE554_ASP.ino.eep"
"C:\\Users\\rdrag\\AppData\\Local\\Arduino15\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/bin/avr-objcopy" -O ihex -R .eeprom "C:\\Users\\rdrag\\AppData\\Local\\Temp\\arduino_build_258761/ECE554_ASP.ino.elf" "C:\\Users\\rdrag\\AppData\\Local\\Temp\\arduino_build_258761/ECE554_ASP.ino.hex"
Multiple libraries were found for "Adafruit_GFX.h"
 Used: C:\Users\rdrag\Documents\Arduino\libraries\Adafruit_GFX_Library
 Not used: C:\Users\rdrag\Documents\Arduino\libraries\Adafruit-GFX-Library-master
Multiple libraries were found for "Adafruit_I2CDevice.h"
 Used: C:\Users\rdrag\Documents\Arduino\libraries\Adafruit_BusIO
 Not used: C:\Users\rdrag\Documents\Arduino\libraries\Adafruit_BusIO-master
Multiple libraries were found for "Adafruit_SSD1306.h"
 Used: C:\Users\rdrag\Documents\Arduino\libraries\Adafruit_SSD1306
 Not used: C:\Users\rdrag\Documents\Arduino\libraries\Adafruit_SSD1306-master
Using library CoRTOS at version 0.2.0 in folder: C:\Users\rdrag\Documents\Arduino\libraries\CoRTOS
Using library Adafruit_GFX_Library at version 1.10.7 in folder: C:\Users\rdrag\Documents\Arduino\libraries\Adafruit_GFX_Library
Using library Adafruit_BusIO at version 1.7.3 in folder: C:\Users\rdrag\Documents\Arduino\libraries\Adafruit_BusIO
Using library Wire at version 1.0 in folder: C:\Users\rdrag\AppData\Local\Arduino15\packages\arduino\hardware\avr\1.8.3\libraries\Wire
Using library Adafruit_SSD1306 at version 2.4.5 in folder: C:\Users\rdrag\Documents\Arduino\libraries\Adafruit_SSD1306
Using library SPI at version 1.0 in folder: C:\Users\rdrag\AppData\Local\Arduino15\packages\arduino\hardware\avr\1.8.3\libraries\SPI
Using library SparkFun_BME280_Arduino_Library-master at version 2.0.9 in folder: C:\Users\rdrag\Documents\Arduino\libraries\SparkFun_BME280_Arduino_Library-master
"C:\\Users\\rdrag\\AppData\\Local\\Arduino15\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/bin/avr-size" -A "C:\\Users\\rdrag\\AppData\\Local\\Temp\\arduino_build_258761/ECE554_ASP.ino.elf"
Sketch uses 28172 bytes (91%) of program storage space. Maximum is 30720 bytes.
Global variables use 1609 bytes (78%) of dynamic memory, leaving 439 bytes for local variables. Maximum is 2048 bytes.
Low memory available, stability problems may occur.

Define "failed to work". If the preprocessor sees a #define LISTSIZE before your file is included it would skip over your #define because it's been defined.

That was the goal. I'd want the earlier one (from the .ino) to override the one in the file.

I've added information. "Fails to work" means that it won't customize the array size. I misremembered the warning/error. Some sort of array mismatch complaint, but there isn't actually anything remotely array-related on that line...

the #define in ino will apply only for .h included in ino, not for the same .h included in other file. the #include directive makes the whole content of .h to be copied into the file with the directive

I was under the impression that the #define in the .ino file would override the .h file's default define entry for all items that included it, since it was the first use of it or something. That doesn't work?

Could you add more details about how the array is declared and defined? From your description, it sound like it is defined in the .h file. From the build output, it looks like it was declared in the .h and defined in a .cpp. Or maybe the .h was included in more than one source file.

The .h is included in two source files for this project IIRC - the .ino and the library's .cpp.  The array is a member of a class which is declared in the .h and populated by a member function that's defined in the .cpp. I believe the class itself is defined in the .cpp using extern.

I have heard that there's a way to set or reset the define statement inside the .ino file to customize this setting for some libraries, but I don't know how to do this myself

There are many ways to achieve what you want, you might not even need the #ifndef macro, use your library class construct to allow user to pass in the list size as an argument and but set the argument with a default value.
YourLibrary.h
class YourLibrary
{
private:
  size_t _userSize;
public:
  YourLibrary::YourLibrary(size_t listSize = 16) {
    _userSize = listSize;
  }
  ...
}

User's sketch .ino
#include <YourLibrary.h>

#define LIST_SIZE 32;

YourLibrary instance(LIST_SIZE);  // instance() would set the _listSize to 16

setup() {

}

loop() {

}

Doesn't that require allocating the item on the heap, though? It's setting the size of an array.

No it does not. Unless you use String object.

BTW, I read your updated post. There is no error as you mentioned regarding #ifndef, so what exactly is the problem and your question?

The problem listed in my post is that adding the #define in the root .ino file does not actually have any effect on the array size in the library. RE your answer, how does setting the variable inside the class as in your example create the array I need? I'm really trying not to dynamically allocate this table, so was that what you meant or is there some sort of magic I'm missing here?


text:
Sending a request with a NodeMCU when a key is pressed
I want to send a request to a server with the GET method with URL parameters when a key is pressed on the NodeMCU. But I can't get this to work; I get the below error in the serial monitor:
 ets Jan  8 2013,rst cause:4, boot mode:(3,7)

wdt reset
load 0x4010f000, len 1384, room 16
tail 8
chksum 0x2d
csum 0x2d
v951aeffa
~ld

My main code:
#include <ESP8266WiFi.h>

const char* ssid = "MobinNet1365";
const char* password = "G12229M1Q64";
const char* host = "webhook.site";

const int button = 8;
int temp = 0;

void setup() {
  Serial.begin(115200);
  pinMode(button, INPUT);
  delay(10);
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);

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

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

void loop() {
  temp = digitalRead(button);
  if (temp == HIGH) {
    Serial.println(host);
    WiFiClient client;
    const int httpPort = 80;

    String url = "/df35c8cd-0398-4c92-b55f-b9e36629b309";
    url += "?switche=";
    url += "1";

    client.print(String("GET ") + url + " HTTP/1.1\r\n" + "Host: " + host + "\r\n" + "Connection: close\r\n\r\n");
  }
}

My request sending code is below:
#include <ESP8266WiFi.h>

const char* ssid = "your-ssid";
const char* password = "your-password";
const char* host = "";

void setup() {
    Serial.begin(115200);
    delay(10);
    Serial.println();
    Serial.print("Connecting to ");
    Serial.println(ssid);
    WiFi.mode(WIFI_STA);
    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED) {
      delay(500);
      Serial.print(".");
    }

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

int value = 0;

void loop() {
  delay(5000);
  ++value;
  Serial.print("connecting to ");
  Serial.println(host);
  WiFiClient client;
  const int httpPort = 80;
  if (!client.connect(host, httpPort)) {
    Serial.println("connection failed");
    return;
  }

  String url = "/";
  /* url += "?param1=";
  url += param1;
  url += "?param2=";
  url += param2;
  */
  Serial.print("Requesting URL: ");
  Serial.println(url);
  client.print(String("GET ") + url + " HTTP/1.1\r\n" + "Host: " + host + "\r\n" + "Connection: close\r\n\r\n");
  unsigned long timeout = millis();
  while (client.available() == 0) {
    if (millis() - timeout > 5000) {
      Serial.println(">>> Client Timeout !");
      client.stop();
      return;
    }
  }

  while (client.available()) {
    String line = client.readStringUntil('\r');
    Serial.print(line);
  }

  Serial.println();
  Serial.println("closing connection");
}

And my key press detector code is below:
const int button = 8;
int temp = 0;

void setup() {
  Serial.begin(9600);
  pinMode(button, INPUT);
}

void loop() {
  temp = digitalRead(button);

  if (temp == HIGH) {
    Serial.println("LED Turned ON");
    delay(1500);
  }
  else {
    Serial.println("LED Turned OFF");
    delay(1500);
  }
}

My circuit is:
NodeMcu => MicroSwitch
VIN => C
D0 => NO
G => 10k => NO
How can I make it so that when the key is pressed it sends a request?

I don't quite understand--what is ypur actual code? One chunk of code never initializes "host", another does. What is the actual code that causes the error? Are you making a request between two NodeMCUs?

No its just for sending a request to a server when a key pressed but i get "ets Jan  8 2013,rst cause:4, boot mode:(3,7)
wdt reset
load 0x4010f000, len 1384, room 16
tail 8
chksum 0x2d
csum 0x2d
v951aeffa
~ld" error and that code has header named main code is my actual code

Please include only the relevant code.

why do you believe that the ets Jan 8 2013,rst cause:4, boot mode:(3,7) .... message is an error message?

IMHO, some consideration :

const int button = 8;
const int button = 5; // CHANGE TO Pin "D1 GPIO5"

GPIO8 is used to connect the flash chip, you may change to Pin "D1" which is GPIO 5.

Check with your board's pinout.

to prevent non-stop keep calling within in the loop, you may use millis();

for example :
void GetUrl() {
    temp = digitalRead(button);
  if (temp == HIGH) {
    Serial.println(host);
    WiFiClient client;
    const int httpPort = 80;

    String url = "/df35c8cd-0398-4c92-b55f-b9e36629b309";
    url += "?switche=";
    url += "1";

    String link = String("GET ") + url + " HTTP/1.1\r\n" + "Host: " + host + "\r\n" + "Connection: close\r\n\r\n";
//    Serial.println( "link : " + link );
    client.print(String("GET ") + url + " HTTP/1.1\r\n" + "Host: " + host + "\r\n" + "Connection: close\r\n\r\n");
  }
}

unsigned long previousMillis = 0;
const long interval = 1000 * 0.5; // 500ms (0.5 sec)

void loop() {
  unsigned long currentMillis = millis();
  if (currentMillis - previousMillis >= interval) {
    GetUrl();
  }
}

Reference :
https://www.arduino.cc/en/Tutorial/BuiltInExamples/BlinkWithoutDelay
https://iotbyhvm.ooo/gpio-pins-esp8266/


text:
LEDs not lighting up even though current is flowing through them, problem with ground?
I'm using a 74HC595N shift register to light up 8 LEDs but for some reason they won't turn on even though current is flowing through all of them. I provided an image of my circuit below, there is a test LED for checking current flow:

I am using a 9A103G resistor network to connect all the LEDs to a common ground. I have tried this with 8 individual 330 ohm resistors in the past but the result is the same, and every time the problem was with the ground wire, current is not flowing through it even though all the resistors I've used showed that current was flowing through them (see below):

The following image shows the same test LED not lighting up when connected to the common ground pin of the resistor network:

I could use some help fixing this issue because it is preventing me from using shift registers for future projects (this only happens when I use shift registers) - I would like to know what is causing this problem so I can avoid it later on. Thanks in advance!

You're short circuiting your LEDs with the breadboard. Rotate them 90°.

That was the problem!! Thank you so much! I forgot about the columns.

Good pictures by the way.

(Just to illustrate what Majenko is saying.)
This is the inside of a breadboard:

All your connections are on one side of that; you've tied everything to a single point.

Yes you're right, thank you


text:
Help with understanding fuses for an embedded AVR project
I am planning to build a project, but it's something quite embedded and I have no need for the extra features or bootloader of a standard Arduino. At the same time, I think I want to use the ATmega 328P rather than an ATTiny, which is what I'm familiar with for this.
I'm running into confusion with the boot size bits and I'm not too sure about the clock setup bits either (normally I run an ATTiny with internal clock). I'm fairly sure I bought some 16MHz crystals and capacitors for this sort of thing a while back, but I'm also sure there will be times that the internal crystal will be fine.
Does anyone have a favored fuse config for this?
I am using an external programmer over the six-pin SPI/ISP port (well, the pins that would be the equivalent of that) for a "boarduino." I only care about the power filtering and external clock (in cases where I need the latter). I'm not bothering with auto-reset or UART since, again, I'm using a programmer.
I would appreciate both configs for 16 MHz (most Arduino-like, I believe) and internal clock at 8MHz. Thanks!
Edit: Here are my settings so far: http://eleccelerator.com/fusecalc/fusecalc.php?chip=atmega328p&LOW=FF&HIGH=D6&EXTENDED=FF&LOCKBIT=FF. I think that's normal for a "regular" Arduino (minus some stuff I may have messed up in the high fuse) but I'd like to not bother with any bootloader stuff and have my code run right away.
For the internal clock version I have this so far: http://eleccelerator.com/fusecalc/fusecalc.php?chip=atmega328p&LOW=E2&HIGH=D6&EXTENDED=FF&LOCKBIT=FF

The bootloader is entirely optional. If you don't want to use the bootloader then you don't need to install the bootloader, and you don't need to configure the chip to use a bootloader.

I think you need to deselect the Boot Reset vector, to disable the bootloader. That's what I do when I don't use a bootloader. Other than that, those fuses look fine to me. Though I'd enable brownout detection, unless you have a very good reason not to. Note that using the internal RC oscillator will give a less accurate clock, which I found only to be an issue when I was using high speed UART. Most of the time it doesn't matter. I like not having to add a crystal and caps to my PCBs.

I don't want the chip configured to have a bootloader, even if I don't use one (not quite sure what happens if it is and I don't, either). It's as simple as turning off the boot reset vector? Like http://eleccelerator.com/fusecalc/fusecalc.php?chip=atmega328p&LOW=FF&HIGH=D6&EXTENDED=FF&LOCKBIT=FF ? Plus you get more pins without an OSC, admittedly it's less of an issue here. I'll set the BOD as needed, that part I do fortunately understand. Any idea if the internal clock is accurate enough to drive Neopixels or not? I like to use a few as indicators.


text:
Arduino Nano Every: get board name in the code
I would like to identify the target where I'm downloading my Arduino code. Following this example:
How to get board type
I'm able to recognize for example Arduino Mini, etc.. but Arduino Every, quite new board is not in the list and I don't understand where to find the correct "define" name to add in the list.
Can someone help me?
Thanks Andrea.

there really isn't much magic behind it.  Depending on your selection, ide includes a particular core folder from inside hardware so in theory you could look there also.  that specific method is tied to an arduino bootloader- the thing that runs at boot before your program.  As it said, search for avr_cpunames.h header and see if _AVR_CPU_NAME_ helps.

Thanks but I wrote here because searching into Arduino IDE installation I did not found nothing related to "Arduino Every" or even "AT mega 4809" etc.. nothing that seems in the list. So, if someone is more expert to me.. also the file avr_cpunames.h contains nothing related. I tried with many names that could make sense but trying by tentatives.. not so good. Arduino IDE version 1.8.13. With IDE installed I can use Arduino Nano Every perfectly.

default behavior does something evil for downloaded packages - also check %HOMEPATH%\AppData\Local for an Arduino folder.  The Arduino.h header it uses is likely there under packages\arduino\hardware\megaavr

Arduino Nano Every is using the ArduinoCore-megaavr, designed for new chips like AT mega4808/09. For Uno/Nano/Pro Mini, it is using the ArduinoCore-avr. If you can't find your board on IDE or your file system, the chance is that you have not install the ArduinoCore-megaavr.

According to documentation the macro to identify the Arduino board is generated as as ARDUINO_{build.board} where {build.board} is from boards.txt file of the 'platform'.
Nano Every has in boards.txt nona4809.build.board=AVR_NANO_EVERY.
So the macro to identify Nano Every is ARDUINO_AVR_NANO_EVERY.

Great! I was not aware of this documentation. It works perfectly, thanks a lot! I also found that if you need to know if the emulator mega 328 is selected, you can use:     #elif defined(AVR_NANO_4809_328MODE)
#define BOARD F("Every 328 emul")
#elif defined(ARDUINO_AVR_NANO_EVERY)
#define BOARD F("Every") But your answer solved my problem. Many thanks


text:
Circuit to get highest reading value from multiple thermistors?
I need to measure temperature of 6 battery cells. I don't care much about individual cell readings, I just want to sound a buzzer as soon as at least one of the temperatures is above a certain threshold.
I can see the most straightforward way to do it using 6 thermistors, but that's a lot of wires going between Arduino and all these sensors. Is there any other approach that would be more lightweight? Trying to save both space and weight.
If I understand correctly, best I can do with 6 thermistors is share the GND wire and resistor between them, but then I'm still stuck with 6 * 2 + 1 = 13 wires.

not arduino specific

DS18b20 digital thermometers use the 1-Wire protocol which requires only a single data line for a network of devices - so +V (3.3 - 5 Volts), Gnd, and Data, shared among all of them. You can even wire them in "Parasitic mode", skipping the +V, and they will get their power from the data line, so only 2 wires and 1 pin required.From the DS18b20 Datasheet:

Thanks, this is exactly what I needed.


text:
I can get arduino code/board to show voltage using analog input but not python/board
I am trying to simply read a voltage from a battery. I am able to work out how to do this using arduino code on an arduino board. (UNO)
When I try to do the same thing on a board using python the output seems erroneous.
Using arduino I will say for example get a voltage output to serial monitor or 1.39v which stays pretty much constant.
When doing so with the python board (Trinket M0) the output varies from 1.23342 -1.78484 and varies between these values.
My arduino code is as follows:
int offset =0;// set the correction offset value
void setup() {
  // Robojax.com voltage sensor
  Serial.begin(9600);
}

void loop() {
  // Robojax.com voltage sensor
  int volt = analogRead(A0);// read the input
  double voltage = map(volt,0,1023, 0, 2500) + offset;// map 0-1023 to 0-2500 and add correction offset

  voltage /=100;// divide by 100 to get the decimal values
  Serial.print("Voltage: -");
  Serial.print(voltage);//print the voltge
  Serial.println("V");

delay(500);

}

My Python code is as follows
import time
import board
from analogio import AnalogIn

analog_in = AnalogIn(board.A1)

def get_voltage(pin):
    return (pin.value * 3.3) / 65536

while True:
   print((get_voltage(analog_in),))
    time.sleep(0.1)

Have you checked the voltage with a multi-meter while the Trinket M0 is running, to compare against a reference? Perhaps the M0 reading is correct?

Ok, i had made a really stupid mistake and had wired the analogue pin incorrectly. However, now my reading in the serial console read 0.33456 -0.34564 the voltmeter reads voltage as 1.42v


text:
How does Arduino board separate USB traffic (uploading code vs. communication)?
A beginner in Arduino programming here (learning Arduino programming while waiting for my board to arrive).
I am trying to understand how Arduino board is able do these two things using only one USB port it has:

receive compiled code from a PC (from Arduino IDE: Sketch > Upload)
serial communication between a PC application and the Arduino board (e.g. our own Windows application communicates with the Arduino board)

I just cannot wrap my mind around how does it distinguish between these two cases. I have used boards which have 2 USB ports: one is for programming (uploading your code) and the other one is for serial communication between any PC application and the board.
In my opinion there has to be some way for Arduino to detect when is it being flashed, and when is it being used as a regular serial port.

https://learn.adafruit.com/bootloader-basics?view=all#types-of-bootloaders

It doesn't distinguish anything. It's all down to what code is running on the board at any moment.
When you reset or power up the bootloader runs. It listens for uploaded code. If it doesn't get an upload signal from the pc after a short timeout it starts executing your code instead.


text:
Read & Write to EEPROM
I need to implement EEPROM Read & Write functionality to my project.
I've been learning how to use the EEPROM on the last few days, however I'm struggling to Read & Write Strings to EEPROM.
Debugging the Received Data:

Received Data: The data received is correct.
EEPROM Data: It seem it has data but I am receiving Garbage Characters.

After reading several answers, I seem to fail understanding the reason behind my failure.
Sure I could "Copy / Paste", probably make it work and not understand the cloned code, but I wouldn't learn anything from that.
Therefore posting another thread regarding this subject (not exactly duplicate) requesting some help and/or guidance; for the sake of understanding and solving my issue.
Code
int ADDR_USERNAME       = 2;           // Username Data Lenght Address on EEPROM.

/* Get Username from EEPROM */
String EE_ReadUsername()
{
  int dataLength  = EEPROM.read(ADDR_USERNAME);       // Get the Data Length from EEPROM Address Position.
  int dataAddress = ADDR_USERNAME + 1;                // Data Initial Address on EEPROM

  char data[dataLength];                              // Assign the Array Length

  for (int i = 0; i < dataLength; i++)                // Retrieve Data (Char by Char) by Iterating over EEPROM Address Positions.
  {
    char c = EEPROM.read(dataAddress + i);            // Add EEPROM Address Char to Array
  }

  // DEBUG START
  Serial.print("VALUE: ");
  Serial.println(String(data));
  // DEBUG END

  return String(data);                                // Return the Data.
}

/* Save Username to EEPROM */
void EE_WriteUsername(String str)
{
  byte len = str.length();                            // Get the String Length.
  int dataAddress = ADDR_USERNAME + 1;                // Set the Initial Data Address

  EEPROM.update(ADDR_USERNAME, len);                  // Store the String Length to EEPROM

  for (int i = 0; i < len; i++)                       // Iterate over each char in String.
  {
    EEPROM.update(dataAddress + i, str[i]);           // Assign each char from Received String to an Address Position in EEPROM.
  }
}

Thanks in advance.

In EE_ReadUsername(), you wrote:
char c = EEPROM.read(dataAddress + i);

This variable (c) is set but never used. You may want to add that
character to the data character array.
Also, the array has to be terminated with a NUL byte.

Giving this thread some more value while taking into consideration @Edgar Bonet's help (the accepted answer for this thread); I'm answering my own question with my full header class code (more EEPROM features) for further reference for myself and other users, who might be learning.

Note(s):

The regions are there for a backup reference purpose.
Feel free to edit and improve the answer and improve comments with advanced and knowleadgeable information.
Null Terminating char is NOT added to the EEPROM.
The Null Terminating char '\n' or '\0' is added to the array when reading (only).
This prevents writing (unnecessary) addresses to EEPROM.

Code
#pragma region <Includes>
#include <EEPROM.h>
#pragma endregion

#pragma region <Configuration>

#define ADDR_BRIGHTNESS   0           // LCD Brightness Data Address on EEPROM.
#define ADDR_CONTRAST     1           // LCD Contrast Data Address on EEPROM. [NOT IMPLEMENTED]
#define ADDR_USERNAME     2           // Username Data Lenght Address on EEPROM.
#define ADDR_COMPUTERNAME 14          // Computer Data Length Initial Address on EEPROM.

#pragma endregion

#pragma region <CRC>
unsigned long EEPROM_CRC(void)
{
  const unsigned long crc_table[16] =
  {
    0x00000000, 0x1db71064, 0x3b6e20c8, 0x26d930ac,
    0x76dc4190, 0x6b6b51f4, 0x4db26158, 0x5005713c,
    0xedb88320, 0xf00f9344, 0xd6d6a3e8, 0xcb61b38c,
    0x9b64c2b0, 0x86d3d2d4, 0xa00ae278, 0xbdbdf21c
  };

  unsigned long crc = ~0L;

  for (int index = 0 ; index < EEPROM.length()  ; ++index)
  {
    crc = crc_table[(crc ^ EEPROM[index]) & 0x0f] ^ (crc >> 4);
    crc = crc_table[(crc ^ (EEPROM[index] >> 4)) & 0x0f] ^ (crc >> 4);
    crc = ~crc;
  }

  return crc;
}

/* Performs a Cyclic Redundancy Check and Prints a Report on Serial Monitor */
void EE_CRC()
{
  Serial.println(" *** Performing EEPROM Cyclic Redundancy Check...");
  Serial.print(" *** EEPROM Length: ");                                // Print Length of Data to run CRC on.
  Serial.println(EEPROM.length());

  Serial.print(" *** EEPROM CRC32 Data: 0x");                          // Print the Result of Calling EEPROM_CRC()
  Serial.println(EEPROM_CRC(), HEX);
}
#pragma endregion

/* Iterate Through Each byte of the EEPROM Storage and Set all of the bytes to 0. */
void EE_ERASE()
{
  Serial.println(" *** ERASING EEPROM MEMORY...");

  for (int i = 0; i < EEPROM.length(); i++)
  { EEPROM.write(i, 0); }

  Serial.println(" *** EEPROM ERASED!");
}

#pragma region <User Name>
/* Get Username from EEPROM */
String EE_ReadUsername()
{
  int dataLength  = EEPROM.read(ADDR_USERNAME);         // Get the Data Length from EEPROM Address Position.
  int dataAddress = ADDR_USERNAME + 1;                  // Data Initial Address on EEPROM

  char data[dataLength +1];                             // Assign the Array Length (+1 to Add the Null Terminating Char).

  for (int i = 0; i < dataLength; i++)                  // Retrieve Data (Char by Char) by Iterating over EEPROM Address Positions.
  {
    data[i] = EEPROM.read(dataAddress + i);             // Add EEPROM Address Char to Array
  }

  data[dataLength] = '\0';                              // Terminate the char String (Add Null Terminating Char)

  return String(data);                                  // Return the Data.
}

/* Save Username to EEPROM */
void EE_WriteUsername(String str)
{
  byte len = str.length();                              // Get the String Length.
  int dataAddress = ADDR_USERNAME + 1;                  // Set the Initial Data Address

  EEPROM.update(ADDR_USERNAME, len);                    // Store the String Length to EEPROM

  for (int i = 0; i < len; i++)                         // Iterate over each char in String.
  {
    EEPROM.update(dataAddress + i, str[i]);             // Assign each char from Received String to an Address Position in EEPROM.
  }
}
#pragma endregion

#pragma region <Computer Name>
/* Get Computer Name from EEPROM */
String EE_ReadComputername()
{
  int dataLength  = EEPROM.read(ADDR_COMPUTERNAME);     // Get the Data Length from EEPROM Address Position.
  int dataAddress = ADDR_COMPUTERNAME + 1;              // Data Initial Address on EEPROM

  char data[dataLength +1];                             // Assign the Array Length (+1 to Add the Null Terminating Char).

  for (int i = 0; i < dataLength; i++)                  // Retrieve Data (Char by Char) by Iterating over EEPROM Address Positions.
  {
    data[i] = EEPROM.read(dataAddress + i);             // Add EEPROM Address Char to Array
  }

  data[dataLength] = '\0';                              // Terminate the char String (Add Null Terminating Char)

  return String(data);                                  // Return the Data.
}

/* Save Computer Name to EEPROM */
void EE_WriteComputername(String str)
{
  byte len = str.length();                              // Get the String Length.
  int dataAddress = ADDR_COMPUTERNAME + 1;              // Set the Initial Data Address

  EEPROM.update(ADDR_COMPUTERNAME, len);                // Store the String Length to EEPROM

  for (int i = 0 ; i < len; i++)                        // Iterate over each char in String.
  {
    EEPROM.update(dataAddress + i, str[i]);             // Assign each char from Received String to an Address Position in EEPROM.
  }
}
#pragma endregion

#pragma region <Brightness>
int EE_ReadBrightness()
{
  return EEPROM.read(ADDR_BRIGHTNESS);
}

void EE_WriteBrightness(int val)
{
  EEPROM.update(ADDR_BRIGHTNESS, val);
}
#pragma endregion


text:
Can this display's address be changed?
I need two displays hooked up to an Arduino MKR Wifi 1010, and I saw this video which shows how to do it: this video. I also would like to have a full color oled display about 1 inch big so I would like to use this display. But I don't believe that you can change the address and would not like to buy it until I find out if you can.
Thanks in advance.

The Adafruit display uses SPI. Different SPI devices can be selected via their respective CS (Chip Select) pins. You can connect the SPI bus (MOSI, MISO ans SCK) to multiple displays in parallel and choose which one to control by enabling their CS pin (although the display library will usually do this for you).

There are two different OLED screens in the links you shared.
1. OLED Display on Adafruit Link
The OLED display on the Adafruit link does not have an address as it communicates via the SPI interface.
2. OLED Display on YouTube Link
This OLED display communicates via I2C interface. OLED displays that communicate over the I2C interface have a slave address. This provides the possibility to connect devices with different slave addresses on the same I2C line. The address of this screen can only take two different values. If you solder the 0 Ω resistor to the left field, its address will be 0x7A; if you solder the 0 Ω resistor to the right field, its address will be 0x78.

Suggestions
This OLED display with 0.96" screen size communicates via I2C interface and its address can be changed. If a 0 Ω resistor is connected to the A0 pad, the I2C slave address of the OLED display will be 0x3D; otherwise the I2C slave address of the OLED display will be 0x3C.

If you have a address conflict the generic solution would be to use I2C mux that will switch between the circuits or use different hardware I2C or bitbang a software I2C.


text:
How exactly do Bicycle LEDs work? (Arduino Project)
Table of contents:

What I want to achieve
Problem I'm facing
What I've tried
Possible Hypotheses

What I want to achieve
Hi guys, I’m working on a DIY LED Light project to install on my bicycle, where I want to re-create how the actual LED bicycle lights work:
[Stage 1] Press button once: LED lights up forever until button is pressed again
[Stage 2] Press button twice: LED blinks forever until button is pressed again
[Stage 3] Press button thrice: LED turns off (goes back to original state)
Problem I’m facing
After a bit of research, I know how to work out the code for [Stage 1] (by tracking the current and previous button states.) But I’m unable to make [Stage 2] happen.
What I’ve tried
I’ve tried to instead of tracking the previous and current button states, why not use a counter, i.e:
Counter = 0 (initial)
When button is pressed once,
Counter = 1 (LED lights up forever until button is pressed again)
When button is pressed one more time,
Counter = 2 (LED blinks forever until button is pressed again)
When button is pressed one more time,
Counter = 3 (LED switches off, goes back to original LOW state)
Counter resets to = 0 again
This is my code below:
const int ledPin = 8;
const int buttonPin = 7;

int buttonState;
int ledState;
int counter = 0;
int newcounter;

void setup() {
  pinMode(ledPin, OUTPUT);
  pinMode(buttonPin, INPUT);
  digitalWrite(ledPin, HIGH);
}

void loop() {
  buttonState = digitalRead(buttonPin);
  if (buttonState == HIGH) {
    newcounter = counter + 1;
    delay(500);
    if (newcounter != counter) {
      switch (newcounter) {
        case 1:
            digitalWrite(ledPin, LOW);
            counter = newcounter;
            break;
        case 2:
            digitalWrite(ledPin, HIGH);
            delay(500);
            digitalWrite(ledPin, LOW);
            delay(500);
            digitalWrite(ledPin, HIGH);
            delay(500);
            digitalWrite(ledPin, LOW);
            delay(500);
            digitalWrite(ledPin, HIGH);
            delay(500);
            digitalWrite(ledPin, LOW);
            delay(500);
            digitalWrite(ledPin, HIGH);
            delay(500);
            break;
        case 3:
            digitalWrite(ledPin, HIGH);
            counter = 0;
            break;
        default:
            digitalWrite(ledPin, HIGH);
            counter = 0;
            break;
      }
    }
  }
}

Possible Hypotheses (Please criticise/correct me if I’m wrong)
A) There is a problem with my code (my programming logic etc)
B) Maybe its not a code/program problem? It could be due to the design of the electric circuit (because I’ve seen videos on YouTube where LEDs can be made to blink using capacitors and transistors. But how does the sequence from Stages 1 to 3 happen in a bicycle LED light? (https://www.youtube.com/watch?v=cXCExzIBNsA)
I’ll be eternally grateful if anyone will be able to help! Thank you!!

So what is the question? Does the code "not work" and you are asking "why it does not work"? If it does not work, what does it do then and how do you expect it to work?

First of all, you need to get rid of all those calls to delay() and implement it in a non-blocking way (look at BlinkWithoutDelay.ino).

@SimSon, you can make that an answer :)

does loop() actually "loop"?

You're missing a counter = newcounter; line in your case 2:, but the real problem (probably, since you haven't actually described what "But I’m unable to make [Stage 2] happen" means) is almost certainly that you only have 3 blinks and then your code exits the state and returns back to the start of the loop. Sim Son has already given you one way of fixing that. Your code might work a bit more like you intend it to if you move the entire switch block outside the if (buttonState == HIGH) block. As you've written it, the case with all the blinks only executes if the button is pressed.

Your problem is that your LED control code is all tangled up with your button press and counter code. Separate them out into completely independent code blocks. One that just increments the counter using a button, and one that displays different things depending on the current counter value.

@glen_geek, That's Arduino code. The Aduino library effectively calls while(true) loop();  https://www.arduino.cc/reference/en/language/structure/sketch/loop/

you are not stating what results you are getting.
I do see you are not presetting your state variables.
This is always good practice to avoid random startup conditions.
you have logic that will only run when the button is held
your if (newcounter != counter) and switch statement only run while the button is pressed.
move them outside of the button state check and look to change things ONLY if the button changed.
try this;
it will only act on button change not continiously so changes only happen on each press
i will leave you to play with the switch conditions
const int ledPin = 8;
const int buttonPin = 7;

int buttonState, chngButtonState = 0;
int ledState;
int counter = 0;
int newcounter;

void setup() {
  chngButtonState = buttonState;
  pinMode(ledPin, OUTPUT);
  pinMode(buttonPin, INPUT);
  digitalWrite(ledPin, HIGH);
}

void loop() {
      buttonState = digitalRead(buttonPin);
      if (buttonState == HIGH && !buttonState == chngButtonState ) {     // read once only if changed button state changed not on every loop
        newcounter = counter + 1;
        delay(500);
        chngButtonState = buttonState;      // mae them equal again
        }                // NOTE I moved 1 of the } from the bottom

        if (newcounter != counter) {
          switch (newcounter) {
            case 1:
                digitalWrite(ledPin, LOW);
                counter = newcounter;
                break;
            case 2:
                digitalWrite(ledPin, HIGH);
                delay(500);
                digitalWrite(ledPin, LOW);
                delay(500);
                digitalWrite(ledPin, HIGH);
                delay(500);
                digitalWrite(ledPin, LOW);
                delay(500);
                digitalWrite(ledPin, HIGH);
                delay(500);
                digitalWrite(ledPin, LOW);
                delay(500);
                digitalWrite(ledPin, HIGH);
                delay(500);
                break;
            case 3:
                digitalWrite(ledPin, HIGH);
                counter = 0;
                break;
            default:
                digitalWrite(ledPin, HIGH);
                counter = 0;
                break;
          }
        }
    }

now just play with the Switch statements to get your results.
pinMode(buttonPin, INPUT);
your button wiring is not clear.
Likely, you have the button connected to VCC and pin 7.  You still should have a pulldown resistor from the arduino pin7 to GND to get reliable states.
However; if the button is from a pin7 to GND and no pullup the state will also not change.
If so;
change pinMode(buttonPin, INPUT); to pinMode(buttonPin, INPUT_PULLUP);   and no external pullup resistor is needed.

Think of the "stages" you identified as states or modes of operation, and the button presses cycle between the stages.
Then for "stage 2", you re-write it as a function that doesn't mostly block and idle for 3.5 seconds, but that immediately returns control back to the loop() so you can check for more button presses quickly:
// this function is patterned after the example in
// https://www.arduino.cc/en/Tutorial/BuiltInExamples/BlinkWithoutDelay
void stage2(void){
  const unsigned long interval = 500;
  static unsigned long last = 0;
  if(millis() - last >= interval){
    last += interval;
    digitalWrite(ledPin, !digitalRead(ledPin));
  }
}

and then you switch on stage in the event loop:
      switch (stage) {
        case 0: // idle
            break;
        case 1: // on
            digitalWrite(ledPin, LOW);
            counter = newcounter;
            break;
        case 2: // blinking
            stage2();
            break;
        case 3: // turn off
            digitalWrite(ledPin, HIGH);
            stage = 0;
            break;
        default:
            digitalWrite(ledPin, HIGH);
            counter = 0;
            break;
      }
      ...

This switch-case takes almost no time, and returns control to the event loop, so the user interface can respond quickly to other button presses, or check for other tasks.
I didn't re-write the rest of your code, but these are the key differences between your code and what's running in a bike light:

Use state variables and state machines to change the mode of operation.

Avoid trapping the processor in "blocking" code that uses delays(), for(;;), while();, etc...  Depend instead on the event loop (loop() in the Arduino), to return control to your functions.

There is a simulation of a Bike Light using these coding patterns on Wokwi at https://wokwi.com/arduino/projects/325075981102482003


text:
Odd behavior of defines - is this Arduino specific and how does it work?
A question I have long had regards an interaction between #define statements and a library header include. I've seen several Arduino libraries use this rather convenient configuration system where you can write a #define statement, then include the #include header instruction and the library will change its behavior.
Does anyone know why this does or does not work? My understanding of how #include works is that it copies the file into its place in the new file and that C/C++ code with headers should thus form something of a tree shape. It would thus make sense that any lines of code present before I #include a library would have to be seen by the library when the preprocessor does its thing and copies the #include-d file.
But I've previously been told it doesn't actually work this way (despite actual examples, but by that point I had misplaced the libraries that did it). However, I've finally tracked down an example of someone doing this, and I'd like to know how this behavior works. Is it a feature of Arduino in specific or something?
Here's a library that does it: https://github.com/madpilot/mDNSResolver

From my reading of the source code for that library I can't see that it can work as described. The library code (cpp files) are different translation units to the sketch where the #define would be located.

Can you explain translation units? I've heard of them, but they seem very nebulous to me.

When you compile a .c or .cpp file it gathers all the header files contents together and literally does string replacement on the #includes and then the #defines. Then compiles that one big resultant file. That's a translation unit. In general for every cpp or c file you have one translation unit. It's a self contained thing which can't be modified by anything outside. The only exception is in Arduino if you have multiple .ino files in a sketch they get concatenated together into one gigantic translation unit.

If I were doing what you describe I'd be using a class with a constructor whose code is in the header file and thus gets recompiled for each translation unit (i.e. within the sketch for example). That constructor would be called with macros you can override from the sketch since the constructor forms part of the same TU as the sketch.

the missing define is not missing from your sketch, it's missing from the lib's cpp file, which is it's own thing. one neat trick i've used is to put all the lib code in an H file instead of the cpp file. The result is basically that that H-file code just pasted in-place in the sketch, which means prior defines are available to it. I don't know  if there's downsides to it, but it works as I expect...

The mDNSResolver library README has

You can change a few settings by defining some constants before including the mDNSResolver header file [in the sketch]

I added "in the sketch", because it is where you include mDNSResolver header file.
This will not work because mDNSResolver.cpp, which uses the values of the defines, is compiled without any knowledge of the ino file content.
A deeper explanation would be too long and out of scope for Arduino SE.

In the first few lines of the library .h file you linked, it tests a symbol it has not defined, ESP32 (#if defined(ESP32)) and alters the compilation according to the definedness of that symbol.
Since the compiler input will be one long file with all the #include files already "spliced" inline, you (or a previously included .h file) have the option to pre-define that variable to alter the compilation as this library writer provided.
Update:
@RDragonflydr: I believe you are correct, that the ESP32 symbol is defined by the compiler (or more likely, the makefile) for the target processor. And to clarify my statement that "the compiler input will be one long file", I'm referring to the compilation of each module of your project, not to the entire project at once. Each library will each be compiled, separately, and each of your modules will be compiled separately, and in each of those cases, the compiler input will consist of the module code with all of the #included files "spliced" into place, the #defined symbols and macros substituted, and comments stripped out.
The library code (the .cpp) is not #included so it does not become part of the translation unit. Only the library header file is included. That is common - and necessary - to all environments, and one of the functions of the C or C++ preprocessor. This happens for each module - separately - in a multi-module compilation. The library files will have been

With a good background in C and C++ since many years, I'm quite stunned. Are you saying that the Arduino build process concatenates all sources of a sketch into one big translation unit? Boy, I wasn't aware of this! Is this also true for default Arduino libraries, or just added libraries?

I'm not quite sure what you're trying to say here. AFAIK the ESP32 define is set by the Arduino core and/or compiler to inform the code what it's running on. That one doesn't have anything to do with the "setting" defines I was asking about.

I know that Arduino's build process concatenates all the files - is that what allows the "settings" defines to work? I'm not sure if there's a way to get this working in other environments than the Arduino IDE specifically. If this works at all, is it only in Arduino and it's fragile if you use a different IDE to code for Arduino?

@thebusybee, only the ino files in the sketch are concatenated to one cpp file, not the C, C++, S files (of course)


text:
Inconsistent behavior of include statements?
This question deals with fonts. Well, actually, singular include files with constants that form bitmap fonts or images for LCD or OLED displays, such as this one: https://github.com/ThingPulse/esp8266-oled-ssd1306/blob/master/src/OLEDDisplayFonts.h. A strangely hard to research (but common) problem occurs when anyone attempts to include one of these font files in multiple files in an application.
Even with an include-guard present, reuse of this .h file will cause strange linker errors about redefinition of a variable. It turns out that any variable actually declared in a .h file will cause it to be created multiple times in the program, and then when the different files depending on the font.h file are linked, the variables collide. An example of it would be here: https://stackoverflow.com/a/4936294/11381501, or in my very own question some time ago here: How to create large progmem arrays and not annoy the linker
The issue is, I've seen some libraries that avoid this error (such as https://github.com/ThingPulse/esp8266-oled-ssd1306/blob/master/src/OLEDDisplay.h#L64) despite having variables declared in .h files. I've even included this OLEDDisplay.h file (indirectly via the main library file for my screen) in multiple of my own .h files in one project and it hasn't caused linker errors. What causes this globally-scoped variable in a .h file to not produce linker errors when my own code usually does?

Include guards only protect against multiple inclusion within the same translation unit. Variables declared in headers like that should be static but really should be just declared in the header as extern and defined in their own separate TU.

This is how I do fonts in my display library: https://github.com/CariadDisplayLibrary/WhiteRabbit/tree/master/src

@Majenko, there is an alternative to static vs extern declaration (with definition elsewhere) in C++17 onwards, where inline may be applied to variables following a one-definition-rule scarcely different (if different at all) from inline specified functions.

@timemage There are far far too many "alternatives" in C++ nowadays. It's become a horrible tangled mess of "features"...

@Majenko Well, it's a solution that involves the insertion of a single keyword. I thought that would have been something helpful to know.

The esp8266-oled-ssd1306 has it wrong, but with examples of the library it is saved by optimization. Other files where the font gets included don't use it so it is optimized away. Otherwise it would be duplicated.
OLEDDisplayFonts.h is included in OLEDDisplay.h which is included in OLEDDisplay.cpp and in SSD1306Wire.h which is included in the sketch. This creates two instances of the variables defined in OLEDDisplayFonts.h. But the instance in OLEDDisplay.cpp is optimized away, because that file doesn't use fonts. So for the linker there is only one instance of the variable.
relevant part from .map file for the SSD1306UiDemo.ino example
 .irom.text.OLEDDisplayFonts.h.857.11
                0x000000004023b7fd     0x25ab ./SSD1306UiDemo.ino.cpp.o
 .irom.text.OLEDDisplayFonts.h.434.10
                0x000000004023dda8     0x13b9 ./SSD1306UiDemo.ino.cpp.o
 .irom.text.OLEDDisplayFonts.h.10.9
                0x000000004023f161      0xaab ./SSD1306UiDemo.ino.cpp.o
 .irom.text.OLEDDisplayFonts.h.10.9
                0x000000004023fc0c      0xaab ./libraries/esp8266-oled-ssd1306/src/OLEDDisplay.cpp.o
 .irom.text.OLEDDisplayFonts.h.10.9
                0x00000000402406c7      0xaab ./libraries/esp8266-oled-ssd1306/src/OLEDDisplayUi.cpp.o

The right way is to put variables in a cpp or c file and if they should be visible from other file, then use extern keyword in that file (usually over an included .h file) to declare that the variable exists.


text:
Working with two analog sensors, ATmega16
I want to work with two analog sensors connected to ATmega16. The first one is the temperature sensor (LM35), connected to PA0. The LED should be ON when the temperature goes high. The second one is the photo-resistor and it's connected to PA1. I want to turn the LED ON when the lighting is low.
I was looking for a solution all over the internet, but couldn't find something similar to my situation. They all just say one thing- you can't read two analog sensors at the same time.
I have this code that works just for one sensor:
#define F_CPU 1600000UL
#include <avr/io.h>

void ADC_Init() {
    DDRA = 0x0;
    ADCSRA = 0x87;
    ADMUX = 0x40;
}

uint16_t ADC_Read(uint8_t channel) {
    ADMUX = (ADMUX & 0xF0) | (channel & 0x0F);
    ADCSRA |= (1 << ADSC);
    while (ADCSRA & (1 << ADSC)) ;
    return ADC;
}

int main(void) {
    ADC_Init();
    DDRB = 0xFF;
    while (1) {
        uint8_t value;
        value = ADC_Read(0);
        if (value > 70) {
            PORTB |= (1<<0);
        } else {
            PORTB &= ~(1<<0);
        }
    }
}

Can you somehow help me to modify this code, give me advice on how can I do it, or some example?

What happens when you change ADC_Read(0) to ADC_Read(1)?

@devnull it works just for one sensor at a time. If I go with ADC_Read(1), it will work for the second sensor. I tried to adjust it using a switch loop, the first case ADC_Read(0), the second one ADC_Read(1), but it won't work.

Good. Since the MCU can't do any two things programmatically at the same time, you can read from channel 0 to one variable, read from channel 1 to another variable, than decide what to do with the LED(s) accordingly to the two values. You may also edit your question to show this second code you mentioned, since your test indicates that the hardware/ADC part is already working for the two sensors.

I reformatted the code for legibility and, while doing so, I took the liberty to add the closing brace that was missing from ADC_Init().

I’m voting to close this question because the user has not been here for over one year, so the chances of this question being accepted is very slim.

I just skimmed over the ATmega16 datasheet, so perhaps take this answer with a grain of salt.
It is technically true that you cannot read two ADC channels at the same time because there is only one ADC and you must multiplex the various channel inputs to that one ADC. You can, most likely, change the ADC source at runtime to switch between the different channels.
Take a look at the ADMUX register description in the datasheet
Right now, you set the mux once during the init() function and then never change it. In your new code, you will have to change the value in the register at runtime (in addition to any other configuration/housekeeping that is required) which should happen in your main loop()
High level description:
int main()
{
    system_init();

    while (1)
    {
        set ADMUX to read from PA0
        read ADC

        set ADMUX to read from PA1
        read ADC

        do stuff
    }

}

I understand what you mean, but if I do it in the main loop it won't run infinitely, and the channel will be changed only once. How can I constantly change between those two sensors?

@cerouno If you put the above code in your while (1) loop it will run indefinitely. I will edit the pseudocode above to show this.

If you read the datasheet carefully, you will find the fact, that you should throw out the first reading after the input switch operation.