text:
How to handle concurrent HTTP request when using interrupt
I'm trying to make a door sensor with a reed switch. Each time the there is a change, the ESP8266 sends an HTTP request to web service.
Unfortunately, the ESP8266 serial monitor dumps a huge stack trace when I'm approaching the magnet to the reed switch:
Exception (9):
epc1=0x40104b14 epc2=0x00000000 epc3=0x00000000 excvaddr=0x00000003 depc=0x00000000

ctx: sys
sp: 3fffeb20 end: 3fffffb0 offset: 01a0

>>>stack>>>
3fffecc0:  00000002 00000006 3ffefdc4 40227108
3fffecd0:  3ffefa74 00000002 00000014 401004e4
3fffece0:  3ffeffbc 3ffeffc0 00000006 00000001
3fffecf0:  402253bc 00000000 00000010 00000000
3fffed00:  00000000 4bc6a7f0 81cac083 00000000
3fffed10:  00000000 00000000 4bc6a7f0 00000000
3fffed20:  40104d40 0037d809 3ffeecd0 00000000
3fffed30:  3ffee520 3ffeecd0 3ffeffbc 40224398
3fffed40:  00000000 00200085 40201578 00001388
3fffed50:  3ffeecd0 00000000 00000050 00000050
3fffed60:  00000000 3fffedd0 3ffefd34 402032e5
3fffed70:  1301a8c0 00000031 3ffeebbc 402039cc
3fffed80:  3ffeedb8 000000ef 000000ef 00000020
3fffed90:  ffffffff 00000050 3fffedd0 40202d5c
3fffeda0:  40204738 1301a8c0 40204738 1301a8c0
3fffedb0:  3ffe8a64 00000005 000...

I think it's because the ESP8266 tries to make concurrent HTTP calls...
How can I solve this?
Here is the code:
// https://www.instructables.com/id/Arduino-Software-debouncing-in-interrupt-function/
// #include "util/atomic.h"
#include "ESP8266WiFi.h"
#include "ESP8266HTTPClient.h"
#include "Wire.h"

const char* ssid = "****";
const char* pass = "****";
const byte interruptPin = 5;
long debouncing_time = 50; //Debouncing Time in Milliseconds
volatile unsigned long last_micros;
const char* host= "192.168.1.19";
const char* doorStates[2] = {"closed", "opened"};

void connection()
{
  // Establish a WIFI connection
}

void setup()
{
  Serial.begin(115200);
  connection();
  pinMode(interruptPin, OUTPUT);

  // Attaching interrupt
  attachInterrupt(digitalPinToInterrupt(interruptPin), handleInterrupt, CHANGE);
}

void loop()
{
  delay(1000);
}

void handleInterrupt() {
  if ((long)(micros() - last_micros) >= debouncing_time * 1000) {
    int val = digitalRead(interruptPin);
      notify(val);
  }
  last_micros = micros();
}
// Make HTTP Call to web service
void notify(int val)
{
  WiFiClient client;
  const String frontDoorState = doorStates[val];
  String url = "http://192.168.1.19/alarm/front-door/state/" + frontDoorState;
  client.connect(host, 80);
    client.print(String("GET ") + url + " HTTP/1.1\r\n" +
                 "Host: 192.168.1.19\r\n" +
                 "Connection: close\r\n\r\n");
                 client.stop();
}

Simple: don't do HTTP requests in the interrupt.
It's usually bad to do anything heavy like that in an interrupt.  Instead you should just set a flag in the interrupt (volatile bool) and examine that flag in loop().
volatile bool sendNotification = false;
volatile int notifyVal = 0;

void loop() {
    if (sendNotification) {
        notify(notifyVal);
        sendNotification = false;
    }
}

void handleInterrupt() {
    if ((long)(micros() - last_micros) >= debouncing_time * 1000) {
        notifyVal = digitalRead(interruptPin);
        sendNotification = true;
    }
    last_micros = micros();
}

Indeed, it was simple :) Thank you. I might need some kind of queue in this case. if the reed switch is open/close very quickly, the state variable might be changed in the meantime.

Indeed it might. In that case, instead of a queue, why not just a count? If it's currently HIGH and there have been 3 transitions, you know they would have been HIGH, LOW, HIGH to get to where you are now. Reset the count as you send it.


text:
Can't upload sketch - avrdude: butterfly_recv(): programmer is not responding
I'm trying to upload a Blink example to run on a pro-micro (leonardo) but it is not working anymore (it was just working yesterday).
Steps to reproduce:

Plug the device in USB port
Open Blink example in Arduino IDE (version 1.8.8)
Select the port and board accordingly to Arduino Leonardo
Compile and try to upload it.

The code compile successfully but when uploading it just halts. The ide console displays:

avrdude: error: programmer did not respond to command: exit bootloader
Forcing reset using 1200bps open/close on port /dev/ttyACM0 PORTS
  {/dev/ttyACM0, } / {/dev/ttyACM0, } => {} PORTS {/dev/ttyACM0, } /
  {/dev/ttyACM0, } => {} PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {}
  PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {} PORTS {/dev/ttyACM0, }
  / {/dev/ttyACM0, } => {} PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } =>
  {} PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {} PORTS
  {/dev/ttyACM0, } / {/dev/ttyACM0, } => {} PORTS {/dev/ttyACM0, } /
  {/dev/ttyACM0, } => {} PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {}
  PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {} PORTS {/dev/ttyACM0, }
  / {/dev/ttyACM0, } => {} PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } =>
  {} PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {} PORTS
  {/dev/ttyACM0, } / {/dev/ttyACM0, } => {} PORTS {/dev/ttyACM0, } /
  {/dev/ttyACM0, } => {} PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {}
  PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {} PORTS {/dev/ttyACM0, }
  / {/dev/ttyACM0, } => {} PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } =>
  {} Uploading using selected port: /dev/ttyACM0
  /home/fabio/Downloads/pacotes/arduino-1.8.8/hardware/tools/avr/bin/avrdude
  -C/home/fabio/Downloads/pacotes/arduino-1.8.8/hardware/tools/avr/etc/avrdude.conf
  -v -patmega32u4 -cavr109 -P/dev/ttyACM0 -b57600 -D -Uflash:w:/tmp/arduino_build_350609/Blink.ino.hex:i
avrdude: Version 6.3-20171130
           Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
           Copyright (c) 2007-2014 Joerg Wunsch
     System wide configuration file is "/home/fabio/Downloads/pacotes/arduino-1.8.8/hardware/tools/avr/etc/avrdude.conf"
     User configuration file is "/home/fabio/.avrduderc"
     User configuration file does not exist or is not a regular file, skipping

     Using Port                    : /dev/ttyACM0
     Using Programmer              : avr109
     Overriding Baud Rate          : 57600
     AVR Part                      : ATmega32U4
     Chip Erase delay              : 9000 us
     PAGEL                         : PD7
     BS2                           : PA0
     RESET disposition             : dedicated
     RETRY pulse                   : SCK
     serial program mode           : yes
     parallel program mode         : yes
     Timeout                       : 200
     StabDelay                     : 100
     CmdexeDelay                   : 25
     SyncLoops                     : 32
     ByteDelay                     : 0
     PollIndex                     : 3
     PollValue                     : 0x53
     Memory Detail                 :

                              Block Poll               Page                       Polled
       Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
       ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
       eeprom        65    20     4    0 no       1024    4      0  9000  9000 0x00 0x00
       flash         65     6   128    0 yes     32768  128    256  4500  4500 0x00 0x00
       lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
       signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

     Programmer Type : butterfly
     Description     : Atmel AppNote AVR109 Boot Loader

Connecting to programmer: .avrdude: butterfly_recv(): programmer is
  not responding
avrdude: butterfly_recv(): programmer is not responding

A strange behavior I noticed is each time I plug the device again in the usb port different leds are light up, some times only RX, sometimes only TX and sometimes none (the power led is always on)
What could be happening here? Can it be the problem on the hardware?

I experienced the same frustrating issue for days. It was Ubuntu.
The fix was also so easy: sudo apt purge modemmanager
Until I discovered it, I suffered headache for days.
The auto upgrader may cause issues with this command. It can be solved
with the following command:
sudo dpkg-reconfigure -plow unattended-upgrades
At the first prompt, choose not to download and install updates.
Then reboot.

Holy crap, this actually worked for me. I couldn't program a "SMAKN Beetle USB ATMEGA32U4 board" Leonardo clone, and this fixed it. Thank you so much.

On fedora and using a Pro Micro, I did systemctl restart ModemManager and upload using micro board on Arduino IDE.

Purging modemmanager worked for me too! It is important to reboot after removing the package. Thanks so much!

