text:
Getting weird output for following object detection code using interrupts on HUZZAH ESP8266 and motor controller L293D along with 3 HCSR04 sensors
I am trying to implement a bot which can sense obstacle in front, left or right and post detection send interrupts. Which in turn will perform the appropriate motor function to avoid these obsticles. Any help would be highly appreciated.
It would be great if you could make changes in this code and post it so that I can actually run, simulate and find out where actually I have gone wrong.
My code
#define trigPin 14
#define echoPin 12
#define echoPin1 13
#define echoPin2 15

//Initialize Digital Pins
const int leftForward = 2;
const int leftBackward = 16;
const int rightForward = 5;
const int rightBackward = 4;

// Define variables:
long duration;
long duration1;
long duration2;
int distance;
int distance1;
int distance2;
boolean goesForward = false;
bool flag = false;
bool flag1 = false;
bool flag2 = false;

void f5(void){
  flag = true;
}

void f2(void){
  flag1 = true;
}

void f3(void){
  flag2 = true;
}

void inter1(){
    Serial.print("Distance1 = ");
    Serial.print(distance2);
    Serial.println(" cm");
    moveStop();
    delay(3000);
    moveBackward();
    delay(4000);
    moveStop();
    delay(3000);
    turnRight();
    moveStop();
    delay(3000);
}

void inter2(){
    Serial.print("Distance2 = ");
    Serial.print(distance2);
    Serial.println(" cm");
    moveStop();
    delay(3000);
    moveBackward();
    delay(4000);
    moveStop();
    delay(3000);
    turnRight();
    moveStop();
    delay(3000);
}

void inter3(){
    Serial.print("Distance2 = ");
    Serial.print(distance2);
    Serial.println(" cm");
    moveStop();
    delay(3000);
    moveBackward();
    delay(4000);
    moveStop();
    delay(3000);
    turnRight();
    moveStop();
    delay(3000);
}

void setup() {
  // Define inputs and outputs:
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(echoPin1, INPUT);
  pinMode(echoPin2, INPUT);

  // set control pins as Output
  pinMode(leftForward,OUTPUT);
  pinMode(leftBackward,OUTPUT);
  pinMode(rightForward,OUTPUT);
  pinMode(rightBackward,OUTPUT);

  attachInterrupt(digitalPinToInterrupt(echoPin), f5, RISING);
  attachInterrupt(digitalPinToInterrupt(echoPin1), f2, RISING);
  attachInterrupt(digitalPinToInterrupt(echoPin2), f3, RISING);
  //Begin Serial communication at a baudrate of 9600:
  Serial.begin(9600);
}

void loop() {
  // Clear the trigPin by setting it LOW:
  digitalWrite(trigPin, LOW);
  delayMicroseconds(5);

  // Trigger the sensor by setting the trigPin high for 10 microseconds:
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  // Read the echoPin, pulseIn() returns the duration (length of the pulse) in microseconds:
  duration = pulseIn(echoPin, HIGH);
  // Calculate the distance:
  distance= duration*0.034/2;

  duration1 = pulseIn(echoPin1, HIGH);
  // Calculate the distance:
  distance1= duration1*0.034/2;

  duration2 = pulseIn(echoPin2, HIGH);
  // Calculate the distance:
  distance2= duration2*0.034/2;

  // Print the distance on the Serial Monitor (Ctrl+Shift+M):

  if (distance <= 20){
      attachInterrupt(digitalPinToInterrupt(12), f5, RISING);
    }
  else{
    moveForward();
  }

  if (distance1 <= 20){
    attachInterrupt(digitalPinToInterrupt(13), f2, RISING);
  }
  else{
    moveForward();
  }

  if (distance2 <= 20){
    attachInterrupt(digitalPinToInterrupt(15), f3, RISING);
  }
  else{
    moveForward();
  }

  if(flag)
 {
  inter1();
  flag = false;
 }

  if(flag1)
 {
  inter2();
  flag1 = false;
 }

 if(flag2)
 {
  inter3();
  flag2 = false;
 }

 delay(1000);
 /* // run forward

  digitalWrite(leftForward,HIGH);
  digitalWrite(leftBackward,LOW);
  digitalWrite(rightForward,HIGH);
  digitalWrite(rightBackward,LOW);

  delay(1000);

  // run left
  digitalWrite(leftForward,LOW);
  digitalWrite(leftBackward,LOW);
  digitalWrite(rightForward,HIGH);
  digitalWrite(rightBackward,LOW);

  delay(1000);

  // run forward
  digitalWrite(leftForward,HIGH);
  digitalWrite(leftBackward,LOW);
  digitalWrite(rightForward,LOW);
  digitalWrite(rightBackward,LOW);

  delay(1000);

  // run backward
  digitalWrite(leftForward,LOW);
  digitalWrite(leftBackward,HIGH);
  digitalWrite(rightForward,LOW);
  digitalWrite(rightBackward,HIGH);

  delay(1000);
  delay(50);
  */
}
void moveStop(){

  digitalWrite(rightForward, LOW);
  digitalWrite(leftForward, LOW);
  digitalWrite(rightBackward, LOW);
  digitalWrite(leftBackward, LOW);
}

void moveForward(){

  if(!goesForward){

    goesForward=true;

    digitalWrite(leftForward, HIGH);
    digitalWrite(rightForward, HIGH);

    digitalWrite(leftBackward, LOW);
    digitalWrite(rightBackward, LOW);
  }
}

void moveBackward(){

  goesForward=false;

  digitalWrite(leftBackward, HIGH);
  digitalWrite(rightBackward, HIGH);

  digitalWrite(leftForward, LOW);
  digitalWrite(rightForward, LOW);

}

void turnRight(){

  digitalWrite(leftForward, HIGH);
  digitalWrite(rightBackward, HIGH);

  digitalWrite(leftBackward, LOW);
  digitalWrite(rightForward, LOW);

  delay(500);

  digitalWrite(leftForward, HIGH);
  digitalWrite(rightForward, HIGH);

  digitalWrite(leftBackward, LOW);
  digitalWrite(rightBackward, LOW);

}

void turnLeft(){

  digitalWrite(leftBackward, HIGH);
  digitalWrite(rightForward, HIGH);

  digitalWrite(leftForward, LOW);
  digitalWrite(rightBackward, LOW);

  delay(500);

  digitalWrite(leftForward, HIGH);
  digitalWrite(rightForward, HIGH);

  digitalWrite(leftBackward, LOW);
  digitalWrite(rightBackward, LOW);
}

why are you asking us to guess what problems you are having?

What is your  "weird output"? Please show us by editing your question


text:
Digispark ATtiny 85 erases flash after power loss
I have some issues with my Digispark ATtiny85 board.
If I upload the blink sketch for example the LED starts blinking and everything looks fine. But as soon as I unplug the Digispark from the USB port and plug it back in nothing happens. I know that the programm starts with a delay of 5 seconds so programming via USB becomes possible, but still nothing. Its seems like the flash-memory (where the programm is stored) of the ATtiny 85 is empty.
Here is the example blink sketch:
// the setup routine runs once when you press reset:
void setup() {
  // initialize the digital pin as an output.
  pinMode(0, OUTPUT); //LED on Model B
  pinMode(1, OUTPUT); //LED on Model A
}

// the loop routine runs over and over again forever:
void loop() {
  digitalWrite(0, HIGH);   // turn the LED on (HIGH is the voltage level)
  digitalWrite(1, HIGH);
  delay(1000);               // wait for a second
  digitalWrite(0, LOW);    // turn the LED off by making the voltage LOW
  digitalWrite(1, LOW);
  delay(1000);               // wait for a second
}

I also tried uploading the sketch from a Laptop running on Windows but without success.
I am using Linux Mint and Arduino IDE 1.8.10.
Since I am new to Microcontrollers, I would be grateful for explainations, tipps or useful links.
Thank you!

How is the eeprom used? Or you're confusing program memory (flash) with eeprom? The programmer selection is for flashing code (or bootloader by next menu item) into it over ISP connection using some programmer.

The code is saved in flash, not in EEPROM. The blink sketch does not use the EEPROM. So the actual problem is: You have a running blink sketch, but if you unplug the digispark and again plug it in, the blink sketch isn't running anymore?

Or could a floating reset pin be the reason for this behavior? the official digispark has the reset pin disabled, so you get an extra GPIO pin. So it can't be a floating reset pin.

Okay I confused flash with EEPROM. Thanks for pointing this out, I will change that in the question. @chrisl Yes that's my problem

I found that on the digistump forum: "I get the same behavior, except Arduino 1.6.5-r5.  5 boards all exhibit the same behavior.  These do not say "Digispark" on them; just "ATttiny" (85"https://digistump.com/board/index.php?topic=3161.0)
Might this problem be related to the arduino IDE?

I got the same issue, on two boards. Will probably try to burn the bootloader using usbasp, maybe they burned the wrong one back in china.

