text:
My ESP32 WROOM clone will not register touch sensor when using a 5v power bank with usb cable
I have a very simple touch sensor program that works fine and lights an led to show the sensor works; while hooked up to the computer via usb cable it works fine.  When using a power bank with the same usb cable the board lights up but does not read the touch sensor.  I have tried other cables with the same result.

what is your specific question?

What is your schematic? What is this "touch sensor" of which you speak?

My specific question is about the esp32 touch sensors which are built in touch sensors on the esp32.  Is this normal behavior when trying to use a 5 volt external supply with a usb cable? Has anyone experienced this problem when using the touch sensors? I don't know how to upload the code or a schematic.

Perhaps this is the wrong forum to ask this question.  I use the Arduino ide to program my esp32 as well as some Arduino boards.

@JerryG1112 This is the right forum, but I suspect you are looking at the wrong problem.  "Everything" works fine when the board is powered by the PC, but your touch sensor doesn't work (but the board does?) when running off the battery pack.
So whats the difference?  Whats the output of your battery pack (Volts and Amps)?  My first though was there wasn't enough juice.
A drawing/photo would help, because I'm wondering if you have the touch sensor connected directly to the power supply somehow.  Like wise details of the touch sensor will help, because not all touch sensor are equal :)

@JerryG1112 - Can you run blink on your board on the battery pack?

touch doesn't work as well with battery-powered things or things that are outside. for a motorcycle, consider a cheap microwave radar motion detector module.

I have considered and tried the other types of motion detectors [motion pir, radar, sound, }but they have too many false alarms. i am only trying to prevent gasoline theft.  My last resort will be laser alarm but it is so difficult to setup. Yes blink works.  Gil has provided the path to a solution, but i have yet to complete it.  My current problem is using a larger cap sensor than a wire because I cannot differentiate the touch/no touch states with even a kitchen pot or pan.

This is hard to explain but your problem in not unique. I hope this helps. It is your ground reference. When connected to the computer which is grounded either/or a ground wire or capacitive coupling to earth. Your body is capacitively connected to ground that way and when you touch the switch it is recognized.  To make it work with the battery pack you need to couple to the person touching it. You can do that capacitively by adding a ground plain to your circuit. This can be a conductive plate that will capacitively couple the ground to the atmosphere or any other practical means.

I am using Touch0  which is on GPIO 4.  The led is on  GPIO22 as digital output pin.  I uploaded a blink sketch and it does work on the battery.  The board powers onbaord led under battery power but will not respond to a touch, so I think Gil has the right solution.  i just don't know how to make a conductive plate. Perhaps if I connect the touch wire to my motorcycle it will work as I intend.  (a burglar alarm)

Anything conductive would work. If you power it from the motorcycle the ground plane becomes the frame no other connections needed unless the electrical system is isolated but I doubt it.

I will try that solution tomorrow.  Thank you for the help.


text:
Are resistors necessary for 8x8 LED matrix?
I was following the official tutorial of LED matrix integration and couldn't figure out why there is no resistor.
I assumed there are built-in resistors in the LED matrix, so I did an experiment by connecting pin 9 of the LED matrix to v5 of my Arduino Leonardo board and pin 13 of the LED matrix to GND of the same board. You can refer to the schematic diagram below to know I was trying to lit up the LED at the position [0, 0].
Unfortunately, the LED next to [0, 0] burned immediately and I still couldn't figured out it.

Question

Are resistors necessary for 8x8 LED matrix?

If yes, why the official example doesn't have any resistor?
If no, why my experiment failed?
If no, why are there so many unofficial examples use resistors for each wire?

Source
https://docs.arduino.cc/built-in-examples/display/RowColumnScanning
Circuit

Schematic

Since the pins of a microcontroller cannot provide much current, they got away without resistors. However, they might be using the chip out of its maximum limits. But as you connected the LED directly to the power source, it delivered all it can.

as per my comment in your previous question, the LEDs are lit only one at a time ... that means that each led is turned on very briefly ... so briefly, that the LEDs do not heat up enough to burn

Well done Arduino, you did a great job providing a magic-smoke tutorial [sarkasm off]. IDK how this tutorial could make it into their official docs, it should not be there!
You definitely need series resistors at each column or at each row to protect the LEDs/GPIOs (that's 8 resistors). There may be matrices that integrate resistors, but your one and the one they use in their docs does not.
An alternative is to configure the column GPIOs as inputs with enabled pullups and the row GPIOs as ordinary outputs. This way, current will be limited by the pullup resistors. But as those are quite large (several 10kOhm depending on MCU) the LEDs will be very dim.

The issue has already been documented: https://github.com/arduino/Arduino/issues/8950

@Mikeologist if they know about the issue already I wonder even more why the tutorial is still online! I'd expect them to know how to drive a simple LED...

source: Stack Exchange

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

sort: votes


text:
High frequency sampling with Arduino
I need to sample signals up to about 200 kHz using the Arduino as a kind of oscilloscope. I have already seen that by itself it is unable to do it, since the sample frequency is about 9.6 kHz. But would it be possible to connect it with an external ADC?
Thanks.

If the signal is about 200kHz, the sample rate must be greater than 400kHz.
So, you actually can use some external ADC with parallel interface, but what do you do next with this data stream?

The idea was to process them in the Arduino to obtain a graph

The rule of thumb for scopes is about 5X the frequency. 2X will give you some information but a lot will be missing. What is the voltage range of the input signals? How many bits of accuracy do you need. How about probes? Then there is memory.
You cannot access the internal memory of the Arduino so it will have to be external and dual ported. Dual ported indicates two different sources can access it. How are you going to refresh the memory if dynamic? Static would work but is more expensive.
I would highly recommend you purchase your scope unless this is a learning experience. You can get some very inexpensive scopes for under $100 or even a used one. I think these would work much better then anything you can build for for the same cost.
Many scopes have a interface to external devices can access them, this may be just what you need?

In the end it seems that I don't have to sample at such a high frequency. But, thanks for the information.

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


text:
Conversion from ASCII uint8_t to string
I am sending a string from a Raspberry Pi to an ESP32 via BT. I am getting one ASCII value per line. How to convert it into one whole String? I tried as follows, but I get an error while running the method  printReceivedMEssage(buffer):
invalid conversion from 'uint8_t {aka unsigned char}' to 'uint8_t* {aka unsigned char*}' [-fpermissive]
uint8_t buffer;

void printReceivedMessage(const uint8_t* buf) {
  char string_var[100];
  size_t bufflen = sizeof(buf);

  for (int i = 0; i < bufflen; ++i) {
    Serial.println(static_cast<char>(buf[i]));
  }

  memcpy( string_var, buf, bufflen );
  string_var[bufflen] = '\0'; // 'str' is now a string
  Serial.print("string_var=");
  Serial.println(string_var);
}

void loop() {
  buffer = (char)SerialBT.read();
  Serial.println(buffer); // THIS SHOWS AN ASCII VALUES ONE PER LINE
  printReceivedMessage(buffer); // ERROR
  delay(1000);
}

https://majenko.co.uk/blog/our-blog-1/reading-serial-on-the-arduino-27

Your buffer is only one byte

There are multiple problems with your code. They suggest, that you don't know what strings really are.
In C/C++ strings are actually arrays of characters (char). A uint8_t is the same size of a single character, so you can only save a single character in it. For saving a string, you would need an array of them. So buffer should be declared like
uint8_t buffer[20] = "";

Now buffer can hold a string of 19 characters. The 20th character is the terminating null character \0, which marks the end of a string. You must always leave enough space for the null character to terminate your strings correctly.
Serial reading: There are many ways how you can read from Serial. Look at the Serial.readStringUntil() function, which will read from Serial until it reaches a specified character. This way you can easily divide the continuous stream of bytes from Serial into distinct messages. It is common to end all ASCII encoded messages with a newline \n character to mark the end of the message. With Serial.readStringUntil('\n') (note the single quotes for a single character) you will read until it reaches the newline character (or it times out). You can then process the read string as a full message.
Providing a string as parameter to a function: In C/C++ you cannot just provide an array as parameter to a function as other variables. It is a bit more complex. That is because internal the array consists just of a few bytes in a row and the variable just points to the first element of it. It is a pointer (thats a specific C/C++ term). Pointers are marked with *, which you already did with your
void printReceivedMessage(const uint8_t* buf)

function. So the parameter is just a pointer to a uint8_t. That also explains the error message, because you provided an uint8_t, but the function expects a pointer to uint8_t instead. While you still can access the array data through this parameter (given you have implemented what I wrote above about the array), sizeof(buf) will only give you the size of the pointer (2 bytes on most Arduino platforms). So you need to add a parameter and also provide the size of the array. Or you can utilize the correct termination of strings with the null character and get the length of the string with strlen(). That functions iterates the pointer of the array, until it finds the null character and gives you the resulting length.


text:
Trying to keep my main code running unless an input is LOW for a certain amount of time
I have code that creates a sequential signal with 4 LEDS. It cascades to the right. This works when I hold down the input button. What I need help with is having the code run exactly the same when there is an input signal of .5s HIGH --> .5s LOW (repeat). So what I am thinking in terms of pseudo-code is a code that keeps reading a HIGH signal as long as the signal is not low for more than .5s.
//LED outputs
int LED_5 = 6;
int LED_6 = 7;
int LED_7 = 8;
int LED_8 = 9;

//right turn signal
int RTS_IN  = A0;

//state variable for switch case statements
int stateRightTurn = 0;

//time variable
unsigned long t = 0;
//interval is the time spacing between case statements
unsigned long interval = 100;
//time for shutting off the code
unsigned long off = 600;

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

  //inputs
  pinMode(RTS_IN,  INPUT);

  //right turn signal output from left to right
  pinMode(LED_5, OUTPUT);
  pinMode(LED_6, OUTPUT);
  pinMode(LED_7, OUTPUT);
  pinMode(LED_8, OUTPUT);

}

void loop()
{
  StateRight();

}

//sequential turn signals
void StateRight()
{

   switch (stateRightTurn)
    {

    case 0: //idle
          if (digitalRead(RTS_IN) == HIGH)
          {
              Serial.println("0000");
              t = millis();
              SwitchRightLedsOff();
              stateRightTurn = 1;
          }
          break;

      case 1: //One LED On
          if (digitalRead(RTS_IN) == LOW)
          {
              Serial.println("1111-LOWLOWLOW");
              SwitchRightLedsOff();
              stateRightTurn = 0;
          }
          else if (millis() > t + interval)
          {
              Serial.println("1111-HHHHHHHH");
              t = millis();
              digitalWrite(LED_5, HIGH);
              stateRightTurn = 2;
          }
          break;

      case 2: // Two LEDs On
          if (digitalRead(RTS_IN) == LOW)
              {
                  Serial.println("2222-LOWLOWLOW");
                  SwitchRightLedsOff();
                  stateRightTurn = 0;
              }
              else if (millis() > t + interval)
              {
                  Serial.println("2222-HHHHHHHH");
                  t = millis();
                  digitalWrite(LED_6, HIGH);
                  stateRightTurn = 3;
              }
          break;

      case 3: //Three LEDs On
          if (digitalRead(RTS_IN) == LOW)
          {
              Serial.println("3333-LOWLOWLOW");
              SwitchRightLedsOff();
              stateRightTurn = 0;
          }
          else if (millis() > t + interval)
          {
              Serial.println("3333-HHHHHHHH");
              t = millis();
              digitalWrite(LED_7, HIGH);
              stateRightTurn = 4;
          }
          break;

      case 4: //Four LEDs On
          if (digitalRead(RTS_IN) == LOW)
          {
              Serial.println("4444-LOWLOWLOW");
              SwitchRightLedsOff();
              stateRightTurn = 0;
          }
          else if (millis() > t + interval)
          {
              Serial.println("4444-HHHHHHHH");
              t = millis();
              digitalWrite(LED_8, HIGH);
              stateRightTurn = 5;
          }
          break;

      case 5: //No LEDs on
          if (digitalRead(RTS_IN) == LOW)
          {
              Serial.println("5555-LOWLOWLOW");
              SwitchRightLedsOff();
              stateRightTurn = 0;
          }
          else if (millis() > t + interval)
          {
              Serial.println("55555-HHHHHHHH");
              SwitchRightLedsOff();
              stateRightTurn = 0;
          }
          break;
    }
}