I have successfully solved this a year ago and I am trying to remember how I did it. So while it's fresh in my head this thing has to do with the bootloder.
The first and most obvious thing you can do is try to doubletap the reset and ground contact. Double tapping it will force the Arduino to reset and start in the bootloader for 8 seconds.
This is how I managed to install the driver for my pro-micro, it wouldn't install unless you did it when Arduino was in bootloader mode. But this strategy doesn't work for the code upload for some reason although many people claim it was the only thing that helped.
Another thing that could maybe help is clearing the Arduino's cache. When I was trying to compile a year ago, after many attempts I had to clear the pro-micro with another Arduino once in a while (you may need this later on). [thebusybee's note: I never heard about a cache in AVR micros. If a sketch is uploaded it will be flashed into the non-volatile memory overwriting all that was at its place before.]
Something else I remembered (if this is the case it would make things very problematic for me) is the USB cable. Again before my 1 year break I remembered that uploading the sketch for me only worked with 1 out of like 15 micro-USB cables I had (the one that's the shortest and thickest). That cable is broken now so I can't really check this unless I start researching microUSB cables right this instant.
Finally it may be the system. If nothing works try uploading the sketch from another preferably clean system.
Anyway, I hope you solve this because I am trying to solve the same issue.
Good luck

source: Stack Exchange

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

sort: votes


text:
How to drive N channel gate correctly from Adafruit Feather pinout?
I am learning how to create a soft latch power switch, using an N channel mosfet.
Currently, I have this:

simulate this circuit – Schematic created using CircuitLab
The idea is (so far) that I can turn it on with the switch, the Arduino immediately brings the power control high (ensuring the FET stays on), and brings that same pin low after 1.5s (simulating a timed shutdown).
However; when the power control goes low, I still see about 1.8v in the power control line (I'm presuming its floating?), which leaves this particular FET partially open.
If I disconnect the power control line from the MCU, I get the behaviour I expect. I can touch the power control to +ve and the FET will switch on.  If I lift the control line from +ve, the FET closes the gate, due to the pull down resistor.
I'm struggling to understand why the FET works in isolation, but does not work when connected to the MCU output pin.  The pinMode is OUTPUT.
FET (3055VL): https://www.onsemi.com/pub/Collateral/MTP3055VL-D.PDF
Here's the test code I'm using.
It simply flashes a build in LED 10 times then does a power off.
int ledPIN = 17;
int controlPin = 11;
int lDelay = 150;

bool shouldBeUp = true;

void setup()
{
  pinMode(ledPIN, OUTPUT);
  pinMode(controlPin, OUTPUT);
  digitalWrite(controlPin, HIGH);
}

void loop()
{
  if (shouldBeUp) {
    for (int i = 0; i < 10; i++)
    {
      digitalWrite(ledPIN, LOW); // on
      delay(lDelay);
      digitalWrite(ledPIN, HIGH); // off
      delay(lDelay / 2);
    }

    // Leave the LED low
    digitalWrite(ledPIN, LOW);
    digitalWrite(controlPin, LOW);
    shouldBeUp = false;
  }
}

Any help is appreciated! Thank you :)

Your problem is that the GPIO pin is referenced to ground - and the MOSFET is isolating that ground.
You need instead to switch the power not the ground - and for that, you use a P-channel MOSFET.

simulate this circuit – Schematic created using CircuitLab
To hold the power on you now set the GPIO LOW instead of HIGH.
If you need to switch a higher voltage than the operating voltage of the MCU you will need to add another N-channel MOSFET to pull down the P-channel's gate.

Thanks for this. I have a p-channel on the way to try this out.   Does that mean a circuit such as described here (https://www.youtube.com/watch?v=0IjJH3ksqfs) see 1:27m, would also not work, since the PWR_CTRL would have the same problem?

That circuit is what I mean when I refer to adding an n fet for switching a higher voltage.

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


text:
how can I upload a hex file to an arduino uno?
I have a Rostock Max 3d with an Arduino Uno as the controller. The OEM has a firmware version I would like to upload, but it is in the hex file format.
I have looked all over the Arduino IDE, but did not found a way to upload a hex file to the Arduino. I tried using AVRDUDE, but the Arduino only communicates with my PC when I set the "Programmer" to AVRISP. I have uploaded other codes for blink, and hello_world, but haven't been able to compile the firmware source. I was hoping I could just use the hexfile included in the firmware package.
My OS is Linux.

You can enable "Verbose output" under File -> Preferences for uploading the code.
The Arduino IDE also uses avrdude to upload its sketches - you may "steal" the command it uses from that verbose output.
After that, simply edit the command used by the IDE to point to your .hex file.

I've been using Xloader. http://www.hobbytronics.co.uk/arduino-xloader

I use a standalone programmer that uploads a .hex file from an SD card via the ICSP interface.

I recommend looking at the arduino IDE files located at "(install path)/hardware/arduino/avr/" (on windows anyway, I should assume the same on linux).
I am unsure if the following files have the .txt extension on them, but if not use just the file name.

Open and look in "boards.txt" and find the associated entries starting with "uno." keeping this file open.
Next open "platform.txt" looking for the entries "tools.avrdude" (the avrdude part comes from boards.txt "uno.upload.tool" entry) and copy into a new text editor the value of "tools.avrdude.upload.pattern" you can fill in the parameters later.
With the command you copied replace the following:
from platform.txt

"{cmd.path}" = "tools.avrdude.cmd.path"
"{config.path}" = "tools.avrdude.config.path"
"{upload.verbose}" = "tools.avrdude.upload.params.verbose"
"{upload.verify} = "tools.avrdude.upload.verify"

now from boards.txt

"{build.mcu}" = "uno.build.mcu"
"{upload.protocol} = "uno.upload.protocol
"{{serial.port}" = Your serial port (according to research something like /dev/ttyS0)
"{upload.speed}" = "uno.upload.speed"
"{build.path}" and "{build.project_name} = path to file you are trying to upload

So with the above set out for me to upload a program to an Arduino uno I would use something like the following in windows:
assuming install path was "C:\Arduino\"

"C:\Arduino\hardware\tools\avr\bin\avrdude.exe" "-CC:\Arduino\hardware\tools\avr\etc\avrdude.conf" -v -patmega328p -carduino "-PCOM1" -b115200 -D "-Uflash:w:C:\MyArduinoProject\build.hex:i"

for linux it could possibly be (I really am unsure):
assuming install path was "/opt/Arduino/"

"/opt/Arduino/hardware/tools/avr/bin/avrdude" "-C/opt/Arduino/hardware/tools/avr/etc/avrdude.conf" -v -patmega328p -carduino "-P/dev/ttyS0" -b115200 -D "-Uflash:w:/usr/MyArduinoProject/build.hex:i"

The above should work for you, I have previously written my own program to upload a hex file to the Arduino utilizing the above commands and avrdude.

I think you can use this software http://www.mediafire.com/file/tx2l85gsdkpf5d4/HEXtoArduino_V1.0.0.zip/file

I found the definitive answer to this.

Start Arduino IDE
To to File...Preferences...
Turn on Show verbose output during: [X] upload (image 1 below)
Upload a sketch to your Arduino Uno
I used the sample blink sketch and saw the following (image 2 below):

AVRDude: is used to upload
You want that first line shown in white --- when you expand it you'll see that it is the entire line of code that is used to upload the HEX file of your program to the Uno.
The entire command on my computer looks like the following:
C:\Users\<username>\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17/bin/avrdude -CC:\Users\<username>\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17/etc/avrdude.conf -v -patmega328p -carduino -PCOM3 -b115200 -D -Uflash:w:C:\Users\<username>\dev\arduino\STK2UPDI\build\blink.ino.hex:i

I'm going to break this down into a few lines:
First, it's the full path to the avrdude exe.
Then it is passing the -C argument with the full path to the avrdude.conf file
c:\longpath\avrdude -C C:\avrdude.conf
Then a bunch of params to set up avrdude properly:
-v -patmega328p -carduino -PCOM3 -b115200 -D -Uflash:w:
And finally the full path to the HEX file you want to upload
c:\longpath\blink.ino.hex:i
All You Have To Do
All you have to do is take that extremely long line and replace the full-path to the hex file to be your target HEX file and then run the entire command and you'll see something like what is shown in image 3 below.
Image 1

Image 2

Image 3

neat, I'll check that out. what version are you using?

using Arduino IDE 1.8.15


text:
ESP-8266 stopped working due to possibly faulty perfboard layout
I have been following this tutorial to set up my ESP8266. I have also recreated on a perfboard the circuit provided in the tutorial, and I intend to use this perfboard circuit in my project.
The problem arises when I plug my ESP into the perfboard and try to talk to it through the serial monitor. When using a baud rate of 115200, the ESP responds to commands but in a garbled format. Also, the blue LED stays on after powerup for increasingly long periods of time. Now the blue LED is always on and the ESP no longer responds to any commands, except when reset and asked for the startup firmware info. I suspect that the ESP is now broken but am not sure how to check.
Also note that the ESP was working fine on a breadboard at 9600 baud, prior to the blue LED incident. Now it won't work with the breadboard either.
All commands were sent with newline and carriage return.
Is the ESP8266 broken? Could there be something wrong with my perfboard circuit? The circuit is rather dense and contains wiring for several other components in addition to the ESP-8266.

most ESP8266's default baud rate is the non standard 74880 (which is 115200 * 26 / 40)

@JaromandaX when serial monitor is set to 74880 baud the "boot message" shows up when resetting the board. However I'm unable to get a response from any commands sent to the board, at any baud rate.

It turns out the real culprit was the AT+IPR=9600 command bricking the board. The board was "fixed" by obtaining the firmware and flashing it to the board using esptool.py. Download the repo's source code, navigate to the directory bin/at/, and see the file README.md to see which addresses to flash the different parts to.


text:
Precise On/Off control for IR LED
My goal is to be able to send/receive IR messages in my own custom format and send messages ~10 bytes long. My message object will get serialized down to individual bits, which are transmitted by turning the IR LED on/off at specific timings of my choosing to represent logical ones and zeros. From what I've seen, an IR LED can be turned on/off in either a while loop or as a PWM signal in order to transmit the message. I'm under the assumption the only thing gained by using a PWM signal is that the work there is done on a timer callback and let other code run seemingly simultaneously. For simplicity, I opted for the while loop approach.
The issue I am seeing is one of two. Either the receiver is not reading the timings right, or the transmitter is not turning the LED on/off as fast as I would expect.
For the example code below, the IR LED is turned on for 600 microseconds, and off for 300. (Eventually, my custom messages will be built up using something along these lines.) However, as you can see in the Sample Outputs below the receiver is not seeing the IR signal as on or off for anywhere near that amount of time.
Not sure if this is a setup issue, or something else. The two Arduino boards I'm using are both Arduino Pro ATmega328p boards. For the board sending the IR signal, Pin 6 goes to a 330 Ohm resistor, then to the LED, then to ground. The IR Receiver on the other board has no resistors, just direct connections to pins. When reading the IR signals, I hold the receiver a few centimeters away from the LED.
My questions are:

Is this a viable setup? Should this work? Or am I all wrong in my assumptions and need to look some other way of doing this?
Is my assumption about turning the LED on/off with a while loop vs. a PWM signal true? Or should I remove the loop concept and only use a PWM signal.

IR Transmit Code:
#define IRpin          6

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

void loop() {
  //LED On
  PORTD |= (1 << IRpin);
  delayMicroseconds(600);

  //LED Off
  PORTD &= ~(1 << IRpin);
  delayMicroseconds(300);
}

IR Receive Code (taken from an online example, only modifications are to output text):
#define IRpin_PIN      PIND
#define IRpin          2

// the maximum pulse we'll listen for - 65 milliseconds is a long time
#define MAXPULSE 65000
#define RESOLUTION 20

uint16_t pulses[300][2];  // pair is high and low pulse
uint8_t currentpulse = 0; // index for pulses we're storing

void setup(void) {
  Serial.begin(9600);
  Serial.println("Ready to decode IR!");
}

void loop(void) {
  uint16_t highpulse, lowpulse;  // temporary storage timing
  highpulse = lowpulse = 0; // start out with no pulse length

  while (IRpin_PIN & (1 << IRpin)) {
    // count off another few microseconds
    highpulse++;
    delayMicroseconds(RESOLUTION);

    // If the pulse is too long, we 'timed out' - either nothing
    // was received or the code is finished, so print what
    // we've grabbed so far, and then reset
    if ((highpulse >= MAXPULSE) && (currentpulse != 0)) {
      printpulses();
      currentpulse = 0;
      return;
    }
  }
  // we didn't time out so lets stash the reading
  pulses[currentpulse][0] = highpulse;

  // same as above
  while (! (IRpin_PIN & _BV(IRpin))) {
    // pin is still LOW
    lowpulse++;
    delayMicroseconds(RESOLUTION);
    if ((lowpulse >= MAXPULSE)  && (currentpulse != 0)) {
      Serial.println("Breaking - Hit max Pulse Low");
      printpulses();
      currentpulse = 0;
      return;
    }
  }
  pulses[currentpulse][1] = lowpulse;

  // we read one high-low pulse successfully, continue!
  currentpulse++;
}

void printpulses(void) {
  uint32_t totalMicroseconds = 0;
  for (uint8_t i = 0; i < currentpulse - 1; i++) {
    Serial.print("On(");
    Serial.print(pulses[i][1] * RESOLUTION , DEC);
    Serial.print(");");
    Serial.println("");
    Serial.print("   Off(");
    Serial.print(pulses[i + 1][0] * RESOLUTION , DEC);
    Serial.println(");");

    totalMicroseconds += pulses[i][1] * RESOLUTION;
    totalMicroseconds += pulses[i + 1][0] * RESOLUTION;

    if (i % 8 == 0) {
      Serial.println("");
    }
  }

  Serial.print("On(");
  Serial.print(pulses[currentpulse - 1][1] * RESOLUTION, DEC);
  Serial.print(");");
  totalMicroseconds += pulses[currentpulse - 1][1] * RESOLUTION;

  Serial.println("");
  Serial.print("Total Microseconds: ");
  Serial.println(totalMicroseconds, DEC);
}

Sample Outputs:
Ready to decode IR!
On(20);
   Off(62064);

On(0);
   Off(12060);
On(360);
   Off(1860);
On(440);
   Off(8940);
On(20);
   Off(15460);
On(80);
   Off(25672);
On(40);
Total Microseconds: 127016
On(40);
   Off(6740);

On(300);
   Off(6740);
On(20);
   Off(8520);
On(40);
   Off(6740);
On(1540);
   Off(15720);
On(40);
   Off(34860);
On(20);
Total Microseconds: 81320

On(3000);
   Off(35384);

On(40);
   Off(14180);
On(1220);
   Off(54440);
On(980);
Total Microseconds: 109244

On(200);
Total Microseconds: 200
On(20);
   Off(29160);

On(60);
   Off(26700);
On(60);
   Off(22880);
On(20);
   Off(2928);
On(20);
Total Microseconds: 81848

I don't know for sure, but my guess is that while 65 milliseconds is a long time for a microprocessor, it may not be a long time for LED lighting and receiving.  It may take the LED longer than you or I would think to emit at a readable level, for instance- I don't know. I would at least consider slowing things waaaay down-  like seconds - and see if you get reliable transmission and reception at very very slow speeds. You may also need to consider outside light interference, movement of your hand, etc

I ended up also asking this question at electronics.stackexchange.com. I know that's frowned upon, but the topic really did toe the line between being an Arduino subject or electronics.
To summarize the accepted answer, no IR messages cannot be sent/received the way I thought. The IR LED needs to be on/off at a frequency that matches what the receiver is set to be able to receive. Generally 38kh. So On for 13 microseconds, then Off for 13 microseconds. Then repeat.
https://electronics.stackexchange.com/questions/417387/precise-on-off-control-for-ir-led/417391


text:
Please Correct my Delay Code without using delay();
This is my loop()function:
if(Serial.read() == 't') {
  tarestate = true;
}

while(tarestate == true) {
  timeNowTare = mills();
  if(mills() - timeNowTare >= 3000) {
    Serial.println("Tare");
  }
  tareState = false;
}

Where tareStare is a boolean, timeNowTare is a long.
I need to print on serial:

Tare

three seconds after I enter "t" into serial.
With everything I have tried to date, the program either stops or tares immediately after entering “t”.
EDIT: Thanks to everyone who responded with answers.
The solution was simply to move the timeNowTare = true; declaration up to the Serial.read() if statement. I also changed the while loop to an if statement because it seemed to make my code run quicker.

the only place you initialise timeNowTare is just before you use it ... so, that will never be > 3000 ... perhaps timeNowTare = mills(); inside the first if

Please use the answer box to make an answer. Comments are for clarifying the question. Thanks! :)

not easy on a mobile device - plus was giving the OP a chance at an "aha" moment and fixing the code by themselves :p

Move timeNowTare = millis(); inside first if:
if (Serial.read() == 't') {
  tareState = true;
  timeNowTare = millis();
}

and tareState = false inside second if:
while (tareState) {
  if (millis() - timeNowTare >= 3000) {
    Serial.println(F("Tare"));
    tareState = false;
  }
}

The easiest solution is to just use delay():
if (Serial.read() == 't') {
    delay(3000);
    Serial.println(F("Tare"));
}

What? You said “no delay()”? OK, then just write your own
implementation of delay() and inline it in place of the actual call to
delay():
if (Serial.read() == 't') {
    uint32_t timeNowTare = millis();
    while (millis() - timeNowTare < 3000) continue;  // wait
    Serial.println(F("Tare"));
}

This seems to be more or less what you attempted. You write a while
loop that blocks the program for three seconds. It is also what leoc7's
answer does.
However, doing so is completely foolish. Why would you write your own
version of delay() when the Arduino core provides you with a well
tested one? Why would you want to avoid the standard delay() in the
first place?
It turns out there is a very good reason to avoid delay(). The reason
is that delay() blocks your program for the entire delay duration.
If your code needs to be responsive to some external inputs (as any non
trivial program at some point needs), this means within that time window
the program will be completely unresponsive. The bad thing about
delay() is not the implementation (there is no point in replacing it
with your own), it's the fact that it blocks your program. If you
replace delay() by your own blocking code you have won nothing.
The real solution is to think in terms of a finite state machine. Either
the program is running in “tare mode” or not. The possible state
transitions are:

upon reading a 't' on the serial port, you enter tare mode and take
note of the current time
if you are already in tare mode and three seconds have elapsed since
you entered that mode, then you print out "Tare" and exit tare mode.

Here is a straight forward implementation of such state machine:
static bool tare_mode = false;
static uint32_t tare_start_time;  // meaningful only in tare_mode
if (Serial.read() == 't') {
    tare_mode = true;
    tare_start_time = millis();
}
if (tare_mode && millis() - tare_start_time >= 3000) {
    Serial.println(F("Tare"));
    tare_mode = false;
}

Now you can add more code to loop() and this extra code will never be
blocked by your “tare” feature.


text:
Using TCA9548A to read 30 ADCs
I want to read 30 differential ended analog sensors.
Using ADS1115 16 bit this is possible, but we end up having only 4 address on I2C, so i chose TCA9548A breakout board with 8 I2C multiplex channels,
Is it possible to read the ADC as shown in the block diagram
if yes, please help with code.

based on the datasheet for the tca9548a - what you propose is possible - help, would be to google arduino TCA9548A

If using arduino is not essential, this post could be moved to the electrical engineering stack exchange.


text:
Radio tx/rx makes my oled screen not work
I've been struggeling with this assignment for school for a couple of days. I have finally figured out where the problem lies.
I have an oled screen that is supposed to print out the temperature of a DHT11, at the same time a RF sender should transmit the temperature to another microcontroller. The first microcontroller should also be able to recieve messages via RF and display them on the screen.
I've been having trouble with the oled screen. When i include my RF communication .head file, the oled wont work!!! I Cant understand why and it's really bugging me, I'm thinking it might be a memory problem, but the arduino IDE tells me it is only using 61% of the storage space. I'm using a arduino nano but i also have an Uno and a Mega laying around.
Do you think i should try the Uno or is there a problem in the code somehow?
Thank you so much!
main.ino:
#include "display.h";
//#include "DHT.h";
#include "Radiocom.h";

//long temperature;
String message = "abc123";

void setup()
{
  Serial.begin(115200);
  //initDHT();
  initDisplay();
  //initRF();
}

void loop()
{
  //temperature = readTemp();
  //delay(1000);
  //printTemp(temperature);
  printMessage(message);
  //sendMsg();
  //RFlisten();
  delay(1000);
}

radiocom.h:
#include <RH_ASK.h>
//for feather huzzah ESP:
//RH_ASK rf_driver(2000,13, 12, 14);
RH_ASK rf_driver;

void initRF(){
  rf_driver.init();
  Serial.println("Radio transmitter initiated..");
}

void sendMsg(){
  const char *msg = "testing testing, one two";
  rf_driver.send((uint8_t *)msg, 24);
  rf_driver.waitPacketSent();
  delay(1000);

}

void RFlisten(){
  uint8_t buf[24];
  uint8_t buflen = sizeof(buf);
  if(rf_driver.recv(buf, &buflen)){
    Serial.print("Message received: ");
    Serial.println((char*)buf);

  }

}

display.h:
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>  // Include core graphics library for the display
#include <Adafruit_SSD1306.h>  // Include Adafruit_SSD1306 library to drive the display

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

// Define SPI pins:

#define OLED_MOSI   9
#define OLED_CLK   6
#define OLED_DC    7
#define OLED_CS    8
#define OLED_RESET 13

// Create display
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT,
  OLED_MOSI, OLED_CLK, OLED_DC, OLED_RESET, OLED_CS);