I got the same issue, on two boards. Will probably try to burn the bootloader using usbasp, maybe they burned the wrong one back in china.
EDIT:
As expected flashing the micronucleus bootloader using USBasp solved the problem on both of the boards. I've used burn-o-mat as the arduino was not seeing my programmer.
Just download the firmware from github (I've used this: https://github.com/f4goh/micronucleus/archive/master.zip )
and connect like so (here the guy is using arduino uno, doesn't matter): https://hamprojects.wordpress.com/2018/12/27/digispark-microcontrollers-implementation/

source: Stack Exchange

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

sort: votes


text:
High-frequency PWM on an Adafruit Feather M0
I'm trying to get a Bluefruit Feather M0, which has a SAMD21G on it, to do high-frequency  PWM by accessing timer registers directly, rather than using the Arduino API to do PWM at ~1 kHz or ~500 Hz. Actual frequency isn't important at this stage, I just want a lot more than 1 kHz.
I found an example for an MKR1000, based on a similar processor. I've adapted it as shown below. Comparing the Adafruit pinout with the original code and with the datasheet, it's apparent that the pin numberings are different and that pin 11, which is the only one of the two example pins that is accessible, is on TCC0 here and not TCC1.
The only change I see that I needed to make is to duplicate all the TCC1 setup in setupTimers() and the TCC1 duty cycle control in loop() for TCC0. Yet on the scope, I see no PWM output. I then tried setting pin 13 to PWM as well, so I'd see it on the on board LED. Still nothing. I'm somewhat stuck now.
Does anyone have any ideas?
void setup() {
    // put your setup code here, to run once:
    setupTimers();
    Serial.begin(9600);
}

void loop() {
    // put your main code here, to run repeatedly:
    int t = 0;
    Serial.println("\nRunning PWM 0 to 100%");
    for (t = 0; t < 1000; t = t + 1) {
        REG_TCC1_CC1 = t;                              // TCC1 CC1 - on D3  - PWM signalling
        while (TCC1->SYNCBUSY.bit.CC1);                // Wait for synchronization
        REG_TCC0_CC1 = t;                              // TCC1 CC1 - on D3  - PWM signalling
        while (TCC0->SYNCBUSY.bit.CC1);                // Wait for synchronization
        delay(1);
        Serial.print(".");
    }

    delay(2000);
}

// Output PWM 24Khz on digital pin D3  and D11 using timer TCC1 (10-bit resolution)
void setupTimers() {
    REG_GCLK_GENDIV = GCLK_GENDIV_DIV(1) |          // Divide the 48MHz clock source by divisor N=1: 48MHz/1=48MHz
        GCLK_GENDIV_ID(4);            // Select Generic Clock (GCLK) 4
    while (GCLK->STATUS.bit.SYNCBUSY);              // Wait for synchronization

    REG_GCLK_GENCTRL = GCLK_GENCTRL_IDC |           // Set the duty cycle to 50/50 HIGH/LOW
        GCLK_GENCTRL_GENEN |         // Enable GCLK4
        GCLK_GENCTRL_SRC_DFLL48M |   // Set the 48MHz clock source
        GCLK_GENCTRL_ID(4);          // Select GCLK4
    while (GCLK->STATUS.bit.SYNCBUSY);              // Wait for synchronization

    // Enable the port multiplexer for the digital pin D3 and D11  **** g_APinDescription() converts Arduino Pin to SAMD21 pin
    PORT->Group[g_APinDescription[3].ulPort].PINCFG[g_APinDescription[3].ulPin].bit.PMUXEN = 1;
    PORT->Group[g_APinDescription[11].ulPort].PINCFG[g_APinDescription[11].ulPin].bit.PMUXEN = 1;
    PORT->Group[g_APinDescription[13].ulPort].PINCFG[g_APinDescription[13].ulPin].bit.PMUXEN = 1;

    // Connect the TCC1 timer to digital output D3 and D11 - port pins are paired odd PMUO and even PMUXE
    // F & E specify the timers: TCC0, TCC1 and TCC2
    PORT->Group[g_APinDescription[2].ulPort].PMUX[g_APinDescription[2].ulPin >> 1].reg = PORT_PMUX_PMUXO_E;  // D3 is on PA11 = odd, use Device E on TCC1/WO[1]
    PORT->Group[g_APinDescription[11].ulPort].PMUX[g_APinDescription[11].ulPin >> 1].reg = PORT_PMUX_PMUXE_F; // D11 is on PA08 = even, use device F on TCC1/WO[0]
    PORT->Group[g_APinDescription[13].ulPort].PMUX[g_APinDescription[13].ulPin >> 1].reg = PORT_PMUX_PMUXE_E; // Try the LED.. doesn't work with E or F

    //Actually, pin 11 on the Feather is on PA16. Still even, not sure of the significance, but it's now TCC0/WO[6] and still port F.
    //All the stuff further down is about TCC1!

    // Feed GCLK4 to TCC0 and TCC1
    REG_GCLK_CLKCTRL = GCLK_CLKCTRL_CLKEN |         // Enable GCLK4 to TCC0 and TCC1
        GCLK_CLKCTRL_GEN_GCLK4 |     // Select GCLK4
        GCLK_CLKCTRL_ID_TCC0_TCC1;   // Feed GCLK4 to TCC0 and TCC1
    while (GCLK->STATUS.bit.SYNCBUSY);              // Wait for synchronization

    // Dual slope PWM operation: timers countinuously count up to PER register value then down 0
    REG_TCC1_WAVE |= TCC_WAVE_POL(0xF) |           // Reverse the output polarity on all TCC0 outputs
        TCC_WAVE_WAVEGEN_DSBOTH;     // Setup dual slope PWM on TCC0
    while (TCC1->SYNCBUSY.bit.WAVE);               // Wait for synchronization

    // Each timer counts up to a maximum or TOP value set by the PER register,
    // this determines the frequency of the PWM operation: Freq = 48Mhz/(2*N*PER)
    REG_TCC1_PER = 1000;                           // Set the FreqTcc of the PWM on TCC1 to 24Khz
    while (TCC1->SYNCBUSY.bit.PER);                // Wait for synchronization

    // Set the PWM signal to output , PWM ds = 2*N(TOP-CCx)/Freqtcc => PWM=0 => CCx=PER, PWM=50% => CCx = PER/2
    REG_TCC1_CC1 = 500;                             // TCC1 CC1 - on D3  50%
    while (TCC1->SYNCBUSY.bit.CC1);                   // Wait for synchronization
    REG_TCC1_CC0 = 500;                             // TCC1 CC0 - on D11 50%
    while (TCC1->SYNCBUSY.bit.CC0);                   // Wait for synchronization

    // Divide the GCLOCK signal by 1 giving  in this case 48MHz (20.83ns) TCC1 timer tick and enable the outputs
    REG_TCC1_CTRLA |= TCC_CTRLA_PRESCALER_DIV1 |    // Divide GCLK4 by 1
        TCC_CTRLA_ENABLE;             // Enable the TCC0 output
    while (TCC1->SYNCBUSY.bit.ENABLE);              // Wait for synchronization

    //Do everything again for TCC0

    // Dual slope PWM operation: timers countinuously count up to PER register value then down 0
    REG_TCC0_WAVE |= TCC_WAVE_POL(0xF) |           // Reverse the output polarity on all TCC0 outputs
        TCC_WAVE_WAVEGEN_DSBOTH;     // Setup dual slope PWM on TCC0
    while (TCC0->SYNCBUSY.bit.WAVE);               // Wait for synchronization

    // Each timer counts up to a maximum or TOP value set by the PER register,
    // this determines the frequency of the PWM operation: Freq = 48Mhz/(2*N*PER)
    REG_TCC0_PER = 1000;                           // Set the FreqTcc of the PWM on TCC1 to 24Khz
    while (TCC0->SYNCBUSY.bit.PER);                // Wait for synchronization

    // Set the PWM signal to output , PWM ds = 2*N(TOP-CCx)/Freqtcc => PWM=0 => CCx=PER, PWM=50% => CCx = PER/2
    REG_TCC0_CC1 = 500;                             // TCC1 CC1 - on D3  50%
    while (TCC0->SYNCBUSY.bit.CC1);                   // Wait for synchronization
    REG_TCC0_CC0 = 500;                             // TCC1 CC0 - on D11 50%
    while (TCC0->SYNCBUSY.bit.CC0);                   // Wait for synchronization

    // Divide the GCLOCK signal by 1 giving  in this case 48MHz (20.83ns) TCC1 timer tick and enable the outputs
    REG_TCC0_CTRLA |= TCC_CTRLA_PRESCALER_DIV1 |    // Divide GCLK4 by 1
        TCC_CTRLA_ENABLE;             // Enable the TCC0 output
    while (TCC0->SYNCBUSY.bit.ENABLE);              // Wait for synchronization
}

If you only want a PWM signal on D11 (PA16 on your MCU) then do not configure other pins from which you you know they are not supported. Perhaps your program crashes. Do you see the "." on the serial monitor? BTW: the example does configure D2 instead of D3 by accident.  But now you need only D11 ;-). Then do not configure both TCC, just the one you need.

For your specific problem: the Feather's D11 is the SAMD's PA16 and on TCC0/WO[6] (use REG_TCC0_CCB2 and PORT_PMUX_PMUXE_F), and also on TCC2/WO[0] (use REG_TCC2_CCB0 and PORT_PMUX_PMUXE_E).
An easier way: I have made a high-frequency-PWM library for this (called Arduino_SAMD21_turbo_PWM), and I have implemented the pin table for the Adafruit Feather M0.
I haven't tested it though, mainly because I don't have an Adafruit Feather M0. Still, feel free to have a try.
The pin mapping table itself for the Adafruit Feather M0, which AFAIK has the same pin mappings as the Arduino Zero, is here on Github; maybe it can help as well.

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


text:
Servo MG996R - what is the maximum load for very long time?
I am working on a device which will have to periodically switch positions and keep the position for very long time, as accurate as possible, under tension.
Never worked with servo motors before, but I found MG996R interesting. It has a stall torque of approx 12kg*cm (@6V).
My question is:
To what maximum safe continuous load I could subject the motor if I need to keep it in position for 24h+ (it may switch position occasionally, but worst scenario would be like 24h-48h continuous locking in same position) ?

perhaps you could use a brake of some type ... release the brake to move to another position, then re-apply the brake

i'm trying to limit the weight, but thank you for the suggestion! Another option was a latch mechanism, to lock in place once position has been changed, but I am still interested to figure out how much stress a servo motor would take considering my requirements.

There is by far not enough information to answer your question. The force that acts on the motor axis depends on the rotation angle. the length of the lever the direction of the "tension" force vector. The time the motor can withstand a force depends on it's stall torque, the current through the motor on high load and the time the motor is allow to be driven with this current. It also depends on the  current through the driver and the time the driver can handle this. There is also a rot angle where the torsion force to the motor is minimal (near 0), so it dep. on the mech. robustn. o.t. motor.


text:
Uno Wifi rev2 - SSL socket connection
On Arduino Uno Wifi rev2 I want to create an SSL socket to my own SSL socket server implementation.
The board can download a webpage with encryption (after I've installed the certificate into it of course).
For my own SSL socket server implementation I'm using OpenSSL.
The board can connect to my own SSL socket server without any issues.
I want to enable SSL_VERIFY_PEER in my socket server.
With this option I can verify if peer is valid and true.
However after enabling this option, the Arduino is not able to connect to my socket anymore.
My question: is peer certificate sending can be achieved on Ublox NINA W10x?

What is the current code you're using?

I understand the question, but I don't know the answer. the firmware updater allows to upload certificates to nina firmware. the ESP32 IDF used to build the firmware has support for verifying a client certificate.

@MaximilianGerhardt the question is what code do I need to use to ask NINA to provide the client certificate upon request.

@Juraj: Can ESP32 IDF make a firmware for NINA W10x?

you have the firmware in the Uno WiFi Rev 2. only I don't know if the firmware and the library support client certificates

Yes I know that the firmware is in the Uno. (To be more exact it is in the NINA W10x). Do you know ESP32 IDF is able to create a firmware for the NINA W10x?

I don't understand. The arduino nina-fw project uses the IDF framework https://github.com/arduino/nina-fw


text:
Reducing the noise of an SSD1306 display by reducing pre-charge in Adafruit SSD1306 library
I have issues with electrical noise on my board (>300mV switching noise on top of 3.3V rail, its quite a lot), which is generated by my I2C SSD1306 OLED display. After some research I found that the noise may be reduced by changing the pre-charge duration in the SSD1306 controller. I am using an Arduino IDE with Adafruit_SSD1306.h library to program my chip. As I understand the initialization bits should be passed via I2C to the controller.
I found the following command in the Adafrui_SSD1306.cpp:

And the relevant bit of datasheet:

The D9 register is defined as SSD1306_SETPRECHARGE in Adafruit_SSD1306.h:

I am using the following code:
void setup(){
...
display.ssd1306_command(SSD1306_SETPRECHARGE); //0xD9
display.ssd1306_command(0x11);
display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
}
...

I am trying to set to 0x11, so to give the pre-charge byte lowest value possible. I've also tried putting the same command into the loop. Nothing has any effect on the display brightness though, which from my understanding should decrease with decreasing the pre-charge value. The noise also stays exactly the same. It seems I fail to pass the values to the SSD1306 correctly. I also tried changing the value in the Adafruit_SSD1306.cpp file:

Still no change. The noise stays exactly the same as well as the brightness. It's clear to me I'm doing something wrong, or I misunderstand the effect of changing the pre-charge value completely. I couldn't find anything in adafruit documentation on this matter. What am I doing wrong?
UPDATE:
I used other commands, such as setcontrast, which did have an effect on the display, so I did pass the values to the controller. It seems that changing the pre-charge value do not have much of an effect. On the other hand I discovered that I2C bus might be introducing the unwanted noise. When bypassing the data of clock line to ground via a capacitor the noise decreases. It seems I was looking for an issue in the wrong place.

At the first glance ssd1306_commad1 should be wrapped in a transaction. This is missing in your code. Add the wrapping macros TRANSACTION_START and TRANSACTION_END or try using ssd1306_command instead.

Apologies, I was using ssd1306_command, forgot to edit it in here. I also discovered that my commands did update the values in the ssd1306 (using other commands like setcontrast etc.), but there was no visible difference when I changed the pre-charge value either in noise or in brightness.


text:
Only print when the button is pressed and not being pressed anymore
I have an Arduino and a microswitch that I want to use to know when the switch is initially being pressed (get "OnsetTime" on Serial) and when the switch is not being pressed anymore (get "OffsetTime" on Serial).
Imagine a bird sitting on the switch. I want to get an output "OnsetTime" when the bird first sits on the switch and an output "OffsetTime" when the bird flies away from the switch.
Right now, I have an output that constantly prints out "OnsetTime" when the switch is pressed.
I would appreciate it if anybody can help me figure out how can I implement the below code to get the outputs only when the switch is initially pressed and not being pressed anymore.
void setup() {
  pinMode(7, INPUT);
  Serial.begin(9600);
}

void loop() {
  if (digitalRead(7) == HIGH) {
    Serial.println("OnsetTime");
    }
}
    //Serial.println("GetOffsetTime");

If you want to be simple, you can use this library. The code will be
#include <ezButton.h>

ezButton button(7);  // create Button object that attach to pin 7;

void setup() {
  Serial.begin(9600);
  button.setDebounceTime(100); // set debounce time to 100 milliseconds
}

void loop() {
  button.loop(); // MUST call the loop() function first

  if(button.isPressed())
    Serial.println("OnsetTime");

  if(button.isReleased())
    Serial.println("GetOffsetTime");
}

If you want to understand in depth, You can see the code and instruction in this tutorial

Hi. This gives me the error: 'class Button' has no member named 'setDebounceTime'

did you install ezButton library ? if not, follow this instruction to install libraray

Yes, I did. This is an unusual case so I'm a bit confused. Did you try it and does it work?

Yes, I tried, it works. I think, you may install multiple Button libraries. Please check it. Or please run example code from library.
If still happened, which Arduino are you  using?

Do you mean I'd want to delete other Button libraries if I have any? I am using Arduino Uno.

I've tried deleting other Button libraries and now the code works. Thank you!

You can save the value of the switch read to compare it on the next loop. This way you're able to detect changes.
int lastValue;

void setup() {
  pinMode(7, INPUT);
  lastValue= digitalRead(7);

  Serial.begin(9600);
}

void loop() {
  int currentValue = digitalRead(7);
  if (lastValue != currentValue) {
    lastValue = currentValue;

    if (currentValue == HIGH) {
      Serial.println("OnsetTime");
    } else {
      Serial.println("OffsetTime");
    }
  }
}

Please be aware that switches bounce. If you see multiple messages at each mechanical change, insert a delay(...).


text:
MAX30003 using Arduino
I am doing project on Single-lead ECG & Heart rate Variability using MAX30003 using Arduino.  I have added the code for this project also. Can anyone please tell me how to include Timer.h library. I am getting following error:

F:\TRACKER WAVE\MAX INT\max
  ard\Protocentral-protocentral_max30003-v0.1-12-ge141d22
  (1)\Protocentral-protocentral_max30003-e141d22\software\protocentral_max30003_arduino\protocentral_max30003\protocentral_max30003.ino:34:22:
  fatal error: TimerOne.h: No such file or directory
#include
compilation terminated.
exit status 1 Error compiling for board Arduino/Genuino Uno.

The code is here:
#include<SPI.h>
#include <TimerOne.h>
#include "MAX30003.h"

#define MAX30003_CS_PIN   7
#define CLK_PIN          6

volatile char SPI_RX_Buff[5] ;
volatile char *SPI_RX_Buff_Ptr;
int i=0;
unsigned long uintECGraw = 0;
signed long intECGraw=0;
uint8_t DataPacketHeader[20];
uint8_t data_len = 8;
signed long ecgdata;
unsigned long data;

char SPI_temp_32b[4];
char SPI_temp_Burst[100];

// 32KHz clock using timer1
void timerIsr()
{
    digitalWrite( CLK_PIN, digitalRead(CLK_PIN ) ^ 1 ); // toggle Digital6 attached to FCLK  of MAX30003
}

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

    pinMode(MAX30003_CS_PIN,OUTPUT);
    digitalWrite(MAX30003_CS_PIN,HIGH); //disable device

    SPI.begin();
    SPI.setBitOrder(MSBFIRST);
    SPI.setDataMode(SPI_MODE0);

  //please enable the below lines if you are using older version of Protocentral_max30003 board without 32k f-clock generator
    /*SPI.setClockDivider(SPI_CLOCK_DIV4);
    pinMode(CLK_PIN,OUTPUT);

     //Start CLK timer
    Timer1.initialize(16);              // set a timer of length 100000 microseconds (or 0.1 sec - or 10Hz => the led will blink 5 times, 5 cycles of on-and-off, per second)
    Timer1.attachInterrupt( timerIsr ); // attach the service routine here
*/
    MAX30003_begin();   // initialize MAX30003
}

void loop()
{
    MAX30003_Reg_Read(ECG_FIFO);

    unsigned long data0 = (unsigned long) (SPI_temp_32b[0]);
    data0 = data0 <<24;
    unsigned long data1 = (unsigned long) (SPI_temp_32b[1]);
    data1 = data1 <<16;
    unsigned long data2 = (unsigned long) (SPI_temp_32b[2]);
    data2 = data2 >>6;
    data2 = data2 & 0x03;

    data = (unsigned long) (data0 | data1 | data2);
    ecgdata = (signed long) (data);

    MAX30003_Reg_Read(RTOR);
    unsigned long RTOR_msb = (unsigned long) (SPI_temp_32b[0]);
   // RTOR_msb = RTOR_msb <<8;
    unsigned char RTOR_lsb = (unsigned char) (SPI_temp_32b[1]);

    unsigned long rtor = (RTOR_msb<<8 | RTOR_lsb);
    rtor = ((rtor >>2) & 0x3fff) ;

    float hr =  60 /((float)rtor*0.008);
    unsigned int HR = (unsigned int)hr;  // type cast to int

    unsigned int RR = (unsigned int)rtor*8 ;  //8ms

     /*Serial.print(RTOR_msb);
     Serial.print(",");
     Serial.print(RTOR_lsb);
     Serial.print(",");
     Serial.print(rtor);
     Serial.print(",");
     Serial.print(rr);
     Serial.print(",");
     Serial.println(hr);      */

      DataPacketHeader[0] = 0x0A;
      DataPacketHeader[1] = 0xFA;
      DataPacketHeader[2] = 0x0C;
      DataPacketHeader[3] = 0;
      DataPacketHeader[4] = 0x02;

      DataPacketHeader[5] = ecgdata;
      DataPacketHeader[6] = ecgdata>>8;
      DataPacketHeader[7] = ecgdata>>16;
      DataPacketHeader[8] = ecgdata>>24;

      DataPacketHeader[9] =  RR ;
      DataPacketHeader[10] = RR >>8;
      DataPacketHeader[11] = 0x00;
      DataPacketHeader[12] = 0x00;

      DataPacketHeader[13] = HR ;
      DataPacketHeader[14] = HR >>8;
      DataPacketHeader[15] = 0x00;
      DataPacketHeader[16] = 0x00;

      DataPacketHeader[17] = 0x00;
      DataPacketHeader[18] = 0x0b;

      for(i=0; i<19; i++) // transmit the data
      {
        Serial.write(DataPacketHeader[i]);

       }

    delay(8);
}

void MAX30003_Reg_Write (unsigned char WRITE_ADDRESS, unsigned long data)
{

    // now combine the register address and the command into one byte:
     byte dataToSend = (WRITE_ADDRESS<<1) | WREG;

     // take the chip select low to select the device:
     digitalWrite(MAX30003_CS_PIN, LOW);

     delay(2);
     SPI.transfer(dataToSend);   //Send register location
     SPI.transfer(data>>16);     //number of register to wr
     SPI.transfer(data>>8);      //number of register to wr
     SPI.transfer(data);      //Send value to record into register
     delay(2);

     // take the chip select high to de-select:
     digitalWrite(MAX30003_CS_PIN, HIGH);
}

void max30003_sw_reset(void)
{
    MAX30003_Reg_Write(SW_RST,0x000000);
    delay(100);
}

void max30003_synch(void)
{
    MAX30003_Reg_Write(SYNCH,0x000000);
}

void MAX30003_Reg_Read(uint8_t Reg_address)
{
    uint8_t SPI_TX_Buff;

    digitalWrite(MAX30003_CS_PIN, LOW);

    SPI_TX_Buff = (Reg_address<<1 ) | RREG;
    SPI.transfer(SPI_TX_Buff); //Send register location

    for ( i = 0; i < 3; i++)
    {
       SPI_temp_32b[i] = SPI.transfer(0xff);
    }

    digitalWrite(MAX30003_CS_PIN, HIGH);
}

void MAX30003_Read_Data(int num_samples)
{
    uint8_t SPI_TX_Buff;

    digitalWrite(MAX30003_CS_PIN, LOW);

    SPI_TX_Buff = (ECG_FIFO_BURST<<1 ) | RREG;
    SPI.transfer(SPI_TX_Buff); //Send register location

    for ( i = 0; i < num_samples*3; ++i)
    {
      SPI_temp_Burst[i] = SPI.transfer(0x00);
    }

    digitalWrite(MAX30003_CS_PIN, HIGH);
}

void MAX30003_begin()
{
    max30003_sw_reset();
    delay(100);
    MAX30003_Reg_Write(CNFG_GEN, 0x081007);
    delay(100);
    MAX30003_Reg_Write(CNFG_CAL, 0x720000);  // 0x700000
    delay(100);
    MAX30003_Reg_Write(CNFG_EMUX,0x0B0000);
    delay(100);
    MAX30003_Reg_Write(CNFG_ECG, 0x805000);  // d23 - d22 : 10 for 250sps , 00:500 sps
    delay(100);

    MAX30003_Reg_Write(CNFG_RTOR1,0x3fc600);
    max30003_synch();
    delay(100);
}

some parts of your code are properly formatted ..  the rest is not ... why are you not asking how to format the code?

Nowadays, the Arduino IDE has a Library Manager helping to properly install and add libraries to projects. Perhaps you remove TimerOne manually and add it again using that tool. (Manager, then Sketch -> include Library )


text:
Understanding SAM3x8e boot program. Misunderstanding the datasheet
I'm trying to make my own firmware uploader for the Arduino DUE by using an ESP32.
While reading through the datasheet I saw that once there's data transmitted over the UART port, the sam3x8e will go into the SAM-BA monitor mode. The flowchart that the datasheet provides is as follow:

How does this make sense, since you can obviously communciate with the DUE over UART?
Do you have to avoid certain hex combinations, or does it get out of this loop automatically?

As far as I remember, it starts if the Flash memory is erased (by holding ERASE input pin low for more than about 250ms). And for example STM32 chips are controlled by BOOT0/BOOT1 input pins to run from bootloader section or flash section or even from RAM

There is a setting in flash that controls whether to boot from flash or to boot from ROM. When you erase the chip it defaults it to ROM.  When you program the chip you (usually) set that setting to boot from flash.


text:
What is ECC608 crypto chip accelerator used for in Arduino Uno Wifi rev2?
Arduino Uno Wifi rev2 includes an ECC608 crypto accelerator chip.
Even their documentation states "As for the WiFi connection, that's made secure with the new ECC608 crypto chip accelerator."
My question is: how exactly the ECC608 is used? I'd like to see the sources the Arduino makes the "WiFi secure" with it.

The library for the chip is ArduinoECCX08. It is used by the ArduinoBearSSL library. The ArduinoBearSSL is used by the ArduinoIoTCloud
 library and Arduino_OAuth library.
.

Thanks. So normally when using WiFiSSLClient (https://www.arduino.cc/en/Tutorial/WiFiNINAWiFiSSLClient), ECC608 is not used at all?

for WiFiNINA, the esp32 firmware handles secure connection with IDF framework utilities.


text:
PC not recognizing Arduino when working with a class and MIDIUSB library
I've recently bought an Arduo Due to create some sort of a Midi controller together with the MIDIUSB library.
I have create a simple a test program with 1 potentiometer (without the use of a class) to test the MIDIUSB library and everything works fine, so I decided to expanded my program to make it work with more than 1 potentiometer (with the use of a class).
However my pc stopped recognizing my Arduino as a MIDI device with my updated code. When I upload my previous example code it all works fine. I get no compile errors or whatsoever.
I don't understand what I'm doing wrong.
If anybody could explain me what I'm doing wrong or could give me a solution you would be a hero since I can't really work further if this issue doesn't get resolved.
Thanks!
Here is my code for Custom_MIDI_controller_V2.ino:
#include "MIDIUSB.h"
#include "Class.h"
#define TOLERANCE 8

byte NUMBER_POTS = 5;

Pot PO0(A0, 1, 14);
Pot PO1(A1, 1, 15);
Pot PO2(A2, 1, 16);
Pot PO3(A3, 1, 17);
Pot PO4(A4, 1, 18);

Pot *POTS[] = {&PO0, &PO1, &PO2, &PO3, &PO4};

void setup() {

}

void loop() {
  for (int i = 0; i < NUMBER_POTS; i++) {
    int potValue = POTS[i]->getValue();
      if(potValue != 255) {
        controlChange(POTS[i]->_channel, POTS[i]->_control, potValue);
        MidiUSB.flush();
      }
   }
}

void controlChange(byte channel, byte control, byte value) {
  midiEventPacket_t event = {0x0B, 0xB0 | channel, control, value};
  MidiUSB.sendMIDI(event);
}

Here is my Class.cpp code:
#include "Arduino.h"
#include "Class.h"

#define TOLERANCE 8

Pot::Pot(int pin, int channel, int control) {
  _pin = pin;
  _channel = channel;
  _control = control;
  _value = analogRead(_pin);
  _oldValue = _value - 10;
}

int Pot::getValue() {
  int diff = abs(_value - _oldValue);
  if(diff > TOLERANCE)
  {
    _oldValue = _value;
    return map(_value, 0, 1023, 127, 0);
  } else {
    return 255;
  }
}

And this is my header Class.h code:
#ifndef Class_h
#define Class_h
#include "Arduino.h"

class Pot
{
  public:
    Pot(int pin, int channel, int control);
    int getValue();
    int _pin;
    int _channel;
    int _control;
    int _value;
    int _oldValue;
};

#endif

Unrelated error: analogRead() is called only once, in the constructor.

Please show the test program that worked.

@CL unrelated? That may well be the root cause - the constructor get called before main() which is where things like analogRead()` may be pre-configured. So it may never get past that point of the program.

What is the point of creating an array of pointers? Just create an array of objects as shown here, for example.

You need to take care with constructors in C++.  They get called during the global variable initialisation phase of the execution, which happens before main() gets called.
main() calls the routines that initialise and configure the peripherals and such in the chip, and by having analogRead() in your constructor (which is itself another error I will mention below) there is a good chance (I don't know the full initialisation sequence of that chip though) that it will never complete, and thus your program hangs at that point.
Your analogRead() doesn't want to be in the constructor, anyway, since that will only execute once when the object is constructed.  Instead you want to have analogRead() called at the point you need to get the analog value. In your code that would be at the start of int Pot::getValue().


text:
Controlling Multiple Brushless Motors with Arduino
I'm working on making an FPV racing drone as an introductory project to using Arduino. I need to be able to control four brushless motors using an Arduino Uno.
First of all, does anyone have any recommendations for motor type and ESC type? But my real question is: how can I power all four motors using one battery? What components do I need to buy? I've tried searching the internet for the answer but I can't find my specific use case, although it doesn't seem like it's uncommon at all.

The uncommon thing in this use case is the Arduino. These days nearly noone uses an Arduino for building a drone. Taking all the sensory input, doing the fusion of the sensor data and controlling the drone accordingly is not a trivial task. A dedicated flight controller is better fit for this task and these days not that expensive. I'm sure, that there are plenty of drone building tutorials on the web, that does not involve Arduino.

Arduino really isn't the best processor for a drone. It can certainly be done however. You can buy a MultiWii flight controller which is based around an Arduino Mega and functions as a drone flight controller.
You can't just ask which motors and ESCs to use. How heavy is your drone? How fast does it need to fly? Is there a payload? To figure out which motors to use, go watch some videos by FliteTest or a multitude of other videos online suggesting how to build a drone. You can certainly power everything off one battery. Again, watch some videos on how multirotor drones are made.
Takeway: An Arduino is a very poor choice for making a flight controller, and there quite a few components needed to build a drone, so watch some videos and learn how!


text:
Arduino Uno & Wemos (0.66” Across) OLED Shield
As I wrote in title, I have Arduino Uno and Wemos (0.66” Across) OLED Shield which i bought along wemos d1 mini.
For some reason I want to use it with uno. but there are just 0.96 tutorials internet and I don't know which pins to connect. I would appreciate any help.
PINS UNDER blue stick are
TX
RX
D1
D2
D3
so on..

how do you know i didn't?

were you this informative when you asked your first question?

I can find the code i have problem with connecting pins. i would appreciate if you help

The first thing I see when googling "0.66 lolin oled" is the link to https://wiki.wemos.cc/products:d1_mini_shields:oled_shield and their Get started guide. This yields the libraries to be used with it:

for the OLED: https://github.com/mcauser/Adafruit_SSD1306/tree/esp8266-64x48 with the dedicated test sketch
for the A & B buttons: https://github.com/wemos/LOLIN_OLED_I2C_Button_Library

thanks for the help man, but my problem is mainly connecting pins

You just stack it ontop of the D1 mini? what hardware are you working with? Also the included schematics (https://wiki.wemos.cc/_media/products:d1_mini_shields:sch_oled_v2.1.0.pdf) show you all the pins.

No, the thing is, I am not using it with D1 mini, i just bought it along that's it. right now, i need to use it with arduino uno.

The Uno is a 5V device and the OLED runs on 3.3V logic. You need a logic level shifter (for example this one https://www.sparkfun.com/products/12009) and then just conned the SCL and SDA pins to your Uno for the I2C connection (see schematics for which pin), plus power. I'm not sure if the library is Arduino-Uno compatible though, you'll have to find out and adapt it as necessary.


text:
1.7MHz Square wave generator
const uint8_t OUTPUT_PIN = 3;  // = OC2B
const uint8_t PERIOD = 9;      // 9 CPU cycles ~ 1.778 MHz

void setup()
{
    pinMode(OUTPUT_PIN, OUTPUT);
    TCCR2B = 0;           // stop timer
    TCNT2  = 0;           // reset timer
    TCCR2A = _BV(COM2B1)  // non-inverting PWM on OC2B
           | _BV(WGM20)   // fast PWM mode, TOP = OCR2A
           | _BV(WGM21);  // ...ditto
    TCCR2B = _BV(WGM22);  // ...ditto
    OCR2A = PERIOD - 1;
    OCR2B = PERIOD/2 - 1;
}

void soundBuzzer() {
    TCCR2B |= _BV(CS20);  // F_CPU / 1
}

void silenceBuzzer() {
    TCCR2B &= ~_BV(CS20);
    TCNT2 = 0;
}

I got it from here, look down to the answers
This program supposed to generate a square-wave of frequency around 1.7MHz but it is not working for me. I have tried the simulation on Proteus 8 and there is no output. Only one error shows during the compilation which is the 'loop' function is missing, I have added one and still there is no output. Please somebody help me.

i suggest that you start by exporing the example sketches in the Arduino IDE ... pay attention to the format of the sketches

In the setup there is some settings for timer2, but no change of prescaller, so the timer stays stopped.
Obviously it was started by calling soundBuzzer() somewhere in code. But this function name is now kinda misleading. Just set prescaller in the setup and it should be working.


text:
Need help in the problem with analog input readings and RTC DS3231
I have 3 analog input(0-1024). I want two outputs based on levels of analog inputs. Eg. inputs have 2 levels. for A0 at 300,digital output pin3 turns ON; and A0 at 500, digital output pin 4 turns ON. Similar for all analog inputs have two levels. Digital output pin 3 turns ON for 1st level and for 2nd level, pin 4 should turn ON. Both should not turn ON at same time. Also, pin 3, should turn ON for specific time in a day for 1 hour.
Problem Facing: (1) I tried this program but outputs doesnt switch according to levels of analog inputs. Once Pin 3 turns ON, it doesnt let pin4 to turn ON. Also, after removing analog inputs, LED remains ON as it is  (2) RTC doesnt turn ON on correct time.
#include<DS3231.h>
#include<Wire.h>
DS3231 rtc(SDA,SCL);
Time t;
const int OnHour=15;  // specified time to turn pin3 ON
const int OnMin=26;
const int OffHour=15;
const int OffMin=28;
int CO2=0;
int Temp=0;
int Humidity=0;

void setup() {

Serial.begin(115200);
rtc.begin();
for(int i=2;i<6;i++){
  pinMode(i, OUTPUT);
}
 }

void loop() {
  t=rtc.getTime();
  delay(1000);
  CO2=analogRead(A0);   //analog input 1
  Temp=analogRead(A1);   //analog input 2
  Humidity=analogRead(A2); //analog input 3

  if((CO2>500)&&(CO2<700)) //500 is low level and 700 is high level
  {
    digitalWrite(2,HIGH);  //indicator LED for low level
    digitalWrite(4,HIGH);  //actual output for low level
    digitalWrite(3,LOW);   //indicator LED for high level
    digitalWrite(5,LOW);   //actual output for high level

  }
  else if(CO2>700) //700 is high level
  {
    digitalWrite(3,HIGH);
    digitalWrite(5,HIGH);
    digitalWrite(2,LOW);
    digitalWrite(4,LOW);

  }

  if((Temp>450)&&(Temp<600))
  {
    digitalWrite(4,HIGH);
    digitalWrite(2,HIGH);
    digitalWrite(3,LOW);
    digitalWrite(5,LOW);

  }
  else if(Temp>600)
  {
    digitalWrite(3,HIGH);
    digitalWrite(5,HIGH);
    digitalWrite(2,LOW);
    digitalWrite(4,LOW);

  }

  if((Humidity>300)&&(Humidity<850))
  {
    digitalWrite(4,HIGH);
    digitalWrite(2,HIGH);
    digitalWrite(3,LOW);
    digitalWrite(5,LOW);

  }
  else if(Humidity>850)
  {
    digitalWrite(5,HIGH);
    digitalWrite(3,HIGH);
    digitalWrite(2,LOW);
    digitalWrite(4,LOW);

  }

  if (t.hour==OnHour && t.min==OnMin)
  {
    digitalWrite(2,HIGH);
    digitalWrite(4,HIGH);
    digitalWrite(3,LOW);
   digitalWrite(5,LOW);

  }
  else if(t.hour==OffHour && t.min==OffMin)
  {
    digitalWrite(2,LOW);
    digitalWrite(4,LOW);
    digitalWrite(3,LOW);
    digitalWrite(5,LOW);

 }
}

Please format your code correctly like you did with your first code. You can put a horizontal line between the codes by adding --- surrounded by free lines. Also please be more specific how the codes don't work. Explain, what the code does and what you expected from it. And do you really want to have 2 seperate codes?

I don't see how the code isn't working, maybe it's because of this line: for(int i=2;i<6;i++){   pinMode(i, OUTPUT); }. try defining pin 2-6 as OUTPUT one by one instead of using that method...

The first problem I see is that you did not set the actual time of the RTC. Do you program it with another piece of code? The second problem I see is, that you are manipulating all LEDs in all conditional cases. Probably you overwrite the information of CO2 with Humidity or Temp or both.  But as far as I don't know what the LEDs mean and how exactly you want them to behave, this is just a rough guess.

Your description is not clear, but definitely different from your code. >"Also I put other 3 LEDs to read which analog input is higher." I don't see such a comparison.

thank you for sparing your time to read my question. I have edited my question here. I guess it can be clearly pictured now.


text:
Servomotor AND Button
I am having trouble trying to make servomotor and button work together. The button code here below works fine when alone in a separate code but when it is transferred to the code with the servomotor function in it, it doesn't work.
Is there anything I need to be wary of when integrating the button code here to the preexisting code?
#include <Servo.h> // Library required for the servomotor (Make sure to download)
#include <Button.h> // Library required for the microswitch (Make sure to download)

// Parameters for the experiment
// Note: 1000 is one second
char Experiment = 'Acclimatization';
char Bird_Name = 'birdname here';
int Frequency = 30 * 1000; // The motor moves every x seconds
int Frequency_Deviation = 5 * 1000; // There are x second deviations plus and minus from the frequency set above
int Duration = 3 * 1000;  // The food is uncovered for x seconds

int servoPin = 9; // Declare the servomotor pin (Can be varied from setup to setup)
Button button(7); // Declare the microswitch pin (Can be varied from setup to setup)

Servo Servo1;

void setup() {
   Servo1.attach(servoPin);
   //analogWrite(servoPin, 0);
   Serial.begin(9600);
   button.setDebounceTime(100); // set debounce time to 100 milliseconds
}

void loop(){
   // Get onset and offset times of when the bird arrives and leaves the perch
   button.loop();
   if(button.isPressed())
    Serial.println("OnsetTime");
   if(button.isReleased())
    Serial.println("OffsetTime");

   // Calculate the acclimatization parameters below
   delay(random(Frequency-Frequency_Deviation,Frequency+Frequency_Deviation)); // Calculates frequency (See paramaters above)
   Servo1.write(0); // Starts from 0 degrees
   delay(Duration); // Duration that the food is uncovered (See parameters above)
   Servo1.write(75); // Goes to the x degrees
}

In your code, you used delay() function two times. This may make Arduino miss some pressing event. Use timestamp instead of delay. See BlinkWithoutDelay example  to see how to use timestamp.
Please note that debouncing function of library does NOT use delay() function. Therefore, you do NOT need to worry about blocking issue

Short answer: You have a blocking delay interrupting your button debounce time of 100ms.
Your button library has a debounce time of 100ms. This means you must be holding the button down for more that 100ms before it will register as pressed.
You have a 3 second blocking delay at the end of your loop. When you call delay(XX), your processor cannot do anything during this time (like check for a button), it's just waiting.
Think about how the code is running. In your main loop, you are calling the function button.loop(), and it's checking to see if your button is pressed. If it's pressed, it's starts a timer (your debounce). The goal of this timer is for another 100ms to pass by with your button still being pressed to make sure you actually pressed it. Button.isPressed() fails, and it moves to its next set of instructions, which is move the servo and wait 3 seconds, during which time it cannot check the button. Then it starts all over again, and it calls button.loop() again. This all happens MUCH faster than 100ms. From the start of void loop() to the time it takes for it to wind back up at the 3 second blocking delay is in the nano seconds. This never gives your button library the 100ms of "pressed down" button it needs for button.isPressed() to return true.
I suggest spending some time looking at the behind the scenes of your button library and see how the debounce works. You can do that, or you can use the example debounce sketch off the main arduino website and learn how that works. The next thing you'd want to do is to learn how to make your code "wait" without using the blocking call delay(). This is done by using timers with millis(). A good way to learn this is the example arduino sketch "Blink Without Delay".
Hope that clears some things up.

Thank you for the feedback. What if I need the day function though? Can I still make the button work while using the delay duration of 3 seconds for example?

@John "This is done by using timers with millis()."

@HavocRC, That library does NOT block in debounce time. The library uses timestamp for debouncing. It does NOT use delay() function. Please read the library reference before anwsering

@John like I said you can get your code to work exactly how you want it to, but you need to use slightly more complicated code. I'm pointing you in the right direction in my answer, if you study and use those two sketches I suggested, you'll have all the knowledge you'll need to accomplish what you wish.

@RozonaZoro I didn't say there was a delay in the debounce library I'm talking about the 3 second delay in the OP's sketch (3rd line from the bottom).


text:
How to connect accelerometer, GPS, microphone and a GSM module to a Arduino?
I am a noob in the Arduino world and have only started reading about it. I have zero experience with Arduino some suggestions to increase my level will also be highly appreciated. But I have a lot of ideas, I want to work on.
I want to measure the velocity and noise levels with the GPS coordinates of a moving vehicle and send it to my phone using gsm or wifi.
Should I include a small LCD also? again suggestions will be highly appreciated.

https://arduino.stackexchange.com/tour

It depends.
If you are a beginner, do it in steps:

Get an Arduino Uno
Get a feeling for MCUs connecting a LED and resistor.
Connect the buzzer and get it working.
Disconnect it, connect the display and get it working.
Same for one sensor.
Than try multiple sensors.
Than play with the WIFI module.
Than combine everything.

The key is to split up your (for a beginner) big project into smaller easier to handle projects.
If you want to add an LCD, depends fully on YOUR requirements; we don't know exactly what you want. If you send all data via WIFI in principle the receiver can display it, but maybe you have a good reason to display it on a display.


text:
Lock screen if I leave my seat?
Background: I change the job and in the new company you need to pay pizza for the whole team if you forget to lock your screen :-)
I want it to be automated: I walk away and the screen should lock. No additional action should be required. Keyboard shortcuts, special mouse movements or unplugging devices from USB are not valid solutions.
How could this be solved (with or without arduino)?
Please write slowly, I never worked with sensors or arduino before :-)
I need this for Mac and Ubuntu.

Windows 10 has something called Dynamic Lock, where the PC lock when your paired mobile phone gets out of range. You might be able to replicate that for Mac/Linux. Or having one of those BLE key chaines (like Tile). When it's out of range, (or the RSSI is low enough), lock the computer.

How many times have you bought pizza so far?

It would be wise to elaborate more specifically on the circumstances that you consider should engage this automation. For example, you might wheel your chair over to talk to your next door neighbour, or stand up to get the attention of someone at the other end of the office: are these acceptable triggers to lock your screen? Both false positives and false negatives in this system have the potential to have annoying consequences, so if you insist on using automation to recognise these criteria minimal ambiguity is key.

Easy: just never leave your chair.

You are seeking a technical solution to a social problem. Expect to be berated for "cheating", if you implement such a solution. Perhaps paying for the occasional pizza might be a worthwhile price to pay to be to be treated like a team member, rather than a smart ass who steals the pizza from others' mouths. Just sayin' ;-)

A social problem? I am unsure. I see it like this: there are rules. I respect the rule. I want to follow the rule. I think automation is the key to success. I like no-brainers and "don't make me think".

@Mawg This is a technical problem: The company (sensibly) doesn't want other people accessing private data on an unlocked computer. Nobody cares about how this is achieved, just that it is. The whole idea behind these policies is to get people to start taking security serious in a nicer manner than having to talk with a manager.

Hard to understand why you want to create another solution to a quick Windows+L keypress ....

The irony here is that locking your console is intended to be a security measure, while many of the proposed solutions arguably introduce vulnerabilities.

@Voo - I disagree. It is not technical, but social. In my security cleared job (I could tell you more, but ...) locking is a requirement. Don't do it and there are severe consequences, far beyond buying pizza.  Hmmm ... wait ... thinking ... maybe my government should develop such a technician solution for all of us. If they feel strongly enough, then it is theirresponsibility.  But, having worked with humans (or as close as developers can be) for a few decades now, I can assure you that the OP will be berated for "cheating" if he implements his own solution ...

... maybe best to ask the company to implement a solution for all

@Mawg Yeah the government is known for being on the forefront of technology and never makes their employees do extra work instead of implementing a simple technical solution ;) But you haven't told me yet why a technical solution that guarantees (if well done) that no desktop is unlocked would somehow be worse than relying on fallible humans to remember to press a button dozens a time a day? (Admittedly some of the solutions here are dubious)

how do you feel about putting an rfid in your hand?  when your hand leaves proxmity to your computer, lock screen. this could be done very simply.

@voo - it's the people factor (exacerbated by the fact that the OP is the FNG) - his coworkers are going to feel that "it's not fair" and that he is "cheating" them out of their pizza. I understand that they could all make their own solution, but almost all will not, and so will complain. Even if he made one for everyone on the team, they will miss the fun of random pizzas & it will all be his fault. I can think of several ways to implemet a solution, but would never be so dumb as to do so. Again, this is not a techncial; problem, but a social one.

@Mawg Having people with that attitude sounds like an awful place to work at. Here, people would be interested in the technical solution and not worried about something as trivial as a bit of free food. I can't imagine most workplaces being like that - in my experience this is just a bit of good fun if someone forgets once in a while.

We are never going to see eye to eye, so I will ask @guettli to post his coworkers' attitude after he implements his solution (for which an ESP32 would be a better choice than an Arduino; heck I bought such a device form eBay about 15 years back, and now Gerben says that Windows has built in support). I won't post again until we hear from teh OP

Sorry, no Arduino required, but you probably already have a web cam on your desktop. If you don't mind being observed like Schrodinger's Cat, you can use a small utility like YawCam in Windows or Motion on Linux to trigger the screen lock when you are no longer visible at your console.

Overall this is a good suggestion, but "you probably already have a web cam on your desktop" seems like a pretty bold assumption. Webcams may be standard equipment on laptops these days, but I can count on one hand the number of desktop computers I've encountered in a business environment that had one installed.

@jmbpiano , how about now that we've all spent 2 years shut up in our home offices Zooming?

Bluetooth!
In the same vein as Gerben's comment, it is quite easy to use your phone for this, assuming that both your PC and your phone have bluetooth (and you take your phone with you, when you leave your seat). Moreover, if your PC does not have BT, cheap BT dongle will solve this.
Next step is writing a script that gets a list of all nearby/found BT devices and if your phone is not on that list, it just sends system call to lock.
As I have actually tried this once (although with a WIN PC), I can say it works more reliably than I would have initially expected (YMMV, obviously).
The great thing is that you (potentially) do not need any extra hardware, just a bit of code.

This works well - I used to do it many years ago. The good thing about writing your own script is that you can customise it for your situation: eg. set the signal strength threshold that will lock/unlock (you don't want to go help out a workmate behind you and not have your auto-lock script trigger!)

RFID (NFC) might be the way to go.  Have an RFID tag in a wristband and an RFID reader by the side of (or under) your keyboard. As long as you keep your hands close to the keyboard the RFID reader should detect your wristband. When it doesn't sense it for a pre-defined period of time send a signal to the PC to trigger it to lock. It could then trigger the unlock when your wristband is back in range again.

The usual range of RFID/NFC will probably make that quite awkward. Using RFID/NFC, I see only two options: either you have a card with a lanyard, and whenever you leave your desk, the card must come with you, or the card and reader are somewhere that moves less that your arms e.g. the tag on your belt and the reader somewhere on the chair.

It may be easier to have a flexible NFC tag sticker type thing on a piece of paper in your back pocket, and a reader under the seat, perhaps?

If you chair has a gas cylinder to adjust height, it sinks a bit when sat in. My dip is about a centimeter. That's more than enough for a beam-interruption or reflection sensor, a hall effect sensor, or even a dead-simple magnetic reed switch, like those used by home alarms to monitor windows.
You could have the reed switch turn on/wake up a micro like an ESP8266, which uses ESP-NOW to talk to another ESP plugged into a usb serial on the desktop. Once the message is sent, the micro can go into deep sleep. The desktop's serial port is read by the lang of your choice; node.js, python, c#, etc, and runs a command or fires a key combo to lock the workstation.

Which has the downside of locking your screen every time you shift in your seat. Was my first idea as well, though. I think you need some delay on it, like if it's longer than 3 seconds or so.

This also has the disadvantage of wire trailing from your chair to computer - wheeling your chair around could end up bringing your computer with you (added benefit of you not being 'away' from the computer I guess...).

If you have a busted cylinder, like many of us do, you'll always be at the lowest point, so you won't see any sink. Or if you constantly raise your seat and it lowers over time, like mine, it could register as occupied, even though it's just failed to support you.

At a previous job we also had the rule that the screen had to be locked (usually done   by pressing Win+L).
However, there was no pizza; instead, the computer was used to send mass e-mails to colleagues. The topics of the e-mails was as varied as the imaginations of people:

invitations to various events;
invitations to various celebrations at the desk of the not locked computer;
selling of expensive items for very low prices, providing whatever reasons;
etc etc

Many times, the content of the e-mail was the result of team-work.
The only limit was that the messages should use a decent language and not be (very) offensive. Also, I have never heard of e-mails sent in order to really harm the forgetful person (e.g. termination notice, offensive language to bosses or cutomers...).

The easiest and cheapest method is to just use Win+L. After you buy pizza for everybody for a few times, and have to endure their jokes / sarcasm at the same time, you will never forget to lock it again.
It is like learning to not pee in the bed during the night. It happens a few times, until you get it right.

For a technical solution, the sky is the limit.
As an (impractical) joke, you may want to have a look at the OMGWTF and the winners.
Example: configure the screensaver to kick in and lock the screen after ~ 5 seconds of inactivity (that is roughly the time you need to stand up and walk away, before any colleague has a chance to start typing without you noticing). It will create some trouble for you also, but you are sure that the computer will never remain unlocked. No additional software, hardware or work required - besides moving the mouse and hitting buttons on the keyboard. At the same time, you will become the most productive employee in the company. :)

On a more serious note, the purpose of that rule is to make people more aware of the security needs, and the need of them being involved in the process. Usually, locking the screen is the least one can do towards security, even before choosing good passwords - screen not locked, password not needed at all.
If one fails to do even that (lock the computer screen when the computer remains unattended), then there is a big chance that the other security rules are not followed either.

+1 for "the purpose of that rule is to make people more aware of the security needs, and the need of them being involved in the process." Yes, people need to be consciously aware of security. Automated systems only work as well as the people setting them up, and all too often those people aren't very security minded or they are so security minded that people with a legit need to use something still can't do to overbearing procedures.

@computercarguy I had a boss once who had the same idea and insisted that people had to consciously install Windows updates instead of using GPOs to handle that automatically. You can guess how many PCs were rarely up to date. Humans are awful at doing things regularly without failing, I don't believe a single person who thinks they'd never forget to lock their PC (I do believe that they don't remember forgetting to lock though, absolutely)

@Voo,there's a difference between a simple key-combo to lock a computer and installing updates manually. I realize (security) people don't realize it, though. Updates should be automated, since they can be complicated and large amount of them, as well as an IT dept potentially managing them. Also, installing updates is likely not the employee's focus at work, so their time is better spent not managing updates. Not to mention that locking a computer is akin to locking the front door to a house or business when it's not occupied.

@computercarguy So you're saying you agree it's impossible for people to once a week type "check for upda" reliably, but it's trivial to remember to press win+L hundreds of times in a week without fail?

@Voo, what I'm saying is that something as potential for failure as updates should be overseen by people who should know what they're doing, which the average office worker won't. And hitting a 2 key combo on the keyboard becomes 2nd nature after doing it for a short time. I do it unconsciously anymore. There are even times when I think about leaving my seat and hit it, only to realize I had one more thing to do/check before I left the seat. You might think checking for updates is easy, but that's only because you've done it so much and so often, which is the point with Win+L.

@Voo, yes, it is very different then checking OS updates. because to press the key combination is an automatic routine mechanical move, like for example  switching the turn signal at driving a car

A single distance sensor, properly placed, should be enough to detect when you leave. That's the arduino part.
With python you can then use the serial over USB to read the output from the arduino. And run the command to activate the screen lock, according to your reading.

Facing the chair might not be good enough, it should be faced 'over' the chair, because otherwise the back of the chair is measured, and you get a false positive when you move back like 8 inches.

arduino micro with keyboard library can send the key combination to lock the screen

Place a ultrasonic distance sensor HC-05 close to your monitor, facing towards your chest. Check the distance measured against a defined threshold (potentiometer?) and send a key press to your PC to lock it if it is exceeded.
I can go into more details if wanted, it's actually a project I thought about implementing before.
Edit: Whoops, @Eduardo Trápani suggested it already, but I think I can add to that.
I would use a digispark-like chip that can emulate key presses (WIN + L), this won't get you into trouble for installing software on your PC.

The simplest solution would be using a pressure sensor (pressure pad) in your seat. Or a pressure mat if you use a standing up desk.
Ideally, you can calibrate it with an Arduino and send a "Windows Key + L" or a "Ctrl + Cmd + Q" if it is an Apple.
I reckon no other solution can be simpler to implement nor to maintain.
If you want a slightly more refined solution you can connect a scale, tare it with your weight and set a weight threshold for the Arduino to send the signal.
Edit: In ubuntu, you can set up any key combination to lock the screen. But the rest of the answer stands.

What type of pressure sensor would you recommend?

Hello @dotancohen
Manufacturing your own seems the best option https://www.tekscan.com/blog/flexiforce/how-create-pressure-sensor-pad
Or this link https://www.instructables.com/id/Use-a-DIY-Pressure-Plate-Switch-to-Automate-Your-H/

Using a key-comb manually is simpler to implement and maintain, since it'll quickly become automatic. It doesn't require any coding, batteries, wires that break or get in the way, and doesn't have to be rewritten for different OSes. It also doesn't break some IT policies against attaching personal peripherals to a computer. Then there's the modification of the chair to accommodate the sensor, which might not be welcome. Also, using an off the shelf load cell is more reliable than a homemade version.

Use an obscure window manager which other people don't know how to use.
I use i3 and like to deliberately leave my workstation unlocked, because it's funny when I come back and find people pressing various key combinations to try and activate the group chat window (sending a funny message in my name is how they would prove they've 'hacked me') which I put into a hidden buffer.
Two and a half years in this role and they still haven't figured it out...all they need to do is RTFM...

OP would still be buying pizza, as the screen would be unlocked. It also sounds more like security by obfuscation, no?

@BruceWayne "security by obfuscation" yes, definitely. Though if OP's workplace's last line of security is the screen lock on OP's computer, then OP's company has bigger things to worry about ;-)

Since this isn't actually securing their PC, this is a bad suggestion. If others just need to RTFM to get around your suggestion, then it doesn't solve any problems, but rather creates new problems.


text:
Overflow while working with SD library
i am currently working on a Project with an SD card. I want to open a .csv-file on my sd card (later it should be the last file) and then read the ID that is at the start of the .csv-file.
Yesterday it worked like a charm but now i get -1 as output for every read() or peek() i use. I cant seem to work out the problem. It could probably be anything in my code but i hope the error lies in this function
Any help is very appreciated.
This is my function:
unsigned int EKG_recording::get_record_from_SD(File dir)
{
  Serial.println("Its in the function\n");
  //dir.rewindDirectory();
  File entry = dir.openNextFile();

  Serial.println(entry.name());

  if (entry)
  {
    first_digit = entry.read(); //ASCII CODE
    Serial.println("one digit:");
    Serial.println(first_digit);

    Serial.println("peek:");
    Serial.println(entry.peek());

    if (entry.peek() == seperator) { // Check if next Byte ";"
      Serial.println("one digit");
      Serial.println((first_digit - '0'));
      return (first_digit - '0');
    }

    second_digit = entry.read();
    Serial.println("2 digit:");
    Serial.println(second_digit);

    Serial.println("peek:");
    Serial.println(entry.peek());

    if (entry.peek() == seperator) { // Check if next Byte ";"
      all_digits = (first_digit - '0') * 10 + (second_digit - '0') ;
      Serial.println("two digits");
      Serial.println(all_digits);
      return (all_digits);
    }

    third_digit = entry.read();
    Serial.println("3 digit:");
    Serial.println(third_digit);

    Serial.println("peek:");
    Serial.println(entry.peek());

    if (entry.peek() == seperator) { // Check if next Byte ";"
      all_digits = (first_digit - '0') * 100 + (second_digit - '0') * 10 + (third_digit - '0');
      Serial.println("Three digits");
      Serial.println(all_digits);
      return (all_digits);
    }
  }
  else {
    Serial.println("No File found");
  }

  entry.close();

}

I think i get some kind of overflow because all Serial.prints return -1
13:20:09.630 -> Its in the function
13:20:09.630 ->
13:20:09.630 -> /System Volume Information
13:20:09.630 -> one digit:
13:20:09.630 -> -1
13:20:09.630 -> peek:
13:20:09.630 -> -1
13:20:09.630 -> 2 digit:
13:20:09.630 -> -1
13:20:09.630 -> peek:
13:20:09.630 -> -1
13:20:09.630 -> 3 digit:
13:20:09.630 -> -1
13:20:09.630 -> peek:
13:20:09.630 -> -1
13:20:09.630 ->

This are my variables for the function
//Funktion get_record_id
     int first_digit = 0;
     int second_digit = 0;
     int third_digit = 0;
     int all_digits = 0;
    unsigned int seperator = 59;

I call the function like this. I dont create folders or anything on the SD-Card, it just contains .csv-files
File root = SD.open("/");
  EKG_recording_1.get_last_record_from_SD(root);

Here is the CardInfo Example for ESP32
17:14:22.777 -> SD Card Type: SDHC
17:14:22.777 -> SD Card Size: 7624MB
17:14:22.777 -> Listing directory: /
17:14:22.777 ->   DIR : /System Volume Information
17:14:22.777 ->   FILE: /1.CSV  SIZE: 9060
17:14:22.811 ->   FILE: /2.CSV  SIZE: 9060
17:14:22.811 ->   FILE: /3.CSV  SIZE: 9056
17:14:22.811 ->   FILE: /4.CSV  SIZE: 9056
17:14:22.811 -> Creating Dir: /mydir
17:14:22.913 -> Dir created
17:14:22.913 -> Listing directory: /
17:14:22.913 ->   DIR : /System Volume Information
17:14:22.913 ->   DIR : /mydir
17:14:22.913 ->   FILE: /1.CSV  SIZE: 9060
17:14:22.913 ->   FILE: /2.CSV  SIZE: 9060
17:14:22.946 ->   FILE: /3.CSV  SIZE: 9056
17:14:22.946 ->   FILE: /4.CSV  SIZE: 9056
17:14:22.946 -> Removing Dir: /mydir
17:14:22.980 -> Dir removed
17:14:22.980 -> Listing directory: /
17:14:22.980 ->   DIR : /System Volume Information
17:14:22.980 -> Listing directory: /System Volume Information
17:14:22.980 ->   FILE: /System Volume Information/WPSettings.dat  SIZE: 12
17:14:22.980 ->   FILE: /System Volume Information/IndexerVolumeGuid  SIZE: 76
17:14:23.013 ->   FILE: /1.CSV  SIZE: 9060
17:14:23.013 ->   FILE: /2.CSV  SIZE: 9060
17:14:23.046 ->   FILE: /3.CSV  SIZE: 9056
17:14:23.046 ->   FILE: /4.CSV  SIZE: 9056
17:14:23.046 -> Writing file: /hello.txt
17:14:23.046 -> File written
17:14:23.080 -> Appending to file: /hello.txt
17:14:23.113 -> Message appended
17:14:23.113 -> Reading file: /hello.txt
17:14:23.113 -> Read from file: Hello World!
17:14:23.113 -> Deleting file: /foo.txt
17:14:23.113 -> Delete failed
17:14:23.113 -> Renaming file /hello.txt to /foo.txt
17:14:23.146 -> File renamed
17:14:23.146 -> Reading file: /foo.txt
17:14:23.146 -> Read from file: Hello World!
17:14:23.146 -> Failed to open file for reading
17:14:32.208 -> 1048576 bytes written for 9036 ms
17:14:32.208 -> Total space: 7604MB
17:14:32.208 -> Used space: 1MB

/System Volume Information -- Is that really the file you want to open...?

I dont even know what this is. I want to open the main folder so "/". Do you know what /System Volume Information is or how i can open the root folder? I never had that name thats why i put it in there

Ok it seems like there is some invisible folder on my sd card that i cant delete. I already formated the sd card. It still shows up. I think i will just test if the dir.openNextFile() chatches a folder or a file

That file is created by Windows for storing extended attribute information.

Well how can i work around this problem? Always delete System Volume Information at the beginning or what should i do?
while(entry.isDirectory()){     entry = dir.openNextFile();   }
Ok i just used this to test if i get a folder from dir.openNextFile(), now i get correct return values again

SD library doesn't use long file names. run the CardInfo example

I edited it to the Main post

try unsigned int EKG_recording::get_record_from_SD(File& dir)