text:
Serial available doesn't work right after upload
I have 2 programs to test serial communication, an simple arduino program that echoes whatever is on the serial port and a python program that writes to the serial port and prints the reply.
I'm having an issue where whenever I upload the arduino program and try to run the python code the arduino code wouldn't detect serial available on the first run.  I would have to either

open and close serial monitor before I run python program
run the python program, quit, and run it again

and it would continue to work until I re-upload the arduino then the same thing happens.  Does anyone know what is the issue?  This is on Ubuntu.
arduino
String str;

void setup() {
// Turn the Serial Protocol ON
  Serial.begin(115200);
}

void loop() {
  if (Serial.available()) {
      str = Serial.readStringUntil('\n');     // Read the serial input
      Serial.println(str);             // sends ascii code

  }
}

Python
import serial

ser = serial.Serial('/dev/ttyACM1', 115200)

for i in range(0,4):
    str = "test string\n"
    ser.write(str)
    print ser.readline()

Even: void setup() {                   Serial.begin(115200); Serial.println("Hello, World!"); } fails right after upload. This seems to have happened relatively recently in the development of the IDE; I've no idea why but I'd sure like to fix it.

This fails due to the typical auto-reset-on-open serial port configuration interacting with a problematic assumption made by the PC code.
The first issue means that it will typically take a few seconds between when the port is opened (unless the port is configured not to manipulate modem control signals on open) and when the usual bootloader times out, yields to the custom sketch loaded in the Arduino, and the latter becomes able to accept input and potentially respond.
The second issue is with the PC side code:
for i in range(0,4):
    str = "test string\n"
    ser.write(str)
    print ser.readline()

Assuming that import serial refers to pySerial, then because you did not specify a timeout when opening the port, the ser.readline() is an eternally blocking read.  To quote the documentation:

Be carefully when using readline(). Do specify a timeout when opening the serial port otherwise it could block forever if no newline character is received.

If we look at what happens with your python program and a typical serial port configuration where modem status lines change on open, then the first thing your program does is implicitly reset the Arduino.  Next, it writes "test string\n" - but because of the reset, it writes this at the bootloader, not the sketch which is not running yet.  Finally your program eternally waits for a newline terminated reply - which it will never receive, because your sketch will not send that until it receives something from the PC, which will not send anything else until it receives the newline terminated response to its first message.
Your programs are thus stuck in a "no, after you" deadlock.
There are many potential ways to work around this.  For example, you might open the port with a timeout, wait a few seconds, and conduct this test write and attempt to read a reasonable number of times, but declare an error to the user if success is not achieved in ten or so seconds of those attempts.
Note also that the sketch may start running midway through transmission of the test string, so you will have to handle the possibility of a message with the beginning missing, either by declaring an error or discarding it and waiting for a subsequent intact one.


text:
Code example SPI multiple slaves Arduino DUE
I'm trying to get 2 devices (camera and sd card)to work on the SPI interface with an Arduino DUE.  I'm having trouble finding example code online showing how to communicate with multiple slaves on the DUE as I know it is slightly different than with the UNO.
Questions I have include:
How do you indicate you want to talk to a slave on pin 4? Instead of digitalWrite(4,LOW) do you call SPI.begin(4)? etc..
Can someone post some example code?

Everything you need is given here - you just need to know how to put it together:

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

There are variants of all the major methods that take an extra parameter - that parameter is the first parameter in the parameter list and defines the SS Pin to use for that function.  That includes the .transfer() function.
To use it you have to begin() all the pins you want to use SPI with. Then you can use .transfer() with those pins:
void setup() {
    SPI.begin(10);
    SPI.begin(4);
}

void loop() {
    // Receive using pin 10 as SS
    byte byteFromTen = SPI.transfer(10, 0x00);
    // Transmit 123 using pin 10 as SS
    SPI.transfer(10, 123);
    // Both directions:
    byte otherByteFromTen = SPI.transfer(10, 123);

    // Receive using pin 4 as SS
    byte byteFromFour = SPI.transfer(4, 0x00);
    // Transmit 123 using pin 4 as SS
    SPI.transfer(4, 123);
    // Both directions:
    byte otherByteFromTen = SPI.transfer(4, 123);
}

Doing multi-byte transfers is slightly more complex since you don't have control over the SS pin, so you have to use yet another version of the transfer() function that tells it to "continue" the transaction:
// Receiving 3 bytes using pin 4:
byte firstByte = SPI.transfer(4, 0x00, SPI_CONTINUE);
byte secondByte = SPI.transfer(4, 0x00, SPI_CONTINUE);
byte thirdByte = SPI.transfer(4, 0x00);

Of course, mixing reading and writing is pretty much the same as usual. For instance, to read the port A values from an MCP23S17 would look like:
SPI.transfer(4, 0x41, SPI_CONTINUE); // Address 0, read bit set
SPI.transfer(4, 0x12, SPI_CONTINUE); // Select register 0x12 (GPIOA)
byte porta = SPI.transfer(4, 0x00);

The SPI_CONTINUE tells the SPI system to keep the SS pin LOW. It is only then raised once it gets a .transfer() without the SPI_CONTINUE. This is the same as the traditional way of using digitalWrite() to lower SS before the first transfer and raise it after the last transfer.

source: Stack Exchange

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

sort: votes


text:
Making a timer accurate to 1 millisecond possible? Using MAX7219 LED
I'm using the Max7219 (8 digits, 7bits) led display to try and make a timer.  I have downloaded an example code from the following site to set the led digits:
https://www.brainy-bits.com/arduino-countdown-timer-using-the-max7219-display/
However the original code simply loops as fast as possible and decriment the timer so it is not a true time.  I tried to add a 10 ms delay to make it decriment 10ms on the right most digit so the 3rd digit to the right would be seconds, however I found this to be inaccurate and taking slightly longer than 1 second .
My question is is it possible to make a timer with 1ms accuracy using led display and if so how do I do it?
/* CountDown Timer version 2 using Max7219

Created by Yvan / https://Brainy-Bits.com
This code is in the public domain...
You can: copy it, use it, modify it, share it or just plain ignore it!
Thx!

*/

#define Max7219DIN 7  // Pin 7 connected to DIN (DataIN)
#define Max7219CLK 6  // Pin 6 connected to CLK
#define Max7219CS 5   // Pin 5 connected to CS

#define Buzzer 8  // Pin 8 connected to Buzzer +positive pin
int BuzzTrigger=0;  // Variable to store buzzer trigger value

#include "LedControl.h"  // LedControl Library created by Eberhard Fahle at http://playground.arduino.cc/Main/LedControl

LedControl lc=LedControl(Max7219DIN,Max7219CLK,Max7219CS,1);   // Last number represent the number of Max7219 Modules connected

long int countnumber=24001000 ; // Countdown timer start value HH:MM:SSSS

// Variables to store individual numbers
int  firstnum=0;
int  secondnum=0;
int  thirdnum=0;
int  fournum=0;
int  fivenum=0;
int  sixnum=0;
int  sevennum=0;
int  eightnum=0;

void setup() {
    lc.shutdown(0,false);  // Wake up the display
    lc.setIntensity(0,7); // Set Brightness 0-15
    lc.clearDisplay(0);  // Clear display
    pinMode(Buzzer, OUTPUT);
    digitalWrite(Buzzer, LOW);  //Buzzer Off at startup

}

void loop() {

    for (countnumber; countnumber != -1; countnumber--) {
        String mystring = String(countnumber); // Transform Counter Int to String for manipulation

        // Convert number to a time value
        for (int z = 0; z < 6; z++) {

            if (mystring.substring(z) == "999999") {
                countnumber = (countnumber - 400000);
            }

            if (mystring.substring(z) == "9999") {
                countnumber = (countnumber - 4000);
            }
        }

        //  Display number on Display depending on number of digits remaining
        if (countnumber > 9999999) {
            firstnum = ((countnumber / 10000000) % 10);
            secondnum = countnumber / 1000000 % 10;
            thirdnum = countnumber / 100000 % 10;
            fournum = countnumber / 10000 % 10;
            fivenum = countnumber / 1000 % 10;
            sixnum = countnumber / 100 % 10;
            sevennum = countnumber / 10 % 10;
            eightnum = countnumber % 10;

            lc.setDigit(0, 7, firstnum, false);
            lc.setDigit(0, 6, secondnum, false);
            lc.setDigit(0, 5, thirdnum, false);
            lc.setDigit(0, 4, fournum, false);
            lc.setDigit(0, 3, fivenum, false);
            lc.setDigit(0, 2, sixnum, false);
            lc.setDigit(0, 1, sevennum, false);
            lc.setDigit(0, 0, eightnum, false);
            delay(10); //<<<<<<<<<<< I ADDED THIS
        } else {
            if (countnumber > 999999) {
                //      firstnum = ((countnumber/10000000)%10);
                secondnum = countnumber / 1000000 % 10;
                thirdnum = countnumber / 100000 % 10;
                fournum = countnumber / 10000 % 10;
                fivenum = countnumber / 1000 % 10;
                sixnum = countnumber / 100 % 10;
                sevennum = countnumber / 10 % 10;
                eightnum = countnumber % 10;

                lc.setChar(0, 7, '-', false);
                lc.setDigit(0, 6, secondnum, false);
                lc.setDigit(0, 5, thirdnum, false);
                lc.setDigit(0, 4, fournum, false);
                lc.setDigit(0, 3, fivenum, false);
                lc.setDigit(0, 2, sixnum, false);
                lc.setDigit(0, 1, sevennum, false);
                lc.setDigit(0, 0, eightnum, false);
                delay(10); //<<<<<<<<<<< I ADDED THIS
            } else {
                if (countnumber > 99999) {
                    //          firstnum = ((countnumber/10000000)%10);
                    //          secondnum = countnumber/1000000%10;
                    thirdnum = countnumber / 100000 % 10;
                    fournum = countnumber / 10000 % 10;
                    fivenum = countnumber / 1000 % 10;
                    sixnum = countnumber / 100 % 10;
                    sevennum = countnumber / 10 % 10;
                    eightnum = countnumber % 10;

                    lc.setChar(0, 7, '-', false);
                    lc.setChar(0, 6, '-', false);
                    lc.setDigit(0, 5, thirdnum, false);
                    lc.setDigit(0, 4, fournum, false);
                    lc.setDigit(0, 3, fivenum, false);
                    lc.setDigit(0, 2, sixnum, false);
                    lc.setDigit(0, 1, sevennum, false);
                    lc.setDigit(0, 0, eightnum, false);
                    delay(10); //<<<<<<<<<<< I ADDED THIS
                } else {
                    if (countnumber > 9999) {
                        //             firstnum = ((countnumber/10000000)%10);
                        //             secondnum = countnumber/1000000%10;
                        //             thirdnum = countnumber/100000%10;
                        fournum = countnumber / 10000 % 10;
                        fivenum = countnumber / 1000 % 10;
                        sixnum = countnumber / 100 % 10;
                        sevennum = countnumber / 10 % 10;
                        eightnum = countnumber % 10;

                        lc.setChar(0, 7, '-', false);
                        lc.setChar(0, 6, '-', false);
                        lc.setChar(0, 5, '-', false);
                        lc.setDigit(0, 4, fournum, false);
                        lc.setDigit(0, 3, fivenum, false);
                        lc.setDigit(0, 2, sixnum, false);
                        lc.setDigit(0, 1, sevennum, false);
                        lc.setDigit(0, 0, eightnum, false);
                        delay(10);//<<<<<<<<<<< I ADDED THIS
                    } else {
                        if (countnumber > 999) {
                            //              firstnum = ((countnumber/10000000)%10);
                            //              secondnum = countnumber/1000000%10;
                            //              thirdnum = countnumber/100000%10;
                            //              fournum = countnumber/10000%10;
                            fivenum = countnumber / 1000 % 10;
                            sixnum = countnumber / 100 % 10;
                            sevennum = countnumber / 10 % 10;
                            eightnum = countnumber % 10;

                            lc.setChar(0, 7, '-', false);
                            lc.setChar(0, 6, '-', false);
                            lc.setChar(0, 5, '-', false);
                            lc.setChar(0, 4, '-', false);
                            lc.setDigit(0, 3, fivenum, false);
                            lc.setDigit(0, 2, sixnum, false);
                            lc.setDigit(0, 1, sevennum, false);
                            lc.setDigit(0, 0, eightnum, false);
                            delay(10);//<<<<<<<<<<< I ADDED THIS
                        } else {
                            //              firstnum = ((countnumber/10000000)%10);
                            //              secondnum = countnumber/1000000%10;
                            //              thirdnum = countnumber/100000%10;
                            //              fournum = countnumber/10000%10;
                            //              fivenum = countnumber/1000%10;
                            sixnum = countnumber / 100 % 10;
                            sevennum = countnumber / 10 % 10;
                            eightnum = countnumber % 10;
a
                            lc.setChar(0, 7, '-', false);
                            lc.setChar(0, 6, '-', false);
                            lc.setChar(0, 5, '-', false);
                            lc.setChar(0, 4, '-', false);
                            lc.setChar(0, 3, '-', false);
                            lc.setDigit(0, 2, sixnum, false);
                            lc.setDigit(0, 1, sevennum, false);
                            lc.setDigit(0, 0, eightnum, false);
                            delay(10);//<<<<<<<<<<< I ADDED THIS
                        }

                    }
                }
            }
        }

    }
}