void initDisplay(){

  delay(100);

  display.begin(SSD1306_SWITCHCAPVCC);

  display.clearDisplay();  // Clear the buffer

  display.setTextColor(WHITE);  // Set color of the text

  display.setRotation(0);  // Set orientation. Goes from 0, 1, 2 or 3

  display.setTextWrap(false);  // By default, long lines of text are set to automatically “wrap” back to the leftmost column.
                               // To override this behavior (so text will run off the right side of the display - useful for
                               // scrolling marquee effects), use setTextWrap(false). The normal wrapping behavior is restored
                               // with setTextWrap(true).

  display.dim(0);  //Set brightness (0 is maximun and 1 is a little dim)

  Serial.println("Display initiated..");

}

void printMessage(String message){
  display.setTextSize(0);  // Set text size. We are using a custom font so you should always use the text size of 0
  display.setTextColor(WHITE);
  display.setCursor(0,50);
  display.clearDisplay();
  display.print(message);
  display.display();
  Serial.println("printing message on display");
  delay(1000);

}
void printTemp(long temp){

  display.setTextSize(0);  // Set text size. We are using a custom font so you should always use the text size of 0

  display.clearDisplay();  // Clear the display so we can refresh
  // Print text:
  display.setCursor(25, 15);  // (x,y)
  display.println("temp:");  // Text or value to print
  // Draw rectangle:
  display.drawRect(79, 0, 35, 27, WHITE);  // Draw rectangle (x,y,width,height,color)
                                           // It draws from the location to down-right

  // Print variable with left alignment:
  display.setCursor(83, 20);  // (x,y)
  display.println(temp);  // Text or value to print

  display.display();  // Print everything we set previously
  Serial.println("Printing temp..");

}

I thought I rad somewhere that SPI on the nano uses 10 (SS), 11 (MOSI), 12 (MISO), 13 (SCK) - though, if that were a hard and fast rule, I guess your code wouldn't work with the OLED either way .. edit: oh, I see, you're using using software (bitbang) SPI

It could be memory, yes. What many people don't realise is that using the SSD1306 display normally eats up a quarter of their RAM with a dynamic allocation of a display buffer. This does not show in the "used memory" in the IDE.

Make sure that when talking to your display it's chip select is asserted and your RF radio's chip select is de-asserted .   Reverse this when talking to the radio.  One of the drivers is likely leaving one of the chip selects in the wrong state.


text:
Display Wireless Temperature Sensor data to Web page by using Serial communication
I am reading from wireless temperature sensor with help of gateway receiver connected to Arduino UNO, using this code
I need to display the data of the wireless sensor on the webpage.
Any suggestion on which help to start working using serial com or should I have to use Ethernet port for this?

On what web page?

So you want to read serial port data from a webpage, I am not a web developer, but I suggest you to read the following links.
You can use a local server to read the data (NodeJs, php) :

https://stackoverflow.com/questions/20549151/how-to-read-serial-port-data-from-javascript
https://stackoverflow.com/questions/29619929/read-data-form-serial-port-on-windows-with-php


text:
C: No communication to a connected serial port?
I'm trying to connect to an arduino Mega At2560 unit connected via usb serial port in my linux based PC.
Using C code, I'm trying to send and receive simple text strings, just I'm able to send and receive on both sides.
On arduino:
int incomingByte = 0;    // for incoming serial data

void setup() {
    Serial.begin(19200);    // opens serial port, sets data rate to 9600 bps
}

void loop() {
  // send data only when you receive data:
  if (Serial.available() > 0) {

    // read the incoming byte:
    incomingByte = Serial.read();

    // say what you got:
    Serial.print((char)incomingByte);
  }

}