//method to switch LEDs off
void SwitchRightLedsOff()
{
  digitalWrite(LED_5, LOW);
  digitalWrite(LED_6, LOW);
  digitalWrite(LED_7, LOW);
  digitalWrite(LED_8, LOW);
}

And what is your actual question? You didn't ask one. And your description doesn't seem clear to me. Please isolate a single issue with your code, describe only this issue, what happened when you tried it and what you expected to happen.

@chrisl I have updated main description. Let me know if that makes more sense.

If you really are going to use this in an actual vehicle, please consider what should happen with your "sequential turn signals" when the vehicle's hazard lights are flashing at the same time. What should the turn signals be doing if the brake light is on at the same time?

@VE7JRO I have all of that code working simultaneously with the code above. I deleted it all out and segmented just this code for simplicity.

It isn't your issue, but you should move t to the other side of the > sign in expressions like this: (millis() > t + interval) so that you are always comparing intervals rather than timestamps.  // Your proposed solution is a debouncing, or lock-out of a low inputs for 0.5s after the last observed high.

millis()-t is the proper way to handle clock rollover as long as millis() and t are of the same type and interval is smaller than rollover value

If I understand your requirements correctly, you could use a variable to determine if your sequential lights should be flashing or not. If the input signal is LOW for more than 1/2 second, the variable should change to LOW, telling the Arduino to stop flashing your sequential lights.
Let's pretend that your input signal is at the correct voltage and is very accurate with it's time keeping. At the 501ms mark, with no HIGH input signal, your lights should stop flashing.
A simple timer and state variable may work. Here is a test sketch.
// Sketch uses 1144 bytes (3%) of program storage space.
// Global variables use 19 bytes (0%) of dynamic memory.
class MillisTimer{

  private:

    unsigned long m_timeInMilliSeconds;
    unsigned long m_previousMillis;
    byte m_timerActive;

  public:

    MillisTimer(unsigned long timeInMilliSeconds):
      m_timeInMilliSeconds(timeInMilliSeconds),
      m_timerActive(0),
      m_previousMillis(0){
    }

    bool Update(){
      if(m_timerActive && (millis() - m_previousMillis >= m_timeInMilliSeconds)){
        m_previousMillis += m_timeInMilliSeconds;
        return 1;
      }
      else{
        return 0;
      }
    }

    void Start(){
      m_timerActive = 1;
    }

    void Stop(){
      m_timerActive = 0;
    }

    void ReStart(){
      m_timerActive = 1;
      m_previousMillis = millis();
    }

    byte IsActive(){
      return m_timerActive;
    }

};

// Make a copy of the object to work with.
MillisTimer MyTimer(501);

byte inputPin = 2;
byte signalActive = 0;

void setup(){

  // NOTE: Pull-down resistor required if input floating.
  pinMode(inputPin, INPUT);
  MyTimer.Start();

  // Timer status indicator for testing purposes.
  pinMode(LED_BUILTIN, OUTPUT);
  digitalWrite(LED_BUILTIN, LOW);

}

void loop(){

  if(digitalRead(inputPin) == HIGH){
    signalActive = 1;
    MyTimer.ReStart();
  }

  if(MyTimer.Update()){
    signalActive = 0;
  }

  // Test ouput of "signalActive" variable using built in LED on an Uno.
  if(signalActive == 1){
    digitalWrite(LED_BUILTIN, HIGH);
  }
  else{
    digitalWrite(LED_BUILTIN, LOW);
  }

}

I am trying to get this work. I will let you know.

Assuming that digitalRead(RTS_IN) is the input, I'd read it once at the top of the loop and save the timestamp if it is HIGH, and then use the condition millis() - timestamp <= 500 as a latched input variable.
I'd also do the rest of the Input (i.e.: millis()) at the top of the function, convert the time comparisons from absolutes into intervals, and consider factoring the not-enabled case out of the switch's cases.
Untested code:
//LED outputs
int LED_5 = 6;
int LED_6 = 7;
int LED_7 = 8;
int LED_8 = 9;

//right turn signal
int RTS_IN  = A0;

//state variable for switch case statements
int stateRightTurn = 0;

//time variable
unsigned long t = 0;
//interval is the time spacing between case statements
unsigned long interval = 100;
//time for shutting off the code
unsigned long off = 600;

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

  //inputs
  pinMode(RTS_IN,  INPUT);

  //right turn signal output from left to right
  pinMode(LED_5, OUTPUT);
  pinMode(LED_6, OUTPUT);
  pinMode(LED_7, OUTPUT);
  pinMode(LED_8, OUTPUT);

}

void loop()
{
  StateRight();

}

//sequential turn signals
void StateRight()
{
  const int latchInterval = 500; // ms
  static unsigned long lastHigh = -latchInterval; // initialize into the rolled-over past
  unsigned long now = millis();
  int inState = digitalRead(RTS_IN);
  if (inState == HIGH) { //update timer
    lastHigh = now;
  }
  bool enabled = (now - lastHigh <= latchInterval) ; // latched on for 500 ms after off

  switch (stateRightTurn)
  {
    case 0: //idle
      if (enabled)
      {
        Serial.println("0000");
        t = now;
        SwitchRightLedsOff();
        stateRightTurn = 1;
      }
      break;

    case 1: //One LED On
      if (!enabled)
      {
        Serial.println("1111-LOWLOWLOW");
        SwitchRightLedsOff();
        stateRightTurn = 0;
      }
      else if (now - t > interval)
      {
        Serial.println("1111-HHHHHHHH");
        t = now;
        digitalWrite(LED_5, HIGH);
        stateRightTurn = 2;
      }
      break;

    case 2: // Two LEDs On
      if (!enabled)
      {
        Serial.println("2222-LOWLOWLOW");
        SwitchRightLedsOff();
        stateRightTurn = 0;
      }
      else if (now - t >  interval)
      {
        Serial.println("2222-HHHHHHHH");
        t = now;
        digitalWrite(LED_6, HIGH);
        stateRightTurn = 3;
      }
      break;

    case 3: //Three LEDs On
      if (!enabled)
      {
        Serial.println("3333-LOWLOWLOW");
        SwitchRightLedsOff();
        stateRightTurn = 0;
      }
      else if (now - t > interval)
      {
        Serial.println("3333-HHHHHHHH");
        t = now;
        digitalWrite(LED_7, HIGH);
        stateRightTurn = 4;
      }
      break;

    case 4: //Four LEDs On
      if (!enabled)
      {
        Serial.println("4444-LOWLOWLOW");
        SwitchRightLedsOff();
        stateRightTurn = 0;
      }
      else if (now - t > interval)
      {
        Serial.println("4444-HHHHHHHH");
        t = now;
        digitalWrite(LED_8, HIGH);
        stateRightTurn = 5;
      }
      break;

    case 5: //No LEDs on
      if (!enabled)
      {
        Serial.println("5555-LOWLOWLOW");
        SwitchRightLedsOff();
        stateRightTurn = 0;
      }
      else if (now - t > interval)
      {
        Serial.println("55555-HHHHHHHH");
        SwitchRightLedsOff();
        stateRightTurn = 0;
      }
      break;
  }
}

//method to switch LEDs off
void SwitchRightLedsOff()
{
  digitalWrite(LED_5, LOW);
  digitalWrite(LED_6, LOW);
  digitalWrite(LED_7, LOW);
  digitalWrite(LED_8, LOW);
}

This worked perfectly! I understand it as well. I was trying to do something with the same thought process

The trick is turning your input(s) into the helpful "an input is LOW for a certain amount of time"  timer-based state variable that your code can use.


text:
Can't type backslash (\) with Keyboard library
I'm trying to make a macro keyboard, where I can press a single button and it will open programs for me.
I'm trying to type this, for example: "c:\windows"
but it gets typed out like this: cÑ}windows
I tried using double backslash (\), but it still isn't working
#include <HID-Project.h>
#include <HID-Settings.h>

#include <Keypad.h>

#define L_ALT KEY_LEFT_ALT
#define TAB KEY_TAB
#define WIN KEY_LEFT_GUI
#define ENTER KEY_RETURN

const byte FILAS = 4;
const byte COLUMNAS = 4;
//define the cymbols on the buttons of the keypads
char Keys[FILAS][COLUMNAS] = {
  {'1', '2', '3', 'A'},
  {'4', '5', '6', 'B'},
  {'7', '8', '9', 'C'},
  {'*', '0', '#', 'D'}
};

byte pinesFilas[FILAS] = {9, 8, 7, 6};
byte pinesColumnas[COLUMNAS] = {5, 4, 3, 2};

char TECLA;

Keypad teclado = Keypad( makeKeymap(Keys), pinesFilas, pinesColumnas, FILAS, COLUMNAS);

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

void loop() {
  TECLA = teclado.getKey();

  if (TECLA) {

    switch (TECLA) {
      case '1':
        Serial.print("Tecla 1 presionada");
        break;
      case '2':
        Serial.print("Tecla 2 presionada");
        break;
      case '3':
        Serial.print("Tecla 3 presionada");
        break;
      case 'A':
        Serial.print("Tecla A presionada");

        break;
      case '4':
        Serial.print("Tecla 4 presionada");

        Keyboard.press(WIN);
        Keyboard.write('r');
        Keyboard.release(WIN);
        delay(100);
        Keyboard.print("C:\Program Files (x86)\AIMP\AIMP.exe");   //Here's the problem
        //Keyboard.write(ENTER);
        break;
      case '5':
        Serial.print("Tecla 5 presionada");
        break;
      case '6':
        Serial.print("Tecla 6 presionada");
        break;
      case 'B':
        Serial.print("Tecla B presionada");
        break;
      case '7':
        Serial.print("Tecla 7 presionada");
        break;
      case '8':
        Serial.print("Tecla 8 presionada");
        break;
      case '9':
        Serial.print("Tecla 9 presionada");
        break;
      case 'C':
        Serial.print("Tecla C presionada");
        break;
      case '*':
        Serial.print("Tecla * presionada");
        break;
      case '0':
        Serial.print("Tecla 0 presionada");
        break;
      case '#':
        Serial.print("Tecla # presionada");
        break;
      case 'D':
        Serial.print("Tecla D presionada");
        break;
    }
  }
}

That sounds like you have a different keyboard layout set up at your PC than the Keyboard library has. I think it uses the standard US layout.

You have to keep in mind that the Arduino doesn't send characters to the
computer. Instead, it simulates key presses, and the computer has to
translate those into characters, according to some keyboard layout. By
default, the Keyboard library assumes the US keyboard layout.
If you are using another layout, you have to tell the library when
initializing it. E.g.
Keyboard.begin(KeyboardLayout_es_ES);

would work with a Spanish keyboard layout.
C.f. the documentation of Keyboard.begin().
If you are using an unsupported layout, you may need to write your own
layout file and add it to the library. You may then contribute it
upstream so that it becomes part of future versions of the Keyboard
library.
Alternatively, you could switch your layout to US in your OS.
PS: The Keyboard library only supports international keyboard
layouts since version 1.0.3, released on 2021-11-04.