new implementation using millis
#define Max7219DIN 7  // Pin 7 connected to DIN (DataIN)
#define Max7219CLK 6  // Pin 6 connected to CLK
#define Max7219CS 5   // Pin 5 connected to CS

#include "LedControl.h"  // LedControl Library created by Eberhard Fahle at http://playground.arduino.cc/Main/LedControl

LedControl lc=LedControl(Max7219DIN,Max7219CLK,Max7219CS,1);   // Last number represent the number of Max7219 Modules connected

unsigned long countnumber;

// Variables to store individual numbers
int  firstnum=0;
int  secondnum=0;
int  thirdnum=0;
int  fournum=0;
int  fivenum=0;
int  sixnum=0;
int  sevennum=0;
int  eightnum=0;

void setup() {
  lc.shutdown(0,false);  // Wake up the display
  lc.setIntensity(0,7); // Set Brightness 0-15
  lc.clearDisplay(0);  // Clear display
  Serial.begin(9600);
}

void loop() {

  countnumber = millis();

  firstnum = countnumber / 10000000 % 10;
  secondnum = countnumber / 1000000 % 10;
  thirdnum = countnumber / 100000 % 10;
  fournum = countnumber / 10000 % 10;
  fivenum = countnumber / 1000 % 10;
  sixnum = countnumber / 100 % 10;
  sevennum = countnumber / 10 % 10;
  eightnum = countnumber % 10;

  lc.setDigit(0, 7, firstnum, false);
  lc.setDigit(0, 6, secondnum, false);
  lc.setDigit(0, 5, thirdnum, false);
  lc.setDigit(0, 4, fournum, false);
  lc.setDigit(0, 3, fivenum, false);
  lc.setDigit(0, 2, sixnum, false);
  lc.setDigit(0, 1, sevennum, false);
  lc.setDigit(0, 0, eightnum, false);

}

You code also takes some time to execute. So your loop takes 10ms, plus the time the code takes. To make it 10ms independent of the amount of code, you store the value of millis() at the beginning of the loop, and them at the end of the loop, wait till the difference between millis() and the stored millis value is greater that, or equal to 10.

Requiring “1 ms accuracy” doesn't make any sense if you don't specify over what time span you want that accuracy. Getting 1 ms accuracy is trivial if you are measuring a 100 ms time interval. It is far from trivial if you are measuring a 1 year interval. The accuracy you can get on an Arduino out of the box depends on the measured interval, on whether your Arduino has a crystal or a resonator, and on whether you are willing to calibrate it. Please read http://jorisvr.nl/article/arduino-frequency to get a general idea on what “accuracy” can mean in respect to Arduino timing.

@EdgarBonet what about over 5min trivial or no?

1 ms ÷ 5 min = 3.33 ppm. Not trivial but doable. You won't get that accuracy out of the Arduino's internal clock unless it is a crystal and you calibrate it against a reliable reference. Easiest solution would probably be using a high accuracy RTC, like the DS3231, which integrates a temperature-compensated crystal oscillator (TCXO). The ubiquitous DS1307 will likely not be accurate enough. Use either the 32kHz or the SQW output and one of your MCU's counters. Please, tag your question with the type of Arduino you are using.

You generally cannot rely on a processor for correct time keeping without a real time clock somewhere in your circuit.  However, the best way of doing things at certain times, is to call millis() which will return the number of milliseconds since the program started.  With that number you can determine how long something has taken (eg. 1 second) and then do something in response.  You can, for example, print out how long your loop is taking by setting a long integer to millis() at the start of the sketch and then subtracting it from mills() at the end of the loop and printing out the result.
void loop() {
   long start_time = millis();
   delay(500);
   long end_time = mills();
   Serial.println(end_time - start_time);
}

What do you rekon is the accuracy without real time clock? within 20ms?

From this article I understand that millis is incremented each 1.024ms, but if the error approaches 1ms then value is automatically corrected. Therefore in span of 20 ms error could accumulate to be close to half of a millisecond.

@bakalolo Try micros()?

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


text:
CJMCU-116 9DOF mpu9250 driver

I've recently bought a CJMCU-116 sensor equipped with MPU9250. It features magnetometer, accelerometer and gyroscope. It uses I2C for communication.
I've scouted everywhere but I could not find any library to make it work properly, just one that seems to work but I'm not 100% sure.
Can someone point me to the right direction, please?
 I'm using this library
found here. I know this is not the same sensor but the chip is the same, so it should work, am I right?

"Seems to work" but you're not sure...? Either it works or it doesn't. Which is it?

It reads values but sometimes suddenly stop working, even though everything is connected. I've updated the question with the links to the libraries.

The make and model number of the sensor is of no importance. It's just a PCB to hold the chip and power circuitry. Maybe it's your wiring. I2C can be iffy and lock up with loose connections.

So it's enough to get a driver for the MPU9250 regardless the sensor?

Yep. It's the chip you're communicating with, not the board.

Well, I suppose this would be of great help, thank you, I'll keep you posted!

If you use a 5V Arduino board without level shifter for the I2C, then the MPU-9250 might have been damaged by now. The Sparkfun library was the first thing that came to my mind. You can use that library. How long are the I2C wires ? what kind of cable do you use for I2C ? Use seperate wires without cable and a maximum of 50 cm for the I2C.

I'm using 20cm jumper wires male/female and I'm powering the sensor with 3.3v. Why do you think it could have been damaged?

I'm voting to close this question as off-topic because it seeks to find an external resource in the form of a library.

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


text:
Can I connect a camera without a shield?
I have an Arduino Uno and an ArduCAM-mini 2MP camera:
http://www.arducam.com/tag/arducam-mini/
Is it possible to connect this camera, or similar cameras, to the arduino without a shield?  The only tutorials I've found use a shield.
edit - here is what my cam looks like:

The first picture on that page shows it connected without a shield.

I see the photo, but with no supporting information I won't get far.  It looks like the vcc and gnd pins from the camera are connected to the wires.  It wasn't clear to me that I should bend the camera pins as such (mine has 8 pins pointing downward).  Sorry, complete novice.  Any help is appreciated.

