text:
How to set a sampling frequency of 10ksps AD7606 through Aurdino?
This is the code for interfacing AD7606 with arduino. This code is working and I am able to read all the 8 channels. But my requirement is to set 10ksps.
#include <SPI.h>

uint32_t startTime, elapsedTime, old_res;
#define SCALE_FACTOR 0.000152587890625

#define BUSY 32               // you can use any digital pin

#define START_CONVERSION 34   // you can use any digital pin
#define CHIP_SELECT 53        // SPI CS
#define D7_out 50             // SPI MISO there is no need to use MOSI port with the ad7606
#define RD 52                 // SPI SCLK

#define TOTAL_RAW_BYTES 16
SPISettings _spiSettings;

int bytesToRead = TOTAL_RAW_BYTES;
byte raw[TOTAL_RAW_BYTES];
uint16_t parsed[8];

//--------------SETUP-UP---------------------------
void setup()
{
  initial();
  Serial.begin(2000000);
  while(!Serial){} // wait for usb connection
  SPI.begin();
}
//---------------LOOP--------------------------
void loop()
{
  startTime = micros();
  readData();
  elapsedTime = micros() - startTime;
  if (elapsedTime != old_res)
  {
    Serial.print("Conversion time:\t");
    Serial.print(elapsedTime);
    Serial.println(" microseconds");
    old_res = elapsedTime;
  }
  parseRawBytes();

  for (int i = 0; i < 8; i++) {
    Serial.print((float)parsed[i] * SCALE_FACTOR, 5);
    Serial.print(",");
  }

  Serial.print("\r\n");
}
//-----------------------------------------
void initial()
{
  pinMode(BUSY, INPUT);

  pinMode(START_CONVERSION, OUTPUT);
  pinMode(CHIP_SELECT, OUTPUT);
  pinMode(D7_out, OUTPUT);
  pinMode(RD, OUTPUT);
  digitalWrite(START_CONVERSION, HIGH);
  digitalWrite(CHIP_SELECT, HIGH);

}
//-----------------------------------------
void parseRawBytes() {
  for(int i = 0; i<(sizeof(parsed) / sizeof(int));i++)
    {
      parsed[i] = (raw[i*2] << 8) + raw[(i*2)+1];
    }
}
//-----------------------------------------

//-----------------------------------------
void conversionPulse(uint8_t port)
{
  digitalWrite(port, LOW);
//  delayMicroseconds(1);
  digitalWrite(port, HIGH);
}
//-----------------------------------------
/*
1- start conversion START_CONVERSION HIGH
2- wait until the busy is LOW again
3- put the CS to LOW
4- Read a byte from the SPI
*/
void readData()
{
  conversionPulse(START_CONVERSION);
  while (digitalRead(BUSY) == HIGH) {
  //  delayMicroseconds(1);
  }
  SPI.beginTransaction(_spiSettings);
  digitalWrite(CHIP_SELECT, LOW);
  while (bytesToRead > 0) {
    raw[TOTAL_RAW_BYTES - bytesToRead] = SPI.transfer(0x00);
    bytesToRead--;
  }
  digitalWrite(CHIP_SELECT, HIGH);
  SPI.endTransaction();

  bytesToRead = TOTAL_RAW_BYTES;
}
//-----------------------------------------

What speed does it do now?

Hi Rohit Gupta, Now i am getting a sampling frequency of 1.8ksps,i checked this sampling frequency (start conversion signal) through dso.

Please format your code, this is very hard to read.

@PMF Hi PMF Please Refer I updated the code

I'm not sure about the capabilities of the ADC, but a quick estimate suggests this could be hard. An Arduino UNO has a clock frequency of 16 Mhz, requiring a 10kHz sampling rate would require that a single loop does not take more than 1600 clock cycles. Probably possible, but only with optimized code (e.g., remove unnecessary output)

Thank u for your response dear PMF


text:
TCP server on ESP32 CAM
I am writing a TCP server on ESP32 CAM to receive joystick coordinates as a JSON string. I have a TCP client on my laptop which sends joystick coordinates from a joystick connected to my laptop. In have implemented a 0.8 second throttling on the client side, such that JSON strings are only sent 0.8 seconds apart. When I test this, I am able to run the joystick reliably for about a minute before the ESP crashes due to a Guru Meditation Error.
This is the exception I get:
Guru Meditation Error: Core  0 panic'ed (IllegalInstruction). Exception was unhandled.
Memory dump at 0x4016797c: c00289c0 f01d0020 40004136
Core  0 register dump:
PC      : 0x40167980  PS      : 0x00060030  A0      : 0x40105dff  A1      : 0x3ffbc110
A2      : 0x00000002  A3      : 0x00000011  A4      : 0x3ffbe0d4  A5      : 0x00000000
A6      : 0x3ffbc13c  A7      : 0x0000005d  A8      : 0x80084f78  A9      : 0x3ffbc0f0
A10     : 0x00000001  A11     : 0x00000000  A12     : 0x00000000  A13     : 0x3ff42034
A14     : 0x0000001e  A15     : 0xfffffffe  SAR     : 0x00000017  EXCCAUSE: 0x00000000
EXCVADDR: 0x00000000  LBEG    : 0x4008a674  LEND    : 0x4008a690  LCOUNT  : 0xffffffff

Backtrace: 0x4016797d:0x3ffbc110 0x40105dfc:0x3ffbc180 0x400d5fd8:0x3ffbc1a0 0x400d5f21:0x3ffbc1c0 0x400d6a8e:0x3ffbc1f0 0x4016f10b:0x3ffbc220

This is my stack trace:
PC: 0x40167980: sub32 at /Users/ficeto/Desktop/ESP32/ESP32S2/esp-idf-public/components/mbedtls/mbedtls/library/ecp_curves.c line 980
EXCVADDR: 0x00000000

Decoding stack results
0x4016797d: sub32 at /Users/ficeto/Desktop/ESP32/ESP32S2/esp-idf-public/components/mbedtls/mbedtls/library/ecp_curves.c line 979
0x40105dfc: psram_cmd_end at /Users/ficeto/Desktop/ESP32/ESP32S2/esp-idf-public/components/esp_hw_support/port/esp32/spiram_psram.c line 385
0x400d5fd8: psramInit at C:\Users\ikibf\AppData\Local\Arduino15\packages\esp32\hardware\esp32\2.0.11\cores\esp32\esp32-hal-psram.c line 69
0x400d5f21: initArduino at C:\Users\ikibf\AppData\Local\Arduino15\packages\esp32\hardware\esp32\2.0.11\cores\esp32\esp32-hal-misc.c line 240
0x400d6a8e: app_main() at C:\Users\ikibf\AppData\Local\Arduino15\packages\esp32\hardware\esp32\2.0.11\cores\esp32\main.cpp line 70
0x4016f10b: main_task at /Users/ficeto/Desktop/ESP32/ESP32S2/esp-idf-public/components/freertos/port/port_common.c line 141