text:
Why is there a cutoff on these accelerometer measurement values? - ADXL375
I'm using a Teensy 3.2 to read data from an ADXL375 using SPI. In general the communication is going just fine and I can activate settings etc.
However, when I try to read X, Y or Z data it seems like some part of the measurement values are missing.
I'm performing measurements with the ADXL375 and writing the LSB values straight to an SD card, so no conversion to g or anything like that. The accelerometer range goes to +/- 200g, so that should give a max LSB value of about 200*20(scale factor) = +/- 4000 LSB.
During some tests I was swinging the accelerometer with my hand, and tapping it directly with a pen, which gives a momentary high impact. The swinging values are represented well and look credible to me, however the pen tapping values seem to be cut off at precisely 511 LSB, see graphs. That seems incorrect. So why is that?
N.B. The range of the ADXL is fixed to 200 g, so no choice to be made there.
My thinking is that something is going wrong with the conversion of the two ADXL registers (two's complement) to form a single number.
This is the conversion I'm doing (i.e. I'm reading out the FIFO in one go):
void ADXL375::saveFIFO(){
    int fifo_index;
    int16_t x, y, z;
    fifo_index=0;
//    readFrom(DEVICE,ADXL375_INT_SOURCE_REG,1,buff);

    for(int i=0;i<32;i++){
        multiByteReadSPI(ADXL375_DATAX0_REG, 6, bufferSPI); //read the acceleration data from the ADXL375
        x = (((uint16_t)bufferSPI[1]) << 8) | (uint16_t)bufferSPI[0];
        y = (((uint16_t)bufferSPI[3]) << 8) | (uint16_t)bufferSPI[2];
        z = (((uint16_t)bufferSPI[5]) << 8) | (uint16_t)bufferSPI[4];

        // Serial.print(bufferSPI[5], BIN); Serial.println(bufferSPI[4], BIN); // z
        // Serial.print(bufferSPI[1], BIN); Serial.print(","); Serial.println(bufferSPI[0], BIN);  // x

        if (x & 0x8000){ // Check if the binary number is negative, by checking whether left most bit is 1 or not.
            // If negative, then perform not operation and add one to get magnitude
            x = ~x + 1;
            x = - x;
        }
        if (y & 0x8000){ // Check if the binary number is negative, by checking whether left most bit is 1 or not.
            // If negative, then perform not operation and add one to get magnitude
            y = ~y + 1;
            y = - y;
        }
        if (z & 0x8000){ // Check if the binary number is negative, by checking whether left most bit is 1 or not.
            // If negative, then perform not operation and add one to get magnitude
            z = ~z + 1;
            z = - z;
        }

        lastFiFo[fifo_index]    =   newistFiFo[fifo_index];
        newistFiFo[fifo_index]  =   x;
        fifo_index++;
        lastFiFo[fifo_index]    =   newistFiFo[fifo_index];
        newistFiFo[fifo_index]  =   y;
        fifo_index++;
        lastFiFo[fifo_index]    =   newistFiFo[fifo_index];
        newistFiFo[fifo_index]  =   z;
        fifo_index++;
        // debugPrint(x); // debugPrintln(", Saving fifo");

                // x = (((int16_t)bufferSPI[1]) << 8) | bufferSPI[0];
        // y = (((int16_t)bufferSPI[3])<< 8) | bufferSPI[2];
        // z = (((int16_t)bufferSPI[5]) << 8) | bufferSPI[4];
        // scaleXYZ(&x,&y,&z);

    }

 }

This is the SPI Multibyte Read function I'm using:
void ADXL375::multiByteReadSPI(uint8_t regAddr, uint8_t numberOfBytes, uint8_t *dataBuffer){

    SPI.beginTransaction(SPISettings(5000000, MSBFIRST, SPI_MODE3));

    digitalWrite(_chipSelectPin,LOW);

    uint8_t readMBaddr;

    if (numberOfBytes > 1){ // for an actual multibyte read
        readMBaddr = 0b11000000 | regAddr; //  From left to right: read (1),  yes multibyte (1), and then a bunch of zeros
    }
    else{ // for single byte read
        readMBaddr = 0b10000000 | regAddr; //  From left to right: read (1),  not multibyte (0), and then a bunch of zeros
    }

    SPI.transfer(readMBaddr);

    for (uint8_t k = 0; k < numberOfBytes; k++ ){
      dataBuffer[k] = SPI.transfer(SPI_DUMMY_VALUE);
    }

    digitalWrite(_chipSelectPin,HIGH);

    SPI.endTransaction();

}

I also had a look whether the SPI transfers are okay. The image shows one multibyte read, consisting of a command byte on the far left, and then 6 read bytes after that. Nothing out of the ordinary there.

link to EE SE version of the question: https://electronics.stackexchange.com/questions/611607/why-is-there-a-cutoff-on-these-accelerometer-measurement-values-adxl375