Hey! This looks like an awesome piece of hardware! It can definitely work without a shield since it communicates using the SPI interface which the arduino can handle.... I might be able to help you further if you take a picture of the labels on it :p (i can't find a decent one :/)

Judging by the photo (below) it is specifically designed to plug into the SPI ports on a Uno or similar (that is, pins 10 to 13). The other two wires are going to the ICSP header, presumably to pick up +5V and ground.

So yes, most certainly you can use it like that. With the pins done like that it even points horizontally.

It wasn't clear to me that I should bend the camera pins as such (mine has 8 pins pointing downward).

You can buy pins with a 90° angle. If yours are not already soldered on, I would use the bent connector. If the pins are already soldered on, then the camera would lie flat, so just rotate the Arduino itself to point to where you want it to.
However you would need to do something with the +5V and Gnd pins, so that they can be rerouted to the correct place.

Looking at another photo on that site.

The pins would match most of the pins on a Uno, like this:

The only one that is wrong is AREF - you need +5V into that pin, not AREF, which is why they bent those two pins outwards (+5V and Gnd) and ran wires to the ICSP header.

If you mean all your pins are at right-angles already, then you really only need to fix the +5V one (you can probably bend it up). This is the pin-out for the ICSP header (view from above):

As you can see, you can pick up +5V from pin 2 (Vcc). Alternatively, run the +5 wire over to where +5 is marked on the Uno on the other side.

Another possible approach would be to not bend anything, but solder on a wire to the +5V pin and leave it plugged into AREF. AREF is just an input (analog reference voltage) and it won't hurt to have it left at +5V.

Note that some people choose to just connect 5V direct to the AREF pin since connecting 5V to AREF is perfectly valid (though pretty pointless) so you then don't need to bend any pins.  See this other recent question pertaining to a similar device: http://arduino.stackexchange.com/questions/24528/what-is-vref-pin

Yep, I realized that and made yet another edit. Nice to know I wasn't the only one with that idea. :)

authors: طالبة الغفران


text:
Which relay should I use to control the power from mains?
I was making a home automation project in which I want to control appliances like a fan and a bulb through voice commands with the help of an arduino uno and a relay but I am confused which relay to use. Please tell me the specifications of a 4 channel relay fit for this project.

Do you want to control a mains powered fan and light? Please let us know. (For educational experiments something battery powered would be much safer.)

@Andy yes I want to control mains powered fan and light but first I will test the circuit with some leds and a dc motor

There are two factors you need to consider when choosing a relay:

Can it power the devices I want it to power without the contacts melting?
Can I control it?

The first one is simple enough. Find out the current requirements for each of the devices and add them together. Make sure that the relay is capable of switching at least that much at the AC voltage of your country's mains supply.  If in doubt go slightly higher.
For the second point you need to consider the interfacing circuitry and what DC power supply you are using in your system. For instance, if you have a 12V power supply for the Arduino you might consider a 12V coil relay and use the 12V power as the switching power. If you are running from 9V then you might consider a 5V relay and use the Arduino's regulated 5V pin as the switching power source. Either way you need a driving circuit. That could be as simple as an NPN transistor, two resistors, and a diode (the circuit can be found throughout the web if you Google "Arduino Relay"), or more complex involving an opto-isolator.
The simplest solution is to find an all-in-one module - a relay with driver circuit all as a single product. There are many of these around directly targeted at the Arduino, and most are the slightly more complex (and thus better) opto-isolator driving circuit. You still have to consider the same two points - switching capacity and coil voltage - but you don't then need to worry about making your own driving circuit for them.

Your 2 factors omit the most important issues - is it safe and do I have the knowledge to work with potentially lethal mains power.

Well, yes there are those factors as well, however Natural Selection is no bad thing...

@Majenko will the power to be supplied to arduino depend on the power requirements of the appliances to be controlled. I guess it would be best if I will be able to control the relay with arduino's 5 V supply.

@Jasmeetsingh No, the power provided to the Arduino has nothing at all to do with the devices being controlled.

@Majenko So if I use 9 V supply for the arduino is there any chance that the board will malfunction or get hot?

@Jasmeetsingh Possible - it depends what you have connected to the Arduino. 9V is within the specifications of the board, so chances are it will be fine, but I am not psychic and don't know what you are thinking of connecting to your Arduino.

In the US there is a set of products - plug-in modules - collectively known as X10, which uses signals sent over the house wiring to control devices elsewhere in the house. If they are available where you are, this is the safest way to control mains-powered devices with an Arduino because the Arduino needs no connection to the house wiring.
The Wireless Transceiver module receive X10 commands over RF and transmit them onto the power wiring. Using this and a small RF transmitter known here as "X10 Firecracker CM17A", your Arduino can be completely isolated from the house wiring, sending its control commands over the air instead. Amazon shows both products on this page; the CM17A (which you use by removing its circuit board from the plastic package), and the RF control module, of which you only need one. The transceiver module can directly control one fan or light; for additional devices you'd use any other, non-RF (read "less expensive") X10 module, which will "hear" whatever the transceiver module sends.
There is an Arduino library already written for X10 communication.


text:
is there any archives of melody tones for buzzer used in arduino?
I am using buzzer in my arduino and I read some articles about using array of tones(notes in music) with different frequencies to play play pleasant melodies.however, I do not find any site and archives for tones used in industrial, such as Start,Stop,warning,danger,next level,.... is there any site that collects these things and if not how can I create my own array of tones?
this is notes I have
#define NOTE_B0  31
#define NOTE_C1  33
#define NOTE_CS1 35
#define NOTE_D1  37
#define NOTE_DS1 39
#define NOTE_E1  41
#define NOTE_F1  44
#define NOTE_FS1 46
#define NOTE_G1  49
#define NOTE_GS1 52
#define NOTE_A1  55
#define NOTE_AS1 58
#define NOTE_B1  62
#define NOTE_C2  65
#define NOTE_CS2 69
#define NOTE_D2  73
#define NOTE_DS2 78
#define NOTE_E2  82
#define NOTE_F2  87
#define NOTE_FS2 93
#define NOTE_G2  98
#define NOTE_GS2 104
#define NOTE_A2  110
#define NOTE_AS2 117
#define NOTE_B2  123
#define NOTE_C3  131
#define NOTE_CS3 139
#define NOTE_D3  147
#define NOTE_DS3 156
#define NOTE_E3  165
#define NOTE_F3  175
#define NOTE_FS3 185
#define NOTE_G3  196
#define NOTE_GS3 208
#define NOTE_A3  220
#define NOTE_AS3 233
#define NOTE_B3  247
#define NOTE_C4  262
#define NOTE_CS4 277
#define NOTE_D4  294
#define NOTE_DS4 311
#define NOTE_E4  330
#define NOTE_F4  349
#define NOTE_FS4 370
#define NOTE_G4  392
#define NOTE_GS4 415
#define NOTE_A4  440
#define NOTE_AS4 466
#define NOTE_B4  494
#define NOTE_C5  523
#define NOTE_CS5 554
#define NOTE_D5  587
#define NOTE_DS5 622
#define NOTE_E5  659
#define NOTE_F5  698
#define NOTE_FS5 740
#define NOTE_G5  784
#define NOTE_GS5 831
#define NOTE_A5  880
#define NOTE_AS5 932
#define NOTE_B5  988
#define NOTE_C6  1047
#define NOTE_CS6 1109
#define NOTE_D6  1175
#define NOTE_DS6 1245
#define NOTE_E6  1319
#define NOTE_F6  1397
#define NOTE_FS6 1480
#define NOTE_G6  1568
#define NOTE_GS6 1661
#define NOTE_A6  1760
#define NOTE_AS6 1865
#define NOTE_B6  1976
#define NOTE_C7  2093
#define NOTE_CS7 2217
#define NOTE_D7  2349
#define NOTE_DS7 2489
#define NOTE_E7  2637
#define NOTE_F7  2794
#define NOTE_FS7 2960
#define NOTE_G7  3136
#define NOTE_GS7 3322
#define NOTE_A7  3520
#define NOTE_AS7 3729
#define NOTE_B7  3951
#define NOTE_C8  4186
#define NOTE_CS8 4435
#define NOTE_D8  4699
#define NOTE_DS8 4978
#define REST      0

// DURATION OF THE NOTES
#define BPM 480      //you can change this value changing all the others
#define H 2*Q //half 2/4
#define Q 6000U/BPM //quarter 1/4
#define E Q/2   //eighth 1/8
#define S Q/4 // sixteenth 1/16
#define W 4*Q // whole 4/4

There certainly wouldn't be a website that collects Arduino tone arrays. There may be examples around, but no one would collect the arrays together in one place - pretty pointless and obscure.  If you want to map the different musical notes to the actual frequencies then the examples in the IDE have "pitches.h" that contain macros that map the notes for you so you don't need to find out all the frequencies. Then it's just a matter of getting all the right notes in the right order with the right delays. How you implement that is up to you.

I already said that I need industrial notes. I have pitches.h and I need a site to that have a collection of melodies to choose. something to create different melodies for different situation.

There's plenty of places with sound samples of industrial situations - but you would have to transcribe those to individual notes for playing, which you'd need to do by hand.  Most "industrial" systems use sirens and klaxons with predefined tones built in.

not industrial by put the link here https://github.com/robsoncouto/arduino-songs and https://codebender.cc/sketch:238461#Songs%20on%20Piezo.ino

you don't really want to use pleasant melodies in an industrial setting

@jsotola,yeah I don't intend to put Super-mario melody . actually I need 2 or 3 Notes for a specific beep.

@david Could you further define what you mean by "industrial notes"? A "tone" and a "melody" are two different thinks, so I wonder whether you're looking for a song or a certain sound... btw, are you firm with how music "works"?

@SimSon I am not a musician everything I know are from articles I read and they may be incorrect but a "tone" is proportional to a frequency and declared by a Note. a melody is a train of tones. My definition of "Industrial Notes" is single or array of multiple tones that can be heard from an industrial device. for example warning signals is a repeatition of a single tone + no tone or if you might hear a beep in an elavator when it changes a level

Do you know tone()? (https://www.arduino.cc/reference/en/language/functions/advanced-io/tone/). With this you can generate a tone, but composing a melody for start,stop,... is up to you.

maybe this may help you ... https://onlinesequencer.net/

try a sequence C5, E5, G5, C6

@jsotola thanks It was very Helpful,however I have to first set it to 8 bit square wave to get a real buzzer sound

see the toneMelody example in Arduino IDE. or try this sketch https://arduino.stackexchange.com/questions/48166/how-to-loop-a-specific-tone/48173#48173

or use this library https://github.com/evert-arias/EasyBuzzer

@Juraj, Thanks ,It was helpful

#define NOTE_C4  262
#define NOTE_CS4 277
#define NOTE_D4  294
#define NOTE_DS4 311
#define NOTE_E4  330
#define NOTE_F4  349
#define NOTE_FS4 370
#define NOTE_G4  392
#define NOTE_GS4 415
#define NOTE_A4  440
#define NOTE_AS4 466
#define NOTE_B4  494
#define REST      0

int piezoPin = 13;
int numTones = 15;
int tempo = 2.5;

//Twinkle Twinkle Little Star:

int tones[] = {NOTE_C4, NOTE_C4, NOTE_G4, NOTE_G4, NOTE_A4, NOTE_A4, NOTE_G4, NOTE_F4, NOTE_F4, NOTE_E4, NOTE_E4, NOTE_D4, NOTE_D4, NOTE_C4, REST};

int duration[] = {500, 500, 500, 500, 500, 500, 1000, 500, 500, 500, 500, 500, 500, 1000, 4000};

void setup()
{
  for (int i = 0; i < numTones; i++)
  {
    tone(piezoPin, tones[i], duration[i] / tempo);
    delay(duration[i] / tempo);
  }
  noTone(piezoPin);
}

void loop()
{
} // Reset to play the song again

Twinkle twinkle.  Very industrial.

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


text:
Issue with IF statement condition
I am using 2 accelerometers connected to an arduino. The code below does not work.
> if((acc1 >= 20 && acc1 <= 40) && (acc2 >= 20 && acc2 <=40)) //If acc1 is between 20 and 40 AND if acc2 is between 20 and 40
>     {
>         digitalWrite(13, HIGH);
>     }

But, the following code does:
> if((acc1 >= 20 && acc1 <= 40)) //If acc1 is between 20 and 40
>     {
>         digitalWrite(13, HIGH);
>     }

Can anyone tell me why please?
Edit with full code:
const int acc1_xPin = 0; //X Pin on acc1
const int acc1_yPin = 1; //Y Pin on acc1
const int acc2_xPin = 2; //X Pin on acc2
const int acc2_yPin = 3; //Y Pin on acc2

int xAcc1_maxVal = 409; //Maximum value for X-axis Acc1
int xAcc1_minVal = 269; //Minimum value for X-axis Acc1
int yAcc1_maxVal = 410; //Maximum value for Y-axis Acc1
int yAcc1_minVal = 270; //Minimum value for Y-axis Acc1

int xAcc2_maxVal = 411; //Maximum value for X-axis Acc2
int xAcc2_minVal = 268; //Minimum value for X-axis Acc2
int yAcc2_maxVal = 402; //Maximum value for Y-axis Acc2
int yAcc2_minVal = 263; //Minimum value for Y-axis Acc2

//Hold Calculated Values
double acc1; //acc1 angle
double acc2; //acc2 angle

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

// the loop function runs over and over again forever
void loop() {

  int acc1_xRead = analogRead(acc1_xPin); //acc1 X-axis
  int acc1_yRead = analogRead(acc1_yPin); //acc1 Y-axis
  int acc2_xRead = analogRead(acc2_xPin); //acc2 X-axis
  int acc2_yRead = analogRead(acc2_yPin); //acc2 Y-axis

  //convert read values to degrees -90 to 90 - Needed for atan2
  int acc1_xAng = map(acc1_xRead, xAcc1_minVal, xAcc1_maxVal, -90, 90);
  int acc1_yAng = map(acc1_yRead, yAcc1_minVal, yAcc1_maxVal, -90, 90);
  int acc2_xAng = map(acc2_xRead, xAcc2_minVal, xAcc2_maxVal, -90, 90);
  int acc2_yAng = map(acc2_yRead, yAcc2_minVal, yAcc2_maxVal, -90, 90);

  //Caculate 360deg values like so: atan2(-yAng, -zAng)
  //atan2 outputs the value of -π to π (radians)
  //We are then converting the radians to degrees
  acc1 = RAD_TO_DEG * (atan2(-acc1_yAng, -acc1_xAng) + PI); //acc1 in degrees
  acc2 = RAD_TO_DEG * (atan2(-acc2_yAng, acc2_xAng) + PI); //acc2 in degrees

  if((acc1 >= 20 && acc1 <= 40) && (acc2 >= 20 && acc2 <= 40))
  {
    digitalWrite(13, HIGH);
    Serial.println("HIGH");
  }
  else if ((acc1 >= 41 && acc1 <= 60) && (acc2 >= 41 && acc2 <= 60))
  {
    digitalWrite(13, LOW);
    Serial.println("LOW");
  }

  Serial.print("Acc1: ");
  Serial.print(acc1);
  Serial.print(" Acc2: ");
  Serial.print(acc2);
  delay(1000);

}

I'd really appreciate any input as to way the if statements are not working when I have 2 conditions in them but will work when I have 1 condition.
Edit:
I have corrected the typos in the code. My laptop gave up on me last night so I had to retype the code on a friends laptop, hence the typos and why I didn't post the whole code initially.
The IF statements still don't work as stated above when the 2 conditions are in the IF statements together, but when I only put 1 condition in, it works fine.

Because acc2 is never between 20 and 40 at the same time that acc1 is?

@Majenko That makes no sense. They are 2 separate sensors so why can't they be between 20 and 40 at the same time?

I don't know. Maybe something else in your program, or in your setup, is stopping them being both between 20 and 40 at the same time.

I have also put in code to check their values outside the if statement and they are between those values at the same time. I am not getting any errors when I use either if statement

Please post your entire code and a description or schematic of your setup. At the moment all we can do is wildly stab in the dark which is of no use to anyone.

Why test: acc2 >= 41 && acc2 >= 60 ? Surely testing for >= 60 would do? Because that is also >= 41.

I actually got it working. I added extra brackets to it. Eg: if(((acc1 >= 20) && (acc1 <= 40)) && ((acc2 >= 20) && (acc2 >= 40))) this seems to have worked. Thanks for your help

I think this is your problem (from the full code snapshot)
(acc2 >= 20 && acc2 >= 40))

I believe it should be (like your first snapshot)
(acc2 >= 20 && acc2 <= 40))