Sometimes I get this exception:
rst:0xc (SW_CPU_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
configsip: 0, SPIWP:0xee
clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
mode:DIO, clock div:1
load:0x3fff0030,len:1344
load:0x40078000,len:13964
load:0x40080400,len:3600
entry 0x400805f0
Guru Meditation Error: Core  0 panic'ed (LoadProhibited). Exception was unhandled.

Core  0 register dump:
PC      : 0x401061a9  PS      : 0x00060030  A0      : 0x80085042  A1      : 0x3ffbc0f0
A2      : 0x00000001  A3      : 0x00000000  A4      : 0x0ffd114c  A5      : 0x00000000
A6      : 0x0000001e  A7      : 0xfffffffe  A8      : 0x00020000  A9      : 0x3ff44024
A10     : 0x700000eb  A11     : 0x00000000  A12     : 0x00000008  A13     : 0x3ffbc0cc
A14     : 0xb7a8d869  A15     : 0x3ff42080  SAR     : 0x0000000f  EXCCAUSE: 0x0000001c
EXCVADDR: 0x00000001  LBEG    : 0x40106144  LEND    : 0x4010614d  LCOUNT  : 0x00000000

Backtrace: 0x401061a6:0x3ffbc0f0 0x4008503f:0x3ffbc110 0x40105d02:0x3ffbc180 0x400d5fd8:0x3ffbc1a0 0x400d5f21:0x3ffbc1c0 0x400d6a8e:0x3ffbc1f0 0x4016f10b:0x3ffbc220

Which produces this stack trace:
PC: 0x401061a9: psram_set_cs_timing at /Users/ficeto/Desktop/ESP32/ESP32S2/esp-idf-public/components/esp_hw_support/port/esp32/spiram_psram.c line 674
EXCVADDR: 0x00000001

Decoding stack results
0x401061a6: psram_set_cs_timing at /Users/ficeto/Desktop/ESP32/ESP32S2/esp-idf-public/components/esp_hw_support/port/esp32/spiram_psram.c line 676
0x4008503f: psram_enable at /Users/ficeto/Desktop/ESP32/ESP32S2/esp-idf-public/components/esp_hw_support/port/esp32/spiram_psram.c line 998
0x40105d02: esp_spiram_init at /Users/ficeto/Desktop/ESP32/ESP32S2/esp-idf-public/components/esp_hw_support/port/esp32/spiram.c line 163
0x400d5fd8: psramInit at C:\Users\ikibf\AppData\Local\Arduino15\packages\esp32\hardware\esp32\2.0.11\cores\esp32\esp32-hal-psram.c line 69
0x400d5f21: initArduino at C:\Users\ikibf\AppData\Local\Arduino15\packages\esp32\hardware\esp32\2.0.11\cores\esp32\esp32-hal-misc.c line 240
0x400d6a8e: app_main() at C:\Users\ikibf\AppData\Local\Arduino15\packages\esp32\hardware\esp32\2.0.11\cores\esp32\main.cpp line 70
0x4016f10b: main_task at /Users/ficeto/Desktop/ESP32/ESP32S2/esp-idf-public/components/freertos/port/port_common.c line 141

This is the TCP server:
#include <WiFi.h>
#include <WiFiAP.h>

#include <WiFiClient.h>
#include <ArduinoJson.h>
#include "helper_funcs.h"
#include "esp_wpa2.h"
#include "wifi_credentials.h"   // contains wifi connection params

// JSON setup stuff
const int buffer_size = 512;
char json_buffer[buffer_size];
int buffer_index = 0;

const int port = 8990;

WiFiServer server(port);

// Rest of code
void setup(){
  init_motors();

  // connect to WiFi
  Serial.begin(115200);
   WiFi.disconnect(true);
  WiFi.mode(WIFI_STA);
  WiFi.begin(WIFI_SSID, WPA2_AUTH_PEAP, EAP_IDENTITY, EAP_USERNAME, EAP_PASSWORD);

  while(WiFi.status() != WL_CONNECTED){
    Serial.println("Connecting to WiFi....");
    delay(1000);
  }

  Serial.println("Connected to WiFi with IP: ");
  Serial.println(WiFi.localIP());

  // Start TCP/IP server
  server.begin();
  Serial.println("Started TCP/IP server");
}

void loop(){
  WiFiClient client = server.available();

  // if a client has connected to the TCP/IP server, read PWM data and use it
  if(client){
    Serial.println("Client connected");
    while(client.connected()){
      if(client.available()){
        char c = client.read();

        if((buffer_index != buffer_size-1) && (c != '\n')){
          json_buffer[buffer_index++] = c;
        } else {
          // parse the JSON object
          json_buffer[buffer_index] = '\0';
          StaticJsonDocument<buffer_size> doc;
          DeserializationError error = deserializeJson(doc, json_buffer);

          if(error){
            Serial.println("JSON parsing unsuccessful");
            Serial.println(error.c_str());
          } else {
            // get PWM data
            int x = doc["x"], y = doc["y"];
            Serial.print("X: ");
            Serial.println(x);
            Serial.print("Y: ");
            Serial.println(y);

            control_motors(x, y);
          }

          // reset JSON buffer for next data
          buffer_index = 0;
        }
      }
    }

    client.stop();
    Serial.println("Client disconnected");
  }

}

Does anyone know how I should solve this?

try to change the PSRAM setting in Tools menu

@Juraj I enabled PSRAM after chnaging the board to ESP Dev Module as the PSRAMoption was not available when using ESP32 Wrover Module. Unfortunately, the ESP will reboot randomly, which shuts down the server

source: Stack Exchange

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

sort: votes


text:
How to send multiple and different bytes via SPI using custom function
I need to send multiple bytes via SPI to a controller.
I would like to have a function which I can use for doing that as I need to do some other things with it (timing, setting pin states etc.).
The issue is, that I need to pass a variying size of bytes and also I need to change these bytes in the code.
My not compiling try to do it:
const int CS = 9;
const int A_0 = 7;
#define STOP 0xFFF

void setup() {
 pinMode(CS, OUTPUT);
 pinMode(A_0, OUTPUT);
 digitalWrite(CS, 0);
 digitalWrite(A_0, 0);
 SPI.begin();
 SPI.beginTransaction(SPISettings(1000000, MSBFIRST, SPI_MODE3));
 DispData(1, (int []){0xE3, 0xE4, 0x00, 0x122, STOP});
 SPI.endTransaction;
 //some code
 SPI.beginTransaction(SPISettings(1000000, MSBFIRST, SPI_MODE3));
 DispData(1, (int []){0xE6, 0xE7, 0x02, STOP});
 SPI.endTransaction;
}

void DispData(int chip, int data[] ){
  digitalWrite(CS, chip);
  digitalWrite(A_0, 0);
  int i=0;
  delayMicroseconds(12);
  digitalWrite(A_0, 1);
  delayMicroseconds(7);
  while(data[i] != STOP)
  {
    SPI.transfer(data[i]);
    i++;
  }
}

I could get your code to compile with the solution described in the answer to this question. Note: In the first call to DispData you have 3 parameters, though the function only takes 2 parameters.

@chrisl I've corrected the function call with 2 parameters now. How did you do it exactly? I did not really understand the solution from your link.

@chrisl - Just to clarify: are you referring to the accepted answer or zett42's answer? I assume you mean the accepted answer but just wanted to be sure. :-)

@Greenonline The accepted answer. Should have mentioned that XD

After more searching I found one solution, using const int instead of int:
const int CS = 9;
const int A_0 = 7;
#define STOP 0xFFF

void setup() {
 pinMode(CS, OUTPUT);
 pinMode(A_0, OUTPUT);
 digitalWrite(CS, 0);
 digitalWrite(A_0, 0);
 SPI.begin();
 SPI.beginTransaction(SPISettings(1000000, MSBFIRST, SPI_MODE3));
 DispData(1, (const int []){0xE3, 0xE4, 0x00, 0x122, STOP});
 SPI.endTransaction;
 //some code
 SPI.beginTransaction(SPISettings(1000000, MSBFIRST, SPI_MODE3));
 DispData(1, (const int []){0xE6, 0xE7, 0x02, STOP});
 SPI.endTransaction;
}

void DispData(int chip, const int data[] ){
  digitalWrite(CS, chip);
  digitalWrite(A_0, 0);
  int i=0;
  delayMicroseconds(12);
  digitalWrite(A_0, 1);
  delayMicroseconds(7);
  while(data[i] != STOP)
  {
    SPI.transfer(data[i]);
    i++;
  }
}

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


text:
Arduino Pro Mini & FTDI USB can't upload sketh
As the title says, I have an Arduino Pro Mini 3.3V & FTDI FT232RL that I connected to the arduino board. It worked for a while, on and off but the serial monitor wasn't working. Fixed that by using 57600 baud rate but now I get these errors. I tried multiple things from [this][1] post but they didn't work. Any help would be appreciated.
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x53
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0xec
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x3c
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x71
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x87
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x60
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0xe0
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0xe8
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x7d
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0xd0
Failed chip erase: uploading error: exit status 1

  [1]: https://arduino.stackexchange.com/questions/17/avrdude-stk500-getsync-not-in-sync-resp-0x00-aka-some-dude-named-avr-won


text:
Multiple Ultrasonic Sensors with Arduino and 74HC595 Shift Register
I'm currently developing a project aimed at streamlining the process of identifying available closets within my school lockers room. The objective is to utilize ultrasonic sensors to determine the occupancy status of each closet, ensuring that students can easily locate an unoccupied one without searching through each door. For testing purposes, I'm using an Arduino along with just 8 ultrasonic sensors and one 74HC595 shift register. The final implementation will involve an ESP32, expanding the system to cover approximately 48 closets, each equipped with its own ultrasonic sensor and LED indicator.
I searched about the 74HC595 shift register and tried to implement my own testing code.

the functionality i've aimed to implement:

This Arduino code is designed to interface multiple HC-SR04 ultrasonic sensors with an Arduino using a 74HC595 shift register. The shift register is utilized to control the VCC (power) of each ultrasonic sensor individually. The wiring involves connecting the echo pins of all sensors together and connecting them to a single Arduino pin (EchoPin). Similarly, the trigger pins of all sensors are connected together and linked to another Arduino pin (TrigPin). The ground pins of all sensors are connected to a common ground pin on the Arduino.
Upon pressing a button connected to pin A0, the Arduino initiates a distance measurement sequence. The 74HC595 shift register is used to selectively provide power to each ultrasonic sensor one at a time. This is achieved by shifting a binary value corresponding to a specific sensor's power pin into the shift register and updating the latch pin to activate the chosen sensor. The distance readings from each sensor are then obtained and stored in an array (sensorsValue).
The getDistance function calculates the distance using the HC-SR04 sensor's echo and trigger pins, based on the time it takes for the ultrasonic pulse to travel to the target and back.
Overall, this code enables efficient control and reading of multiple ultrasonic sensors through a single Arduino, optimizing power consumption by activating sensors selectively. The serial monitor outputs the distance readings for each sensor when the button is pressed.

my code :

/******************************************************************************/
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   Shifter.ino                                        :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: unknown <unknown@student.1337.ma>        +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2024/02/28 21:26:13 by unknown          #+#    #+#             */
/*   Updated: 2024/02/28 22:55:14 by unknown         ###   ########.fr       */
/*                                                                            */
/******************************************************************************/

/*

   Trigger HC-SR04 units with a 74HC595

   Wiring :

    Arduino pin 2 to echo of all HCSR04
    Arduino pin 3 to trig of all HCSR04
    Arduino Ground pin to GND of all HCSR04

    74HC595 ` POWER ` pin (16) to vcc of the Arduino (5v)
    74HC595 ` OUTPUT 1 ` pin (15) to VCC of the first HCSR04
    74HC595 ` SERIAL INPUT ` pin (14) to Arduino pin (6)
    74HC595 ` OUTPUT ENABLE ` pin (13) to Arduino (GND)
    74HC595 ` REGISTER CLOCK / LATCH ` pin (12) to Arduino pin (7)
    74HC595 ` SHIFT REGISTER CLOCK ` pin (11) to Arduino (8)
    74HC595 ` SHIFT REGISTER CLEAR ` pin (10) to Arduino GND
    74HC595 pin (9) NOT USED

    74HC595 ` OUTPUT 2 ` pin (1) to VCC of the second HCSR04
    74HC595 ` OUTPUT 3 ` pin (2) to VCC of the third HCSR04
    74HC595 ` OUTPUT 4 ` pin (3) to VCC of the fourth HCSR04
    74HC595 ` OUTPUT 5 ` pin (4) to VCC of the fifth HCSR04
    74HC595 ` OUTPUT 6 ` pin (5) to VCC of the sixth HCSR04
    74HC595 ` OUTPUT 7 ` pin (6) to VCC of the seventh HCSR04
    74HC595 ` OUTPUT 8 ` pin (7) to VCC of the eighth HCSR04
    74HC595 ` Ground ` pin (8) to vcc of the Arduino (GND)
*/

/*When Clicking the button, Arduino will read the value of
  each sensor value continuously (the first sensor, then the second , ...) and store it in  the sensors_value double array*/
int btn_trigger = A0;

// HCSR04 echo && trig pins
const int EchoPin = 2;
const int TrigPin = 3;

// Binary pin values for shift register
const int sensorsPin[8] = {
  B00000001,  /*1*/
  B00000010, /*2*/
  B00000100, /*4*/
  B00001000, /*8*/
  B00010000, /*16*/
  B00100000, /*32*/
  B01000000, /*64*/
  B10000000 /*128*/
};

double sensorsValue[8] = {
  0.00,
  0.00,
  0.00,
  0.00,
  0.00,
  0.00,
  0.00,
  0.00,
};

// Pin connected to ST_CP of 74HC595
const int latchPin = 7;

// Pin connected to DS of 74HC595
const int dataPin = 6;

// Pin connected to SH_CP of 74HC595
const int clockPin = 8;

// Pin connected to MR (SRCLR) of 74HC595 (active low)
const int clearPin = 9;

double getDistance(int triggerPin, int echoPin);

void setup() {
  Serial.begin(9600);
  Serial.println("HCSR04BitShiftV1 Initialization...");

  pinMode(btn_trigger, INPUT_PULLUP);

  pinMode(EchoPin, INPUT);
  pinMode(TrigPin, OUTPUT);

  // Set pinMode for 74HC595 pins
  pinMode(latchPin, OUTPUT);
  pinMode(dataPin, OUTPUT);
  pinMode(clockPin, OUTPUT);

  // Additional pin for clearing the shift register
  pinMode(clearPin, OUTPUT);
  digitalWrite(clearPin, LOW);  // Clear the shift register initially
}

void loop() {
  // Check if the button is pressed
  int buttonState = digitalRead(btn_trigger);

  if (buttonState == LOW) {
    Serial.println("Getting Distance ...");
    // Iterate through each sensor
    for (int i = 0; i < 8; i++) {
      // Set the latchPin LOW before sending data
      digitalWrite(latchPin, LOW);

      // Shift out the binary value for the current sensor
      shiftOut(dataPin, clockPin, MSBFIRST, sensorsPin[i]);

      Serial.print("Shifted Value: ");
      Serial.println(sensorsPin[i], BIN);

      // Set the latchPin HIGH to update the shift register
      digitalWrite(latchPin, HIGH);

      // Get the distance for the current sensor and store it in the array
      sensorsValue[i] = getDistance(TrigPin, EchoPin);

      // Print the distance for debugging
      Serial.print("Sensor ");
      Serial.print(i + 1);
      Serial.print(": ");
      Serial.print(sensorsValue[i]);
      Serial.println("cm");
      // Delay between sensor readings
      delay(1000);
    }
  }
}

/*Get the Distance value*/
double getDistance(int triggerPin, int echoPin)
{
  unsigned long duration = 0;
  double distance = 0.0;
  float soundspead = 0.034;

  digitalWrite(triggerPin, LOW); // Clear the trigger
  delayMicroseconds(2);
  // Sets the trigger pin to HIGH state for 10 microseconds
  digitalWrite(triggerPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(triggerPin, LOW);
  pinMode(echoPin, INPUT);
  // Reads the echo pin, and returns the sound wave travel time in microseconds
  duration = pulseIn(echoPin, HIGH);

  Serial.print("Pulse Duration: ");
  Serial.print(duration);
  Serial.println(" microseconds");

  distance = (soundspead * duration) / 2;
  return distance;
}

Wiring :

Problem :

But I've encountered a big problem which is that the pulse duration readings for all ultrasonic sensors consistently show 0 microseconds, resulting in distance readings of 0.00 cm. This suggests that the pulseIn function, responsible for measuring the duration of the echo signal, is not receiving valid signals or is not functioning as expected. I suspect potential problems in the wiring, shared echo, and trigger pin configurations, as well as issues with the timing of trigger signals, echo signal reception, and the overall configuration of the 74HC595 shift register.

Output :

HCSR04BitShiftV1 Initialization...
Getting Distance ...
Pulse Duration: 0 microseconds
Sensor 1: 0.00cm
Pulse Duration: 0 microseconds
Sensor 2: 0.00cm
Pulse Duration: 0 microseconds
Sensor 3: 0.00cm
Pulse Duration: 0 microseconds
Sensor 4: 0.00cm
Pulse Duration: 0 microseconds
Sensor 5: 0.00cm
Pulse Duration: 0 microseconds
Sensor 6: 0.00cm
Pulse Duration: 0 microseconds
Sensor 7: 0.00cm
Pulse Duration: 0 microseconds
Sensor 8: 0.00cm

Clarification :

I apologize for any confusion caused by my initial message. To clarify, in my first attempt, I inadvertently connected the ultrasonic sensor's trig pin directly to the output of the shift register, rather than controlling the power of each sensor individually. Additionally, I used separate pins on the Arduino for each sensor's echo pin. While this configuration did work, it resulted in the utilization of a significant number of pins . That's why I thought using shift register to control sensors would be a better approach.
Initially, I attempted to control four ultrasonic sensors by connecting their trig pins directly to the output of the shift register. Here is the link to the corresponding Tinkercad project!
In my second attempt, I explored a different approach by connecting the VCC of all sensors to the outputs of the shift register for control, aiming to minimize the number of pins used. You can view the project on Tinkercad via the following link
as I mentioned before Indeed, each closet has its own ultrasonic sensor, all connected to a single ESP32. My plan involves using 6 shift registers, each controlling 8 ultrasonic sensors with one 74HC595, thereby minimizing the number of pins used to 2 main pins shared among all shift registers and six separate control pins (one for each shift register). While using 48 ultrasonic may seem excessive and complex, that's the task I've been assigned. However, I'm exploring whether it's feasible or if alternative sensor options would be more suitable in terms of cost and functionality.
I would be extremely grateful for your guidance. Thank you in advance for any help you can provide.

I'm not sure I understand your concept. You're triggering all sensors with just one pin and also expect the echo on a single pin, the shift register only controls which sensor has "power". Unfortunately, a sensor that does not have power may still interfere with your measurement, as the resistance of the output lines to ground is not infinite. Also, I doubt that the shift register can provide enough power on its outputs to drive the sensors.

Any particular reason you use ultrasonic sensors? Wouldn't a simple LED sensor barrier be easier?

The 74HC595 datasheet claims 6mA output current. This guide states a working current for the typical HC-SR04 ultrasonic sensor module as 15mA, which is - in fact - higher than 6mA. So I would second PMF here. And also you probably need to isolate each echo pin somewhat with a diode. Depends on if the echo pin gets actively driven in each state.

why do you have eight ultrasonic sensors, when the final product will have only one?

@jsotola I think the OP means that "each [of the 48 closets] has it's own ultrasonic sensor", but all connected to a single ESP32.

@PMF Thank you for your response and insights. I apologize for any confusion caused by my initial message. To clarify, in my first attempt, I inadvertently connected the ultrasonic sensor's trig pin directly to the output of the shift register, rather than controlling the power of each sensor individually. Additionally, I used separate pins on the Arduino for each sensor's echo pin. While this configuration did work, it resulted in the utilization of a significant number of pins . That's why I thought using shift register to control sensors would be a better approach.

@PMF Initially, I attempted to control four ultrasonic sensors by connecting their trig pins directly to the output of the shift register. Here is the link to the corresponding Tinkercad project: https://www.tinkercad.com/things/35OOmRfpQJs-ultrasonic-distance-sensing-with-shift-registers/editel?returnTo=%2Fdashboard%3Fcollection%3Ddesigns%26type%3Dcircuits&sharecode=_WTT3Y3u6X5gkH5PY6UbP6dCHOSni9hURti0_H86PB0

@PMF In my second attempt, I explored a different approach by connecting the VCC of all sensors to the outputs of the shift register for control, aiming to minimize the number of pins used. You can view the project on Tinkercad via the following link:
https://www.tinkercad.com/things/4VS2loCt9BO-shifter/editel?returnTo=%2Fdashboard%3Fcollection%3Ddesigns%26type%3Dcircuits&sharecode=BCOL5jWmQpCFJMlmZkSDTaiuxuDvl_GYz6KLmYQfPEY

@PMF as u mentioned to jsotola Indeed, each closet has its own ultrasonic sensor, all connected to a single ESP32. My plan involves using 6 shift registers, each controlling 8 ultrasonic sensors with one 74HC595, thereby minimizing the number of pins used to 2 main pins shared among all shift registers and six separate control pins (one for each shift register). While using 48 ultrasonic may seem excessive and complex, that's the task I've been assigned. However, I'm exploring whether it's feasible or if alternative sensor options would be more suitable in terms of cost and functionality.

If connecting the echo pins to individual input pins works, that could be a possible solution. You could use an Arduino Due instead of an ESP32 - it's a bit more expensive but has more than 50 input pins.

@PMF Thank you for suggesting the Arduino Due as an alternative to the ESP32. However, purchasing an Arduino Due in my country's electronic stores is quite expensive. I'm still exploring options to use ultrasonic sensors with a shift register while minimizing the number of pins used as much as possible. In my opinion, it might be more efficient to consider using alternative sensor types with the shift register instead of ultrasonic sensors. Do you have any suggestions for alternative sensors that could be used in this setup?

One possible alternative I already mentioned above was a LED light barrier. A led on one side and a photoresistor on the other side of the cabinet. Or they could even be on the same side if the cabinets are metallic. I use https://sensorkit.joy-it.net/de/sensors/ky-033 with some reflective tape on the other side for a similar application.

@PMF Thank you for your recommendation regarding the IR sensor or the LED and photoresistor combination as alternatives for detecting the occupancy of the cabinet. I will certainly explore the possibility of using them with my colleague. Additionally, I'm considering that while the recommended sensors you suggested are affordable, they may work just fine if they are well-positioned in the cabinet to detect the entire cabinet space.


text:
Control a JQC-3F relay with ESP32
I have this circuit I build and I have a problem. When I activate/deactivate SW1, I can hear the RLY1 flip on and off which is fine. But when I activate the PIN 13, the RLY2 do not work. When the relay is connected, I can measure 1.1V but when I disconnect the relay, my multimeter show me 3.3V.
Anyone have an idea of what I could do to fix this issue and be able to control my 3V relay with PINS in ESP32?

simulate this circuit – Schematic created using CircuitLab

the ESP32 cannot provide enough current to activate a relay ... research how to drive a relay with a microcontroller

Thank you so much, I didn't formulated that in that way in Google, I found how to do it, it now work with the usage of a transistor :D

You should post an answer, as comments get deleted over time.


text:
ESP32 pseudo hardware flow control for Bluetooth SPP
I'm using an ESP32 as a Bluetooth SPP to USB-serial null modem between a MacBook Pro (via SPP) and a laptop running Windows 11.
The ESP32 program logic is about as simple as it gets:
int nextByte;
void loop() {
    nextByte = Serial.read();
    if (nextByte > 0) {
        if (bt.isReady())
            bt.write(nextByte & 0xff);
        else
            dieAndBlinkLed();
    }
    nextByte = bt.read();
    if (nextByte > 0)
        Serial.write(nextByte & 0xff);
}

At the Mac & Windows ends, I'm using JSerialComm with event-driven reads and blocking direct writes.
The problem I'm having is, if I call port.writeBytes(byteArray, byteArray.length) with a byteArray that's longer than approximately 520-540 bytes (i.e. slightly longer than 512, but way less than 768 or 1024, let alone 4096), it seems to silently drop bytes.
I have JSerialComm's receive listener configured to buffer bytes and deliver them to my callback when a 0 byte is received (I'm using COBS to escape-out zero bytes). It seems to be dropping the heads and delivering only the 520-540 byte tails of each frame, but I'm not really sure what's happening between the moment I call port.writeBytes() on the Mac end and send a chunk larger than ~540 bytes to the Bluetooth SPP port and the moment the callback at the other end delivers only the tail end.
If push came to shove, I suppose I could rewrite the program to use 500-byte frames (~509-512 bytes with overhead) instead of 4000-byte frames (~4010-4028 bytes with overhead), but then the relative overhead would quadruple from ~0.6% to ~2.5% (every frame has a 4-byte header at the start, a 4-byte crc32 at the end, and 1-16 bytes of COBS overhead... 1, plus one for every 254+ bytes in a row without at least one zero byte).
Before I throw in the towel, I'm trying to get a better understanding of what the actual hard constraints imposed by esp32 Bluetooth SPP are, and make sure I'm not just making a stupid mistake somewhere along the line that's causing behind the scenes flow control to fail in a way I can fix.
Off the top of my head, I can think of the following points of failure:

JSerialComm's handling of the bytes before delivering them to OSX
OSX's serial buffer overflowing because the bluetooth spp stack is declining to accept bytes while it's busy (re)transmitting earlier ones
my esp32 event loop being too slow and dropping bytes
serial wire loss between the esp32 and cp2102
overflowing the cp2102's buffer in between USB polls
USB control mode being unable to ferry the bytes from the cp2102 through the USB port fast enough (64 bytes/millisecond max... assuming it actually gets called every millisecond, and most of those 64 bytes are available for use)
the cp2102 driver on Windows overflowing its own buffer before JSerialComm grabs its contents
JSerialComm itself having a buffer smaller than ~576 bytes and overflowing before it sees the next 0 and delivers the chunk to my callback

Before tackling the possibility of a JSerialComm-related problem at StackOverflow, I want to eliminate anything esp32-related as a potential problem.
So.. first... is there any possibility that the way I'm relaying data between the ports a byte at a time could be the problem? For what it's worth, dieAndBlinkLed() has never triggered... and the problems I've observed so far have involved data entering the pipeline at the Mac/bluetooth-SPP end and ending up at the USB/Windows end.
Does anybody have any idea what the max sustainable SPP bitrate between a Macbook Pro (M3, 2023 edition) and esp32 a few inches away even IS?
As I understand it, SPP uses timeslices and a "raw" link rate somewhere in the neighborhood of 1-2mbps. However, I've also gotten the impression that you're only "guaranteed" (in the loosest sense) 1 slice per period, and that you normally can only use more than one if a whole complicated chain of dependencies and conditions is satisfied... including "both bluetooth modules are from the same vendor", "same bluetooth stack at both ends", and "bluetooth stack itself is willing to use more".
AFAIK, Espressif and Apple almost beyond doubt don't satisfy the "both bluetooth modules from same vendor" requirement, and "same bluetooth stack" would probably be the final deathblow even if they did (because everything Apple does is proprietary).
(UPDATE: It looks like the effective best-case transfer rate for normal SPP is 128kbps... anything faster is a vendor-proprietary extension that probably won't work in this situation).
Is there anything I can/must do at the esp32 end to eliminate  it as a likely chokepoint? Like, is the size of the esp32's local bluetooth and/or Serial port buffer something that's configurable via esptool.py? Or, as theorized earlier, is the esp32 itself (and the software running on it) likely to be the least of my problems?
Any additional insight anyone might have about SPP (via JSerialComm or otherwise) between an ESP32 and "real" computer is welcome, though I suspect that's probably something I'll have to ask at StackOverflow.

Update
I ran some experiments at three different baudrates, and transmitted 501 510-512 byte packets with varying delays between them.
Surprising discovery: reducing the baudrate made things worse

with 200ms delay between packets, I received 499, 499, and 500 packets at 57600, 115200, and 230400 baud respectively.
with 100ms delay between packets, I received 404, 474, and 486 packets at 57600, 115200, and 230400 baud
with 50ms delay between packets, I received 47(!!!), 335, and 423 packets at 57600, 115200, and 230400 baud
with 25ms delay between packets, I received 14(!!!), 75, and 311 packets at 57600, 115200, and 230400 baud

Revised theory about what I think might be going wrong: I think the bluetooth stack is buffering the outbound bytes and lying to the serial port driver that they've been sent, and reducing the baudrate makes things worse by creating a logjam further downstream.

At 57600 baud, a block of data hits the ESP32 at some much higher signaling rate via bluetooth, then logjams in the esp32 because it's trying to shove all 500 bytes through a metaphorical cocktail straw into the cp2102.
At 230400 baud, a block of data takes longer to transmit between the Macbook and ESP32 than the baudrate would suggest, but the combination of throttling the rate it's being fed to the Macbook's bluetooth stack and using a fast baudrate between the ESP32 and CP2102 allows the incoming buffer on the esp32 to be emptied almost immediately upon receipt.

Assuming I'm right, I think I somehow need to find a way to get the serial port library to recognize when the bluetooth stack's outbound buffer is full. I don't know whether the problem is with my code, with the serial port library (JSerialComm), or can't be solved at all within the constraints of Java's ability to communicate with Apple's bluetooth stack.

The read() is blocking call and it might be waiting for example whole second until it times out. Meanwhile other serial might have steady flow of bytes that nobody consumes for long time

Where do you see that read() is a blocking call? I was under the impression that it immediately returns a value between 0..255 if there's at least one byte in the buffer, and -1 if the buffer is empty (source: https://www.arduino.cc/reference/en/language/functions/communication/serial/read/)

You are right, I had it somehow "stored" in memory as blocking, but it was for readString and similar https://www.arduino.cc/reference/en/language/functions/communication/serial/settimeout/

If it's any consolation, I almost wish you had been right, because at least then I'd have an explanation of where the problem is occurring.
My current (as yet unverified) theory is that maybe JSerialComm's writeBytes() blocks until the bluetooth stack merely accepts the bytes for sending, as opposed to blocking until they're confirmed to have been sent. So, JSerialComm and I might be relentlessly throwing huge byte arrays at it expecting the buffer to already be empty, and eventually overflowing the bt stack's own buffer without any warning.

Maybe try to measure how long it stays on different parts of loop (probably just set some pins before and clear after it and watch it on oscilloscope)


text:
About MAX30102, MLX90614 & Nodemcu-32s
I am using Nodemcu-32s with MAX30102 & MLX90614.
I noticed a thing that when I was working with both sensor individually then both of them were working fine but when I started them using together by connecting them on breadboard then both of them were not working.
I checked by changing jumper wires & checking almost all holes of breadboard, then I came to know that both jumper wires & bread board are working fine.
After that, when I started using them individually again then I got "sensor not found" error.
I am not sure where I am making mistake.
I am connecting

MAX30102 Pins
Nodemcu-32s Pins

Vin
5V

SDA
G21

SCL
G22

GND
GND

MLX90614 Pins
Nodemcu-32s Pins

Vin
5V

GND
GND

SDA
G21

SCL
G22

I don't know if my sensors were burnt or not so how can I verify for the same? Apart from this I am not aware how can I get accurate Pulse Rate & SpO2

Welcome to SE/Arduino! Please take the [tour] to learn how this site works, and read "[ask]". If your sensors worked before you put them on the same I²C bus at the same time, and they don't work individually now, chances are high that there is a wiring error or a damage. Are the sensors working, when you revert to your very first circuits? -- On your last statement: Please separate issues, ask a separate question for this. Probably this makes sense only after you have working sensors again.

what have you tried so far? On paper I mean.


text:
beginner 7-segment code using 74hc595
Was trying this basic circuit using 74HC595 but 7-segment doesn't light at all in Anode Common. When switched to Cathode common, it just stays at 9 instead. Trying to achieve changing value from 0-9 after clicking the button. The code I used:
int data = 0;
int clock = 2;
int latch = 1;
int button = 3;

byte segment[10] = {B11111100, //0
                     B11000000, //1
                     B11011010, //2
                     B11110010, //3
                     B01100110, //4
                     B10110110, //5
                     B10111110, //6
                     B11100000, //7
                     B11111110, //8
                     B11100110, //9
                    };
void setup()
{
  pinMode(button, INPUT);
  pinMode(data, OUTPUT);
  pinMode(clock, OUTPUT);
  pinMode(latch, OUTPUT);
}

void loop()
{
  digitalWrite(latch, LOW);
  shiftOut(data, clock, LSBFIRST, segment[9]);
  digitalWrite(latch, HIGH);
}

Do you have the part number for the display? That would help. Also a schematic or a picture which clearly shows all the wiring.  But a schematic is much preferred. Also, all the code. Most of the time it is asked to reduce the code down to only the part that does not work. But they mean all of the reduced version of the code.

What do you mean "it just stays at 9 instead"? Your code just writes the digit 9 to the display (repeatedly and very fast), so isn't this what you want?

Thank you for adding a schematic.

@aims, if the answer works for you please accept it. If it does not, please add a comment. The goal is to create a list of searchable questions and accepted answers for others to use in future.

If the display works when wired up for common cathode then likely it is a common cathode LED display.
Going on, it would appear that the only thing this code does is write out data to display the number "9" over and over again:
  shiftOut(data, clock, LSBFIRST, segment[9]);

To test the display, add lines with different indices into the array which contains the 7 segment display patterns. For example:
  shiftOut(data, clock, LSBFIRST, segment[0]);
  delay(1000);
  shiftOut(data, clock, LSBFIRST, segment[1]);
  delay(1000);
  shiftOut(data, clock, LSBFIRST, segment[2]);
  delay(1000);
  shiftOut(data, clock, LSBFIRST, segment[3]);
  delay(1000);
  shiftOut(data, clock, LSBFIRST, segment[4]);
  delay(1000);
  shiftOut(data, clock, LSBFIRST, segment[5]);
  delay(1000);
  shiftOut(data, clock, LSBFIRST, segment[6]);
  delay(1000);
  shiftOut(data, clock, LSBFIRST, segment[7]);
  delay(1000);
  shiftOut(data, clock, LSBFIRST, segment[8]);
  delay(1000);
  shiftOut(data, clock, LSBFIRST, segment[9]);
  delay(1000);

... should cycle through numbers 0 through 9 then repeat.
Adding a momentary push button is difficult because of mechanical switch bounce. Because the processor can sample the switch very fast, random switch bounces can make a project such as this one appear broken. Displaying what appears to be random numbers.
Read how to de-bounce a push button here in the arduino.cc document pages.
The best approach to writing a good program is to remove all calls to delay(). Instead, after reading how to de-bounce a switch, consider creating a state machine where each button push will advance to the next state. Create 10 states where each state display a different number 0 through 9.


text:
Reading MODBUS on ESP32
I'm working on a project for Smart Meter in this I'm reading MODBUS RS485 on ESP32 via MAX485 TTL To RS485
Overview : So, basic flow is, reading MODBUS as per MOSBUS Mapping list given by Smart Meter Manufacturers, I added those hardcoded values in code, read those register values one by one, convert the reading to decimal/float, arrange all required reading in specific format, send the JSON data with https POST request. And then further display those on graph or whatever on server.
Note : I'm reading only 4 slave ID's as of now. So maximum 4 Numbers of meter can be connected once at a time.
Testing Scenario (a lab with less noise and interference around) : I'm able to read data on ESP32 perfectly fine, with changing MODBUS Slave IDs on the meter, even while running.
Onsite Scenario (a place with HIGH voltage Electrical Panel) : Sometime it reads data perfectly fine, Some it reads only some of the Slave IDs (Out of 4), other time there is no data readings on ESP32
Debugging : To rectify the onsite issue, I checked if the meter is working fine or not with RS485-to-USB converter and read data on MODSCAN Application on PC. And meter is working perfectly fine. Then what I noticed is, ESP32 also started getting reading while I have connected RS485-to-USB converter in parallel.

And if I removed the RS485-to-USB converter, ESP32 immediately stopped reading any data.
Temporary Solution : To fix this, I removed the RS485-to-USB converter from my PC, and given direct 5V supply to RS485-to-USB Converter. And ESP32 started reading data again from MODBUS.

Question I need help with are

I couldn't understand what does the RS485-to-USB converter
connection in parallel doing.
Does it helping in improving RS485 signal and as a repeater?
What is the easier way to overcome this, as hardware as well as if only firmware fix is possible?

Some References and term I used above

ESP32 30 Pins
RS485-to-USB

MAX485 TTL To RS485

PCB inside Panel :

Additional as Required

Meter Manufacturer 1 A-B:50.5 Ohm      B-A:42.9K Ohm
Meter Manufacturer 2 A-B:0.329M Ohm    B-A:0.327M Ohm
MAX485 to TTL        A-B:120 Ohm       B-A:120 Ohm
RS485-to_USB         A-B:26.5 Ohm      B-A:26.3 Ohm

Could you please re-write the post, because I cannot understand what's going on. How are you connecting the ESP32 to the modules? Where are your grounds? This needs a lot more to determine how to fix this; it indeed seems like a noise issue. I would say that this can probably be fixed with an RS485 repeater. It also potentially sounds like you might be missing a terminating resistor.

@jsotola My bad, please take a look again. let me know if there is any other I can provide you to understand the issue I'm facing

@NickS. I rewrite the question in detail now, please take a look again

How long is your cable, RS485 requires twist pair with shielding, not just two plain wire, this is especially important in the noisy application environment. 2) RS485 requires two terminal resistors (120 ohms) at the two end of the bus, maybe your MAX485 module doesn't have the termination resistor, but your USB-RS454 dongle provided that...

@JustdoinGodswork can you measure the resistance between A and B on the MAX485 module? When it's powered off. How about on the meters? If you can power them off. Also, the last picture shows me that the ESP32 is simply connected to the RS485-USB dongle thru the MAX485 module, how does that enable you to read meter data?

@hcheung At one location it's not even 1 meter long, just three meters are connected with different slave IDs (ID:1, ID:2, and ID:3). But there are CTs nearby of 2000/5A ratio. So I'm not sure if that is causing the issue.
I'm using CAT6 for RS485 between Meters but from the last meter to ESP32 its plain wire as shown in last image (connection to orange Screw-Terminal connector)

@NickS. Added the required resistance values in the above question. In the last picture you can see an orange colored Screw Terminal, that's where I connected RS485 from Electric Meter (yellow colored two wire refer last picture)

Also, it doesn't seem just about the resistor issue. Because if it's a resistor issue, it should be fixed even with RS485-to-USB connected in parallel without any power. but ESP32 only reads when the USB connected to a power source as I showed in the picture above of Temporary Solution.

@JustdoinGodswork those don't look good per se, but I don't know how you're measuring them. We have verified that the module has a terminating resistor and that's good. One thing I don't understand - have you tried plugging the meter's RS485 connection into the green connector on the MAX485 module or are you solely using the orange terminals? If yes, why? Are the two connected on the board?

@NickS. For measuring resistance, I removed all connections from the meter, MAX485 Converter module, and USB. Then use a multimeter in resistance-measuring mode.  The orange connector comes out of the casing/box, so I'm using that for meter RS485 as of now. Also, they are shorted on the PCB with A to A and B to B. This already works perfectly fine while testing in lab with the orange connector only.

@JustdoinGodswork let's continue in the chat.


text:
PCINT of PortC for an analog device
I would like to use analog signals from joystick axes in program. Firstly, I found out that external interrupts can be applied for 2 and 3 pins of PortB only. Now I am trying to use PCINT for A0 and A1 pins for instant reaction in program and implementation transition between modes of alarm clock, which is the main goal of a project. I saw how it cold be done with encoder, but I have a joystick physically. Can PCINT-interrupts can be used to react changing of analog signals?
Target part of code and breadboard diagram are below.
#include <LiquidCrystal.h>
#include <RTClib.h>
#include <ezButton.h>

#define set0(R,b) R&= ~(1<<b)
#define set1(R,b) R|= 1<<b

//#include <avr/io.h>
//#include <avr/interrupt.h>

int lcd_V0 = 13;
int RS = 11;
int RW = 10;
int E = 9;
int D4 = 4;
int D5 = 5;
int D6 = 6;
int D7 = 7;

int DHT11 = 12;
int Buzzer = 8;
int Joystick_button = 1;

LiquidCrystal lcd(RS, RW, E, D4, D5, D6, D7);
RTC_DS1307 rtc;
ezButton button(Joystick_button);

int Joystick_X = A1;
int Joystick_Y = A0;
bool X_changed = false;
bool Y_changed = false;
volatile int X = 0;
volatile int Y = 0;

void setup() {
  lcd.begin(16,2);
  lcd.display();

  rtc.begin();

  pinMode(Buzzer, OUTPUT);
  pinMode(Joystick_button, INPUT_PULLUP);

  set0(DDRC, 0);
  set1(PORTC, 0);
  set0(DDRC, 1);
  set1(PORTC, 1);
  set1(PCICR,PCIE1);
  set1(PCMSK1,PCINT8);
  set1(PCMSK1,PCINT9);
}

void loop() {
  button.loop();
  if(X_changed){
     X = analogRead(Joystick_X);
     Y = analogRead(Joystick_Y);
     lcd.setCursor(0, 0);
     lcd.print(String(Y) + String(X));
     }
  if(Y_changed){
     X = analogRead(Joystick_X);
     Y = analogRead(Joystick_Y);
     lcd.setCursor(0, 1);
     lcd.print(String(Y) + String(X));
     }
  }

ISR( PCINT1_vect )
{
  if((PINC&(1<<0))==0){Y_changed = true;}
  if((PINC&(1<<1))==0){X_changed = true;}
}

PCINTx_vect are for GPIO pins. There is ADC_vect (ADC conversion complete vector). Open the datasheet and search for "Interrupt Vectors" table within the datasheet and read the chapter about ADC to see how to use it, or alternatively google "ATmega328 ADC interrupt".

If the joystick is going to be operated by a human, or any sort being incapable of sub-millisecond moves, then you don't need interrupts. As long as your loop() is non-blocking, simply reading the analog values within loop() will be fine.

There is no equivalent of Pin Change interrupts for the ADC. While you can trigger the ADC automatically and then interrupt on completion via ADC_vect, that is not fitting for your situation. Also you would need to switch between both A0 and A1, since there is only one ADC in the Uno. I second Edgar here: There is no good reason to use interrupts for this. Your current loop()  is already running faster than any human can notice or react, even if you don't check for a changed pin. So just do it in loop()


text:
Problem in serial communication between ESP32 and GSM A7670C
I am using A7670C GSM breakout board with an ESP32.
Connections

RX-TX
TX-RX
GND-GND

I am giving external power to the GSM module, 3.8 V according to theproduct description.
When I sent the AT command to GSM module, I don't get output on the serial monitor of the Arduino IDE.
The message is sent to a particular number successfully, but I don't receive the message from mobile.
This is my code:
#include <HardwareSerial.h>

HardwareSerial mySerial(2);

void setup() {
  mySerial.begin(115200); // Setting the baud rate of GSM Module
  Serial.begin(115200);   // Setting the baud rate of Serial Monitor (Arduino)
  delay(100);
  SendMessage();
  RecieveMessage();
}

void loop() {
  if (Serial.available() > 0)
    Serial.write(Serial.read());

  switch(Serial.read()) {
    case 's':
      SendMessage();
      break;
    case 'r':
      RecieveMessage();
      break;
  }

  if (mySerial.available() > 0)
    Serial.write(mySerial.read());
}

void SendMessage() {
  mySerial.println("AT+CMGF=1");    // Sets the GSM Module in Text Mode
  delay(1000);  // Delay of 1000 milli seconds or 1 second
  mySerial.println("AT+CMGS=\"+91XXXXXXXXXX\"\r"); // Replace x with mobile number
  delay(1000);
  mySerial.println("I am SMS from GSM Module"); // The SMS text you want to send
  delay(100);
  mySerial.println((char)26); // ASCII code of CTRL+Z
  delay(1000);
}

void RecieveMessage() {
  mySerial.println("AT+CNMI=2,2,0,0,0"); // AT Command to receive a live SMS
  delay(1000);
}

Other AT commands also don't give me an OK message on the serial monitor, or any other message. I have tried software serial, but it doesn't work.


text:
OS detection with Arduino Uno
I've been searching for a bit, and feel like it's impossible, but I will ask anyway: is it possible for an Arduino to detect what OS it uses, like how a rubber ducky does via USB?
I want specific code to run when it's plugged in a different operating system.
Is there any possible way to do that?
I've tried to find libraries for it, or any other stuff, but I can't seem to find any.

Not sure, how a rubber ducky does it, though it will definitely will be by a clever use of the USB protocol. With the Uno that would only work, if you hack the USB-Serial chip (Atmega32u4 I believe), which handles the USB connection for the Uno.

According to the Rubber Ducky’s Web site, it uses passive OS fingerprinting. You may try FingerprintUSBHost on a Leonardo or similar USB-enabled Arduino (not an Uno).


text:
I encounter an error in the ISR function when using the code specified in this community for arduinodue to act as a slave in spi communication
#include<SPI.h>

volatile boolean received;
volatile byte receivedData;

ISR (SPI_STC_vect)        //Inerrrput routine function
{
  receivedData = SPDR;   // Get the received data from SPDR register
  received = true;       // Sets received as True
}

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

  pinMode(MISO,OUTPUT);   //Sets MISO as OUTPUT
  SPCR |= _BV(SPE);       //Turn on SPI in Slave Mode
  received = false;
  SPI.attachInterrupt();  //Activate SPI Interuupt
}