basically just a loop that checks if there is serial data, and if so reads it and prints it back. there's a (char) conversion so I'll see right away the sent data is what I got back (linux side)
For the linux code I use the pretty standard code for opening a port which I found here
I call the Arduino "Table" as it will eventually operate a moving table through USB commands.
C file:
#include "TableFunctions.h"

bool connected=false;
int fd;
char *portname;

int set_interface_attribs (int fd, int speed, int parity)
{
        connected=false;
        struct termios tty;
        struct termios tty_old;
        memset(&tty, 0, sizeof tty);
        if (tcgetattr (fd, &tty) != 0)
        {
                printf("PC: Error %d from tcgetattr  \n", errno);
                return -1;
        }
        tty_old = tty;

        cfsetospeed (&tty, (speed_t)B19200);
        cfsetispeed (&tty, (speed_t)B19200);

        //tty.c_cflag |= B19200;
        tty.c_cflag     &=  ~PARENB;            // Make 8n1
        tty.c_cflag     &=  ~CSTOPB;
        tty.c_cflag     &=  ~CSIZE;
        tty.c_cflag     |=  CS8;

        tty.c_cflag     &=  ~CRTSCTS;           // no flow control
        tty.c_cc[VMIN]   =  1;                  // read doesn't block
        tty.c_cc[VTIME]  =  5;                  //
        tty.c_cflag     |=  CREAD | CLOCAL;     // turn on READ & ignore ctrl lines
        cfmakeraw(&tty);
        tcflush( fd, TCIFLUSH );

        if (tcsetattr (fd, TCSANOW, &tty) != 0)
        {
                printf("PC: Error %d from tcsetattr  \n", errno);
                return -1;
        }
        return 0;
}

void set_blocking(int fd, int should_block)
{
        struct termios tty;
        memset(&tty, 0, sizeof tty);
        if (tcgetattr (fd, &tty) != 0)
        {
                printf("PC: Error %d from tggetattr  \n", errno);
                return;
        }

        tty.c_cc[VMIN]  = should_block ? 1 : 0;
        tty.c_cc[VTIME] = 10;            // 0.5 seconds read timeout

        if (tcsetattr (fd, TCSANOW, &tty) != 0)
                printf("PC: Error %d setting term attributes  \n", errno);
}

void OpenSerialPort()
{
    char *portname = "/dev/ttyACM0";

    printf("PC: Opening port to table \n");

    int fd = open(portname, O_RDWR | O_NOCTTY | O_SYNC);

    usleep(2000000);
    if (fd < 0)
    {
        printf("PC: Error %d opening %s: %s  \n", errno, portname, strerror(errno));
        return;
    }

    set_interface_attribs(fd, B19200, 0);  // set speed to 19,200 bps, 8n1 (no parity)
    set_blocking(fd, 0);                // set no blocking
    printf("PC: Connected\n");
    connected = true;
}
void PrepareWriteCommand(int numberOfCommands, const char *commands[numberOfCommands])
{
    if(connected) //check if arduino still connected
    {
        for(int i = 0; i<numberOfCommands; i++) //go through commands
        {
            int bufferSize = strlen(commands[i]); //get the buffer size needed for this command
            char charArray[bufferSize]; //helper char array
            memcpy(charArray,commands[i],bufferSize);//copy command to the char array
            charArray[bufferSize]=0; //make sure there is a stop symbok at the end
            WriteSerialPort(charArray); //command is ready to be sent, send it.
        }
    }
}
int WriteSerialPort(const char *buffer)
{
    printf("PC: Now writing: ");
    int n_written = 0; //how many bytes were written

    n_written = write(fd, buffer, strlen(buffer)); //write the command and return how many bytes were written

    printf("\n");

    //check bytes send and return ouput (error, nothing or x bytes sent)
    if(n_written<0)
    {
        printf("PC: Error %d from %s \n",errno, strerror(errno));
    }
    else if(n_written == 0)
    {
        printf("PC: Nothing was written  \n");
    }
    else
    {
        printf("PC: Written %i bytes  \n", n_written);
    }

}

int ReadSerialPort(char *buffer, unsigned int buff_size)
{
    //check if arduino still connected
    if(connected)
    {
        //read the serial data
        if(read(fd,buffer,buff_size))
            return sizeof(buffer); //return how much bytes were read
        else
        {
            //else print nothing received
            printf("PC: Arduino not Connected (ReadSerialPort) \n");
        }
    }
}

in OpenSerialPort I basically open a new fd, and call the functions that set the communication settings.
I use PrepareWriteCommand to make sure commands input from users are with a stop symbol and send them to WriteSerialPort where I use write() and print how many bytes were sent.
H file:
#include <errno.h>
#include <fcntl.h>
#include <termios.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <stdbool.h>

#define MAX_DATA_LENGTH 256

int set_interface_attribs (int fd, int speed, int parity);
void set_blocking(int fd, int should_block);
void OpenSerialPort();
void PrepareWriteCommand(int numberOfCommands, const char *commands[numberOfCommands]);
int WriteSerialPort(const char *buffer);
int ReadSerialPort(char *buffer, unsigned int buff_size);

Main:
#include "TableFunctions.h"
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
    {
        char output[MAX_DATA_LENGTH]; //char array to hold arduino output
        int received = 0; // check if read() got any bytes
        const char* commands[]={"test"}; //test command

        OpenSerialPort(); // open serial port

        PrepareWriteCommand((sizeof(commands)/sizeof(commands[1])),commands); //prepare command for sending

        usleep(500000); //wait for arduino response

        while(true)
        {
            ReadSerialPort(output,MAX_DATA_LENGTH);//check serial port for response
            if(strlen(output)>0) //if anything received
            {
                printf("PC: received %i\n",received); //if yes, how many bytes
                printf("PC: %s\n",output); //and what was received
                usleep(500000);
            }
            else if(strlen(output)<=0) //else print nothing received
            {
                printf("PC: Nothing received\n");
            }
        }
        return 0; //finish program
    }

I tried tweaking the tty flags settings with no success. Each time I run the C code I see the arduino resets (and after opening a new fd I give it some time for bootloading) but no communication is sent between the two.
Output:
PC: Opening port to table
PC: Connected
testPC: Now writing:
PC: Written 4 bytes

PC: received 0
PC:

Any help with understanding why the C code can't communicate with the Arduino will be highly appreciated!

Are you waiting for the bootloader to finish executing before you try sending ... ?

@Majenko yep: int fd = open(portname, O_RDWR | O_NOCTTY | O_SYNC);
usleep(2000000);

was told I never assign received again in ReadSerialPort(), so I fixed it and now I get:
PC: received 8
PC:
I send only 4 bytes so arduino might be sending twice the data in the given time untill PC reads it. It doesn't matter though, right now PC still shows nothing in buffer after I call read()

I might be wrong and the 8 bytes are the size of the pointer (sizeof(buf))

This makes no sense: void PrepareWriteCommand(int numberOfCommands, const char *commands[numberOfCommands])