Note that the first is greater than or equal to 40 rather than less than or equal to. Also note you've done this when determining whether or not acc2 is between 41 and 60 in the else if part of that same if statement.
I have no idea why the code differs between your first and third snapshot. Potentially you have spotted this already and failed to update the full code being run?

I have corrected the typos in the code. My laptop gave up on me last night so I had to retype the code on a friends laptop, hence the typos and why I didn't post the whole code initially. The IF statements still don't work as stated above when the 2 conditions are in the IF statements together, but when I only put 1 condition in, it works fine.

Can you tell us what the values of acc1 and acc2 are when you are testing? They aren't negative? Can you also elaborate on what you mean by not working, I assume you just never see the LED on pin 13 be driven high? Maybe put some serial output inside the if statements too to rule out any possible hardware gremlins

When testing if Acc1 and Acc2 are between the values at the same time, I have put in Serial.println("HIGH") and Serial.println("LOW") within the IF statements but they are not coming up on the serial monitor when the 2 conditions are within the IF statements. So if I have (acc1 >= 20 && acc1>= 40) within the If statement it will work but if I have ((acc1 >= 20 && acc1>= 40)&&(acc2 >= 20 && acc2>= 40)) within the statement, the serial monitor just shows the values and 'HIGH' or 'LOW' does not appear even though I can see both acc1 and acc2 are within the values at the same time

The code you have sent in your comment
((acc1 >= 20 && acc1>= 40)&&(acc2 >= 20 && acc2>= 40))
is wrong. This will only execute when both are above 40 not in between the 20 and 40.
Can you update your code in the OP to represent what you are actually running.

Sorry, it should b: ((acc1 >= 20 && acc1<= 40)&&(acc2 >= 20 && acc2<= 40)) and the other one should be (acc1 >= 20 && acc1<= 40). I actually have it correct in the code in the main question.

Your code has the following lines:
acc2 = RAD_TO_DEG * (atan2(-acc1_yAng, -acc1_xAng) + PI); //acc1 in degrees
acc2 = RAD_TO_DEG * (atan2(-acc2_yAng, acc2_xAng) + PI); //acc2 in degrees

If I'm going to believe the comments, the first line should start:
acc1 = ...

That doesn't fully explain: they are between those values at the same time.

Agreed - but it can't help! If acc1 meets the criteria when it isn't even initialised, then the formula could be wrong for both. He might see the arm with those angles, but maybe it comes out negative in the formula or something

It's odd that his full code is nothing like the snippets in the original question. :)

I have corrected the typos in the code. My laptop gave up on me last night so I had to retype the code on a friends laptop, hence the typos and why I didn't post the whole code initially. The IF statements still don't work as stated above when the 2 conditions are in the IF statements together, but when I only put 1 condition in, it works fine.


text:
How can I calculate remaining battery life time with arduino
I want to display a 3.7V battery's remaining life time on LCD screen using arduino. Like a laptop does. 1h 23m remaining or others. Do I need any kind of module to measure the thing? Can anyone tell the method please?

you may use ADC(analogRead) to measure Li-Ion Cell voltage. unlike Ni-Cd or Ni-Mh batteries, a Li-Ion Cell Voltage is a good measure for battery status. the discharge cycle of an usual Li-Ion cell Starts at 4.2v(full charged, better avoid that!) which quickly comes down to 3.7v. it remains about 3.7 volts most of the cycle and at the end, comes down again to about 2v which battery protector circuit cuts battery off circuit.
but if the Arduino itself is powered from li-ion battery, it can't measure the battery voltage as the ADC Reference is the current varying cell voltage itself. in this case you need to set VREF of Arduino to a lower internal constant reference(1.1v):
https://www.arduino.cc/reference/en/language/functions/analog-io/analogreference/
and implement a voltage divider

simulate this circuit – Schematic created using CircuitLab
now you can measure cell voltage compared to a fixed reference. a full battery of 4.2 will be read in ADC as about 1000 (4.2* (1/1+3.3) * 1024). 3.7 should be read about 880 and 2.2v (if the Arduino is still ON!) will be read 500 in ADC unit.

Note that the discharge curve of a lithium battery isn't linear. So you'd have to do some additional math to convert the battery voltage to a percentage-of-charge. Also, don't discharge a battery to as low as 2.2V, as that will degrade the battery.

but sir this is the method for getting the battery voltage I guess... I need to print the remaining time of the battery life...

@Shojib the cell voltage for "Lithium" cells is a good representation of the battery status.(unlike NiMH) many applications like mobile phones use this method of calculation.


text:
missing /dev/ttyACM* on Ubuntu
I installed the Arduino IDE according to the arduino.cc instructions (invoking install.sh) rather than sudo apt install .... The ports /dev/ttyACM* were present when the following Linux command is issued.
ls -l /dev/ttyACM*
This shows that the devices have membership in the dialout group. It is necessary to add myself as a user to the group dialout.
sudo usermod -a -G dialout <username>
I selected the board and the port and did a download which eventually completed but it seemed to take a long time. The program probably wasn't working since the program was to flash an LED at a 2 second period but the flash rate was definitely much faster so it seems the download did not work.
I deleted the IDE and reinstalled and the ports disappeared.
I have applied this fix for using the Arduino IDE on Linux.
From the description of the fix the instruction is to issue the following commands:
wget https://github.com/adafruit/Trinket_Arduino_Linux/raw/master/99-adafruit-boards.rules

sudo cp 99-adafruit-boards.rules /etc/udev/rules.d/

Next reboot Linux.
According to this page on Arduino for Linux there ought to be some devices at /dev/ttyACM* but mine are missing. What is the solution to this problem? I have replaced the USB cable and it makes no difference.
The board is Adafruit Feather 32u4 which has an ATmega32u4. The OS is Ubuntu 16.04.

what board? and more important what chip for USB?

@Juraj The ATmega32u4 has built-in USB.

try this docs https://learn.adafruit.com/adafruit-feather-32u4-adalogger/faq

@abu-ahmedal-khatiri you should post that as an answer. I don't know what fixed it but that link did suggest a double click might be necessary. I don't know the click rate on a double click for this board but eventually it worked.

i will help you but i don't have Feather board to try that docs, did you check your list ports with type ll /dev/tty*  what appears as ttyACM* or ttyUSB*

let i see what the output of dmesg | grep udev

did you try sudo systemctl restart ModemManager.service and check again with sudo lsof | grep ACM?

If the Arduino IDE does not show the port or does not allow you to select the port, load a known to be working program (such as Example > Blink), start a download, and then double-click the board's reset button.
For the same advice plus extraneous information view this help page on the particular Feather, the 32u4 micro-controller board, which seems to suggest the use of a verbose download mode but that seems to be unnecessary because you can just try again if it failed. The verbose download mode is enabled in preferences. Even though it is unnecessary I eventually decided to always use the verbose download mode because it gives what appears, to me at least, more immediate and obvious feedback about success and failure.

it same purpose that speeded up of @Majenko and Juraj.

/dev/ttyACM* mine are missing.

I think that something udev rules issue, you can define another rules with add Feather32u4.rules and remove 99-adafruit-boards.rules file before.
SUBSYSTEM=="usb", ATTRS{idProduct}=="0c9f", ATTRS{idVendor}=="1781", MODE="0660", GROUP="dialout"
ATTRS{idVendor}=="239a", ENV{ID_MM_DEVICE_IGNORE}="0"
ATTRS{idVendor}=="239a", MODE="0660", GROUP="dialout"
SUBSYSTEM=="tty", ATTRS{idProduct}=="8011", ATTRS{idVendor}=="239a", MODE="0660", GROUP="dialout"
SUBSYSTEM=="tty", ATTRS{idProduct}=="0011", ATTRS{idVendor}=="239a", MODE="0660", GROUP="dialout"

after saved and copy your files to /etc/udev/rules.d/
sudo cp Feather32u4.rules /etc/udev/rules.d/

and then restart your udev
sudo reload udev

or,
sudo udevadm control --reload-rules
sudo udevadm trigger

don't forget to restart your service
sudo systemctl restart ModemManager.service

check again your port with following ll /dev/tty*, if it appear with named /dev/ttyUSBx or /dev/ttyACMx add a user to your group
sudo usermod -a -G plugdev <user>

also try to automatically reset button with add a delay into your sketch
while(!Serial){
  delay(1000);
}
Serial.begin(115200);

if it not showed port on /dev/tty list, try

Enabled verbose upload in the Arduino Preferences.
Open the Blink example.
and add automatically reset above.

that will showed as the Bootloader COM/Serial Port with bootloading mode.
If didn't work, i advice install driver on Adafruit_Driver Windows only using Wine or PlayOnLinux, and remove udev files. also check again your /dev/tty* list.
Hope this helps.

According to this page on Arduino for Linux there ought to be some devices at /dev/ttyACM*

That is not the case. On a "traditional" Arduino board, like the Uno, you have two chips: the main MCU which you program, and a USB interface chip, which is pre-programmed with code to present a CDC/ACM interface to the computer (which it then creates a /dev/ttyACMx device for).
With the feather you don't have that. You have one single chip. That chip is both the USB interface and the chip that you program - and most importantly, it is your program that provides the CDC/ACM device if you choose. If your program doesn't provide a CDC/ACM device then the computer will never see one, so it will never create /dev/ttyACMx.
In general the Arduino core always adds a CDC/ACM device whether or not you ask for it, since it is often used to initiate a reset into the bootloader. However if your sketch stops working for whatever reason then the CDC/ACM port is no longer there.
The M0 on the feather has a neat trick though - if you reset the board with the reset button twice the startup code recognises that fact and forces it to run the bootloader. That bootloader then presents the needed CDC/ACM device to the computer allowing you to upload new code.
Of course, if your program that you upload then doesn't initialise its own CDC/ACM device, or crashes, the CDC/ACM device will not be presented until you do the double-reset trick again.

doesn't he have a Micro clone? I know the double click trick for M0, but does it work for Micro?

I read the comments. Looks to me like he's talking about the feather.

at Adafruit half of the products are feathers :-)

@Juraj Also the double click thing worked, according to the comments. So the double click thing is the answer. Which means it must logically be an M0 feather.

that is what I have a problem with. the Adafruit FAQ for the 32u4 feather recommends the double click. Do they have a different bootloader or Micro bootloader has the double click too? or is the FAQ copypasted from M0 FAQ and a simple reset worked for OP?

@Juraj Who knows what goes through the mind of an Adafruit designer...?  I mean, why create the feathers at all? ;)

Do you know if the Arduino Micro has the double click trick?

@Juraj No idea. I never use AVR chips if I can help it...

The example Blink program can accept a download even though it seems there is no code related to that. void setup() { pinMode(LED_BUILTIN, OUTPUT); } void loop() { digitalWrite(LED_BUILTIN, HIGH); delay(1000); digitalWrite(LED_BUILTIN, LOW); delay(1000); }