I found the answer. Turns out the datasheet of the ADXL375 is wrong, and the user can actually change the range themselves (even though the datasheet says you can't). In my case, the range was unintentionally set to 25 g (instead of 200 g). See below the full explanation by bvn123 - which was posted in 2017, yet Analog Devices has still not updated the datasheet.

I use ADXL345 and ADXL375 under a uC software, which was written for
ADXL345.
The Datasheet for ADXL345 says about ±2g/±4g/±8g/±16g ranges and
corresponding to these ranges 10/11/12/13bits resolutions.
The Datasheet for ADXL375 shows only one range ±200g and 13bits
resolution. .
Inspite of the ADXL375 Datasheet's info, that Register 0x31 only state
for bits D3:D2:D1:D0 is 1n11 (D3 is the Full resolution bit, D1:D0 are
the Range bits), the ADXL375 reacts for D1:D0  and D3 change in the
Register 0x31 the same way, as the ADXL345,
So, in reality ADXL375 also provides 4 ranges (±25g/±50g/±100g/±200g).


text:
Arduino OLED ssd1315 graphic print questions
I’ve tried to create a system that the rotary sensor as an input and use a 0.96 inch Oled as an output (first pic), try to show the voltage measurements and performance test using a small bar graphic.
And I use this code
#include <SPI.h>
#include <Wire.h>

#include <Adafruit_SSD1306.h>

#define OLED_RESET 4
Adafruit_SSD1306 Display(OLED_RESET);

int r = 0;
int i = 0;

void setup()   {

  Display.begin(SSD1306_SWITCHCAPVCC, 0x3C);  // initialize with the I2C addr 0x3C (for the 128x32)

  // i'll follow the license agreement and display the Adafruit logo
  // and since they were nice enough to supply the libraries
  Display.clearDisplay();
  Display.display();
  delay (1000);

  DrawTitles();

}

void loop() {

  // get some dummy data to display

  r = rand() / 220;
  //r = analogRead(ADJ_PIN);
  //r = r / 7.98;

  Display.setTextSize(2);
  // note set the background color or the old text will still display
  Display.setTextColor(WHITE, BLACK);
  Display.setCursor(0, 33);
  Display.println(Format(r * 7.99 / 204.6, 3, 2));

  //draw the bar graph
  Display.fillRect(r, 50, 128 - r, 10, BLACK);
  Display.fillRect(3, 50, r, 10, WHITE);

  for (i = 1; i < 13; i++) {
    Display.fillRect(i * 10, 50, 2, 10, BLACK);
  }

  // now that the display is build, display it...
  Display.display();

}

void DrawTitles(void) {

  Display.setTextSize(2);
  Display.setTextColor(WHITE);
  Display.setCursor(0, 0);
  Display.println("Bar Graph");

  Display.setTextSize(1);
  Display.setTextColor(WHITE);
  Display.setCursor(0, 19);
  //Display.println("Measured Volts");
  Display.println("Random number");
  Display.display();

}

String Format(double val, int dec, int dig ) {

  // this is my simple way of formatting a number
  // data = Format(number, digits, decimals) when needed

  int addpad = 0;
  char sbuf[20];
  String fdata = (dtostrf(val, dec, dig, sbuf));
  int slen = fdata.length();
  for ( addpad = 1; addpad <= dec + dig - slen; addpad++) {
    fdata = " " + fdata;
  }
  return (fdata);

}

But it only showed the graphic bar and random number without an actual graphic bar at the end, so just wondered if I did something wrong or forgot to add something on my cold?
I'm new to this and I've tried so many things to fix it but seen not any of them working.
Thanks

please add a picture of the OLED output ... also add a drawing of the desired output

I've just add a picture

But it only showed the graphic bar and random number  ... where are those in the picture? ... all I see is text "Bar Graph" and "Random number"

we still do not know what you are trying to display

like the first picture, that's the one i trying to do.

What resolution does your display have? I think your display has a lower vertical resolution than the one in the first picture and assumed in your code. The value and bar graph are not displayed because they are drawn outside of the display's vertical boundary.


text:
Can I use Data Logger Shield with Arduino Sensor shield V5.0?
so I did a little research on this but the answer to my particular problem did not exist.
I have a data logger shield created by deek robot (deek-robot.com) which seems pretty similar to adafruits data logger shield so I assume they would use the same pins, about this one I can research and find the pins.
but in case of the sensor shield I could not find anything specially since there is no reference on the manufacturer on the board and only referred to as "Arduino Sensor Shield V5.0",as this is a shield for sensors and has almost every pin available on it I would assume it can use most of the data pins and depends on which pins I connect.
Now my question is that can I use these shields together if I want to use those digital pins already used by the data logger? or I can use them together only if I leave out the digital pins 10 to 13 out of use on my sensor shield?

The 'data logging' shield by Adafruit and Deek Robot has two devices.
First device is the SD card which uses SPI bus. Every SPI device on the SPI bus has to have a select pin CS. On this shield the SD card has pin 10 as the CS pins.
The second device on the data logger shield is a RTC clock. The RTC clock is on the I2C bus.
So the data logger shield uses the I2C pins, the SPI pins and a pin for CS. Arduino in Uno and Mega R3 form factor have the SPI as a 2x3 header and the I2C pins SDA and SCL are last two pins on the header near the USB connector.
On Uno the data logging shield uses pin 10 as CS, 11, 12, 13 as SPI and A4, A5 as I2C.
If you have the version of the data logging shield which can be used on boards other than Uno, then:

On Mega it uses pin 10 as CS, 50, 51, 52 as SPI and 20, 21 as I2C.
On Leonardo it uses pin 10 as CS, 2, 3 as I2C (and the SPI pins which are only on the SPI header).
On Arduino Zero the shield uses pin 10 as CS, 11, 12, 13 as SPI (and the I2c pins are only on the SDA/SCL header).

The 'sensor shield' doesn't have any devices. So it makes no difference in pins usage. With or without the 'sensor shield' if you have the 'data logging' shield attached, you can use only the pins not used by the 'data logging' shield.
Since SPI and I2C are a bus, you can wire additional SPI devices to the SPI pins and additional I2C devices to the I2C pins, but you can't use these pins for anything else if they are configured for the bus.

Ok thanks, a rather thorough answer, I will mark it right away after testing them , but what you indicated seems to be the right answer and even with more details , just another quick and small question, I read that the I2C can be used with as many devices as you want since they don't have CS of their own? this now means I am down to minus 2 analog and minus 4 digital pins, so assuming I hit this cap I will have to use MUXes I suppose

@Hitman2847, I2C doesn't use CS. the devices on I2C bus have addresses. If you need more pins, switch to Mega, but first check if the 'data logger' shield uses pins 11 to 13 or the 2x3 SPI header and the SDA and SCL pins or the A4 and A5 pins.

well the data logger must use the 11 to 13 pins because it only connects physically on the side pins and the 2x3 SPI header is free and not connected to anything


text:
Arduino Nano BLE 33 default example sketch `USBHID>Keyboard` makes the Arduino unusable
How the problem started
I was playing around with using the Arduino Nano BLE 33 as a keyboard, and stumbled upon the USBHID>Keyboard sketch which I got via the default suggestion from the Board Manager to install Arduino Mbed OS Nano Boards:
See the source on github.com/arduino/ArduinoCore-mbed, or reproduced below:
#include "PluggableUSBHID.h"
#include "USBKeyboard.h"

USBKeyboard Keyboard;

void setup() {
  // put your setup code here, to run once:

}

void loop() {
  // put your main code here, to run repeatedly:
  delay(1000);
  Keyboard.printf("Hello world\n\r");
}

It seemed fairly innocent, so I uploaded it without a second thought thinking that I could trust anything provided from Arduino itself as an example script.
What the problem is
But now, as soon as I plug in the Nano, it types Hello world followed by a newline every. single. second.
If I try to upload the blink sketch to clear it, I first need to select the Port, but the act of going through the menu to choose the correct port takes over a second, and typing in Hello world selects the library manager and ends up opening it when enter is pressed due to the \n\r. So my Arduino Nano has been rendered useless by code included as an example in the default sketches. That's not cool.
Failed Solution Number 1
I tried creating a custom keyboard shortcut to select the port in less than a second, and then pressing cmd-U to upload, but I think there might also be a problem there because I get this error:
    ...
    Found upload port: /dev/cu.usbmodem11401
    /Users/<my username>/Library/Arduino15/packages/arduino/tools/bossac/1.9.1-arduino2/bossac -d --port=cu.usbmodem11401 -U -i -e -w /var/folders/y1/md9_k_td4rz1f0pq26d24crh0000gn/T/arduino_build_230227/<my script name>.ino.bin -R
->  No device found on cu.usbmodem11401
    An error occurred while uploading the sketch
    ....

I'm absolutely certain that cu.usbmodem11401 is the correct port, because that's what shows up when I ls /dev/cu* while the Arduino is plugged in. So I think that the Arduino IDE is attempting to upload to cu.usbmodem11401, but sees that it's a keyboard, and decides that it can't upload code to a keyboard so aborts.
Failed Solution Number 2
I tried uploading blink.ino from a different laptop (also macos) but nothing changed.
Failed Solution Number 3
I tried looking for ways to 'distrust' a keyboard to prevent the Arduino from sending keyboard strokes, but couldn't anything.
Failed Solution Number 4
Maybe attempting to short circuit whichever wire the Arduino uses to communicate with the laptop will work, but I don't know nearly enough to do that so I'd just be randomly connecting wires to ground which I don't really want to do...
Fin
I'm at a loss for what to try. I've logged an issue with the github repo, but I can't think of other solutions.

According to the datasheet...

3.6 Board Recover
All Arduino boards have a built-in bootloader which allows flashing the board via USB. In case a sketch locks up the
processor and the board is not reachable anymore via USB it is possible to enter bootloader mode by double-
tapping the reset button right after power up.

So, plug it in, and press the RESET button twice. That should then load the bootloader and it will sit there waiting for you to reprogram it.

Legend. Thanks so much! Imma go read the datasheet now...


text:
Save data permanently on ESP32
I'm working on a stage (this is my first bigger Arduino project), and I want to create an initializer for it, and for this, I want to store some variables in the memory of ESP32 WROVER-B. For this, I found this solution.
Based on their example (which works fine) I write a basic demo, using their Preferences.h:
#include <Preferences.h>

#define MAX_BUFF_LEN  255

Preferences preferences;

char c;
char str[MAX_BUFF_LEN];
uint8_t idx = 0;

void init(){
  preferences.remove("counter");
  preferences.begin("my-app", false);
  unsigned int counter = 0;
  Serial.printf("Current counter value: %u\n", counter);
  preferences.putUInt("counter", counter);
  preferences.end();
}

void readback(){
  preferences.begin("my-app", false);
  unsigned int counter = preferences.getUInt("counter", 0);
  Serial.printf("Current counter value: %u\n", counter);
  preferences.end();
}

void add(){
  preferences.begin("my-app", false);
  unsigned int counter = preferences.getUInt("counter", 0);
  counter++;
  Serial.printf("Current counter value: %u\n", counter);
  preferences.putUInt("counter", counter);
  preferences.end();
}

void setup() {
  Serial.begin(115200);
  //Serial.begin(9600);
  while (!Serial) ; // wait for serial port to connect. Needed for native USB
  Serial.println("start");
}

void loop() {
  if(Serial.available()>0){
    c = Serial.read();
    if(c != '\n')
      str[idx++] = c;
    else{
      str[idx] =  '\0';
      idx = 0;

      Serial.print("Recieved: ");
      Serial.println(str);
      if(*str == 'r')
        readback();
      if(*str == 'w')
        init();
      if(*str == 'a')
        add();
    }
  }
}

But every time I reset (I mean plug out and in) my ESP it starts counting at the beginning. Also if I disconnect the client on the serial port the same happens. What have I missed here, or how can I do it correctly?

You could try using the https://randomnerdtutorials.com/esp32-flash-memory/  EEPROM for example

@Avon97 which says "This tutorial is outdated. Follow the new tutorial instead: ESP32 Save Data Permanently using Preferences Library"


text:
Power requirements of a 7 Segment Display on Uno vs Nano
As part of a Simhub Dash set up I have been trying to get a 8 Digit 7 segment display working on an Arduino Nano. As part of my fault finding process I have gone back to basics and am using the 7CDemo7Segment example script included with the ledcontrol library . The 8x8Matrix Test is performed with the LCDemoMatrix example script. Both displays are powered by the 5v/Gnd pin combination.  No other devices are connected.
The following image shows the circuit.  Ignore pins (they are as described below) and Uno/Nano are interchangeable.

Completing the following tests I get the described results:

Uno and 7Seg with Pins 678 - OK - proof of library and display
Nano and 7Seg with Pins 678 - FAILS (nothing lights up and if it does it’s incoherent to what it should be going) - same code and display
Nano and 8x8 Matrix with Pins 678 - OK - proof of the Nano and Pins.

I feel the above combinations prove that: the script is correct; the display works; and that the pins are okay.
The only thing I can think is that this is a power/current issue via USB/5V pin?
Would someone be able to confirm.   I have looked at How much current can I draw from the Arduino's pins? and feel that there is not a clear answer for the Nano 5V pin.

With out a schematic we can only guess (or ask a lot of questions).  The Atmel328 processor can handle up to 40mA per pin.  But when you add all the current up you should stay below 200mA.  So, lets say your properly current limited LEDs are suppose to draw 5mA each.  Then, you should not turn on more than 40 on at the same time.  But I suspect you have other problems.  You might be trying to run multiple programs which use the same resources.  For example, you may have a limited number of timers and one program may overwrite the settings of another. Thereby ruining the other's LED control.

@st2000 I have tried to update the question without (hopefully) adding too much unnecessary detail.

So, there is only the 1 display?  Can you also identify the software library (or libraries) you are using?  From the wording in your question I though you had several different displays that worked independently but not together.

Honestly I don't think power is the issue. When powering via USB you should be able to draw the full 500mA, that the USB port gives you. Thats way enough for a normal 7 Seg display, even with 8 digits. Bit you can test this by connecting both Arduinos via USB and then connecting their ground and 5V. That doubles the available current

Please provide a link to the library that you are using

Power requirements of a 7 Segment Display on Uno vs Nano ... they would be the same

Does the voltage regulator on the Nano get hot?

What do you mean by "FAILS"? Please be more specific on the failure, what do you get instead of your expectation?

@st2000 Yes, eventually both should be connected but for the purposes of understanding this problem on a single display is connected

Thanks for answering.  Know this, loading up more than one library or loading up a library intended for a different processor can lead to difficulties.  For example, 2 libraries may try to configure the same timer, interrupt or processor pin.  Likely this will lead to unexpected results.  Can we assume you are loading up only the led control library?

Yes.  I’m using the built in library examples and just changing the pins as appropriate. In my mind it really could not be simpler.


text:
How to get started with writing code for a Hall Effect sensor?
One of my biggest questions concerns coding a Hall effect sensor to find wheel speed with an arduino mega.
I’ve got an lcd in digital pins(7,8,9,10,11,12) and a Hall effect sensor in digital pin 2.
I just have no idea how to code the actual rpm measuring process. Does anyone have any ideas or experience that can help me? My form of measurement is to spin something with a mounted magnet near it. The end game is to measure a car wheel rpm. Pointers? Tips?

yes, many people have ideas and experience ... is that all you wanted to ask?

break the program into individual sections ... start by reading sensor and turning led on and off when signal is detected .... then work on learning how to display numeric data

There are numerous tutorials online. An example is https://maker.pro/arduino/tutorial/how-to-use-a-hall-effect-sensor-with-arduino

You can measure this in either RPM (revolutions per minute) or frequency (cycles per second).
Whether it be a minute or a second, you count the number of times you get a pulse and at the end of the minute/second you copy the total to your variable and reset the counter variable. If you need a fasster update rate, you can count for fractions of minute/second and do the calculation to show it in terms of RPM/frequency.
My first concern when solving this issue is how fast the magnet is going past the sensor (ie how many pulses per second).
If it is slow, you can do it in your main loop as long as you don't have any blocking instructions (such as delay()).
If it is fast you will probably have to look into an interrupt. When the pin goes high, it jumps to the interrupt function and increments a counter. Check the input section for libraires that make the interrupt process easy (or do it the old fashioned way, your choice). Some of the button libraries have interrupt specific functions.

Make sure to only count a pulse once. For example, you could achive this by looking for the rising edge of the pulse.


text:
Why is EEPROM commit not registering int values?
       if(jsonDoc["delayOn"].as<int>() <= 255 && jsonDoc["delayOff"].as<int>() <= 255 && jsonDoc["delayUnitOn"].as<int>() <= 2 && jsonDoc["delayUnitOff"].as<int>() <= 2 &&
         jsonDoc["mode"].as<int>() <= 1 && jsonDoc["blink"].as<int>() <= 1 &&
         jsonDoc["timeOnHour"].as<int>() <= 23 && jsonDoc["timeOnMinute"].as<int>() <= 59 &&
         jsonDoc["timeOffHour"].as<int>() <= 23 && jsonDoc["timeOffMinute"].as<int>() <= 59) {

        int val;
        int addr_init = (relay*eepromSlotsPerRelayPin)*sizeof(int);

        val = jsonDoc["blink"].as<int>();
        EEPROM.put(addr_init,val);
        if(jsonDoc["blink"].as<int>()==1){ //0=off,1=on

          val = jsonDoc["mode"].as<int>();
          EEPROM.put(addr_init+(5*sizeof(int)),val);

          if (jsonDoc["mode"].as<int>()==0){ //blink mode

            val = jsonDoc["delayOn"].as<int>();
            EEPROM.put(addr_init+(1*sizeof(int)),val);
            val = jsonDoc["delayOff"].as<int>();
            EEPROM.put(addr_init+(3*sizeof(int)),val);
            //1=minute,0=second,2=hour
            val = jsonDoc["delayUnitOn"].as<int>();
            EEPROM.put(addr_init+(2*sizeof(int)),val);
            val = jsonDoc["delayUnitOff"].as<int>();
            EEPROM.put(addr_init+(4*sizeof(int)),val);
            EEPROM.end();

          }else if(jsonDoc["mode"].as<int>()==1){ //time switch mode

            val = jsonDoc["timeOnHour"].as<int>();
            EEPROM.put(addr_init+(6*sizeof(int)),val);
            val = jsonDoc["timeOnMinute"].as<int>();
            EEPROM.put(addr_init+(7*sizeof(int)),val);
            val = jsonDoc["timeOffHour"].as<int>();
            EEPROM.put(addr_init+(8*sizeof(int)),val);
            val = jsonDoc["timeOffMinute"].as<int>();
            EEPROM.put(addr_init+(9*sizeof(int)),val);
            EEPROM.end();
          }
          else {
            request->send(412, "text/plain", "unknown mode");
            return;
          }
        }
      }
      else {
        request->send(412, "text/plain", "a parameter is not within limits");
        return;
      }

      //initBlinkPinObjs
      int addr_init;
      int val,uom;
      for(int i = 0; i<maxRelayPins; i++) {
        bPinObjs[i].pin = relayPins[i];
        //EEPROM Slot per Relay dataStruct
        //0=>enable, 1=>durationOn, 2=>durationOnTimeMeasure,
        //3=>durationOff, 4=>durationOffTimeMeasure
        //5=>mode, 6=>timeOnHour, 7=>timeOnMinute,
        //8=>timeOffHour, 9=>timeOffMinute

        addr_init = (i*eepromSlotsPerRelayPin)*sizeof(int);

        val = 0;
        EEPROM.get(addr_init,val);
       bPinObjs[i].enable = val;

        val = 0;
        EEPROM.get(addr_init+(5*sizeof(int)),val);
        bPinObjs[i].mode = val;

        val = 0;
        EEPROM.get(addr_init+(6*sizeof(int)),val);
        bPinObjs[i].timeOnHour=val;

        val = 0;
        EEPROM.get(addr_init+(7*sizeof(int)),val);
        bPinObjs[i].timeOnMinute=val;

        val = 0;
        EEPROM.get(addr_init+(8*sizeof(int)),val);
        bPinObjs[i].timeOffHour = val;

        val = 0;
        EEPROM.get(addr_init+(9*sizeof(int)),val);
        bPinObjs[i].timeOffMinute = val;

        //delayOn
        //convert to millisec
        uom = 0;
        EEPROM.get(addr_init+(2*sizeof(int)),uom);
        switch(uom){
          case 0:
            bPinObjs[i].durationOn=0;
            val = 0;
            EEPROM.get(addr_init+(1*sizeof(int)),val);
            bPinObjs[i].durationOn = val*1000;
          break;
          case 1:
            bPinObjs[i].durationOn=0;
            val = 0;
            EEPROM.get(addr_init+(1*sizeof(int)),val);
            bPinObjs[i].durationOn = val*60000;
          break;
          case 2:
            bPinObjs[i].durationOn=0;
            val = 0;
            EEPROM.get(addr_init+(1*sizeof(int)),val);
            bPinObjs[i].durationOn = val*3600000;
          break;
          default:
          break;
        }
        //delayOff
        //convert to millisec
        uom = 0;
        EEPROM.get(addr_init+(4*sizeof(int)),uom);
        switch(uom){
          case 0:
            bPinObjs[i].durationOff = 0;
            val = 0;
            EEPROM.get(addr_init+(3*sizeof(int)),val);
            bPinObjs[i].durationOff = val*1000;
          break;
          case 1:
            bPinObjs[i].durationOff = 0;
            val = 0;
            EEPROM.get(addr_init+(3*sizeof(int)),val);
            bPinObjs[i].durationOff = val*60000;
          break;
          case 2:
            bPinObjs[i].durationOff = 0;
            val = 0;
            EEPROM.get(addr_init+(3*sizeof(int)),val);
            bPinObjs[i].durationOff = val*3600000;
          break;
          default:
          break;
        }
      }

--JSON INPUT printed from server--

relay:0
blink:1
mode:1
delayOn:56
delayOff:2
delayUnitOn:0
delayUnitOff:0
timeOnHour:5
timeOnMinute:56
timeOffHour:7
timeOffMinute:48

OUTPUT printed from server:
--Objects content--
Size of INT:4
---------0--------- init addr: 0
[0]enable: 0
[1]durationOn: 0
[2]durationOnUom: 0
[3]durationOff: 0
[4]durationOffUom: 0
[5]mode: 0
[6]onHr: 0
[7]onMin: 0
[8]offHr: 0
[9]offMin: 0
---------1--------- init addr: 40
[0]enable: 0
[1]durationOn: 0
[2]durationOnUom: 0
[3]durationOff: 0
[4]durationOffUom: 0
[5]mode: 0
[6]onHr: 0
[7]onMin: 0
[8]offHr: 0
[9]offMin: 0
---------2--------- init addr: 80
[0]enable: 0
[1]durationOn: 0
[2]durationOnUom: 0
[3]durationOff: 0
[4]durationOffUom: 0
[5]mode: 0
[6]onHr: 0
[7]onMin: 0
[8]offHr: 0
[9]offMin: 0
---------3--------- init addr: 120
[0]enable: 0
[1]durationOn: 0
[2]durationOnUom: 0
[3]durationOff: 0
[4]durationOffUom: 0
[5]mode: 0
[6]onHr: 0
[7]onMin: 0
[8]offHr: 0
[9]offMin: 0
---------4--------- init addr: 160
[0]enable: 0
[1]durationOn: 0
[2]durationOnUom: 0
[3]durationOff: 0
[4]durationOffUom: 0
[5]mode: 0
[6]onHr: 0
[7]onMin: 0
[8]offHr: 0
[9]offMin: 0
---------5--------- init addr: 200
[0]enable: 0
[1]durationOn: 0
[2]durationOnUom: 0
[3]durationOff: 0
[4]durationOffUom: 0
[5]mode: 0
[6]onHr: 0
[7]onMin: 0
[8]offHr: 0
[9]offMin: 0
---------6--------- init addr: 240
[0]enable: 0
[1]durationOn: 0
[2]durationOnUom: 0
[3]durationOff: 0
[4]durationOffUom: 0
[5]mode: 0
[6]onHr: 0
[7]onMin: 0
[8]offHr: 0
[9]offMin: 0
---------7--------- init addr: 280
[0]enable: 0
[1]durationOn: 0
[2]durationOnUom: 0
[3]durationOff: 0
[4]durationOffUom: 0
[5]mode: 0
[6]onHr: 0
[7]onMin: 0
[8]offHr: 0
[9]offMin: 0
---------8--------- init addr: 320
[0]enable: 0
[1]durationOn: 0
[2]durationOnUom: 0
[3]durationOff: 0
[4]durationOffUom: 0
[5]mode: 0
[6]onHr: 0
[7]onMin: 0
[8]offHr: 0
[9]offMin: 0

This is inside an esp8266 async webserver server.on method.
My EEPROM.begin is in setup function.
Initially, only the first put within a block becomes committed .
Now, nothing is registering after I implemented the sizeof(int) inside addresses.
The intention is to store int data passed thru http post per relay pin [total of 9 pins]. The program then uses the data to perform on a relay:

blink
switch on/off based on time (hour,minute)
...

I've tried all sorts to fix:

commit,end after every put
EEPROM.begin(512) then commit & end on every put
add delays
use end only instead of commit
add address range for sizeof(int)

try the arduino example code

how do you know that commit applies to only the first put?

I print it in Serial. I did try the write & read from sample but it does not meet my requirement to store int.

(relay*eepromSlotsPerRelayPin)+(relayDataIndex * sizeOf(int)) will try this out as the address values based on @VictorTiamson and @RollyAvecilla suggestions.

edit: ((relay*eepromSlotsPerRelayPin)*sizeof(int))+(relayDataIndex * sizeof(int))

New challenge, now nothing is registering. Edited the code displayed in post with my updates.

Weird, i commented out the val=0; before EEPROM.gets also replaced EEPROM.end with EEPROM.commit.
This is the output now:
--Objects content--
Size of INT:4
---------0--------- init addr: 0
[0]enable: 1
[4]durationOn: 3000
[8]durationOnUom: 0
[12]durationOff: 2000
[16]durationOffUom: 0
[20]mode: 1
[24]onHr: 9
[28]onMin: 11
[32]offHr: 9
[36]offMin: 12
---------1--------- init addr: 40
[40]enable: 1
[44]durationOn: 0
[48]durationOnUom: -1
[52]durationOff: 0
[56]durationOffUom: -1
[60]mode: -1
[64]onHr: -1
[68]onMin: -1
[72]offHr: -1
[76]offMin: -1
---------2--------- init addr: 80
[80]enable: 1
[84]durationOn: 0
[88]durationOnUom: -1
[92]durationOff: 0
[96]durationOffUom: -1
[100]mode: -1
[104]onHr: -1
[108]onMin: -1
[112]offHr: -1
[116]offMin: -1
---------3--------- init addr: 120
[120]enable: 1
[124]durationOn: 0
[128]durationOnUom: -1
[132]durationOff: 0
[136]durationOffUom: -1
[140]mode: 1
[144]onHr: 5
[148]onMin: 56
[152]offHr: 7
[156]offMin: 48
---------4--------- init addr: 160
[160]enable: 1
[164]durationOn: 0
[168]durationOnUom: -1
[172]durationOff: 0
[176]durationOffUom: -1
[180]mode: -1
[184]onHr: -1
[188]onMin: -1
[192]offHr: -1
[196]offMin: -1
---------5--------- init addr: 200
[200]enable: 1
[204]durationOn: 0
[208]durationOnUom: -1
[212]durationOff: 0
[216]durationOffUom: -1
[220]mode: -1
[224]onHr: -1
[228]onMin: -1
[232]offHr: -1
[236]offMin: -1
---------6--------- init addr: 240
[240]enable: 1
[244]durationOn: 0
[248]durationOnUom: -1
[252]durationOff: 0
[256]durationOffUom: -1
[260]mode: -1
[264]onHr: -1
[268]onMin: -1
[272]offHr: -1
[276]offMin: -1
---------7--------- init addr: 280
[280]enable: 1
[284]durationOn: 0
[288]durationOnUom: -1
[292]durationOff: 0
[296]durationOffUom: -1
[300]mode: -1
[304]onHr: -1
[308]onMin: -1
[312]offHr: -1
[316]offMin: -1
---------8--------- init addr: 320
[320]enable: 1
[324]durationOn: 0
[328]durationOnUom: -1
[332]durationOff: 0
[336]durationOffUom: -1
[340]mode: -1
[344]onHr: -1
[348]onMin: -1
[352]offHr: -1
[356]offMin: -1

--JSON inputs--

relay:0
blink:1
mode:1
delayOn:3
delayOff:2
delayUnitOn:0
delayUnitOff:0
timeOnHour:9
timeOnMinute:11
timeOffHour:9
timeOffMinute:12


text:
printf %s gives gibberish
This Code:
String S0 = "";
String S1 = "1";
String S2 = "12";
String S3 = "123";
String S4 = "1234";
String S5 = "12345";
String S6 = "123456";
String S7 = "1234567";
String S8 = "12345678";
String S9 = "123456789";
String S10 = "1234567890";
String S11 = "1234567890a";
String S12 = "1234567890ab";
String S13 = "1234567890abc";
String S14 = "1234567890abcd";
String S15 = "1234567890abcde";
String S16 = "1234567890abcdef";
String S17 = "1234567890abcdefg";
String S18 = "1234567890abcdefgh";
String S19 = "1234567890abcdefghi";
String S20 = "1234567890abcdefghij";
Serial.printf("(0):%s\n", S0);
Serial.printf("(1):%s\n", S1);
Serial.printf("(2):%s\n", S2);
Serial.printf("(3):%s\n", S3);
Serial.printf("(4):%s\n", S4);
Serial.printf("(5):%s\n", S5);
Serial.printf("(6):%s\n", S6);
Serial.printf("(7):%s\n", S7);
Serial.printf("(8):%s\n", S8);
Serial.printf("(9):%s\n", S9);
Serial.printf("(10):%s\n", S10);
Serial.printf("(11):%s\n", S11);
Serial.printf("(12):%s\n", S12);
Serial.printf("(13):%s\n", S13);
Serial.printf("(14):%s\n", S14);
Serial.printf("(15):%s\n", S15);
Serial.printf("(16):%s\n", S16);
Serial.printf("(17):%s\n", S17);
Serial.printf("(18):%s\n", S18);
Serial.printf("(19):%s\n", S19);
Serial.printf("(20):%s\n", S20);

Gives This Result:
(0):
(1):1
(2):12
(3):123
(4):1234
(5):12345
(6):123456
(7):1234567
(8):12345678
(9):123456789
(10):�H�?
(11):�^�?
(12):_�?
(13):�_�?
(14):`�?
(15):0`�?
(16):�`�?
(17):a�?
(18):@a�?
(19):pa�?
(20):�a�?

Any ideas??
PS: IT IS OBVIOUS that for whatever platform it is being used, it is working for short strings and not for longer strings! And it has been answered in the comments after you have closed it! So if you do not know the answer instead of closing, maybe it is better to leave it for others to answer it...

Please provide a complete compilable code as example.

For what board are you compiling with what core? The standard core doesn't have a printf() function for Serial. The ESP32 core does. And the ESP8266 core doesn't take String as a parameter for it. Please provide way more information about your setup

Well, I was working on making you an answer, but... then someone closed it. So, here: you need .c_str() in your calls. .printf() is a variadic function which doesn't really have access to any sort of destination type to do conversions; it relies entirely on your passing the correct format specifiers. It is just supplying the bytes to the String object, which is not simply a const char * (specified %s). If you're curious, the behaviour difference you're seeing is down to whether "small string optimization" is being used.

@timemage Appreciate the time and effort you put explaining this. I would definitely ACCEPT and UPVOTE your answer if someone hasn't decided to close it just because they simply do not know the answer!!! Just by adding .c_str() to S20 I got what I expected and your explanation was TRUE and invaluable. It also proved that no more explanation was required to clarify this obvious question. MANY REGARD

I guess the question was closed because of its quality. Though in the meantime it was reopened (possibly due to the answer in the comments), so @timemage can now put the comment as an answer.

Looks like short string optimization, where shorter strings are stored directly in the object and for longer strings it's used as pointers. You should use: Serial.printf("%s",Sxx.c_str());

@chrisl If I did that now it would be 95% diatribe fueled by contempt.

@AKTanara If you want you can find me and a small collection of others on libera.chat irc network.

Dear timemage, I'll find you there as soon as I find out how this libera.chat irc network works... Thanks again for the good answer you provided and I wished you could post your comment as answer now that the thread is open again so that I can accept it since you were the first one to mention the solution even when it was closed...

@AKTanara, I'm not worried about that. I've been helping people on IRC for a very long time and there's never been a point system there. RowanP has taken the time to turn it into an answer; it's probably better that you accept that answer so that the question is resolved in a technical sense.

(Community Wiki answer assembled from the comments)
Noting that the standard Arduino core doesn't have a Serial.printf() function. The ESP32 core does.
You need .c_str() in your calls. .printf() is a variadic function which doesn't really have access to any sort of destination type to do conversions; it relies entirely on your passing the correct format specifiers. It is just supplying the bytes to the String object, which is not simply a const char * (specified %s). If you're curious, the behaviour difference you're seeing is down to whether "small string optimization" is being used.
Short string optimization is where shorter strings are stored directly in the object and for longer strings it's used as pointers.
The suggested solution is to use: Serial.printf("%s",Sxx.c_str());


text:
What size diode should I use?
I'm building a project with an ESP8266 which requires multiple analog inputs - but the ESP8266 only has one. I know of ways to multiplex with dedicated modules, but since I have lots of diodes lying around I've decided to multiplex with them. I've found lots of tutorials on how to multiplex (e.g. this one) but none of them say what size diode to use.
So which size shall I use? Does it even matter? I have 1N4148s, 1N4007s, 1N5819s, 1N5399s, 1N5408s, 1N5822s, FR107s and FR207s.

By the time you finish mucking around powering different devices from I/O pins (which have a limit to how much current they can source) and then install different diodes for each one, you are probably better off (and more simply) to use a multiplexer like the 74HC4051 which I describe here.
As Gil mentioned in his reply, the 0.7V drop (or thereabouts) that the diodes will incur are going to affect the accuracy of the readings, plus you have the issue that the devices might take a few milliseconds to stablise if you keep turning them on and off.
To answer your question, though, any signal diode should do the trick as there will be very little current drawn, as the analog input is high impedance. For example the 1N4148.
You can connect 8 devices to the 74HC4051 with only 4 connections between it and the microprocessor. Three "selector" pins which therefore give you 8 possible combinations, and the signal pin which would go to your analog input.
You could even get a 74HC4067 and have 16 inputs, for the cost of only one more selector pin.

I do not think it is possible to truly multiplex analog signals with simply using diodes in an 'or' configuration. Your demo shows powering only one sensor at a time and isolating the sensors (pots) output with the diode "or". This demo works as long as only one sensor is powered and or the rest output voltage is below the one you are measuring. You also have a voltage drop across the diode and nothing to keep the signal stable, it will bounce around by the forward voltage of the diode or more. The diode will add about a 10% error and reduce your measurement range. To stabilize it you need to add some resistance between the analog input of the microprocessor and ground (load sensor output). This will introduce some error in your reading but you can compensate for that. Any diode will work, use one that you're comfortable with or you can check their characteristics and make a choice.


text:
Can you write c code in arduino ide?
So i know that the native arduino language is written in c/c++, but does that mean that i can write pure c code in the arduino ide, or that i have to use the arduino specified language? I’m new to this and very confused, please bear with me here :’)

There is no Arduino specific language. Its just C++. Arduino just gives you a framework inside C++ to work with, like a predefined program structure (loop and setup function) and useful functions and libraries. But sure, you can use C code for Arduino - up to the point where the two languages are diverging from one another. It is not easy to spot the exact border on what of the new C features are supported, though with all older C code you should be good. Does this help? If not, can you explain more what confuses you?

Yes, you can write in pure C. Some parts of the Arduino core API are
actually defined in C, e.g. pinMode() and digitalWrite() (at least
in the AVR core). So you can use them. Other parts, like Serial, are
C++ objects, and you will not be able to use them from plain C.
The Arduino IDE, however, will insist on you writing a file with the
.ino extension, that it will compile as preprocessed C++. You do not
need to put anything in that file though. If you want to write your
whole program in pure C, you can create an empty .ino file, and in the
same folder a .c file with your whole program. In that file you can
define your own main(). If you want to use the Arduino core API
though, you should instead define setup() and loop(), and rely on
the core-provided main().


text:
Toggle button switches through case statements with button debouncing
The overview of my code is that I want a toggle button to be pushed and each button push will move the code to the next case statement. In each case statement, there will be different LED functions. I need help with a few things

I need help with blinking 4 of the LEDs continuously with 100ms pause in case 1. Because it is not in the main loop, I am having trouble getting the 4 LEDs to switch on and off. Normally, I could just have a simple code that turns it on, then compares previous to last and if different, turns it off, and this continues.
I need the code to go back to case 0 once the button has been held for 2 seconds.
I cannot get my button debounce code to work from case 0 to case 1. If I add the debounce code in case 0 how I have it in the rest of the cases, it wont run through the rest of the cases.
Below is the code:

//LED variables for left turn signal OUT
int LED_1 = 2;
int LED_2 = 3;
int LED_3 = 4;
int LED_4 = 5;

//LED variables for right turn signal OUT
int LED_5 = 6;
int LED_6 = 7;
int LED_7 = 8;
int LED_8 = 9;

//break signal OUT
int BS_OUT = A5;

//reverse signal OUT
int RS_OUT = 10;

//toggle switch button between different modes
int toggle_IN = A4;

//switch case statement variable for togglemodes
int toggleState = 0;

//variables to see if the toggle button has been pressed or not
boolean oldSwitchStateToggle = LOW;
boolean newSwitchStateToggle = LOW;

//true or false to save whether button has been pressed for switching case statements
bool enabledToggle;

//debounce time to take care of button bouncing
const int debounce = 100; //ms

//time for holding a current time of millis()
unsigned long t = 0;

void setup()
{
  Serial.begin(9600);
  //toggle button input
  pinMode(toggle_IN, INPUT);

  //led outputs
  pinMode(LED_4, OUTPUT);
  pinMode(LED_3, OUTPUT);
  pinMode(LED_2, OUTPUT);
  pinMode(LED_1, OUTPUT);
  pinMode(LED_5, OUTPUT);
  pinMode(LED_6, OUTPUT);
  pinMode(LED_7, OUTPUT);
  pinMode(LED_8, OUTPUT);

}

void loop()
{
   //checking to see if toggle button has been pushed
   newSwitchStateToggle = digitalRead(toggle_IN);
   if(newSwitchStateToggle != oldSwitchStateToggle)
  {
    if(newSwitchStateToggle == HIGH)
    {
      //enabling toggle for if statements
      enabledToggle = true;
      //case switch for flow through 4 different LED output options
      toggleButtonState();

    }
    else
    enabledToggle = false;
    oldSwitchStateToggle = newSwitchStateToggle;
  }
}

void toggleButtonState()
{
  unsigned long nowToggle = millis();
  switch (toggleState)
  {

    case 0:
    Serial.println("0000");
          if(enabledToggle)
          {
            digitalWrite(LED_1, HIGH);
            t = nowToggle;
            toggleState = 1;
          }

          break;

    case 1:
    Serial.println("1111");
          if(enabledToggle)
          {
            digitalWrite(LED_1, LOW);
            digitalWrite(LED_2, HIGH);
            //alows going to next state after 100ms for button debounce
            if(nowToggle - t > debounce)
            {
              toggleState = 2;
              t = nowToggle;
            }
          }

          break;

     case 2:
     Serial.println("2222");
          if(enabledToggle)
          {
            digitalWrite(LED_2, LOW);
            digitalWrite(LED_3, HIGH);
            if(nowToggle - t > debounce)
            {
              toggleState = 3;
              t = nowToggle;
            }
          }

          break;

     case 3:
     Serial.println("3333");
         if(enabledToggle)
          {
            digitalWrite(LED_3, LOW);
            digitalWrite(LED_4, HIGH);
            if(nowToggle - t > debounce)
            {
              toggleState = 4;
              t = nowToggle;
            }
          }
          break;

     case 4:
     Serial.println("44444");
          if(enabledToggle)
          {
            turnOffLeds();
            if(nowToggle - t > debounce)
            {
              toggleState = 0;
              t = nowToggle;
            }
          }
          break;

  }
}

void turnOffLeds()
{
  digitalWrite(LED_1, LOW);
  digitalWrite(LED_2, LOW);
  digitalWrite(LED_3, LOW);
  digitalWrite(LED_4, LOW);
}

updated code: trying to add in debounce but it will not work

int LED_1 = 2;
int LED_2 = 3;
int LED_3 = 4;
int LED_4 = 5;

int LED_5 = 6;
int LED_6 = 7;
int LED_7 = 8;
int LED_8 = 9;

//toggle switch button between different modes
int toggle_IN = A4;

//switch case statement variable for togglemodes
int toggleState = 0;

//variables to see if the toggle button has been pressed or not
boolean oldSwitchStateToggle = LOW;
boolean newSwitchStateToggle = LOW;

//true or false to save whether button has been pressed for switching case statements
bool enabledToggle;

//debounce time to take care of button bouncing
const int debounce = 100; //ms

//time for holding a current time of millis()
unsigned long t = 0;

int ledBlinkState = LOW;

unsigned long prevBlinkMillis = 0;

const int blinkInterval = 150;

bool state1 = false;
bool state2 = false;
bool state3 = false;
bool state4 = false;
bool state0 = false;

void setup()
{
  Serial.begin(9600);
  //toggle button input
  pinMode(toggle_IN, INPUT);

  //led outputs
  pinMode(LED_4, OUTPUT);
  pinMode(LED_3, OUTPUT);
  pinMode(LED_2, OUTPUT);
  pinMode(LED_1, OUTPUT);
  pinMode(LED_5, OUTPUT);
  pinMode(LED_6, OUTPUT);
  pinMode(LED_7, OUTPUT);
  pinMode(LED_8, OUTPUT);

}

void loop()
{
  unsigned long nowToggle = millis();
  Serial.print("NOWWWWWW");
  Serial.println(nowToggle);
   //checking to see if toggle button has been pushed
   newSwitchStateToggle = digitalRead(toggle_IN);
   if(newSwitchStateToggle != oldSwitchStateToggle)
   {
    t = nowToggle;
    Serial.print("TIMEEEEE");
    Serial.println(t);
    if(newSwitchStateToggle == HIGH)
    {
      if(nowToggle - t > debounce)
      {
        //enabling toggle for if statements
        enabledToggle = true;
        //case switch for flow through 4 different LED output options
        toggleButtonState();
      }

    }
    else
    enabledToggle = false;
    oldSwitchStateToggle = newSwitchStateToggle;
  }

  unsigned long currentBlinkMillis = millis();

  if(state0 == true)
  {
    digitalWrite(LED_5, HIGH);
    digitalWrite(LED_6, HIGH);
    digitalWrite(LED_7, HIGH);
    digitalWrite(LED_8, HIGH);

    if(currentBlinkMillis - prevBlinkMillis >= blinkInterval)
    {
      prevBlinkMillis = currentBlinkMillis;
      if(ledBlinkState == LOW)
      {
        ledBlinkState = HIGH;
      }
      else
      {
        ledBlinkState = LOW;
      }
      digitalWrite(LED_1, ledBlinkState);
      digitalWrite(LED_2, ledBlinkState);
      digitalWrite(LED_3, ledBlinkState);
      digitalWrite(LED_4, ledBlinkState);
    }
  }

  if(state1 == true)
  {
    digitalWrite(LED_1, HIGH);
    digitalWrite(LED_2, HIGH);
    digitalWrite(LED_3, HIGH);
    digitalWrite(LED_4, HIGH);

    if(currentBlinkMillis - prevBlinkMillis >= blinkInterval)
    {
      prevBlinkMillis = currentBlinkMillis;
      if(ledBlinkState == LOW)
      {
        ledBlinkState = HIGH;
      }
      else
      {
        ledBlinkState = LOW;
      }
      digitalWrite(LED_5, ledBlinkState);
      digitalWrite(LED_6, ledBlinkState);
      digitalWrite(LED_7, ledBlinkState);
      digitalWrite(LED_8, ledBlinkState);
    }
  }

  if(state2 == true)
  {
    if(currentBlinkMillis - prevBlinkMillis >= blinkInterval)
    {
      prevBlinkMillis = currentBlinkMillis;
      if(ledBlinkState == LOW)
      {
        ledBlinkState = HIGH;
      }
      else
      {
        ledBlinkState = LOW;
      }
      digitalWrite(LED_1, ledBlinkState);
      digitalWrite(LED_2, ledBlinkState);
      digitalWrite(LED_3, ledBlinkState);
      digitalWrite(LED_4, ledBlinkState);
      digitalWrite(LED_5, ledBlinkState);
      digitalWrite(LED_6, ledBlinkState);
      digitalWrite(LED_7, ledBlinkState);
      digitalWrite(LED_8, ledBlinkState);
    }
  }

  if(state3 == true)
  {
    digitalWrite(LED_1, HIGH);
    digitalWrite(LED_2, HIGH);
    digitalWrite(LED_3, HIGH);
    digitalWrite(LED_4, HIGH);
    digitalWrite(LED_5, HIGH);
    digitalWrite(LED_6, HIGH);
    digitalWrite(LED_7, HIGH);
    digitalWrite(LED_8, HIGH);
  }

  if(state4 == true)
  {
    turnOffLeds();
  }

}

void toggleButtonState()
{
  switch (toggleState)
  {

    case 0:
    Serial.println("0000");
          if(enabledToggle)
          {
            turnOffLeds();
            state4 = false;
            state0 = true;
            toggleState = 1;
          }

          break;

    case 1:
    Serial.println("1111");
          if(enabledToggle)
          {
            turnOffLeds();
            state0 = false;
            state1 = true;
            toggleState = 2;
          }

          break;

     case 2:
     Serial.println("2222");
          if(enabledToggle)
          {
            turnOffLeds();
            state1 = false;
            state2 = true;
            toggleState = 3;
          }

          break;

     case 3:
     Serial.println("3333");
         if(enabledToggle)
          {
            turnOffLeds();
            state2 = false;
            state3 = true;
            toggleState = 4;
          }
          break;

     case 4:
     Serial.println("44444");
          if(enabledToggle)
          {
            turnOffLeds();
            state3 = false;
            state4 = true;
            toggleState = 0;
          }
          break;

  }
}

void turnOffLeds()
{
  digitalWrite(LED_1, LOW);
  digitalWrite(LED_2, LOW);
  digitalWrite(LED_3, LOW);
  digitalWrite(LED_4, LOW);
  digitalWrite(LED_5, LOW);
  digitalWrite(LED_6, LOW);
  digitalWrite(LED_7, LOW);
  digitalWrite(LED_8, LOW);
}

1. the toggleButtonState() should not contain any LED code ... it should only set a flag ... the blink code should be inside loop() and be activated by the flag

2. do button detection at begining of loop() ... the button code should only set a flag, nothing more

3. ... read 2.

So for example, I would be in case 1, and it would set a variable to true. Then in the loop, have an if statement to where if that variable is true, then it will loop through that blinking LED code?

yes ... the loop() repeats many times a second ... use millis() to blink ... see blinkWithoutDelay example sketch

@jsotola I got the flagging figure out and my code works great for blinking LEDs. I am now having trouble with getting the debounce code to work. I have it in my updated code but it does not work. I am trying to incorporate it around my button clicking in the loop(). When looking at it on my serial moniter, "t" is holding nowToggle every instance and not holding it at a single value.

I would recommend you start with an existing library to do the "button debouncing" and "long button press" detection.
The EasyButton library on github and via the Arduino IDE library manager has potential.
Here is a test sketch which shows the "button detection" part of your requirement.
If you were to add a variable to represent "state", this code could be adapted to control a case statement bases on state.
// Sketch uses 3286 bytes (10%) of program storage space.
// Global variables use 357 bytes (17%) of dynamic memory.
#include <EasyButton.h>

// EasyButton(uint8_t pin,
//            uint32_t debounce_time = 35,
//            bool pullup_enable = true,
//            bool active_low = true)
EasyButton button(2);

void onPressed(){
  // Your code here to INCREMENT a "state counter".
  Serial.println("Button pressed");
}

void onPressedForDuration(){
  // Your code here to SET the "state counter" to 0.
  Serial.println("Button pressed for duration");
}

void setup(){

  // Test output to serial monitor.
  Serial.begin(9600);

  // Initialize the button.
  button.begin();

  // Add the callback function to be called when the button is pressed.
  button.onPressed(onPressed);

  // Add the callback function to be called when the button is pressed
  // for at least the given time.
  button.onPressedFor(2000, onPressedForDuration);

}

void loop(){

  // Continuously read the status of the button.
  button.read();

}

I would have done it this way, but I am going to transfer this into the eclipse compiler. I am staying away from arduino made libraries. I am trying to find a way to look at what is going on in the background of the easybutton.h. Do you know where I could find this?

@Myles - You can look at the EasyButton source code to see how it works: https://github.com/evert-arias/EasyButton/tree/main/src

I answered how to do a mode switch with just one button many many years ago.  Make use of it what you will... it's just a sample skeleton. Here is the code I used:
/*
 Using a single switch to select between 3 modes
*/
// Schematic: http://www.pwillard.com/files/mode4.jpg
//===============================================================
// Global Variables & Constants
//===============================================================

const int ledPinOne = 2; // LED1 ANODE
const int ledPinTwo = 4; // LED2 ANODE
const int ledPinThree = 7; // LED3 ANODE
const int modePin = 13; // Active HIGH, held low by 4.7K

int mode = 0; // Selector State (Initial state = ALL OFF)
int val = 0; // Pin 13 HIGH/LOW Status
int butState = 0; // Last Button State
int modeState = 0; // Last Mode State
boolean debug = 1; // 1 = Print Serial Enabled / 0 = disabled

//===============================================================
// SETUP
//===============================================================
void setup () {
 pinMode(ledPinOne, OUTPUT);
 pinMode(ledPinTwo, OUTPUT);
 pinMode(ledPinThree, OUTPUT);
 pinMode(modePin, INPUT);
 if (debug){
 Serial.begin(9600);
 Serial.print("Initial Mode: ");
 Serial.println(mode);
 Serial.print("Setup Complete\n");
 }
}

//===============================================================
// Main Loop
//===============================================================
void loop() {

 val = digitalRead(modePin);

 // If we see a change in button state, increment mode value
 if (val != butState && val == HIGH){
 mode++;
 }

 butState = val; // Keep track of most recent button state

 // No need to keep setting pins *every* loop
 if (modeState != mode){

 // If no keys have been pressed yet don't execute
 // the switch code below
 // if (mode != 0) {

 switch ( mode ) {
 //case 1 is actually handled below as default

case 2:
 digitalWrite(ledPinOne, LOW);
 digitalWrite(ledPinTwo, HIGH);
 showState();
 break;
 case 3:
 digitalWrite(ledPinTwo, LOW);
 digitalWrite(ledPinThree, HIGH);
 showState();
 break;
 default:
 mode = 1;
 // loop back to 1 by default, seems redundant but
 // it also handles the "mode is > 3" problem
 digitalWrite(ledPinThree, LOW);
 digitalWrite(ledPinOne, HIGH);
 showState();
 break;
 } // end switch
// } // end of "if mode = 0" check
 } // end of ModeState check
 modeState = mode; // Keep track of mode recent mode value
 delay(10); // slow the loop just a bit for debounce
}

//===============================================================
// Subroutine
//===============================================================
void showState() {
 if (debug){
 Serial.print("Mode: ");
 Serial.println(mode);
 }
}


text:
How to expand this code for more than four 74hc165 shift registers? It works well with maximum four 74hc165 shift registers at a time
#define NUMBER_OF_SHIFT_CHIPS   4
#define DATA_WIDTH   NUMBER_OF_SHIFT_CHIPS * 8

int LoadPin    = 9;
int EnablePin  = 8;
int DataPin    = 11;
int ClockPin   = 12;

unsigned long pinValues;
unsigned long oldPinValues;

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

  pinMode(LoadPin, OUTPUT);
  pinMode(EnablePin, OUTPUT);
  pinMode(ClockPin, OUTPUT);
  pinMode(DataPin, INPUT);

  digitalWrite(ClockPin, LOW);
  digitalWrite(LoadPin, HIGH);

  pinValues = read_shift_regs();
  print_byte();
  oldPinValues = pinValues;
}

void loop()
{
  pinValues = read_shift_regs();
  if (pinValues != oldPinValues)
  {
    print_byte();
    oldPinValues = pinValues;
  }
}

unsigned long read_shift_regs()
{
  long bitVal;
  unsigned long bytesVal = 0;

  digitalWrite(EnablePin, HIGH);
  digitalWrite(LoadPin, LOW);
  delayMicroseconds(5);
  digitalWrite(LoadPin, HIGH);
  digitalWrite(EnablePin, LOW);

  for (int i = 0; i < DATA_WIDTH; i++)
  {
    bitVal = digitalRead(DataPin);
    bytesVal |= (bitVal << ((DATA_WIDTH - 1) - i));

    digitalWrite(ClockPin, HIGH);
    delayMicroseconds(5);
    digitalWrite(ClockPin, LOW);
  }

  return (bytesVal);
}

void print_byte() {
  byte i;
  Serial.println("*Shift Register Values:*\r\n");

  for (byte i = 0; i <= DATA_WIDTH - 1; i++)
  {
    Serial.print(pinValues >> i & 1, BIN);

    Serial.print("  ");

  }
  Serial.print("\n");
  Serial.println(); Serial.println();
}

Welcome to Arduino:SE.  Where did you get this version of the code?

possibly not a code problem

And what happens when you use more than 4 (by daisy chaining more shift registers and setting NUMBER_OF_SHIFT_CHIPS accordingly)? What is the actual problem description? What did you expect to happen and what actually did happen? What was the Serial output and the expected Serial output?

It looks like your read_shift_regs() function returns an unsigned long value, which consists of 32 bits. Each shift register reads back 8 bits, so with 4 of these shift registers you will fill all bits of a 32-bit unsigned long. If you attempt reading more than 4 registers, you will lose previously read bits. The solution is to make a function that can return more than 32 bits.

I would just add another shift register chain. A schematic would help understand better what you are doing.

After I put 'NUMBER_OF_SHIFT_CHIPS' as 5, the 1st shift register doesn't work but 5th one starts working. Also when I put  'NUMBER_OF_SHIFT_CHIPS' as 6 then 1st and 2nd shift registers don't work but rest four shift registers start working. So, I think @StarCat is right. What needs to be changed in this code?

You need to understand the code to think on a solution. There are several possible solutions, but you should try the ones you understand. You may start by thinking how to "organize" more than 32 bits. As you found, an unsigned long cannot do this, perhaps an array of unsigned char or uint8_t is fine. -- We commonly don't give recommendations because that leads to opinion-based discussions, which are frowned upon.

As StarCat mentioned in the comments, you return the read value as an unsigned long, which can hold exactly 4 bytes. When trying to write more into it with your current code you will loose the previous data. So you need a data structure that is able to hold all the data that you want to read.
I suggest that you do it like the shiftIn() function of the Arduino framework: Use a DATA_WIDTH of 8 bits (1 byte) and enclose the reading loop into another for loop, where you iterate over NUMBER_OF_SHIFT_CHIPS, getting exactly one byte from each chip and putting it into an array of byte (aka uint8_t). There are multiple ways to do this, but I will describe only one, not necessarily the best one for your situation.
First declare an array of byte on global scope. It needs to be NUMBER_OF_SHIFT_CHIPS bytes big. We initialize the data to zero:
byte shift_data[NUMBER_OF_SHIFT_CHIPS] = {0};

Set DATA_WIDTH to 8 bits:
#define DATA_WIDTH   8

Now look into read_shift_regs(). Enclose the for loop into another for loop iterating over NUMBER_OF_SHIFT_CHIPS and use that index to write the data into the corresponding byte in shift_data (by using shift_data[j] with the corresponding index j). As we write a global array we don't need to return anything, so you can make the function void (unless you want to return some other information).
void read_shift_regs()
{
  long bitVal;

  digitalWrite(EnablePin, HIGH);
  digitalWrite(LoadPin, LOW);
  delayMicroseconds(5);
  digitalWrite(LoadPin, HIGH);
  digitalWrite(EnablePin, LOW);
  for(int j = 0; j < NUMBER_OF_SHIFT_CHIPS; j++){
    for (int i = 0; i < DATA_WIDTH; i++)
    {
      bitVal = digitalRead(DataPin);
      shift_data[j] |= (bitVal << ((DATA_WIDTH - 1) - i));

      digitalWrite(ClockPin, HIGH);
      delayMicroseconds(5);
      digitalWrite(ClockPin, LOW);
    }
  }
}

Then change all lines with
pinValues = read_shift_regs();

to
read_shift_regs();
And finally - to actually use the read values - you now need to access a complete array instead of a single variable. I will leave that to you. Basically its again just iterating over all elements of the array.
Note:

I have not tested the above code in any way. Its more about explaining the principle.
One can also handle the array with parameters, but if you don't know how to use arrays as parameters, then this can give you a lot of other errors. So I didn't suggest that.

using void before read_shift_regs() function gives error "void value not ignored as it ought to be". Which data type should I use here and why? Also, to print the output I use a for loop to return the shift_data[j] but output does not change.   P.S : I might be wrong here because i am new to arduino coding.

If you look at my implementation of the function you see that I don't use return. The functions doesn't need to return anything because the data is already globally a available in the array. And you get that error because you probably still have pinValues = read_shift_regs(); somewhere. As I instructed you need to remove erything before the function call in that line (so no assignment with = )

What do you nean by "use a for loop to return shift_data[i]"? You can only return one time, not multiple times

If you look at above code in void loop, I have set if(pinValues!=oldpinValues) then the output bytes are printed for complete 8 x 8 matrix. I am not able to get the output here. Can you suggest a way to read values such that I can see them in Serial monitor? So, that I can take it as a reference for printing outputs.


text:
Motor rotates well in one direction but runs slower in other with L298N and L293d
I connected 2 motors with an L293Nn driver. When I control it with my joystick, one motor works fine (Out 1 and 2 of driver.) It rotates in one direction and the other very smoothly.
The problem occurs in the second motor (Out 3 and 4 of driver.) It rotates smoothly in one direction (clockwise) but when rotated in the other(anti-clockwise), the 4000 RPM motor rotates at around 60 RPM. My voltmeter shows a reading of 1V. When I reverse the polarity at the driver, it rotates slowly in the clockwise direction and at proper speed in the anticlockwise direction.
I tried it with another L298N driver and had the same problem. I tried with an L293D driver and still had the same error. The code is the same for both drivers. The motors work fine when just connected to the 12V battery (both directions.)
I do not understand the problem.
My code:
struct Signal{
  uint16_t y1; // Joystick-1 Y 0 to 1023
  uint16_t y2; // Joystick-2 Y 0 to 1023
};
int x1 = 0; // Joystick-1 Y 0 to 255
int x2 = 0; // Joystick-2 Y 0 to 255
Signal data;
#include<SPI.h>
#include<nRF24L01.h>
#include<RF24.h>
RF24 radio(7,8);
const byte address[6] = "HexaT";
void setup() {
  Serial.begin(9600);
  pinMode(1, OUTPUT); // motor b
  pinMode(2,OUTPUT); // motor b
  pinMode(6,OUTPUT); // motor b key

  pinMode(5,OUTPUT); // motor a key
  pinMode(9, OUTPUT); // motor a
  pinMode(10,OUTPUT); // motor a

  radio.begin();
  radio.openReadingPipe(0, address);
  radio.setPALevel(RF24_PA_MAX);
  radio.startListening();

}

void loop() {
  while(radio.available()){
    radio.read(&data, sizeof(Signal));

//motor A
    if(data.y1 > 530){
      x1 = map(data.y1,530,1023, 0, 255);
      analogWrite(5,x1); // motor a key
      digitalWrite(9,LOW); // motor a
      digitalWrite(10,HIGH); // motor a
    }else if(data.y1 < 500){
      x1 = map(data.y1,500,0, 0, 255);
      analogWrite(5,x1); // motor a key
      digitalWrite(9,HIGH); // motor a
      digitalWrite(10,LOW); // motor a
    }else{
      digitalWrite(5,LOW); // motor a key
      digitalWrite(9,LOW); // motor a
      digitalWrite(10,LOW); // motor a
    };

//Motor B
    if(data.y2 > 530){
      x2 = map(data.y2,530,1023, 0, 255);
      analogWrite(6,x2); // motor b key
      digitalWrite(1,LOW); // motor b
      digitalWrite(2,HIGH); // motor b
    }else if(data.y2 < 500){
      x2 = map(data.y2,500,0, 0, 255);
      analogWrite(6,x2); // motor b key
      digitalWrite(1,HIGH); // motor b
      digitalWrite(2,LOW); // motor b
    }else{
      digitalWrite(6,LOW); // motor b key
      digitalWrite(1,LOW); // motor b
      digitalWrite(2,LOW); // motor b
    };

    Serial.println(x1);
    Serial.println(x2);
  }
}

In the serial monitor, I get proper values from 0 to 255 for both the joysticks and send that PWM signal to the driver.

I can't reproduce it now but may I suggest you to don't use PIN 1 as output while using hardware Serial? It uses PIN 1 to transmit and this could cause interference with motor (it should do the same in both directions....)


text:
Code got stuck after initialization with RFM69
I'm working on RFM69 connected to an Arduino Uno. Currently, I was able to initialize the RFM69 using the a code I modified from the internet. However, my Receiver part always encounters error. It doesn't sometimes proceed and sometimes got stuck in the initialization loop. Yesterday, my Transmitter managed to work properly but today, sometimes I also observed same problem with my Receiver.
Here's my wiring.

The code I'm using for both Transmitter and Receiver
#include <SPI.h>
#include <RH_RF69.h>

/************ Radio Setup ***************/

// Change to 434.0 or other frequency, must match RX's freq!
#define RF69_FREQ 434.0

#define RFM69_CS 10
#define RFM69_INT 2
#define RFM69_RST 9
#define LED 13

// Singleton instance of the radio driver
RH_RF69 rf69(RFM69_CS, RFM69_INT);

int16_t packetnum = 0;  // packet counter, we increment per xmission

void setup()
{
  Serial.begin(9600);
  //while (!Serial) { delay(1); } // wait until serial console is open, remove if not tethered to computer

  pinMode(LED, OUTPUT);
  pinMode(RFM69_RST, OUTPUT);
  //digitalWrite(RFM69_RST, LOW);
  //from this point I added it
  digitalWrite (RFM69_RST, HIGH);
  delay (100);
  digitalWrite (RFM69_RST, LOW);
  delay (100);

  Serial.println("LoRa Daughter Board (RFM69) - Transmitter");
  Serial.println();

  // manual reset
  digitalWrite(RFM69_RST, HIGH);
  delay(10);
  digitalWrite(RFM69_RST, LOW);
  delay(10);

  if (!rf69.init()) {
    Serial.println("RFM69 Initialization Failed!");
    while (1);
  }
  Serial.println("RFM69 Initialization Success!");
  // Defaults after init are 434.0MHz, modulation GFSK_Rb250Fd250, +13dbM (for low power module)
  // No encryption
  if (!rf69.setFrequency(RF69_FREQ)) {
    Serial.println("setFrequency failed");
  }

  // If you are using a high power RF69 eg RFM69HW, you *must* set a Tx power with the
  // ishighpowermodule flag set like this:
  //rf69.setTxPower(20, true);  // range from 14-20 for power, 2nd arg must be true for 69HCW

  // The encryption key has to be the same as the one in the server
  uint8_t key[] = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
                    0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08};
  rf69.setEncryptionKey(key);

  pinMode(LED, OUTPUT);

  Serial.print("RFM69 Frequency: ");  Serial.print((int)RF69_FREQ);  Serial.println(" MHz");
}

void loop() {
  delay(1000);  // Wait 1 second between transmits, could also 'sleep' here!

  char radiopacket[20] = "Hello World #";
  itoa(packetnum++, radiopacket+13, 10);
  Serial.print("Sending "); Serial.println(radiopacket);

  // Send a message!
  rf69.send((uint8_t *)radiopacket, strlen(radiopacket));
  rf69.waitPacketSent();

  // Now wait for a reply
  uint8_t buf[RH_RF69_MAX_MESSAGE_LEN];
  uint8_t len = sizeof(buf);

  if (rf69.waitAvailableTimeout(500))  {
    // Should be a reply message for us now
    if (rf69.recv(buf, &len)) {
      Serial.print("Got a reply: ");
      Serial.println((char*)buf);
      Blink(LED, 50, 3); //blink LED 3 times, 50ms between blinks
    } else {
      Serial.println("Receive failed");
    }
  } else {
    Serial.println("No reply, is another RFM69 listening?");
  }
}

void Blink(byte PIN, byte DELAY_MS, byte loops) {
  for (byte i=0; i<loops; i++)  {
    digitalWrite(PIN,HIGH);
    delay(DELAY_MS);
    digitalWrite(PIN,LOW);
    delay(DELAY_MS);
  }
}

Here are screenshots of the results
Taken yesterday: Mar 16

Taken today: Mar 17

please, no screenshots of text ... add the actual text ... some people here cannot view images

I'm surprised that you're getting anything reliable through the level converter at 1MHz. Where you've indicated it's not relevant I deleted that answer. No other suggestions for you.

It may be your environment, I have lots of problems here with RF transmission interference, a nearby radio amateur and proliferation of WiFi seem to exacerbate the problem. I've had some success building an RFM69 relay but have mostly gone over to WiFi using ESP8266 modules as they're much more reliable for communication.

Thank you @Bra1n. Actually Im currently in a laboratory. I was able to communication the RFM9x LoRa Radio by Adafruit in this very same environment, however, our prototype RFM69 didn't communicate at all huhuhu.