@Majenko The function gets an array of commands and cycles through it. Basically just preps each command (making sure there's a stop symbol) and sends the to be written through USB one by one.

Yes, but you can't use a parameter to set the size of a parameter. It makes no sense.  You should be using const char **commands or const char *commands[] since you are using an array of pointers.

regarding: Serial.begin(19200);  what about the number of stop bits?  what about the parity?  what about the number of data bits?  Those all need to be set

regarding: ReadSerialPort(output,MAX_DATA_LENGTH);  I doubt that the function: ReadSerialPort() terminates the input with a NUL byte, so any following calls that are expecting a NUL terminated array of characters will not work.  I would expect that function returns a count of the number of characters read, which can be used to insert a NUL byte into the array output[]

regarding: ReadSerialPort(output,MAX_DATA_LENGTH);  The posted code does not check the returned value from ReadSerialPort() AND the actual function: ReadSerialPort() fails to return an error status when (for instance) the port is not connected

regarding: printf("PC: Now writing: ");  this data will stay in the output stream until something happens (like another call to printf() that (properly) has a '\n' as part of the data (perferably the last character output) forces the data to be passed to the terminal

to call to read() will let the code know if anything is there to read.  Waiting some arbitrary time is not a good method.  Much better to keep calling ReadSerialPort() until some data is seen

OT: regarding: printf("PC: Error %d opening %s: %s  \n", errno, portname, strerror(errno));  Error messages should be output to stderr, not stdout.  Suggest: `fprintf( stderr, "PC: Error %d opening %s: %s  \n", errno, portname, strerror(errno));

the functions in the code that handle the IO communications fail to let the caller know when an error occurs, so the caller will (blissfully) keep right on, as though everything is good

Problem was in OpenSerialPort(). I set another variable fd which is local, thus given priority. then when OpenSerialPort() is done, it is deleted, and the global fd remain unset. This is why I can't send anything from or to the PC.
Thanks.


text:
Is there software to make an interactive GUI for my TFT touch screen shield?
I was wondering this, because realized it takes quite time consuming due to all the lines of code I have to write.

Not for Arduino, no. Only for things like 4D or Nextion displays.

Thank you, I guess I'll get to writing that code ☹


text:
Simultaneous button reading?
I'm currently working on a project that requires that I simultanously check the state of two buttons. Each button HIGH state is assigned to one if loop. Here's the basic concept:
void loop() {
  S1_State = digitalRead(S1_Pin);
  S2_State = digitalRead(S2_Pin);
  ButtonPRESSED = false;

  P1_Time = random(2000, 5000);
  delay(P1_Time);
  digitalWrite(P1_Pin, HIGH);

  while(ButtonPRESSED == false) {
    if (S1_State == HIGH) {
       Serial.print("Player 1 wins");
       Serial.print("");
       digitalWrite(P1_Pin, LOW);
       ButtonPRESSED = true;
       delay(5000); }
    if (S2_State == HIGH) {
       Serial.print("Player 2 wins");
       Serial.print("");
       digitalWrite(P1_Pin, LOW);
       ButtonPRESSED = true;
       delay(5000); }

The problem is that checking for the button states this way requires that the S1_State loop _has to be read before the S2_State loop_, thus giving player 1 an advantage. Although I'm not sure how pronounced this issue is in practice, it certainly was noticable when I was first trying this project out through python code on a Pi through similar means.
Is it possible check the conditions to both if loops simultanously? If not, are there other ways to circumvent this problem?

read through your code line by line ..... imagine that both the buttons are pressed at the same time ....... is that the expected behavior?

There is a very easy solution to your problem, and it's called "interrupts".
The processes inside loop method are executed synchronously, so always one read will be done before second one, and always one check will be done before a second one (even if they are inside one if statement)
Fortunately there is a way of simulating asynchronous behavior in ATmega. It's called "external interrupt". You can setup ATmega inside Arduino to stop processing loop method and instead immediately run a different method whenever a voltage on one of the pins change. You are "interrupting" execution of loop  hence the name "interrupt". In Arduino Uno this can be done (only) on pins 2 and 3.
https://www.arduino.cc/reference/en/language/functions/external-interrupts/attachinterrupt/
I made a little model i Tinkercad

Whenever you push left button PIN2 of the Arduino gets shorted to ground.
Whenever you push right button PIN3 of the Arduino gets shorted to ground.
And now my source code
void setup()
{
  pinMode(2, INPUT_PULLUP);
  pinMode(3, INPUT_PULLUP);

  interrupts();
  attachInterrupt(digitalPinToInterrupt(2), Player1ButtonPress, FALLING);
  attachInterrupt(digitalPinToInterrupt(3), Player2ButtonPress, FALLING);

  Serial.begin(9600);
}

void Player1ButtonPress() {
  Serial.println("Player 1 wins");
}

void Player2ButtonPress() {
  Serial.println("Player 2 wins");
}

void loop()
{
    //nothing here
}

And now some explanation.
In setup we first setup PIN2 and PIN3 as "input with pullup resistor". In our design this means that when button is not pressed those pins will have 5V on them, but as soon as the buttons are pressed voltages go down to 0V. Then we make sure that interrupts are turned on (they are on by default, but I like to show everyone who is reading the code that I will be using them) and then we do some attachInterrupt magic. We make that a "falling edge" (change from 5V to 0V) on PIN2 and PIN3 will immediately run methods Player1ButtonPress and Player2ButtonPress.
When I was playing with buttons they worked perfectly.

And a word about possible cheating. Keeping the button pressed does not create a "falling edge" (voltage on a pin is constantly 0) so if you only add some global variables with info when game starts and who won. Then add some conditions in the two methods responsible for interrupts. You can then use the loop method to start the game, and show result.

Does the interrupt handling give either player an advantage? What happens in the event of a tie?

@Craig The more I think about it the more I think that there still will be a tiny bias, because ATmega will analyze values of pins with 16MHz frequency so there still is possible that a "tie" will happen and one button will be chosen by processor to be a "winner" incorrectly. But this time the decision will take only 1 clock cycle (6 nano seconds). digitalRead take about 50 clock cycles, and we need two of them. So we gained 100 times more resolution and I think it's enough for a "game" to risk suck event. Nothing is perfect in electronics.

You can't connect a button to an interrupt this way, you have to take debouncing precautions: http://ohm.bu.edu/~pbohn/__Engineering_Reference/debouncing.pdf

The game win condition is achieved on first falling edge. Debouncing is unnecessary since every subsequent "bounce" will be counted as a button press after game has ended. Debouncing makes sense only if system has to wait for subsequent input.

Instead of using the high level digitalRead() function access the low level port registers. See this documentation.
A port register is one byte and each bit represents one of the digital inputs on the arduino.
Do something like this:
pin_status = PIND; //Input port D (pins 0-7)
button_1 = bitRead(pin_status, 2); // digital pin 2
button_2 = bitRead(pin_status, 3); // digital pin 3

The values are read simultaneously so it is possible to have a tie.

I think you want after a random time, a 'Start' LED to be lit, and whoever presses his/her button first wins.
There are some problems in your sketch:

It seems even when a button is pressed to early, the button is still taken into account. You should check for this 'cheating'. So check directly after the 'start' LED is lit, that no buttons are pressed. If so, that player loses.
Assuming the players are honest, you check for their buttons, which probably the first iteration it will not be pressed (that would be an immediate reaction speed). However, than you wait 5 seconds; probably both players pressed their buttons, and you check the button of the first player first. It will help, if you change the delay to 1 ms, or even remove it completely.

Untested proposal:
int playerXWon = 0; // No player won yet, 1 = player 1 wins, 2 = player 2 wins, 3 = draw

void loop()
{
   // Delay for a random time.
   P1_Time = random(2000, 5000);
   delay(P1_Time);

   CheatCheck();

   if (playerXWon == 0)
   {
      // Start
      digitalWrite(P1_Pin, HIGH);

      checkFirstPress();
   }
}

void CheatCheck()
{
   // Check if a player did not press its button too early.
   // (Btw, it does not matter if the player presses and release its button before the LED goes on.
   S1_State = digitalRead(S1_Pin);
   S2_State = digitalRead(S2_Pin);

   if (S1_State == HIGH)
   {
      else if (S2_State == HIGH)
      {
         PlayerWin(3);
      }
      else
      {
         PlayerWin(2);
      }
   }
   else
   {
      if (S2_State == HIGH)
      {
         PlayerWin(1);
      }
   }
}

void checkFirstPress()
{
   // Whoever presses first wins.
   while (playerXWon == 0)
   {
      S1_State = digitalRead(S1_Pin);
      S2_State = digitalRead(S2_Pin);

      if (S1_State == HIGH)
      {
         if (S2_State == HIGH)
         {
            PlayerWin(3);
         }
         else if (S1_State == HIGH)
         {
            PlayerWin(1);
         }
      }
      else if (S2_State == HIGH)
      {
         PlayerWin(2);
      }
   }
}

void playerWins(int player)
{
   switch (player)
   {
   case 1:
      Serial.print("Player 1 wins\n");
      break;

   case 2:
      Serial.print("Player 2 wins\n");
      break;

   case 3:
      Serial.print("Both players win\n");
      break;

    default:
       assert(NULL); // Programming error
       break;
   }

   playerXWon = player;

   digitalWrite(P1_Pin, LOW);
}

The cheating pevention will come later, I'm aware of that problem and will add it later. I wanted to tackle this first as it's more important and unlike the cheating prevention I don't know how to do it.

I'm not sure how much that approach would change things as it would most likely still require one button to be read after the other in whatever loop those 5 seconds take place in. Could you clarify what you mean by "change the delay"?

Actually, it's better to remove the delay. When it's removed, many times per ms the buttons are checked, so whoever presses the button first will win. Now it is only checked every 5 seconds, and probably both players press the button within this time easily.

I also split the big function in smaller functions.

Lot's of stuff here I haven't learned yet like switch functions and using void loops as functions, thanks for the pointers.

switch is an if statement to check multiple values easier (instead of if, else if, else.. ). A void function is just to take a fragment of the code and put it separately. This makes your programs much more clear and maintainable. Also you can reuse those fragments without copying them every time.

I was not sure about posting this as an answer, since it is basically some more considerations on the three existing answers (for reference, they are Michel Keijzers's one - using digitalRead -, Craig's one - read the PIND variable at once -, Filip Franik's one - use interrupts), but it became quite long and so a single comment could not fit all of this.
What you and the other answerers wrote is in theory correct. Checking the button of player 1 before player 2 gives an advantage to player one. What you lack is... How much advantage?
Mechanical actions (such as the pressing of a button) have a time duration that is around 50ms*.
Since I assume your application is a reaction time tester, human reaction times are around 250ms.
Moreover mechanical buttons have "bounces". Typical debounce times are in the range 20-100ms. You can avoid this by just checking the first edge.
A player gets an advantage if he is awarded as winner even if the button was pressed at the same time.

_* I tried to find a source for this, but I was not able to get some data. I tried with an online stopwatch and pressing the two spacebars (notebook and USB keyboard) roughly at the same time, obtaining results around 75ms. This is not a real value, so if someone has some measured values or estimations feel free to comment

Now, let's assume you properly coded your program so that you check for ties and avoid delays, since these will greatly affect the following measurements.
In the digitalRead case you are executing this series of actions:

Read status of pin 1 - 3.6us
Read status of pin 2 - 3.6us
Check the statuses and decide who won - some tens of instructions (about 1us)
Loop - a couple instructions (0.5us)

The 60 instructions comes from this thread (3.6us = 57.8 instructions @16MHz); as for the others it's a rough measurement. Let's assume that the function actually samples the pin at the very end of the function.
Now, since you are checking for ties, if both buttons get pressed during phases 3, 4 or 1 you will get a tie (since both buttons will be read as pressed). If both buttons get pressed during phase 2, button 2 will be marked as pressed and button 1 not, thus giving advantage to that player. The time when this happens is about 3.6us long. So you are giving a 3.6us advantage to button 2 player.
In the PIND case you are reading the buttons exactly at the same time. The advantage is thus 0.
In the interrupt case when both EXT0 and EXT1 interrupts are triggered at the same time EXT0 gets executed, since it is before in the ISR. Consequently the player pressing the button on EXT0 has one interrupt checking cycle of advantage. I admit I do not know how often the inputs are checked for the EXT interrupt, but I assume it performs a check every clock cycle (consequently the advantage is 62.5ns).

Now, let's sum up the advantage

digitalRead: 3.6us
PIND: 0
interrupt: 62.5ns

The solution is pretty obvious to me, and it is... Don't care! Even in the worst case scenario you are four order of magnitude faster than your phenomenon. You are giving one player a 4us advantage in a 250ms game (0.0016% of advantage). I'm pretty sure that the mechanical differences between the two buttons (maybe one is a bit stiffer, or has a slightly higher size, or has a slightly lower contact) affect the reading much more than this.
In the end, with this kind of setup you will reasonably be able to have an accuracy that is at most some tens of milliseconds. With other measurement setups (maybe optically based) you can go as low as 1ms. Adding 4us of advantage to one player will not influence the result.
Try to focus on the rest of the program, and for this problem use whichever solution you find more understandable.
NOTE: This is based on the assumption that a proper program is developed, with tie checks  and no delays and so on. The program as you wrote in the question is not ok from this point of view (as it is now it will stay in the loop forever; if you change Sx_State to digitalRead it will become roughly fair - something like 4us of advantage to player one and 3.8us of advantage to player two)

I have to concur with frarugi87 here. The few microseconds taken by
digitalRead() are completely inconsequential for your application. But
let me add that, even if your players were super-humans capable of
sub-millisecond reaction times, you are not giving an advantage to any
of them if you alternatively check button 1, then button 2,
then button 1, and so on. The reason is that, in the small time
window between reading button 1 and reading button 2, you give
an advantage to player 2: he will win if both buttons are pressed
simultaneously. In the following time window (between checking
button 2 and button 1) the same advantage goes to
player 1.
The net result is that the game has a tiny amount of randomness: if both
buttons are pressed simultaneously, the result is seemingly random. But
again, the chances of this happening are so tiny that it makes no sense
to worry about it.
Here is how I would determine the winner. I think this code makes clear
that we are alternatively checking button 1, then button 2,
then button 1...
int find_winner()
{
    for (;;) {
        if (digitalRead(S1_Pin) == HIGH)
            return 1;
        if (digitalRead(S2_Pin) == HIGH)
            return 2;
    }
}


text:
Do I need a pull-up/down resistor for button LED circuit?
When reading up on how to make a circuit that turns an LED on when a button is held down, I keep finding people saying a pull up or down resistor must be involved, to avoid the flickering state of the LED seen with a floating pin. There's also code being implemented, where the state of a pin is read and monitored as the button is pressed down or left raised. What I don't understand, is why this is all necessary. Surely it isn't, considering the circuit below allows the button to be pressed with the LED turning on/off depending on the state of the button.

I made this circuit before drawing it online, and it works exactly as intended. No need for a pull up/down resistor or any code. I must be missing something here, can anyone please explain? It works perfectly with a buzzer as well.
Many thanks.

That problem of turning an led on when a button is pressed is a nice first exercises for getting started with learing arduino, as it makes you learn how to read an input pin, and how to turn on an output pin, and make an led light. What you are doing is sidestepping the whole Arduino part. There isn't anything wrong with that, as as you said, it work the way you want it to work. But you haven't learned anything about inputs and outputs.

your arduino is not doing anything other than supplying power to the LED ..... you can replace the arduino with a battery

The circuit you have made is only using Arduino as a 5V power source. You aren't using any GPIO pins to read the state of the button or to control the LED by an output pin. You've just made a plain-old circuit with a button and LED in series with a power source.
Often for a button-controlling-LED sketch, you will have a button connected between GND and an I/O pin defined as an INPUT_PULLUP, which means the Arduino will be able to read the state of the pin as HIGH (5V) or LOW (0V). The PULLUP part indicates that when the button is not completing the circuit between GND and the pin, a weak voltage is applied to get it up to 5V. In this way it's not "floating" at an unspecified voltage, but is being actively driven to 5V. When you press the button, the input pin is shorted to GND.
A pull-up resistor causes an otherwise un-driven pin to go to logic HIGH. A pull-down resistor causes an otherwise un-driving pin to go to logic LOW.
In the case of a pull-up resistor, reading a logic LOW means the button is pressed, which is kind of the reverse of your circuit operation, so in your sketch code, you would look for LOW to turn on the LED.

No, you don't.
The thing to remember is that you don't put a pulldown (or pullup) resistor on the button - you actually put it on the input.
And since you aren't using an input there is nowhere to put the resistor.
A pullup or pulldown resistor is used to set an input to a pre-defined state. The button or switch is then used to override that pre-defined state.  With your circuit you are just controlling the flow of electrons around a simple loop, from power, through resistor, through LED and back to power. The button just completes that circuit.  There is no "input" to place into a pre-defined state. Hence no pullup or pulldown resistor.

A series resistor is needed to prevent excess current thru the LED or thru the IO pin. 270 ohm to 1K ohm works well.

simulate this circuit – Schematic created using CircuitLab
The internal pullup in the Arduino processer is 30-50K ohm. The external resistor is a current limit resistor. (5V - Vf-led)/resistor = current.
(5V - 2.2V)/270 ohm = 10.3mA. Vf of the LED will vary by color from say 2.2V for a Red to 3.5V for a blue or white.  Insert values if known, or use a 270 to 1K resistor and measure Vf across the LED, then adjust resistor as needed for desired brightness (more current = brighter).

270Ohm pull-up? Isn't that a bit excessive? That would result in 18.5mA of current when the button is pressed, which is a bit wasteful.

See additonal explanation above.


text:
Need help with the syntax for a function that takes a closure
My C++ is very out-of-date. (20+ years, before C++ had closures).
I'm a senior SW engineer, and I spent several hours yesterday trying to figure this out, but I could not work it out.
The background:
I'm trying to create a class, ClosureButton, that is a subclass of another class, ArduinoObject. (An ArduinoObject has setup(), start(), stop(), and loop() methods so that the main program can invoke it.)
(C++ uses the terms closure and lambda to mean different things. In other languages the terms are interchangeable. Forgive me if I'm not using the correct term.)
A ClosureButton's constructor would take a pin number, and a closure with a bool parameter (pressed). I would save that closure to a member variable. When the button's state changed, it would invoke the closure and pass the new button state to the closure.
The question:
I need help with the syntax for the constructor, as well as how to declare the instance variable that would hold the closure.
The constructor would look something like this:
ClosureButton::ClosureButton(uint8_t pin, _unkonwn_syntax_ closure);

(Where I need help with the _unkonwn_syntax_ bit.)
Then I need to declare a member variable on my ClosureButton to hold the closure:
class ClosureButton: ArduinoObject {
  //other stuff
  _other_unkonwn_syntax_ closure;
}

Again, I need help with the syntax to declare a member variable closure of type "closure that takes a bool parameter". (The _other_unkonwn_syntax_ bit.) At this point I don't think my closure will capture variables from its enclosing scope, but at some future date I might need to do that, so help with that would be appreciated as well.)

C/C++ always had pointers to functions

Yup, I'm aware (and I've always found the syntax for C function pointers to be really hard to decipher. I can figure it out, but not easily.) Are you suggesting I use a C function pointer rather than a closure?

There is no difference using a function pointer or a simple (non-capturing) lambda (C++ calls them lambdas).  The only difference is that you provide a lambda instead of a function pointer.
For example:
void (*func)(bool b);

void setup() {
    func = [](bool b) {
        Serial.println(b);
    };

    Serial.begin(115200);
}

void loop() {
    func(digitalRead(0));
}

It's just a normal function pointer, but instead of assigning a function pointer to it you assign a lambda to it - which is just an anonymous function pointer.
To make life easier you can make a typedef for your function pointer variable type:
typedef void (*buttonCallback)(bool);

Then your functions would look like:
ClosureButton::ClosureButton(uint8_t pin, buttonCallback closure);

and:
class ClosureButton: ArduinoObject {
  //other stuff
  buttonCallback closure;
}

The basic syntax of a lambda is quite straight forward:
[](bool foo, int bar) { ... }
^  ^                    ^
|  |                    +- Function body
|  +- Normal parameter list
+- Empty capture list

If you want to return a value and you don't want to rely on the function being an "auto" return type you can specify the return type after the parameter list:
[](bool foo, int bar)->int { ... }
^  ^                   ^     ^
|  |                   |     +- Function body
|  |                   +- Return type
|  +- Normal parameter list
+- Empty capture list

If you don't specify the return type it is inferred from the type of variable/value that is used with return (as if the function were auto).

Here's a full example passing the lambda to a class which stores the pointer to it in a variable to call later:
typedef int (*callback)(bool b);

class MyClass {
    private:
        callback func;
        int pin;

    public:
        MyClass(int pinno, callback myfunc) {
            func = myfunc;
            pin = pinno;
        }

        void doit() {
            Serial.println(func(digitalRead(pin)));
        }
};

MyClass foo(3, [](bool b)->int {
        Serial.println(b);
        return rand();
});

void setup() {
    pinMode(3, INPUT_PULLUP);
    Serial.begin(115200);
}

void loop() {
    foo.doit();
    delay(100);
}

If you want to do capturing with your lambdas then I'm afraid you're out of luck.
The data type for that kind has to be std::function<void> but unfortunately the cut-down C library AVR-LIBC doesn't support that. The STL is generally not included for small microcontrollers since it uses far too many resources to be practical.

Ok, that looks like what I need. Thanks. (Using a typedef definitely makes it easier for me to read). I'll have to try that when I get home.

This won't work for capturing lambdas though. Dealing with those is a whole other kettle of fish.

@ratchetfreak I'm unsure what you mean by "capturing" the lambda. You can pass a lambda through a function, assign it to a variable, whatever - exactly the same as a function pointer.

A capturing lambda is a lambda that captures variables. A non-capturing lambda, like the ones in your examples, is just a plain anonymous function, hardly deserving the name “lambda”.

@EdgarBonet Ah, I see what you mean. I am fairly new to lambdas in C++.

@EdgarBonet Without STL there's no way to pass capturing lambdas as far as I can tell.  There's no std::function.

A functor (an object with operator()(bool) defined) may be a viable alternative.

Or, just don't try and capture variables. Just arrange to have the right parameters available. Or worst case use a variadic function.

@EdgarBonet can you elaborate? I find the syntax of C++ pretty obtuse, so I get kinda lost. I read some info about functors and my eyes started to cross.

I suggested in a comment that a functor may be a viable alternative to a
capturing lambda. This answer is mostly meant to answer the OP's request
to elaborate on that suggestion.
Let's define a ButtonCallback as an object that can be called like a
function taking a single boolean parameter:
class ButtonCallback {
public:
    virtual void operator()(bool) = 0;
};

To break down the syntax:

void operator()(bool) declares a method that allows the object to be
called as if it were a function taking a bool argument and returning
nothing. In other words, if you issue a call such as
my_object(true), that method will be called.
virtual _method_declaration_ = 0; says that the method is not going
to be defined for this class (it's a “pure virtual method”), but it
can be defined by derived classes. A class with such a method is
called an “abstract class”: it defines an interface, it cannot be
instantiated, and it's meant to be used as a parent for classes that
do implement the missing methods.

Now the Button class can be defined like this:
class Button {
public:
    Button(uint8_t pin, ButtonCallback &callback)
    : pin(pin), callback(callback) {}
    void push() {  // for testing only
        Serial.print("press: ");   callback(true);
        Serial.print("release: "); callback(false);
    }
private:
    uint8_t pin;
    ButtonCallback &callback;
};

Notice that the callback is stored as a reference to a
ButtonCallback object. The object itself cannot be stored because it
has an abstract type. Alternatively, a pointer could be used, which
would practically be equivalent.
For using this class, you first have to create the callback as a
concrete class that inherits from from ButtonCallback. Any data you
wish to capture should be stored as class data:
class CapturingLambda : public ButtonCallback {
public:
    CapturingLambda(int data) : some_data(data) {}
    virtual void operator()(bool pressed) {
        if (pressed)
            Serial.println(some_data);
        else
            Serial.println(0);
    }
private:
    int some_data;
};

With all this in place, the following test:
void setup() {
    Serial.begin(9600);
    int data_to_capture = 42;
    CapturingLambda callback(data_to_capture);
    Button the_button(2, callback);
    the_button.push();
}

void loop(){}

outputs:
press: 42
release: 0

Did you said you “find the syntax of C++ pretty obtuse”? I can only
concur with you!

Addendum: Another alternative is to define the callback using the
good old C idiom: a “lambda” is the combination of a function pointer
and a generic data pointer. The function pointer looks like this:
typedef void (*ButtonCallback)(bool, void *);

The second argument is used to provide the callback whatever data it is
supposed to have “captured”. It is a generic pointer (a void *)
because the library does not know what kind of data its client may need.
Now the Button class has to store both the function pointer and the
data pointer, and always provide the data pointer to the callback:
class Button {
public:
    Button(uint8_t pin, ButtonCallback callback, void *callback_data)
    : pin(pin), callback(callback), callback_data(callback_data) {}
    void push() {  // for testing only
        Serial.print("press: ");   callback(true, callback_data);
        Serial.print("release: "); callback(false, callback_data);
    }
private:
    uint8_t pin;
    ButtonCallback callback;
    void *callback_data;
};

The user would have to decide what kind of data it needs, and do
explicit pointer casts to/from the proper pointer type and void *. For
example, assuming we need an int, the callback may be:
void callback(bool pressed, void *data) {
    int *actual_data = (int *) data;
    if (pressed)
        Serial.println(*actual_data);
    else
        Serial.println(0);
}

Here is the test, with the exact same output as before:
void setup() {
    Serial.begin(9600);
    int data_to_capture = 42;
    Button the_button(2, callback, (void *) &data_to_capture);
    the_button.push();
}

void loop(){}

Notice that, syntactic differences apart, this solution does essentially
the same as the previous one. The main difference is that the data is
given to the callback as an explicit pointer instead of the implicit
this pointer. If you have to choose between these two solutions, I
would suggest going for whichever syntax you find easier to work with.
Beware also that in both cases it is the programmer's responsibility to
manage the storage of the callback data and make sure the corresponding
reference (or pointer) remains valid throughout the lifetime of the
Button object.

Excellent answer. Thank you! (Voted). The one part of it that I couldn’t parse is the constructor of CapturingLambda. Can you explain that bit? The some_data(data) part looks a little like the syntax for invoking a parent class’ constructor, but not quite.

@DuncanC: It's a member initializer list. some_data(data) means that the some_data class member is initialized with the value of the data constructor parameter. More or less equivalent to writing some_data = data; within the braces. In some cases (not here) an initializer list is the only way to do an initialization.

Ok, that helps. Why use a member initializer list instead of an explicit constructor that initializes the member variables? And in what cases is a member initializer list the only way to initialize an instance?

@DuncanC: 1. It doesn't really matter. 2. When invoking the parent class’ constructor and when a member is an object with no default constructor.

So can you both invoke the parent class' constructor AND use a member initializer list? And if so, what does that syntax look like?

@DuncanC: parent class' constructor is just a special use case of a member initializer list. I will not digress longer on this.


text:
Need some help on a very small project
Apologies for the simple question, I really couldn’t find any help online with this as when I kept searching, the results had lights that had way too much voltage compared to what I need.
So I have a simple light decoration that requires around 3v and comes with a battery pack to power it (2AA batteries) and I took it apart and was able to connect them via a breadboard to test if is all working.
How do incorporate the Arduino into it so that I can switch the lights on through the Arduino? A lot of the small voltage videos I saw were just simple connecting 1 LED through a digital pin but that’s not enough current for the lights I have and I’m not experienced enough to find myself a solution so help would be greatly appreciated.
For little more info, the 3.3v and 5v pins my Arduino (uno) are already taken up.
Also, I’ll be turning the lights on and off with an IR Remote which I’ve already programmed to a servo that’s powered through the USB supply (5v) and the IR Sensor is connected to the 3.3V.
Sorry if the question was badly worded.

It all depends on the simple light decoration. What is it? Can you show a photo? Do you have a schematic of it? What kind of leds are used? and so on.

https://imgur.com/a/TgPQBDZ https://imgur.com/a/b0l1isT - It’s a small shelf decoration in the shape of ‘&’ @Jot

No @gre_gor, the dude there is calling for a 12v lightbulb.

the 3.3v and 5v pins my Arduino (uno) are already taken up .... no they are not .... run a jumper over to the breadboard so that you can make multiple connections

@jsotola wouldn’t that give less power to each component? I remember trying this with the ir sensor, but it seemed to give the servo less kick.

the comment was about pin availability since you said that you have no more pins for 3.3V and 5V ...... power availability is another issue ..... do not power a servo from the arduino

Thanks for the photo, that could be 10 white leds of 20mA each parallel. The total current is 200mA for leds that are about 3v. Or are they neopixel rgb leds? Was there a controller that could change the color? The first comment by @gre_gor explains that you need a darlington transistor or a mosfet. You also need a resistor of at least 0.5w to limit the current. On the other hand, if they are rgb leds, then they could be for 3v and not for 5v.

@jot thank you for trying to help! They are plain white LED’s. I would really call them white LED’s with a tint of yellow. To turn them on and off, it was a simple switch but as this will be high on a shelf, I don’t want to constantly take it down. I’ll do some research on transistors and see what I find. Thanks again!

I think I managed to make a little circuit that should prevent you from burning up your Arduino.

From what I read you shouldn't connect MOSFET directly to Arduino. Imagine that MOSFET has a little capacitor inside it, and in the beginning that capacitor can take such high current that actually can burn the Arduino pin. Instead you use a simple NPN transistor (with 100kohm resistor) as a "switch". The NPN can survive much higher current, and it will not strain the Arduino pin.
When I simulated this setup using the default "blink" sketch the light bulb was lit when PIN13 was HIGH. Just note that there always is a small voltage drop (think of it as a resistor inside the MOSFET) and it can make the MOSFET get a little warm. In your setup it should not be a problem, but in some cases it's nice to screw a radiator on the MOSFET.

Thank you so much for the reply and schematics. I’ll have to buy a mosfet as the Arduino kit I have didn’t come with one, and then I’ll test it out. Thanks again!

Before I purchase mosfets, as they only come in packs and I will likely never use them again, will anyone of these be sufficient? https://imgur.com/a/U15yVXi (They come with my kit?)

These are not MOSFETs. These are BJT transistors of the NPN type. Since your light decoration will probably not draw much current It's quite possible that you will be able to use just them (just remove MOSFET from my design) Please experiment with different designs in Tinkercad.

After taking out the mosfet, the light turned on. One problem I have before I build the actual circuit is the resistor. I have never decided my own value for resistors before so I don’t know what to do. You mentioned 100k for the mosfet but not that I’m not using it surely I don’t need a 100k resistor? Seems way too much. Also - huge thanks for introducing me to tinkercad. This will help me for tonnns of projects!

MOSFET to work properly needs to be discharged to be opened (that imaginary capacitor is inside) so when the NPN (electronic switch) is "opened" that 100K resistor discharges the MOSFET. But when NPN (electronic switch) is "closed" part the current goes into the MOSFET (charging the imaginary capacitor), and part goes through that resistor. The higher the resistor value the less current is wasted that way (but slower MOSFET discharge) But if you removed the MOSFET you probably don't need to discharge anything, and it's possible that your lights will work without the resistor. Experiment.

Thank for the information! I’ll experiment with some low value resistors and comment if it succeeded.

Just remember that the lower the value of the resistor the more current is wasted, batteries drain faster and the resistor gets hotter.


text:
Arduino IDE / Specified folder/zip file does not contain a valid library
I trying to add library here but it doesn't seem to work https://github.com/esp8266/Arduino
This happens
"Specified folder/zip file does not contain a valid library"
This problem make me no longer upload any library. any solution about this??
Manual installation does not either.

You don't install that repository as a Arduino library.
Read the README file in that repo. It explains how to install it using the Arduino IDE Board manager. That's the correct way to install it.


text:
Arduino hangs after some time
I am using Atmega328p with 5V power supply,
My Arduino getting hangs [or auto restarts] after some times.
I am using libraries:

Wire.h
CRC32.h
EEPROM.h
Arduino.h
TimerOne.h
RtcDS3231.h
SoftwareSerial.h
Adafruit_NeoPixel.h
avr/wdt.h

I have tried to search, some people are deny to use software serial library.

it's possibly some error in your code

This is my code, can you guide me...
https://github.com/savaliyadnk/arduinoswitch

don't use String. use C strings (zero terminated char array) https://majenko.co.uk/blog/evils-arduino-strings

That is only a minimal circuit in theory. Can you show us a photo? We like to see where the decoupling capacitors are and how close the crystal with the 22pF capacitors to the atmega328p is.

Do you have 100nF connected to aref and vcc? It should be to gnd. All gnd and all vcc should be connected to the power. All of them. You have no decoupling capacitors. They are not an optional extra according to this page: http://www.gammon.com.au/bootloader

Not sure if this will fix your problem, but this is a major error:
  char buf1[8], buf2[6];
  sprintf(buf1, "%08lu", myvote.mydate);
  sprintf(buf2, "%06lu", myvote.mytime);

Take a look at sprintf function reference

A terminating null character is automatically appended after the content.

So, the text buffers are too small. It should be at least:
char buf1[9], buf2[7];


text:
About Wemos D1 WiFi
I bought the Wemos D1 WiFi and I am wondering how to operate this. So, inside the Arduino IDE, I downloaded ESP8266 boards, I see WeMos D1 mini, WeMos D1 R1, and WeMos mini Pro/Lite.
Why in the world don't I see Wemos D1?
How can I operate this board without the D1 board to select in the Arduino IDE?
Is there a way to add, or anyways to operate it?
I don't mind using other software besides the Arduino IDE if it's the only way to work with D1.
Board:

I get this Error when trying to upload D1 R1:
C:\...\ArduinoData\packages\esp8266\tools\esptool\2.5.0-3-20ed2b9/esptool.exe -vv -cd nodemcu -cb 115200 -cp COM6 -ca 0x00000 -cf
C:\...\Temp\arduino_build_179604/sketch_jan15a.ino.bin
esptool v0.4.13-1-gf80ae31 - (c) 2014 Ch. Klippel <ck@atelier-klippel.de>
setting board to nodemcu
setting baudrate from 115200 to 115200
setting port from COM1 to COM6
setting address from 0x00000000 to 0x00000000
espcomm_upload_file
espcomm_upload_mem
setting serial port timeouts to 1000 ms
opening bootloader
resetting board
trying to connect
flush start
An error occurred while uploading the sketch
setting serial port timeouts to 1 ms
setting serial port timeouts to 1000 ms
flush complete
espcomm_send_command: sending command header
espcomm_send_command: sending command payload
read 0, requested 1
trying to connect
flush start
setting serial port timeouts to 1 ms
setting serial port timeouts to 1000 ms
flush complete
espcomm_send_command: sending command header
espcomm_send_command: sending command payload
espcomm_send_command: receiving 2 bytes of data
espcomm_send_command: receiving 2 bytes of data
espcomm_send_command: receiving 2 bytes of data
espcomm_send_command: receiving 2 bytes of data
espcomm_send_command: receiving 2 bytes of data
espcomm_send_command: receiving 2 bytes of data
espcomm_send_command: receiving 2 bytes of data
espcomm_send_command: receiving 2 bytes of data
Uploading 287488 bytes from
C:\...\arduino_build_179604/sketch_jan15a.ino.bin to flash at 0x00000000
erasing flash
size: 046300 address: 000000
first_sector_index: 0
total_sector_count: 71
head_sector_count: 16
adjusted_sector_count: 55
erase_size: 037000
espcomm_send_command: sending command header
espcomm_send_command: sending command payload
setting serial port timeouts to 15000 ms
read 0, requested 1
setting serial port timeouts to 1000 ms
warning: espcomm_send_command: didn't receive command response
warning: espcomm_send_command(FLASH_DOWNLOAD_BEGIN) failed
closing bootloader
flush start
setting serial port timeouts to 1 ms
setting serial port timeouts to 1000 ms
flush complete
error: espcomm_upload_mem failed

this is D1 R1 .

Your board is a WeMos D1 R1. You need to select Tools > Board > WeMos D1 R1 in the Arduino IDE.
Here's a good comparison of the difference between the WeMos D1 R1 and the WeMos D1 R2:
https://github.com/arendst/Sonoff-Tasmota/wiki/Wemos-D1-R1-&-R2

I forgot to mention that I get an error when trying to upload WeMos D1 R1.


text:
iBus transmission and read it in Arduino
I am using an Arduino Uno and I want to transmit data from FSi6 to FS-iA6B and read received data in an Arduino. After searching, I found the below link which is iBUStelemetry.
iBustelemetry
I am not able to make out how to get the data from this library and print it on the serial monitor.
I have hooked up receiver ground and power pins to ground and power pins of Arduino. Signal from the receiver is connected to D2.
The author has included an example, but I am not much clear how data is read and printed on the serial monitor.
Can someone please help by telling how do I read data from receiver using this library?

If I understand correctly, the code should look like this.
#include <iBUStelemetry.h>
iBUStelemetry telemetry(4);
byte i;

void setup(){
 Serial.begin(115200);
 telemetry.begin(115200);
 telemetry.addSensor(2);
}

void loop(){
 telemetry.setSensorMeasurement(1, i++);
 delay(1000);
 Serial.println(telemetry);
 //or
 Serial.println(telemetry.setSensorMeasurement(1, i++));
}

https://www.arduino.cc/reference/en/language/functions/communication/serial/print/

Thanks for your reply. The output should be value of each individual channels from the RC remote. This does not give any active results. Expected code should be something like:
for (i = 0; i < noOfCh; i++){  chvals[i] = IBus.readChannel(i); }
Can you kindly check and revert?


text:
Split up Arduino code into multiple files using Arduino IDE
I am working on a very long code that requires multiple functions defined. I want to split the code into two files as main code ("Feeder_Control" in the screenshot) and functions ("connections" in the screenshot) How to import the second file into main code to use its functions?
PS: In C/C++ same thing is done with #include "connections.h". How is it done in Arduino IDE.
.

Though the accepted answer works, I feel while the Arduino "IDE" is great for beginners but it doesn't quite scale well beyond a couple of files. I'd highly recommend checking out platformio as it provides much better project management via integration with atom and vscode, enables you to work with different frameworks including Arduino for AVR, STM32, ESP8266, ESP32 etc and supports debugging if you have the required hardware.

Don't cross post. You already asked this on SO.

There is no need to use an #include directive for the additional .ino file.
Before compilation starts, the Arduino IDE concatenates all .ino files in your sketch into a single file, starting with the .ino file that matches the sketch folder name, followed by the rest of the .ino files in alphabetical order. So there is no difference between one massive .ino file and breaking the same code among multiple .ino files, other than the greater ease of navigating the code via tabs. After a bit more processing, this file is compiled as C++.
Reference:
https://arduino.github.io/arduino-cli/latest/sketch-build-process/#pre-processing

Two comments to answer by per1234 (although old):
You can have multiple .ino files in a project. However:

You can not separate the preprocessor portion from the main file (The file with the project's name) which must include ALL preprocessing.
Arduino IDE compiles all files in a project in a specific order (alphabetically by filename) and includes them into the main .ino file during the linking stage.
Code in later .ino files can access variables and functions defined in earlier ones, but not vice versa.

Please link to the answer and/or state who posted it, rather than saying "answer#1" - the order of answers changes over time, and depending upon the type of ordering selected. Please [edit] and update your answer.

the details you mention, are in the linked page. per1234 is the the tester for Arduino CLI at Arduino and main author of the Arduino CLI documentation including the linked page.

what is that about the preprocessor? there is no such limitation.

Code in later .ino files can access variables and functions defined in earlier ones, but not vice versa That's correct for variables, but not for functions: When concatenating all .ino files into a single .cpp, function prototypes from all .ino files are generated and added to the start of that .cpp file. If that works well, all functions can be used from any part of your code. And it's a good idea to collect all global variables in the projectname.ino file, which comes first in the .cpp concatenation.

Thanks for the details. Yet, I have a main file and in it a large portion of building HTML (or CSS) output code. That HTML portion is currently located in the root of the main. I wish to move it out to a separate file, but it is not defined as an Arduino function and thus it has no prototype function and will not be linked.
Can I define it as a function?
What is the best way to proceed?
Thx

Can I define it as a function? What is the best way to proceed? the question depend on what are the files and data are under one translation unit. There are also  extern storage class specifier that can be used to tell the compiler that a variable is defined externally in a different translation unit.


text:
Error code board and boards.txt? Formatting error? cannot verify alarm.txt or any
Arduino: 1.8.8 (Windows 10), Board: "Arduino/Genuino Uno"
Error reading file (E:\arduino\arduino-1.8.8\hardware\arduino\avr**\boards.txt:0**): Invalid line format, should be 'key=value'
Error compiling for board Arduino/Genuino Uno.[/b]
This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.
I was trying to do this experiment: http://wirebeings.com/arduino-intruder-alarm.html
but with Arduino Uno + geeetech iduino yun shield setup.
http://www.geeetech.com/wiki/index.php/Iduino_Yun_Shield
Please help (also short do you short the two pins properly?)
this is the board.txt file:
unoyun.name=Arduino Uno --Iduino Yún
unoyun.upload.via_ssh=true
unoyun.vid.0=0x2341
unoyun.pid.0=0x0043
unoyun.vid.1=0x2341
unoyun.pid.1=0x0001
unoyun.upload.tool=avrdude
unoyun.upload.protocol=arduino
unoyun.upload.maximum_size=32256
unoyun.upload.maximum_data_size=2048
unoyun.upload.speed=57600
unoyun.upload.disable_flushing=true
unoyun.upload.use_1200bps_touch=true
unoyun.upload.wait_for_upload_port=true
unoyun.bootloader.tool=avrdude
unoyun.bootloader.low_fuses=0xff
unoyun.bootloader.high_fuses=0xde
unoyun.bootloader.extended_fuses=0x05
unoyun.bootloader.file=optiboot/optiboot_atmega328.hex
unoyun.bootloader.unlock_bits=0x3F
unoyun.bootloader.lock_bits=0x0F
unoyun.build.mcu=atmega328p
unoyun.build.f_cpu=16000000L
unoyun.build.board=AVR_YUN
unoyun.build.core=arduino
unoyun.build.variant=standard

and this is the boards.txt file:
# See: http://code.google.com/p/arduino/wiki/Platforms

menu.cpu=Processor

##############################################################

yun.name=Arduino Yún
yun.upload.via_ssh=true

yun.vid.0=0x2341
yun.pid.0=0x0041
yun.vid.1=0x2341
yun.pid.1=0x8041
yun.vid.2=0x2A03
yun.pid.2=0x0041
yun.vid.3=0x2A03
yun.pid.3=0x8041

yun.upload.tool=avrdude
yun.upload.protocol=avr109
yun.upload.maximum_size=28672
yun.upload.maximum_data_size=2560
yun.upload.speed=57600
yun.upload.disable_flushing=true
yun.upload.use_1200bps_touch=true
yun.upload.wait_for_upload_port=true

yun.bootloader.tool=avrdude
yun.bootloader.low_fuses=0xff
yun.bootloader.high_fuses=0xd8
yun.bootloader.extended_fuses=0xfb
yun.bootloader.file=caterina/Caterina-Yun.hex
yun.bootloader.noblink=caterina/Caterina-Yun-noblink.hex
yun.bootloader.unlock_bits=0x3F
yun.bootloader.lock_bits=0x2F

yun.build.mcu=atmega32u4
yun.build.f_cpu=16000000L
yun.build.vid=0x2341
yun.build.pid=0x8041
yun.build.usb_product="Arduino Yun"
yun.build.board=AVR_YUN
yun.build.core=arduino
yun.build.variant=yun
yun.build.extra_flags={build.usb_flags}

##############################################################

uno.name=Arduino/Genuino Uno

uno.vid.0=0x2341
uno.pid.0=0x0043
uno.vid.1=0x2341
uno.pid.1=0x0001
uno.vid.2=0x2A03
uno.pid.2=0x0043
uno.vid.3=0x2341
uno.pid.3=0x0243

uno.upload.tool=avrdude
uno.upload.protocol=arduino
uno.upload.maximum_size=32256
uno.upload.maximum_data_size=2048
uno.upload.speed=115200

uno.bootloader.tool=avrdude
uno.bootloader.low_fuses=0xFF
uno.bootloader.high_fuses=0xDE
uno.bootloader.extended_fuses=0xFD
uno.bootloader.unlock_bits=0x3F
uno.bootloader.lock_bits=0x0F
uno.bootloader.file=optiboot/optiboot_atmega328.hex

uno.build.mcu=atmega328p
uno.build.f_cpu=16000000L
uno.build.board=AVR_UNO
uno.build.core=arduino
uno.build.variant=standard

##############################################################

diecimila.name=Arduino Duemilanove or Diecimila

diecimila.upload.tool=avrdude
diecimila.upload.protocol=arduino

diecimila.bootloader.tool=avrdude
diecimila.bootloader.low_fuses=0xFF
diecimila.bootloader.unlock_bits=0x3F
diecimila.bootloader.lock_bits=0x0F

diecimila.build.f_cpu=16000000L
diecimila.build.board=AVR_DUEMILANOVE
diecimila.build.core=arduino
diecimila.build.variant=standard

two boards.txt files or did I edit it wrong and the "and this is the boards.txt file:" is inside your board.txt file?

two files
both in \hardware\avr - board.txt or boards.txt file worked

nvm, apparently some guys suggesting utf-8 bom encoding change or something because I saw 1 question related to this
(it didn't work)
then I changed it to utf-8 encoding
(both done through notepad++)
it worked.

John Doe, thanks for the tip about utf-8.
I just ran into this exact problem.  boards.txt had been hand-edited in Windows Notepad and saved as utf-8 and was throwing this error.
Arduino: 1.8.10 (Windows 10), Board: "Arduino/Genuino Uno"
loading hardware from C:\Program Files (x86)\Arduino\hardware:
loading package arduino: loading platform release:
Error reading file (C:\Program Files (x86)\Arduino
\hardware\arduino\avr\boards.txt:0):
Invalid line format, should be 'key=value'

I changed the text file format to ANSI and saved, and that fixed the problem, able to compile.  At this point, guessing that maybe changing format merely cleaned up a defect, I saved again to utf-8, but it broke again.  Thus back to ANSI.


text:
Arduino Mega and ADS1256 board
I found code for a Teensy board and now I added just digitalwriteFast library to code and changed port to SPI for Arduino Mega. And now I get just one number out:
#include <SPI.h>
#include <digitalWriteFast.h>

//(other stuff for getting the ADS1526 to work is in the next tab
#define ADS_RST_PIN    48 //ADS1256 reset pin
#define ADS_RDY_PIN    47 //ADS1256 data ready
#define ADS_CS_PIN    46 //ADS1256 chip select

/*
CLK  - pin 52
DIN  - pin 50 (MOSI)
DOUT - pin 51 (MISO)
*/

//put the ADC constants here

double resolution = 8388608.; //2^23-1

//this needs to match the setting in the ADC init function in the library tab
double Gain = 64.; //be sure to have a period

double vRef = 5.0; //reference voltage

//we'll calculate this in setup
double bitToVolt = 0.;

void setup() {
 delay(1000);
 Serial.begin(115200);
 Serial.println("booting");
 //initialize the ADS
 pinMode(ADS_CS_PIN, OUTPUT);

 pinMode(ADS_RDY_PIN, INPUT);
 pinMode(ADS_RST_PIN, OUTPUT);

 SPI.begin();

 initADS();
 Serial.println("done init");

 //determine the conversion factor
    //do some calculations for the constants
 bitToVolt = resolution*Gain/vRef;
}

int32_t val1;
int32_t val2;
int32_t val3;

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

double value = 0;
for (int i = 0; i <1; i++){
 read_three_values();
 value += val1;
}

value /=1.;

 Serial.print(value,8);
 Serial.print("\t");
 Serial.print(val2);
 Serial.print("\t");
 Serial.println(val3);

//
//double value = 0;
//for (int i = 0; i <10; i++){
//  value += read_Value();
//}
//
//value /= 10.;
//value /= bitToVolt;
//
//Serial.println(value,11);
}

I don't know where to connect PDWN pin?
And I have this board:
https://www.ebay.com/itm/NEW-1PC-ADS1256-high-precision-ADC-module-conversion-24-bit-eight-channel/292541380872?hash=item441cd33908:g:uYUAAOSwLpda5BIZ:rk:1:pf:0
Greetings Matej

Please show us a working sketch. The sync/pdwn can be connected to 3.3v or also to 5v since it is 5v tolerant. It is in the datasheet. The spi bus is 5v tolerant but the data out (MISO on the arduino board) signal is only 3.3v. It will probably work, but a 3.3v arduino board is better. At ebay they say that also a dac8532 is on the board, but I can't see that in the photos. I can only see a ads1256 and a 2.5v voltage reference and a voltage regualator. It is a very nice and very cheap module, but without schematic you have to guess how to connect it.

no schematic came with it.

i use this code link is here https://github.com/mbilsky/TeensyADS1256

That code uses an interrupt for the ADS_RDY_PIN, but the arduino mega 2560 does not have an interrupt at pin 47. There is also no digitalPinToInterrupt() for the interrupt pin (the arduino mega 2560 needs that, the teensy does not). You can fix that, but I suggest to find a more basic simple library for the ads1256. You need to make it work in a basic way before trying a library that is optimized for speed.

Ok but will i reach 30000SPS with other library