Hence the 4th paragraph of my answer...

So I tried EVERYTHING... turns out my USB cable was a cheaper cable that didn't have the data pins in it. It is worth making sure your cable supports data transfer by plugging it into something else to make sure it w

ttyACM* didn't show up on my /dev/ also, but as soon as I changed the USB port I was working with, the arduino board started blinking differently. So I checked the IDE again and under Tools > port > Serial Port I saw ttyACM0 came up. Didn't make sense to me but it worked.

For my situation, where I'm using a custom Linux kernel, I was missing the cdc_acm driver.
This excellent page on the Gentoo Wiki helped me find it:
https://wiki.gentoo.org/wiki/Arduino


text:
backup battery for FeatherWing DS3231, RTC
I am working with slightly modified example code for the Adafruit FeatherWing DS3231 RTC (real time clock) board. The DS3231 chip itself is from Maxim. Since the cell is described as a "backup battery" a literal interpretation suggests that you don't need the backup battery in order to operate the board if the board itself is powered and you don't mind that the device cannot remember the time when board power is lost. I might be taking the term "backup battery" too literally since it doesn't seem to work.
The Adafruit (Arduino) code:
> #include <Wire.h>
> #include "RTClib.h"
> RTC_DS3231 rtc;
> void loop()
>{
>     rtc.adjust(DateTime(2018, 1, 1, 0, 0, 0));
>     DateTime now = rtc.now();
>     Serial.print(now.year());
>     Serial.print(" ");
>     Serial.print(now.month());
>     Serial.print(" ");
>     Serial.print(now.day());
>}

The output is:
2165 165 165

The Maxim datasheet says this about the VBAT line which is the line between the DS3231 chip and the missing backup battery:

Backup Power-Supply Input. When using the device with the VBAT input
  as the primary power source, this pin should be decoupled using a
  0.1μF to 1.0μF low-leakage capacitor. When using the device with the VBAT input as the backup power source, the capacitor is not required.
  If VBAT is not used, connect to ground.

So I connected it to ground and it makes no difference. I can't buy a battery until tomorrow morning. Can somebody please confirm that the backup battery is actually essential. EDIT: I installed a battery and it makes no difference.
Aside: A good reason for not having a backup battery if possible is to have fewer user serviceable parts.

Does your code work properly with a battery?

@Gerben, I installed a battery and it makes no difference.

Glad to hear you figured the problem out. Nice job.

The problem was a bad connection for one of the serial lines.
I found the solution at this link.
The battery is not necessary to make this work.

Assuming your code is in Arduino IDE "loop".
Assuming

rtc.adjust(DateTime(2018, 1, 1, 0, 0, 0));
  initializes the rtc.

Your code should be continually printing the rtc.adjust value.
Hence move the rtc.djust out of the "loop" and provide some kind of delay , say 1 second, to print rtc every second.
Then we can take a look why your are getting wrong data.

Removing that line makes no difference. Every time through the loop the year is 2165.

Does  rtc.adjust returns anything - true / false /error ? Your rtc is not initializing / running .

I think .adjust is a void function.

The Adafruit example at File>Examples>RTClib>ds3231 also says the year is 2165.

OK  its RTC 23:30 here ( no pun intended  , so I'll tackle this tomorrow.

Your code does not include the line(s) necessary to initialise the rtc.
in setup, you need something like
rtc.begin()

If you've followed the instructions from the Adafruit website for installing the RTC library:

Start Arduino IDE
File->Examples->RTClib->ds3231

This will open the RTC usage example.
Else, go to the example on the Adafruit Github page
look to the setup() code and see how they initialise the device

I have the call to rtc.begin in my setup. I only show the loop in the above code.

Using the exact same code as the Adafruit example which is a read-only file so I know it is correct (Files>Examples>RTClib>ds3231) the year is still 2165, month 165, day 165.


text:
Why is Serial.write() slower than memcpy()?
I use Serial.write() to transmit 53 bytes to PC. For the time measurement I use micros() (before and after the write function). There is a delay of 1s after each transmission.
The time of the Serial.write() function is 532 us with 1000000 baud rate, and 360 us with 9600 baud rate.
The Serial.write() function is clearly asynchronous because the transmission of 53 bytes with 9600 baud rate is 53*8/9600*1e6 = 44167 us. (By the way, in the case of 1000000 baud rate, it is not so obvious that the function is asynchronous.)
I use Serial.availableForWrite() before Serial.write() to confirm that there is enough space in the buffer (this returns 63 each time, the buffer size is default 64).
I don't understand these numbers. Using memcpy() to copy the 53 bytes only takes 32 us. Is copying to the serial buffer not the same as the memcpy() function? And why is there a difference in the copy times when the baud rate is different? Serial.write() is even slower with higher baud rates according to the results. Why does Serial.availableForWrite() return 63 while the buffer size is 64 (according to SERIAL_TX_BUFFER_SIZE)?
Update:
Thanks for all of your answers.
I have tried another library for serial communication: https://github.com/greiman/SerialPort
It seems to be faster than the original one.
I use 2 time measurements and a delay in the code, these 3 deltaTimes represents the whole step as follows:
writeTime + memcpyTime + delaymicros = computedTime != realTime
The first 2 times are measured, the delaymicros is the theoretical delay (900 us), I can compute the step time from these. This computed step time is different from realTime (the measured step time, I measure the whole step too). It seems that the additional time can be found in the delay.
SerialPort library:
100 + 30 + 900 = 1030 != 1350
writeReal = 100 + 1350 - 1030 = 430
Arduino Serial:
570 + 30 + 900 = 1500 != 1520
writeReal = 570 + 1520 - 1500 = 590
Then I measured the delaymicros time (which is 900 us in theory), the missing time can be found there. I programmed 900 us delay, but the real delay was around 1200 in the first, and 920 in the second test.
These measurements can prove the existence of the interrupts, because measuring only the write functions doesn't give all of the writing time (especially with the downloaded serial library).
The downloaded library can work faster, but requires bigger tx buffer because of errors (256 works properly instead of 64).
Here is the code: I use a checkSum in the sendig function (which is 570-532 = 38 us). I use Simulink to receive and process the data.

struct sendMsg1 {
  byte errorCheck;//1

  unsigned long dT1;//4
  unsigned long dT2;//4
  unsigned long t;//4
  unsigned long plus[10];//40
};//53

sendMsg1 msg1;
byte copyMsg1[53];

unsigned long time1;
unsigned long time2;
unsigned long time3;
unsigned long time4;

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

void loop() {
  sensorRead();
  sendMsg1_f();

  //time3 = micros();
  delayMicroseconds(900);
  //time4 = micros();
}

void sensorRead() {
  time3 = micros();

  msg1.t = micros();
  for (unsigned long i = 0; i < 1; i++) {
    memcpy((void*)&(copyMsg1[i*sizeof(sendMsg1)]), (void*)&msg1, sizeof(sendMsg1));
  }

  time4 = micros();
  msg1.dT2 = time4 - time3;
}

void sendMsg1_f() {
  time1 = micros();

  msg1.errorCheck = 0;
  for (int i = 0; i < sizeof(sendMsg1) - 1; i++) {
    msg1.errorCheck += ((byte*)&msg1)[i];
  }
  Serial.write((byte*)&msg1,sizeof(sendMsg1));

  time2 = micros();
  msg1.dT1 = time2 - time1;
}

Can you provide the code, that you used to get these results?

1 byte of buffer is lost because of ring buffer implementation. tail an head of full buffer can't point at the same index, because tail an head are on same index in case of empty buffer

If you take a look into the implementation:
size_t HardwareSerial::write(uint8_t c)
{
  _written = true;
  // If the buffer and the data register is empty, just write the byte
  // to the data register and be done. This shortcut helps
  // significantly improve the effective datarate at high (>
  // 500kbit/s) bitrates, where interrupt overhead becomes a slowdown.
  if (_tx_buffer_head == _tx_buffer_tail && bit_is_set(*_ucsra, UDRE0)) {
    // If TXC is cleared before writing UDR and the previous byte
    // completes before writing to UDR, TXC will be set but a byte
    // is still being transmitted causing flush() to return too soon.
    // So writing UDR must happen first.
    // Writing UDR and clearing TC must be done atomically, otherwise
    // interrupts might delay the TXC clear so the byte written to UDR
    // is transmitted (setting TXC) before clearing TXC. Then TXC will
    // be cleared when no bytes are left, causing flush() to hang
    ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
      *_udr = c;
#ifdef MPCM0
      *_ucsra = ((*_ucsra) & ((1 << U2X0) | (1 << MPCM0))) | (1 << TXC0);
#else
      *_ucsra = ((*_ucsra) & ((1 << U2X0) | (1 << TXC0)));
#endif
    }
    return 1;
  }
  tx_buffer_index_t i = (_tx_buffer_head + 1) % SERIAL_TX_BUFFER_SIZE;

  // If the output buffer is full, there's nothing for it other than to
  // wait for the interrupt handler to empty it a bit
  while (i == _tx_buffer_tail) {
    if (bit_is_clear(SREG, SREG_I)) {
      // Interrupts are disabled, so we'll have to poll the data
      // register empty flag ourselves. If it is set, pretend an
      // interrupt has happened and call the handler to free up
      // space for us.
      if(bit_is_set(*_ucsra, UDRE0))
    _tx_udr_empty_irq();
    } else {
      // nop, the interrupt handler will free up space for us
    }
  }

  _tx_buffer[_tx_buffer_head] = c;

  // make atomic to prevent execution of ISR between setting the
  // head pointer and setting the interrupt flag resulting in buffer
  // retransmission
  ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
    _tx_buffer_head = i;
    sbi(*_ucsrb, UDRIE0);
  }

  return 1;
}

It basically answers all the questions.
If the buffer is empty and it's not sending anything, it'll send the character directly so it's synchronous (but sending the character will be much faster than overhead of function callbacks and so)
No, you cannot use memcpy, as it just replaces buffer, but it does nothing else, like actually start the data register ready interrupt nor proper setting of head/tail counters (it's round buffer, so there can be scenario you'll overwrite something outside of buffer)
And write function is called for each character separately (all other specialisation of write are using this one)
Also if the buffer is full, it'll wait until there is a space for another character.

The function you were testing is presumably
Serial.write(const uint8_t *buffer, size_t size).
If you search for it in HardwareSerial.h, you will see
    using Print::write; // pull in write(str) and write(buf, size) from Print

and the implementation is in Print.cpp:
/* default implementation: may be overridden */
size_t Print::write(const uint8_t *buffer, size_t size)
{
  size_t n = 0;
  while (size--) {
    if (write(*buffer++)) n++;
    else break;
  }
  return n;
}

This is writing the bytes one by one, and for every byte, the whole code
of HardwareSerial::write(uint8_t c) is being run. This includes the
tests for full or empty buffer, and the arithmetic for updating
_tx_buffer_head.
As stated in the comment above the code, it would have been possible to
override this with a specialized implementation. In principle, you could
copy the linear buffer into the ring buffer using at most two calls to
memcpy(), and updating _tx_buffer_head only once. That would likely
be more efficient than the current implementation, at least for buffer
sizes in the range you are using (close to, but less than the ring
buffer capacity).
Would it be worth it? Maybe for your use case it would. But it could
also make the code more complex and require more flash. And the benefit
is likely to be really small for people who write small buffers. I am
not sure a pull request implementing this sort of optimization may be
accepted. You may try if you feel like so.

Copying to the serial buffer is not the same as memcpy(), no.
The serial buffer is a circular buffer. Because of that there are lots of calculations involved in working out exactly where in the buffer to place the next character. That takes time.  memcpy() just copies one block of memory directly over another. It makes no checks, and it can't wrap around like a circular buffer.
The reason why higher baud rates seem slower is because each character is taken from the buffer by an interrupt. The higher the baud rate the more often that interrupt is triggered, and so the more time is spent by the CPU in processing that interrupt to send the next character. And equally, the less time is available to the CPU to process the placing of data into to the serial buffer.