void loop()
{
  if(received) {
    SPDR = receivedData;    // send back the received data, this is not necessary, only for demo purpose
    received = false;
    Serial.print(receivedData, HEX);
  }
}

the compiler gives an error with isr specified

What is the error?

@JRobert It's quite encrypted, but he mentioned "arduinodue" so I suspect Arduino DUE (with completely different MCU) :D

This program seems to have been written for an AVR-based Arduino, like a
classic Uno or Nano. The registers SPCR and SPDR, the bit SPE on
SPCR, and the SPI_STC interrupt, are all documented on the
ATmega328P’s datasheet.
Yours is an Arduino Due, which uses a completely different
microcontroller. AVR-specific code cannot run on the Due.

There is a code of SPI Slave for DUE at https://forum.arduino.cc/t/arduino-due-spi-interrupt/574857/3.


text:
Interfacing with Arducam OV2640 from Mac to deploy Image processing libraries
I purchased a Arducam OV2640 https://www.amazon.com/gp/product/B012UXNDOY/ however I am on a MAC. So I am not able to run the capture a image from the camera, which runs only on windows.
The example code is here, however I do not see any functions to capture an image or turn on the video streaming. https://github.com/ArduCAM/Arduino/blob/master/ArduCAM/examples/mini/ArduCAM_Mini_2MP_OV2640_functions/ArduCAM_Mini_2MP_OV2640_functions.ino
I tried sending msg to serial port 0x10,0x20 etc but no response.
I want to capture images from the camera and use it on my computer alternatively I want to run a OpenCV like library on the Arduino Module. How do I connect python code to the Arduino Module? Are there image processing models that can be deployed on the Arduino? Please help me get started.
Update: March 24th: I was able to update the code ArduCAM_Mini_2MP_OV2640_functions.ino to the Arduino, and read-write to the serial port through usb. However, the bytes read do not seem to ba a JPEG image. How do I understand the stream of bytes that are returned?
ser = serial.Serial('COM3', 115200)
ser.write(b'8')
ser.write(b'\x10')
import time