text:
OneWire with DS18B20 digital sensor only works on the I2C (20 and 21) pins of my Mega?
I am using an Arduino Mega to read a DS18B20 temperature sensor using the OneWire library in the code below which I got here:

#include <OneWire.h>

#define DS18S20_Pin 20 //DS18S20 Signal pin on digital 20

//Temperature chip i/o
OneWire ds(DS18S20_Pin);  // on digital pin 20

 #define DS18S20_ID 0x10
 #define DS18B20_ID 0x28
 float temp;

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

void loop(void) {
  boolean tempTest = getTemperature();
  Serial.println(tempTest);
  Serial.println(temp);

  delay(1000); //just here to slow down the output so it is easier to read

}

 boolean getTemperature(){
 byte i;
 byte present = 0;
 byte data[12];
 byte addr[8];
 //find a device
 if (!ds.search(addr)) {
 ds.reset_search();
 return false;
 }
 if (OneWire::crc8( addr, 7) != addr[7]) {
 return false;
 }
 if (addr[0] != DS18S20_ID && addr[0] != DS18B20_ID) {
 return false;
 }
 ds.reset();
 ds.select(addr);
 // Start conversion
 ds.write(0x44, 1);
 // Wait some time...
 delay(850);
 present = ds.reset();
 ds.select(addr);
 // Issue Read scratchpad command
 ds.write(0xBE);
 // Receive 9 bytes
 for ( i = 0; i < 9; i++) {
 data[i] = ds.read();
 }
 // Calculate temperature value
 temp = ( (data[1] << 8) + data[0] )*0.0625;
 return true;
 }

When I use this code with the sensor attached to pins digital pins 20 or 21 it reads successfully, ok great, somehow by the grace of god I chose pin 20 on the first try. So then I move on to integrating my next sensor which utilizes the I2C and the Wire library, I should note that I am using this shield so I was able to connect right to the I2C without realizing I was using pins 20 and 21. Now, when I combined the two programs the I2C sensor was initialized second so it ended up getting the pins and the DS18B20 would fail to read, after pulling out my hair for a couple of hours I looked at a Mega pinout and realized it was on the I2C pins and thinking I finally figured it out I went to go and move the DS18B20 to one of the 52 other digital pins, this is when I came to the cold discovery that my DS18B20/OneWire will not work on any pins except pins 20 and 21 which I NEED for I2C. I have not checked every single digital pin but I have checked about half of them and nothing works except pins 20 and 21, I cant figure it out, nothing I can find mentions that OneWire uses or conflicts with the I2C connection.
More Info:

Using latest OneWire
I am not using DallasTemperature and would prefer not to, I could not get it to work whether on pins 20/21 or not
I am using a resistor on the sensor
I am currently only trying to run the code above to debug, no references to I2C sensor or Wire library whatsoever.

Thanks for reading and for any help, I am totally stumped here and thought I was avoiding some of these dumb double use pin issues by using the Mega instead of an Uno...

it is unclear why grace of god was required to choose pin 20 ... the comment in the code listing clearly specifies pin 20

Original code at link did not specify a pin number it only included a function. So I just chose pin 20, which ended up being one of the two working ones.

The difference between pin 20, 21 and the rest of the pins is the pullup resistor on the mega board. I assume that there is something wrong with your pullup resistor for the 1-Wire bus. Its value is far too large or it is not connected.


text:
Error Compiling sketch for Arduino Uno(ld return 1)
I have got an telnet server with esp8266 + SoftwareSerial+ UNO, and here I want to on led with command ON  .
 will be 1 or 2. It is for recive 1 or 2 numbered pins.
And I extract pin from request with indexOf and substring functions and write:
pinMode(pin,OUTPUT);
digitalWrite(pin,HIGH);

I write if pin is not 0 or 1 and it is in range 2-9 for type 1 and if pin is in range 10-13. But at compile time it gives me error compiling for uno. And it gives me this error whn I use pinMode. When I write it to setup it don't give me error. Why? What happenes?
Full code:
#include "WiFiEsp.h"

// Emulate Serial1 on pins 6/7 if not present
#ifndef HAVE_HWSERIAL1
#include "SoftwareSerial.h"
SoftwareSerial Serial1(6, 7); // RX, TX
#endif
 String res = "";
char ssid[] = "ssid";            // your network SSID (name)
char pass[] = "passs";         // your network password
int status = WL_IDLE_STATUS;     // the Wifi radio's status
int reqCount = 0;                // number of requests received

WiFiEspServer server(23);

 WiFiEspClient client;

void setup() {
  pinMode(2,OUTPUT);

  Serial.begin(115200);
  // initialize serial for ESP module
  Serial1.begin(9600);
  // initialize ESP module
  WiFi.init(&Serial1);

  // check for the presence of the shield
  if (WiFi.status() == WL_NO_SHIELD) {
    Serial.println("WiFi shield not present");
    // don't continue
    while (true);
  }

  while ( status != WL_CONNECTED) {
    Serial.print("Attempting to connect to WPA SSID: ");
    Serial.println(ssid);
    // Connect to WPA/WPA2 network
    status = WiFi.begin(ssid, pass);
  }

  Serial.println("You're connected to the network");
Serial.println(WiFi.localIP());

WiFi.config(IPAddress(192,168,0,165));

  // start the web server on port 80
  server.begin();
}

void loop(){
  if(!client){
    client = server.available();
    if(client){
      client.println("Welcome to telnet server!, 192.168.0.165:23");
      client.flush();
    }

  }

  if(client){
if(client.available()>0){
  res = "";
  while(client.available()>0){

char c = client.read();

res += c;

  }
  Serial.println(res);

int i = res.indexOf("ON")+3;
int j = i+1;
String hh = res.substring(i,j);
int type = hh.toInt();
Serial.println(hh);
if(type == 1)
{
  int ii = res.indexOf("ON")+5;
int jj = ii+1;
String hhh = res.substring(ii,jj);
Serial.println(hhh);
int ihhh = hhh.toInt();
if(ihhh != 0 && ihhh != 1 && (2 <=ihhh)&& ( ihhh <= 9 ))
{
  pinMode(ihhh,OUTPUT);
  digitalWrite(ihhh,HIGH);
}
else{
  client.print("Pin is TX/RX, or not 2<= pin <=9\r\n");
  client.flush();
}
}else if(type == 2){
    int iii = res.indexOf("ON")+5;
int jjj = iii+2;
String hhhh = res.substring(iii,jjj);
Serial.println(hhhh);
int ihhhh = hhhh.toInt();
if(ihhhh != 0 && ihhhh != 1 && !((2<=ihhhh)&&(ihhhh <= 9)) && (10 <= ihhhh)&&(ihhhh <= 13 ))
{
  pinMode(ihhhh,OUTPUT);
  digitalWrite(ihhhh,HIGH);
}
else{
  client.print("Pin is TX/RX, or not 2<= pin <=9\r\n");
  client.flush();
}
}

}

    if(!client.connected())
    Serial.println("Client disconnected from Telnet Server");

  }

}

Error is:
Arduino: 1.8.9 (Windows Store 1.8.21.0) (Windows 10), Board: "Arduino/Genuino Uno"
C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.21.0_x86__mdqgnx93n4wtt\hardware\arduino\avr\cores\arduino\HardwareSerial.cpp: In member function 'availableForWrite':
C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.21.0_x86__mdqgnx93n4wtt\hardware\arduino\avr\cores\arduino\HardwareSerial.cpp:203:1: internal compiler error: Segmentation fault
}
^
Please submit a full bug report,
with preprocessed source if appropriate.
See http://gcc.gnu.org/bugs.html for instructions.
lto-wrapper.exe: fatal error: C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.21.0_x86__mdqgnx93n4wtt\hardware\tools\avr/bin/avr-gcc returned 1 exit status
compilation terminated.
c:/program files/windowsapps/arduinollc.arduinoide_1.8.21.0_x86__mdqgnx93n4wtt/hardware/tools/avr/bin/../lib/gcc/avr/5.4.0/../../../../avr/bin/ld.exe: error: lto-wrapper failed
collect2.exe: error: ld returned 1 exit status
exit status 1
Error compiling for board Arduino/Genuino Uno.
Arduino IDE version is:  1.8.9(Windows Store 1.8.21.0)

You forgot to include the error message. Please format your code correctly (use autoformat in the IDE, delete unnecessary empty lines, and fix the indentation).

What is the exact text of the error (all the error, not just the last line). Also, what version of the IDE are you using, and what version of the AVR boards package, and how did you install the IDE?

I thought it might be the "windows store" version. Known to be broken. Delete it. Download the IDE properly from the Arduino website.

@Majenko I didn't know that, what's the difference compared to the "normal" version?

It bundles a broken version of the compiler.

@Majenko I thought the compiler was a part of the AVR Core, not of the IDE itself.

They are separate, but bundled. When you download the IDE it also contains the AVR core and AVR-GCC compiler.

This is a bug in the compiler (linker) used by the Arduino AVR Core. It's not because of a bug in your code, and there's not much you can do about it except using a different version of the AVR Core.
See this forum post:

Here's the traditional workaround:

Tools > Board > Boards Manager
Wait for downloads to finish.
When you move the mouse pointer over "Arduino AVR Boards", you will see a "Select version" dropdown menu appear. Select "1.6.21".
Click "Install".
Wait for installation to finish.
Click "Close".


text:
SD card readline reading batched lines?
So, I am trying to transmit float data, over UART, from my Arduino to another machine. The log of this data is really large, so I am forced to put it on an SD card, and read it into the Arduino line-by-line, then transmit that single line.
The issue is that my code seems to be "grabbing" ~65 lines (or more) at a time, transmitting them over UART, then stopping (or crashing) the Arduino.
My log looks like this (a small snippet of the several thousands of lines):
14.71927
14.71795
14.71787
14.71787
14.71787
14.71799
14.7175
14.71836
14.71746
14.71787
14.71923
14.71878
14.7184
14.71791
14.71893
14.7184
14.71746
14.71799
14.71746
14.71795
14.71874
14.71795
14.71878
14.71836
14.71881
14.72235
14.72781
14.72872
14.72917
14.72826
14.73188
14.73278
14.73595
14.73783
14.74227
14.74231
14.74363
14.74683
14.7495
14.75492
14.75899
14.76396
14.76807
14.77033
14.77161
14.77262
14.77978
14.78524
14.7884
14.78746
14.79695
14.80238
14.80652
14.80648
14.81055
14.81191
14.81865
14.82234
14.82095
14.81733
14.8286
14.82908
14.82999
14.82682
14.83673

And my code looks like this (I know it says 4Hz, but is at 1Hz, but that was to help "see" the "batch" grabbing and printing):

// Define our LED pins
#define greenLED    6
#define redLED      5

// Define our serial BAUD rate
#define BAUDrate    9600

// To read data from the SD card
#include <SD.h>

// To print data to an LCD panel
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd( 0x3F, 16, 2 );

void setup(){
    // Set LED pins as outputs
    pinMode( greenLED, OUTPUT );
    pinMode( redLED, OUTPUT );

    // LED output at start: GREEN = ON, RED = OFF
    digitalWrite( greenLED, HIGH );
    digitalWrite( redLED, LOW );

    // Begin wired comms with MSP board
    Serial.begin( BAUDrate );

    // Begin reading data from SD card
    SD.begin( 4 );                      // Need pin #4 for SD card bit-shifting
    File dataLog;                       // Store our data from the SD card
    dataLog = SD.open( "DATA.TXT", FILE_READ );
    String data = dataLog.readStringUntil( "\n" ); // Prime our data

    int i = 0;

    while( data != "" ){
        i++;
        Serial.print( i );
        Serial.print( "\t" );

        Serial.println( data );         // Send our data to MSP board
        lcdUpdate( data );              // Print our sent data to the LCD screen

        delay( 1000 );                   // Wait 1/4 of a second (4 Hz)

        data = dataLog.readStringUntil( "\n" );    // Reprime our data
    }

    // Close our data log to avoid corrupting SD card contents upon restart
    dataLog.close();

    // Switch our LEDs since we're finished streaming our data
    digitalWrite( greenLED, LOW );
    digitalWrite( redLED, HIGH );
}

void loop(){
}

// Prints the current data being sent over UART to an LCD screen
void lcdUpdate( String ourData ){
    lcd.setCursor( 0, 0 );
    lcd.print( " Sending data:  " );
    lcd.setCursor( 0, 1 );
    lcd.print( "    " );
    lcd.print( ourData );
    lcd.print( "    " );
}

Again, I want it to grab a single line, print it to the serial terminal, print it to the LCD, then grab a second line and repeat.  I'm not able to test the LCD (since I don't have one with me at the moment), but the serial terminal is giving me problems, so I'm assuming the LCD won't work, either.
I'm getting something, as a Serial Terminal output, along the lines of:
1       14.71927
14.71795
14.71787
14.71787
14.71787
14.71799
14.7175
14.71836
14.71746
14.71787
14.71923
14.71878
14.7184
14.71791
14.71893
14.7184
14.71746
14.71799
14.71746
14.71795
14.71874
14.71795
14.71878
14.71836
14.71881
14.72235
14.72781
14.72872
14.72917
14.72826
14.73188
14.73278
14.73595
14.73783
14.74227
14.74231
14.74363
14.74683
14.7495
14.75492
14.75899
14.76396
14.76807
14.77033
14.77161
14.77262
14.77978
14.78524
14.7884
14.78746
14.79695
14.80238
14.80652
14.80648
14.81055
14.81191
14.81865
14.82234
14.82095
14.81733
14.8286
14.82908
14.82999
14.82682
14.83

It seems to want to stop somewhere between the 65th and 69th element, randomly.  I'm assuming that it's running out of buffer space, since it's grabbing everything from the SD card, instead of a single line, one at a time.
This has become more evident with my i = 0 line, and that it isn't iterating for every line, just the once for the ~65 lines.
Am I reading the data in incorrectly, or am I parsing things incorrectly, or is what I'm trying to do simply not possible?

put a Serial.print("."); inside the loop() block

@jsotola It never even gets to the loop() block.  I did what you said, and it just kind of stops, which reaffirms my suspicions that it's grabbing the whole SD card contents and overflowing the buffer, then freezing.

Arduino's reference doesn't help with your readStringUntil call (see SD's documentation), but assuming it's the same as Stream's, it needs a character, not a string as a terminator.
Your output shows that your Arduino tried to read a line, but there were no line endings found - probably because of the '' vs. "". That's why your output starts with a 1 (i's value), and there no other line numbers after that, even though in your output clearly shows newlines.


text:
ESP8266 WiFi.begin() isn't working
I did a project for IoT attendance system using ESP8266 and RDM6300. However, I can connect to wifi using WiFiMulti.addAP() function for my home WiFi.
I tried WiFi.begin() instead of WiFiMulti.addAP() function to connect to my mobile hotspot but the esp8266 is failing to connect. In fact, WiFi.begin() also failed to connect to the same wifi router which was previously connected by WiFiMulti.addAP(). Serial monitor constantly showing the below error.
Exception (3):
epc1=0x4020970d epc2=0x00000000 epc3=0x00000000 excvaddr=0x4003bfc9 depc=0x00000000

>>>stack>>>

ctx: cont
sp: 3ffffbc0 end: 3fffffc0 offset: 01a0
3ffffd60:  00000000 00000004 3ffffe40 3ffffef0
3ffffd70:  4010156c 0000049c 000003fd 40209837
3ffffd80:  0000049c 00001000 000003fd 4010156c
3ffffd90:  40106980 3ffe85ad 3ffffe40 402354f1
3ffffda0:  401004a5 402355db 3fff0c1c 0000049c
3ffffdb0:  000003fd 3ffffef0 3fff0c1c 402355be
3ffffdc0:  ffffff00 55aa55aa 00000035 00000020
3ffffdd0:  00000020 00000048 0000004a aa55aa55
3ffffde0:  000003ff 40235aa8 3fff0c1c 3fff0c1c
3ffffdf0:  000000ff 3fff0c1c 0000049c 00000000
3ffffe00:  401004a5 00000001 3fff0c2c 40235cc2
3ffffe10:  00000008 3fff0c1c 000000ff 3ffffef0
3ffffe20:  3fffff10 3fff0c53 00000035 00000020
3ffffe30:  3fff0cdc 3fffff51 00000001 40235d72
3ffffe40:  3ffffef0 40242be0 00000000 0000000c
3ffffe50:  3fff101c 3fffff10 3fff6f54 40235d41
3ffffe60:  3fff0c1c 40235da8 3ffe84dc 3ffe85ae
3ffffe70:  402019ca 3ffe85ae 3ffe85b3 40201927
3ffffe80:  61666152 00000074 3ffffe60 40204666
3ffffe90:  4000e243 00000030 3ffffe60 402046c4
3ffffea0:  616d7374 2e2e3730 3ffffe00 40204901
3ffffeb0:  3ffffdf0 0693b740 000035af fffffffe
3ffffec0:  00000090 3fffc6fc 00000003 40201dd4
3ffffed0:  3ffee50c 000000f2 000000f2 40206bf8
3ffffee0:  8ab9b001 00a0a64e 00000000 40206057
3ffffef0:  78666152 3fff0c00 0000049c 00000000
3fffff00:  00000a2e 0000007f 3fff0c1c 402356c6
3fffff10:  61666172 66617274 32317461 40209500
3fffff20:  00000001 3fff0c1c 00000000 402099e8
3fffff30:  000003fd 402351a3 00000000 40101538
3fffff40:  00000001 001ce8e7 3ffeea78 402351be
3fffff50:  40235100 00000001 00000081 00000002
3fffff60:  00000004 00000000 3ffee544 00000001
3fffff70:  402083ea 000003e8 000003e8 3ffee870
3fffff80:  3ffee544 00000000 3ffee750 40201194
3fffff90:  00000000 00000000 ffefeffe feefeffe
3fffffa0:  3fffdad0 00000000 3ffee840 40207830
3fffffb0:  feefeffe feefeffe 3ffe8520 40101809
<<<stack<<<

ets Jan  8 2013,rst cause:2, boot mode:(3,6)

load 0x4010f000, len 1384, room 16
tail 8
chksum 0x2d
csum 0x2d
v8b899c12
~ld

this is the code I uploaded to ESP8266:

#include <Arduino.h>

#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>

#include <ESP8266HTTPClient.h>

#include <WiFiClient.h>

#include <rdm6300.h>

#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels

// Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);

#define RDM6300_RX_PIN 2
#define READ_LED_PIN 14

ESP8266WiFiMulti WiFiMulti;
Rdm6300 rdm6300;

String RFID[] = {"5958666", "5958741"};

String SID[] = {"161-115-123", "161-115-124"};

String NAME[] = {"Rafat", "Saney"};

int flag[2] = {0, 0};

void setup() {

  Serial.begin(115200);
  display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
  pinMode(READ_LED_PIN, OUTPUT);
  digitalWrite(READ_LED_PIN, LOW);
  rdm6300.begin(RDM6300_RX_PIN);

  Serial.println();
  Serial.println();
  Serial.println();
  OLED("Connecting...");
  for (uint8_t t = 4; t > 0; t--) {
    Serial.printf("[SETUP] WAIT %d...\n", t);
    Serial.flush();
    delay(1000);
  }

  WiFi.mode(WIFI_STA);
  WiFi.begin("custom", "customjack.xyz");
  Serial.print("Connecting");

  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("Connected");
  OLED("Connected");
  Serial.println(WiFi.localIP());

}

void loop() {
  // wait for WiFi connection
  if ((WiFi.status() == WL_CONNECTED)) {
label:
    OLED("Place Your ID");
    String tag;
    int check = 0;
    if (rdm6300.update())
    {
      tag = String(rdm6300.get_tag_id());
      Serial.println(tag);
      for (int i = 0; i < 1; i++)
      {
        if (RFID[i] == tag) // checking validity of RFID
        {
          tone(READ_LED_PIN, 392);
          delay(100);
          noTone(READ_LED_PIN);
          check = 1;
          if (flag[i] == 1) // Flag=1 meaans already attendance counted
          {
            Serial.println("Attendance Already Counted");
            OLED("Already Counted");
            delay(2000);
            goto label;
          }
          OLED("Welcome "+NAME[i]);
          flag[i] = 1;
          WiFiClient client;
          HTTPClient http;

          Serial.print("[HTTP] begin...\n");
          String url = "http://metrounisas.000webhostapp.com/action.php?ID=" + SID[i];
          if (http.begin(client, url ) ) { // HTTP

            Serial.print("[HTTP] GET...\n");
            // start connection and send HTTP header
            int httpCode = http.GET();

            // httpCode will be negative on error
            if (httpCode > 0) {
              // HTTP header has been send and Server response header has been handled
              Serial.printf("[HTTP] GET... code: %d\n", httpCode);

              // file found at server
              if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY) {
                String payload = http.getString();
                Serial.println(payload);
              }
            } else {
              Serial.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
            }

            http.end();
          } else {
            Serial.printf("[HTTP} Unable to connect\n");
          }
        }
      }
      if (check == 0) {
        tone(READ_LED_PIN, 261);
        noTone(READ_LED_PIN);
        Serial.println("Invalid RFID");
        OLED("INVALID ID");
        delay(2000);
      }
    }
  }

  delay(1000);
}

void OLED(String txt){
  display.clearDisplay();
  display.setTextSize(1);
  display.setTextColor(WHITE,BLACK);
  display.setCursor(30, 30);
  display.println(txt);
  display.display();
  delay(2000);
}

how is it powered?

It's getting powered from PC with micro-USB cable

esp8266 can't get power from USB. you have a development board with esp8266? but then the powering should be OK


text:
Run light sequence function continuously in if statement
My goal - run light sequence function on momentary button press (button 2) continuously until another of the 3 momentary buttons are pressed.
    /* switch
 *
 * Each time the input pin goes from LOW to HIGH (e.g. because of a push-button
 * press), the output pin is toggled from LOW to HIGH or HIGH to LOW.  There's
 * a minimum delay between toggles to debounce the circuit (i.e. to ignore
 * noise).
 *
 * David A. Mellis
 * 21 November 2006
 */
 #include "FastLED.h"

int inPin = 8;         // the number of the input pin
int inPinTwo = 9;
int inPinThree = 10;
int outPin = 13;       // the number of the output pin

int state = HIGH;      // the current state of the output pin
int reading;           // the current reading from the input pin
int readingTwo;
int readingThree;
int previous = LOW;    // the previous reading from the input pin

int pixelNumber;

// the follow variables are long's because the time, measured in miliseconds,
// will quickly become a bigger number than can be stored in an int.
long time = 0;         // the last time the output pin was toggled
long debounce = 200;   // the debounce time, increase if the output flickers

//NEOPIXEL
#define LED_PIN     7
#define LEDPIN 7
#define LED_TYPE     NEOPIXEL
#define NUM_LEDS    2
#define BRIGHTNESS 10
#define FRAMES_PER_SECOND 60
CRGB leds[NUM_LEDS];
#define COLOR_ORDER GRB
#define CHIPSET     WS2811