# Read the size of the JPEG data buffer from Arduino
f = open('image.jpg', 'wb')
print('Send Pic')
i = 0
while i < 10:
    if ser.in_waiting > 0:
        data = ser.read(1)
        print("Received:", data)
        # Write the JPEG data to a file
        f.write(data)
    else:
        print(i)
        i += 1
        time.sleep(1)

f.close()

You said: "I want to run a OpenCV like library on the Arduino Module". There are many Arduino platforms, but likely most of them would run out of resources before any significant amount of the OpenCV library was ported to them.

That is correct; This is a hobby project. The idea is to build and deploy a model onto the board - and use it to take an action based on it.


text:
Heltec WiFi LoRa 32 (V3) - Difference of various datatype packets length
I'm using Heltec WiFi LoRa32 boards (ESP32-S3 + SX1262).
For example I have two measured values:
float temperature = 21.56;
float humidity = 76.21;

I use the official Heltec library for LoRa radio (https://github.com/HelTecAutomation/Heltec_ESP32/blob/master/src/radio/radio.c), I only transfer data via LoRa (not LoRaWAN), so it is necessary to make it work with the library function Radio.Send().
Radio.Send( (uint8_t *)txpacket, strlen(txpacket) ); //send the package out

I would like to know if I spare the data length amount when I'll send values via LoRa in floats like:
void loop() {
  if (lora_idle)  {
    delay(1000);
    Paylaod payload;
    payload.temperature = random(-1000, 1000) / 10.0;
    payload.humidity = random(0, 101) / 100.0;

    Radio.Send( (uint8_t *)&payload, sizeof payload);
    Serial.print("sending packet: temperature = ");
    Serial.print(payload.temperature, 2);
    Serial.print(" and humidity = ");
    Serial.println(payload.humidity, 2);
    lora_idle = false;
  }
  Radio.IrqProcess( );
}

instead of sending them as chars like:
#define BUFFER_SIZE 30 // Define the payload size here

char txpacket[BUFFER_SIZE];

void loop()
{
    if(lora_idle == true)
    {
    delay(1000);

        sprintf(txpacket,"21.5676.24");  //start a package

        Serial.printf("\r\nsending packet \"%s\" , length %d\r\n",txpacket, strlen(txpacket));

        Radio.Send( (uint8_t *)txpacket, strlen(txpacket) ); //send the package out
    lora_idle = false;
    }
  Radio.IrqProcess( );
}

If I spare the number of transmitted bytes, how many bytes occupy one character in char txpacket[BUFFER_SIZE]?
Thanks

what are you using to measure temperature and humidity?

I'm using SHT31 sensor

the sensor is not accurate to two decimal places... it makes no sense to transmit floating point values

It basically doesn't matter which values are transmitted, but my question is how to effectively send  multiple values by LoRa.

Does this answer your question? Heltec WiFi LoRa 32 (V3) - Encode/decode packets to binary (make message shorter)


text:
LGT328P does not work as simple V-USB keyboard project. V-USB Keyboard code compiled for LGT328P with no errors but not working (but works on Uno )
I got the V-USB library to compile for LGT328P without any errors.
I made a V-USB keyboard for arduino Uno which worked-it involved making a simple circuit using a few zener diodes and
resistors and the V-USB software and schematic I used is documented here:
http://code.rancidbacon.com/ProjectLogArduinoUSB
The code I used for the keyboard is the one given in the example above and copied and pasted below (the other part of the circuit is merely a button to pin 12 -which needs a pull down resistor to ground).
So I migrated the project to the LGT328P.
I got the V-USB library and example sketch to compile for LGT328P without any errors and uploaded the compiled
code to the LGT328P.
So I plugged in my V-USB keyboard built around the LGT328P into a windows 10 PC but it just says USB device
is not recognised-but the code and V-USB circuit must be correct as they worked on the arduino Uno-all I simply did
was recompile it for the LGT328P and wired up the simple V-USB circuit (which uses a few zener diodes and resistors) to the LGT328P.
So how to fix this problem?
I am using Arduino IDE 1.8.5 and I know the LGT328p works already because I got a LED blinking sketch to work on it.
I thought it would just me straightforward to move from the V-USB keyboard I made on the Arduino Uno to the LGT328p
clone but I got the above problem.
I think the problem may be because the LGT328P is a clone board it means it doesn't 100% always compatiable with
arduino libraries such as the V-USB. Be interested to know if anyone else had a similar experience with V-USB and LGT328P.

v-usb keyboard example code bundled with library:
#include "UsbKeyboard.h"

#define BUTTON_PIN 12

// If the timer isr is corrected
// to not take so long change this to 0.
#define BYPASS_TIMER_ISR 1

void setup() {
  pinMode(BUTTON_PIN, INPUT);
  digitalWrite(BUTTON_PIN, HIGH);

#if BYPASS_TIMER_ISR
  // disable timer 0 overflow interrupt (used for millis)
  TIMSK0&=!(1<<TOIE0); // ++
#endif
}

#if BYPASS_TIMER_ISR
void delayMs(unsigned int ms) {
   /*
  */
  for (int i = 0; i < ms; i++) {
    delayMicroseconds(1000);
  }
}
#endif

void loop() {

  UsbKeyboard.update();

  digitalWrite(13, !digitalRead(13));

  if (digitalRead(BUTTON_PIN) == 0) {

    //UsbKeyboard.sendKeyStroke(KEY_B, MOD_GUI_LEFT);

    UsbKeyboard.sendKeyStroke(KEY_H);
    UsbKeyboard.sendKeyStroke(KEY_E);
    UsbKeyboard.sendKeyStroke(KEY_L);
    UsbKeyboard.sendKeyStroke(KEY_L);
    UsbKeyboard.sendKeyStroke(KEY_O);

    UsbKeyboard.sendKeyStroke(KEY_SPACE);

    UsbKeyboard.sendKeyStroke(KEY_W);
    UsbKeyboard.sendKeyStroke(KEY_O);
    UsbKeyboard.sendKeyStroke(KEY_R);
    UsbKeyboard.sendKeyStroke(KEY_L);
    UsbKeyboard.sendKeyStroke(KEY_D);
    //UsbKeyboard.sendKeyStroke(KEY_B, MOD_GUI_LEFT);

    UsbKeyboard.sendKeyStroke(KEY_ENTER);
#if BYPASS_TIMER_ISR  // check if timer isr fixed.
    delayMs(20);
#else
    delay(20);
#endif

   }

}

Does this answer your question? V-USB Keyboard on LGT328P arduino clone not working (but is working on Arduino Uno)

@jsotola no, that is a different question-in that question I did not get the code to compile for the LGT328p -in this question I got the code to compile but encountered a new problem. If you had read this new question you would have noticed it is a different question  to the one you give a link to.

you still have not provided the code ... people will not waste time trying to figure out how you connected everything and what code you are using

@jsotola okay, no need to be rude. I added the code.

thank you ... where is the V-USB code?

Mhh, didn't find any information if someone has tried using V-usb on an LGT328P before (considering they are relatively new to the party). That it doesn't work could still be a problem with the frequency. Or some other difference. LGT328Ps are not complete drop-ins.

Please check the formatting and presentation of your question in general, and when making edits. A well presented question is more likely to get an answer.

"they worked on the arduino Uno-all I simply did was recompile it for the LGT328P ", you are assuming LGT328P is 100% copycat of ATmega328p, but that's not what they claims, they add a few peripherals and also taken out something like EEPROM, and overclock it so that they can claim they are not a fake ATmege328p, you should ask them what the differences and why it not working.  Unless some Chinese companies, no one write library to ensure the compatibility with such chip...


text:
How to use do while loop of the u8g library in page drawing mode
I am trying to use a rotary encoder with 128x64 OLED display on an Arduino nano. I am trying to create a menu that can be scrolled through using the rotary encoder. While testing the rotary encoder, I found out it bounces quite a lot, so I used Bounce2 library and few extra lines of code to get the encoder working properly.
https://wokwi.com/projects/393512353441494017
here's the wokwi simulation and code of just the rotary encoder and I have tested this code on real hardware and it works fine.
    #include <Bounce2.h>
    #include "U8glib.h"
    #define ENCODER_CLK 3
    #define ENCODER_DT 2
    #define ENCODER_SW 4

    //buttons
    Bounce2::Button encoder_clk = Bounce2::Button();
    Bounce2::Button encoder_dt = Bounce2::Button();
    Bounce2::Button encoder_sw = Bounce2::Button();
    #define LED_PIN 13

    bool led_state = LOW;

    void setup() {

      //serial monitor
      Serial.begin(115200);

      //encoder and button debouncing
      encoder_clk.attach( ENCODER_CLK, INPUT);
      encoder_dt.attach( ENCODER_DT, INPUT);
      encoder_sw.attach( ENCODER_SW, INPUT_PULLUP);

      encoder_clk.interval(5);
      encoder_dt.interval(5);
      encoder_sw.interval(5);

      encoder_clk.setPressedState(LOW);
      encoder_dt.setPressedState(LOW);
      encoder_sw.setPressedState(LOW);

      //test led
      pinMode(LED_PIN,OUTPUT);
      digitalWrite(LED_PIN,led_state);

    }

    void loop() {

      encoder_clk.update();
      encoder_dt.update();
      encoder_sw.update();

      if (encoder_clk.changed()) {
        // There was a change on the CLK pin
        bool dtValue = encoder_dt.read();
        bool ckValue = encoder_clk.read();
        if (ckValue == LOW && dtValue == HIGH) {
          Serial.println("Rotated clockwise ⏩");
        }
        if (ckValue == LOW && dtValue == LOW) {
          Serial.println("Rotated counterclockwise ⏪");
        }
      }

      if(encoder_sw.pressed()){
        led_state = !led_state;
         digitalWrite(LED_PIN, led_state);
         Serial.println("Button Pressed");
      }
    }

Then I decided to test the OLED display.
Here is the wokwi simulation for oled and rotatry encoder together.
https://wokwi.com/projects/393400062063669249
After adding the code for OLED display and the do while loop of u8g library, it has stopped registering rotary encoder inputs. I cannot get any thing displayed on serial monitor. I have tested this on real hardware as well and the result is the same. How do I fix this problem and what would be the better way to use the do while loop of the u8g library?

Cross posted at forum.arduino.cc and getting attention there.  https://forum.arduino.cc/t/do-while-loop-of-u8g-page-drawing-mode-stops-everything-else-in-void-loop/1240533

Voting to close for the cross post and because the code posted doesn't include the do-while construct that the OP is saying he has problems with.

why do you require the use of a do while loop? ... this appears to be a an XY problem ... asking about a perceived solution to an unspecified problem, instead of asking about the problem itself ... please edit the title to ask about the actual problem that you are trying  to solve

For reliably registering encoder transition, you need your main loop to
be non-blocking. My guess is that the do...while loop blocks the
Arduino for too long. If this is the case, one possible solution is to
perform a single iteration of this do...while loop inside loop().
For instance, your current loop() looks like this:
void loop() {
    handle_the_encoder();

    u8g.firstPage();
    do {
        do_the_drawing();
    } while (u8g.nextPage());
}

You can change it into this:
void loop() {
    handle_the_encoder();

    static bool do_first_page = true;
    if (do_first_page) {
        u8g.firstPage();
        do_first_page = false;
    }
    do_the_drawing();
    if (!u8g.nextPage())
        do_first_page = true;
}

If needed, you may also break the drawing code into smaller chunks, and
do a single chunk per loop iteration. This will require you implementing
a finite state machine.


text:
Help understanding/reading RF data from an ad8362 sensor
It's my first time posting so I apologize if anything is wrong or missing.
I'm doing a project where I'm trying to combine EMF/RF readings with GPS data to create a heat map of exposure levels in an area. Right now I'm trying to make sense/properly read data from this sensor, and so far I have hooked it up to my arduino uno r3 analog and 5V pins.
I've been able to get an output, but from what I can tell it isn't anything viable or usable as it seems to be dependent on the connection rather than the location of the "antenna".
Using code to simply read out the analog pin:
void setup() {
    Serial.begin(9600);

}

void loop() {
   Serial.println(analogRead(0));
   delay(1500);
}

This is the readout:
Seems random to me, when there is no input 'antenna' the value holds at 2 or 3
Here is my crude setup to try and figure the sensor out (I have proper SMA connectors to use in the future):
I understand that I likely won't be getting an answer or a step by step, but I was hoping someone could point me in the right direction or give some advice. I have been trying to figure things out but information is limited, and I am unfortunately not super well versed in small electronics or coding, and need some help finding my way. All assuming this idea is even possible... :)
I should note that precision or units arent super necessary for me, I just need to have a reading that I know is an RF value and that is ballpark.
Open to any questions or suggestions. Thank you in advance!

start by reading the datasheet for the sensor ... determine what output the sensor produces and how the output relates to the received signal ... use an oscilloscope instead of an Arduino

The problem you are facing has nothing to do with code, and therefore nothing to do with Arduino. It is the understand of how the chip work and about RF signalling. The datasheet shown that the output is relatively linear for producing an output voltage between somewhat 0.2v for an input signal at -55dbm to about 3.5v at 10dbm across a wide range of spectrum. You are expecting the dupoint wire at the input would produce an RF signal strong enough for -55dbm with an input impedance matching 50-ohm, unfortunately it doesn't work that way for Radio signal.


text:
Problem with USBSetup not declared
Recently I've got into the Arduino USB HID stuff, so I've been trying it out. i found the library fingerprintusbhost which should in theory get the OS its plugged in.
However, I've come across this error and I'm not sure how to fix or make it work. I've been looking in the library itself, but with my limited knowledge I don't know what is wrong or how to fix it.
In file included from /home/tdvds/Documents/arduino uno/Material_Rubber_Ducky_Arduino_UNO_R3/sketch_mar20a/sketch_mar20a.ino:2:0:
/home/tdvds/Arduino/libraries/FingerprintUSBHost/src/FingerprintUSBHost.h:38:55: error: expected class-name before '{' token
 class FingerprintUSBHost_ : public PluggableUSBModule {
                                                       ^
/home/tdvds/Arduino/libraries/FingerprintUSBHost/src/FingerprintUSBHost.h:52:23: error: 'USBSetup' has not been declared
     int getDescriptor(USBSetup& setup);
                       ^~~~~~~~
/home/tdvds/Arduino/libraries/FingerprintUSBHost/src/FingerprintUSBHost.h:53:16: error: 'USBSetup' has not been declared
     bool setup(USBSetup& setup);
                ^~~~~~~~

exit status 1

Compilation error: exit status 1

Before you say "it's not a Leonardo", you can actually do it with an Uno as well, although it's a bit odder than a Leonardo.

To do this on an UNO involves reprogramming the 32U4 serial bridge chip.  You can't use the same set of libraries that you do with a Leonardo.

So how exactly are you doing it "a bit odder"? Are you compiling for the Atmega32U4 and flashing it with your code?

This is as expected, if you try to use PluggableUSBModule on an Uno (or any board that doesn't have USBCON defined).
To avoid such errors, and get a meaningful compilation error message, you should include a compiler check such as
#if !defined(USBCON)
#error PluggableUSBModule can only be used with an USB MCU.
#endif

just after the #includes at the top of the library's header file, like so
#include <stdint.h>
#include <Arduino.h>
#include "PluggableUSB.h"

#if !defined(USBCON)
#error PluggableUSBModule can only be used with an USB MCU.
#endif

In short, if the FingerprintUSBHost.h had such a check, then users of the library wouldn't be so confused. You should probably raise a Github issue for the author of the FingerprintUSBHost library, pointing out this issue.

Reproducing the error
FWIW, it is easy to reproduce this error, by using the code from this example, Issue with writing USB Mass Storage "PluggableUSB.h" Module. Enter the code for the three files (the main sketch, MassStorage.cpp and MassStorage.h) and compile, with the Uno board selected. You will get the error
MassStorage can only be used with an USB MCU.

Then remove the three lines of the compiler check from MassStorage.h:
#if !defined(USBCON)
#error MassStorage can only be used with an USB MCU.
#endif

and then try to compile. You will get the same errors as you have in your post.
However, if you compile the unaltered original code, with a Leonardo board selected (which does have USBCON defined), you will not see any errors.


text:
The happiness of migration
For many days I've been trying to make a raycasting engine for Arduino in which 3 steps are essential
-making a 3d environment (done)
-making the player move (pending)
-hand the player a assault rifle (pending)
So,here I have problem with the movement of player which I have no I idea with ,I have tried dozens of ways to make the player move but it just glued to one place.If anyone can help then it will be just amazing.I have made this project on wokwi btw.If anyone knows about wokwi then you can also help me there  https://wokwi.com/projects/392425187841246209. AND This is gonna run on a esp32 ,display the game in tft display and inputs by 5 push buttons ......Here's the code
#include <Adafruit_GFX.h>
#include <Adafruit_ILI9341.h>
#include <SPI.h>

#define TFT_CS     15
#define TFT_RST    -1
#define TFT_DC     33

#define BUTTON_UP    4
#define BUTTON_DOWN  36
#define BUTTON_LEFT  34
#define BUTTON_RIGHT 35

#define TFT_WIDTH   320
#define TFT_HEIGHT  240
#define MAP_WIDTH   15
#define MAP_HEIGHT  15

Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC, TFT_RST);

int worldMap[MAP_WIDTH][MAP_HEIGHT] = {
  {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},
  {1,0,0,0,0,0,0,0,0,0,0,0,0,0,1},
  {1,0,0,0,0,0,0,0,0,0,0,0,0,0,1},
  {1,0,0,0,0,1,0,0,0,0,0,0,0,0,1},
  {1,0,0,0,0,0,0,1,0,0,0,0,0,0,1},
  {1,0,0,1,0,0,0,0,0,0,1,1,1,1,1},
  {1,0,0,0,0,0,0,0,0,0,0,0,0,0,1},
  {1,0,0,0,0,0,0,0,0,0,0,0,0,0,1},
  {1,0,0,0,0,0,0,0,0,0,0,0,0,0,1},
  {1,0,0,0,0,0,0,0,0,0,0,0,0,0,1},
  {1,0,0,0,0,0,0,0,0,0,0,0,0,0,1},
  {1,0,0,0,0,0,0,0,0,0,0,0,0,0,1},
  {1,0,0,0,0,0,0,0,0,0,0,0,0,0,1},
  {1,0,0,0,0,0,0,0,0,0,0,0,0,0,1},
  {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}
};

double posX = 13.0, posY = 7.0, posZ = 0;
double dirX = -1.0, dirY = 0.0, planeX = 0.0, planeY = 0.66;
double speedVar = 0.50, rotSpeedVar = 0.1;

void setup() {
  tft.begin();
  tft.setRotation(1);
  Serial.begin(115200);

  pinMode(BUTTON_UP, INPUT_PULLUP);
  pinMode(BUTTON_DOWN, INPUT_PULLUP);
  pinMode(BUTTON_LEFT, INPUT_PULLUP);
  pinMode(BUTTON_RIGHT, INPUT_PULLUP);
}

void loop() {
  handleInput();
  movePlayer(1);
  renderWalls();

}
// Button states
bool upPressed = false, downPressed = false, leftPressed = false, rightPressed = false;

void handleInput() {
  // Read button states
  upPressed = !digitalRead(BUTTON_UP);
  downPressed = !digitalRead(BUTTON_DOWN);
  leftPressed = !digitalRead(BUTTON_LEFT);
  rightPressed = !digitalRead(BUTTON_RIGHT);

  // Update player position based on button presses
  if (upPressed) {
    posY -= speedVar;
    dirY = cos(rotSpeedVar) * dirY - sin(rotSpeedVar) * dirX;
    dirX = sin(rotSpeedVar) * dirY + cos(rotSpeedVar) * dirX;
  }
  if (downPressed) {
    posY += speedVar;
    dirY = cos(-rotSpeedVar) * dirY - sin(-rotSpeedVar) * dirX;
    dirX = sin(-rotSpeedVar) * dirY + cos(-rotSpeedVar) * dirX;
  }
  if (leftPressed) {
    posX -= speedVar;
    dirX = cos(rotSpeedVar) * dirX - sin(rotSpeedVar) * dirY;
    dirY = sin(rotSpeedVar) * dirX + cos(rotSpeedVar) * dirY;
  }
  if (rightPressed) {
    posX += speedVar;
    dirX = cos(-rotSpeedVar) * dirX - sin(-rotSpeedVar) * dirY;
    dirY = sin(-rotSpeedVar) * dirX + cos(-rotSpeedVar) * dirY;
  }
}

   void movePlayer(double deltaTime) {
   //Ensure the player stays within the map boundaries
    posX = constrain(posX, 0.0, double(MAP_WIDTH - 1));
    posY = constrain(posY, 0.0, double(MAP_HEIGHT - 1));
    }

void renderWalls() {
  tft.fillScreen(ILI9341_BLACK);

  for (int x = 0; x < TFT_WIDTH; ++x) {
    double cameraX = 2 * x / double(TFT_WIDTH) - 1;
    double rayDirX = dirX + planeX * cameraX;
    double rayDirY = dirY + planeY * cameraX;

    int mapX = int(posX);
    int mapY = int(posY);

    double deltaDistX = abs(1 / rayDirX);
    double deltaDistY = abs(1 / rayDirY);

    int stepX, stepY;
    double sideDistX, sideDistY;

    if (rayDirX < 0) {
      stepX = -1;
      sideDistX = (posX - mapX) * deltaDistX;
    } else {
      stepX = 1;
      sideDistX = (mapX + 1.0 - posX) * deltaDistX;
    }

    if (rayDirY < 0) {
      stepY = -1;
      sideDistY = (posY - mapY) * deltaDistY;
    } else {
      stepY = 1;
      sideDistY = (mapY + 1.0 - posY) * deltaDistY;
    }

    bool hit = false;
    int side;
    while (!hit) {
      if (sideDistX < sideDistY) {
        sideDistX += deltaDistX;
        mapX += stepX;
        side = 0;
      } else {
        sideDistY += deltaDistY;
        mapY += stepY;
        side = 1;
      }
      if (worldMap[mapX][mapY] > 0) hit = true;
    }

    // Calculate perpendicular distance to wall
    double perpWallDist;
    if (side == 0) {
      perpWallDist = fabs((mapX - posX + (1 - stepX) / 2) / rayDirX);
    } else {
      perpWallDist = fabs((mapY - posY + (1 - stepY) / 2) / rayDirY);
    }

    // Calculate wall height
    int lineHeight = int(TFT_HEIGHT / perpWallDist);

    // Calculate draw start and draw end
    int drawStart = max(0, -lineHeight / 2 + TFT_HEIGHT / 2);
    int drawEnd = min(TFT_HEIGHT - 1, lineHeight / 2 + TFT_HEIGHT / 2);

    // Draw the wall slice
    int color = (worldMap[mapX][mapY] == 1) ? ILI9341_RED : ILI9341_WHITE;
    tft.drawFastVLine(x, drawStart, drawEnd - drawStart + 1, color);
  }
}

Any answer will be grately appreciated

You seem to confuse a few things here, therefore first a few questions: Do you want the buttons to move the character in first-person manner or in a global context (should "up" mean "move forward" or "move to the north")? What's the meaning of the dirX and dirY variables? You want to change position, not direction, I suppose?

Your button actions look confusing, as if they each do both translation and rotation. Also, it looks like you only wired the UP button. For some reason, Wokwi reads the other three buttons as LOW (pressed).

add debug code to your program

the wokwi code works ... the player moves backward

And I don't want that I want it so that the player will only move when a push button is pressed

Arduino SE is a Q&A site. you seek project guidance. for that forum.arduino.cc is better


text:
write me an arduino code that will send a message using gsm module(Sim800L) when a buzer is sounding (active)
I tapped a high signal from a buzzer, i need an arduino uno code that will send a message using gsm module(Sim800L) when the buzer is alarming (active).

what is your question?

start by writing a program that turns on an LED ... when that works then write a program that turns on an LED when buzzer sounds