bool gReverseDirection = false;
CRGBPalette16 gPal;

void setup()
{

  pinMode(inPin, INPUT);
  pinMode(inPinTwo,INPUT);
  pinMode(inPinThree,INPUT);
  pinMode(outPin, OUTPUT);

  Serial.begin(9600);

  // set up LED strip info
FastLED.addLeds<LED_TYPE,LEDPIN>(leds,NUM_LEDS).setCorrection(TypicalLEDStrip);
FastLED.setBrightness(BRIGHTNESS);
}

void loop()
{

//    BUTTON 1 - SOLID LIGHT
  reading = digitalRead(inPin);

  // if the input just went from LOW and HIGH and we've waited long enough
  // to ignore any noise on the circuit, toggle the output pin and remember
  // the time
  if (reading == HIGH && previous == LOW && millis() - time > debounce) {
    if (state == HIGH){
      state = LOW;
      fill_solid(leds,NUM_LEDS,CRGB::Black);
      FastLED.show();
    }
    else{
      state = HIGH;
      fill_solid(leds,NUM_LEDS,0xFAF6D1);
      FastLED.show();
      }

    time = millis();

  }
    digitalWrite(outPin, state);
    previous = reading;

//  BUTTON 2 - GLITTER LIGHT
   readingTwo = digitalRead(inPinTwo);
  if (readingTwo == HIGH && previous == LOW && millis() - time> debounce){
    if(state == HIGH){
      state = LOW;
      fadeToBlackBy( leds, NUM_LEDS, 10);
      addGlitter(30);
      FastLED.show();
      }
    else{
      state = HIGH;
      fill_solid(leds,NUM_LEDS,CRGB::Black);
      FastLED.show();
    }

    time = millis();
    }
    digitalWrite(outPin,state);
    previous = readingTwo;

//  BUTTON 3  - MOVEMENT SENSOR LIGHT
       readingThree = digitalRead(inPinThree);
  if (readingThree == HIGH && previous == LOW && millis() - time> debounce){
    if(state == HIGH){
      state = LOW;
       fill_solid(leds,NUM_LEDS,CRGB::Black);
        FastLED.show();
      }
    else{
      state = HIGH;

    }

    time = millis();
    }
    digitalWrite(outPin,state);
    previous = readingThree;
}

//glitter effect
void addGlitter( fract8 chanceOfGlitter) {
  if( random8() < chanceOfGlitter) {
    leds[ random16(NUM_LEDS) ] += CRGB::White;}
}

The issue - the function seems to be only ran once (see button 2), which doesn't achieve the required effect.  I realize that changing this if statement to a while statement would be beneficial, but I cannot figure out how to break out of this while loop upon button press.  I know that setting state = LOW will break the while loop but if I leave it in, the light sequence function never runs.
//  BUTTON 2
   readingTwo = digitalRead(inPinTwo);
  if (readingTwo == HIGH && previousTwo == LOW && millis() - time> debounce){
    while(state == HIGH){
//      state = LOW;
      fadeToBlackBy( leds, NUM_LEDS, 10);
      addGlitter(30);
      FastLED.show();
  }

    while(state == LOW){
      state = HIGH;

      fill_solid(leds,NUM_LEDS,CRGB::Black);
        FastLED.show();

    }

Any help would be greatly appreciated!

do all of the button reading, debouncing and processing at the beginning of the loop() block .... keep track of the current state and the previous state (use the button presses to change the state variables .... run the LED control blocks depending on the state variables

I already use the button presses to change the state variables and the LEDS depending on them.  Maybe I misunderstand your comment?

read the comment up to the first ....

this rough idea uses only one button ... read button only at begining of loop() ... expand it to your liking with more buttons ....use a state variable with 6 states ... in setup state = 1 ... at beginning of loop() read button ... if it is pressed then increment state ... now the LEDs ... if state==1, run button1 code ... if state==2, run button1.else code and set state=3 ... if state==3, run button2 code ... if state==4, run button2.else code and set state=5 .... similarly for the rest of the code

thanks for expanding your comment jsotola.  I'll test it out and post progress.

I added int btnPress which gets set on each button press.  Then an if statement runs according to btnPress number.  Thanks jsotola for the point in the right direction!
#include "FastLED.h"

int inPin = 8;         // the number of the input pin
int inPinTwo = 9;
int inPinThree = 10;
int outPin = 13;       // the number of the output pin

int state = HIGH;      // the current state of the output pin

int reading;           // the current reading from the input pin
int readingTwo;
int readingThree;
int previous = LOW;    // the previous reading from the input pin
int previousTwo = LOW;
int previousThree = LOW;
volatile int change;
int btnPress;

int pixelNumber;

long time = 0;         // the last time the output pin was toggled
long debounce = 200;   // the debounce time, increase if the output flickers

//NEOPIXEL
#define LED_PIN     7
#define LEDPIN 7
#define LED_TYPE     NEOPIXEL
#define NUM_LEDS    2
#define BRIGHTNESS 255
#define FRAMES_PER_SECOND 60
CRGB leds[NUM_LEDS];
#define COLOR_ORDER GRB
#define CHIPSET     WS2812B

void setup()
{

//BUTTON
  pinMode(inPin, INPUT);
  pinMode(inPinTwo,INPUT);
  pinMode(inPinThree,INPUT);
  pinMode(outPin, OUTPUT);

  Serial.begin(9600);

  // set up LED strip info
FastLED.addLeds<LED_TYPE,LEDPIN>(leds,NUM_LEDS).setCorrection(TypicalLEDStrip);
FastLED.setBrightness(BRIGHTNESS);
btnPress = 1;

}

void loop()
{
//    BUTTON 1 - SOLID LIGHT
  reading = digitalRead(inPin);
  if (reading == HIGH && previous == LOW && millis() - time > debounce) {
    if (state == HIGH){
      state = LOW;
      btnPress = 1;
    }
    else{
      state = HIGH;
      btnPress = 2;
      }

    time = millis();

  }
    digitalWrite(outPin, state);
    previous = reading;

//  BUTTON 2 - GLITTER LIGHT
   readingTwo = digitalRead(inPinTwo);
  if (readingTwo == HIGH && previousTwo == LOW && millis() - time> debounce){
    if(state == HIGH){
      state = LOW;
      btnPress = 3;
      }
    else{
      state = HIGH;
      btnPress = 4;
    }
    time = millis();
    }
    digitalWrite(outPin,state);
    previousTwo = readingTwo;

//  BUTTON 3  - MOVEMENT SENSOR LIGHT
       readingThree = digitalRead(inPinThree);
  if (readingThree == HIGH && previousThree == LOW && millis() - time> debounce){
    if(state == HIGH){
      state = LOW;
       btnPress = 5;
      }
    else{
      state = HIGH;
      btnPress = 6;
    }

    time = millis();
    }
    digitalWrite(outPin,state);
    previousThree = readingThree;

    //BUTTON 1 - SOLID LIGHT
     if (btnPress == 1){
          fill_solid(leds,NUM_LEDS,CRGB::Black);
          FastLED.show();Serial.println("pressed1");
      }

    if (btnPress == 2){
          fill_solid(leds,NUM_LEDS,0xFfffff);
          FastLED.show();Serial.println("pressed2");

      }

    //  BUTTON 2 - GLITTER LIGHT
    if (btnPress == 3){
            fill_solid(leds,NUM_LEDS,CRGB::Black);
          FastLED.show();Serial.println("pressed3");

      }
    if (btnPress == 4){
         fadeToBlackBy( leds, NUM_LEDS, 10);
          addGlitter(30);Serial.println("pressed4");
          FastLED.show();
      }

    //  BUTTON 3  - MOVEMENT SENSOR LIGHT
    if (btnPress == 5){
            fill_solid(leds,NUM_LEDS,CRGB::Black);Serial.println("pressed5");
          FastLED.show();

      }
    if (btnPress == 6){
        Serial.println("pressed6");
      }
  }

//glitter effect
void addGlitter( fract8 chanceOfGlitter) {
  if( random8() < chanceOfGlitter) {
    leds[ random16(NUM_LEDS) ] += CRGB::White;}
}


text:
How do I send Sensor Data from one Arduino to another Arduino that is a Webserver to post it?
I have been looking for over 2 hours now and just cant get it figured out. Im very confused as to how to do this. The solution I thought I found was to use HTTP POST. But I just cant get it to work. To be honest i'm guessing this should be very simple. Im using the variable
sensorValue = analogRead(0);

And then want to sent that Variable to my Webserver with the ip 172.20.10.5
Then I wish to save this variable into an array on my Webserver. I am sorry for this request I of course looked at least on 20 diffrent sites and questions and cant find a solution.

#include <SPI.h>
#include <Ethernet.h>
#include "ESP8266WiFi.h"

IPAddress server(172,20,10,5);
 if(client.connect(server, 80)) {
  client.println("POST /Raum1 HTTP/1.1");
  client.println("Host: 172.20.10.5");
  client.println("User-Agent: Arduino/1.0");
  client.println("Connection: close");
  client.print("Content-Length: ");
  client.println(sensorValue.length());
  client.println();
  client.println(sensorValue);
}
void setup(){
Serial.begin(9600);                            // sets the serial port to 9600
  WiFi.begin("iPad von Tobias", "12345678");  //Connect to the WiFi network

  while (WiFi.status() != WL_CONNECTED) {  //Wait for connection

    delay(500);
    Serial.println("Waiting to connect…");

  }

  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());  //Print the local IP
 }

//byte server[] = {172, 20, 10, 5}; //IP
void loop(){
sensorValue = analogRead(0);       // read analog input pin 0
Serial.print("AirQuality=");
Serial.print(sensorValue, DEC);               // prints the value read
Serial.println(" PPM");
delay(1000);

This is my current code on the ESP8266 I have the sensor on. The error im getting the most is: "client" has not been definied in this context.
I had the HTTP POST in the loop, out of the loop, in the setup, it just doesn't work. I tried diffrent methods to write the IPAddress which didnt help either. I also do not know how to then save that Data on the Webserver. They are connected over WIFI. Maybe the http way is completly wrong?. I can't find anything for this.
I would most likely have it look like this but this doenst work either.
#include <SPI.h>
#include <Ethernet.h>
#include "ESP8266WiFi.h"
int sensorValue;

void setup(){
Serial.begin(9600);                            // sets the serial port to 9600#
WiFi.begin("iPad von Tobias", "12345678");  //Connect to the WiFi network

  while (WiFi.status() != WL_CONNECTED) {  //Wait for connection

    delay(500);
    Serial.println("Waiting to connect…");

  }

  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());  //Print the local IP
 }

 IPAddress server(172,20,10,5);
 client.connect(server, 80)
void loop(){sensorValue = analogRead(0);       // read analog input pin 0
Serial.print("AirQuality=");
Serial.print(sensorValue, DEC);               // prints the value read
Serial.println(" PPM");
delay(1000);
  client.println("POST /Api/AddParking/3 HTTP/1.1");
  client.println("Host: 172.20.10.5");
  client.println("User-Agent: Arduino/1.0");
  client.println("Connection: close");
  client.print("Content-Length: ");
  client.println(sensorValue.length());
  client.println();
  client.println(sensorValue);
}

Thank you for your help, I dont need a direct solution if you can point me to literatur that will help me solve this problem.

use GET request to post a single value

And how do i do that? @Juraj

try to adapt this example https://github.com/arduino-libraries/WiFi/blob/master/examples/WiFiWebClient/WiFiWebClient.ino

In the first block of code, you have an if statement that is not inside a function. It is immediately after  IPAddress server(.... This is invalid syntax. If statements must be inside a function and this could well be the source of the error about client not being defined. Also, you never actually declare client, you might start with the examples and try to adapt them...

If found that you can also use UDP to do what I want.