text:
Capturing frequency using a photodiode
I've just bought the following photodiode (here) and I am trying to make a simple Arduino circuit/code so that the photodiode is able to record an LED blinking at an arbitrary refresh rate (frequency).
I have an Arduino Uno driving the sensor, and a Raspberry Pi driving the LED at a given frequency.
I would like some help as my knowledge in signal processing is minimal, and I would appreciate any feedback or tips on whether what I am doing is correct or not.
Here is the Arduino code:
CODE UPDATED!!
//#include <TimerOne.h>
#include <Arduino.h>

const unsigned long ONESEC = 1000000; // microseconds
const int size = 600;
int sensorValue[size];
int dly = 1000000 / size; // delay so to fill N samples during 1 complete second (1,000,000 microseconds)

int maxValue = 0;
int minValue = 1000000;
double Alpha = 0.1; // [0.0 - 1.0] weight parameter
double filteredValue = 0.0;
double prevValue = 0.0;
double avgsum = 0.0;

int total = 0;
int avgtotal = 0;
const int s = 10;
int rounds = size / s;
int tmparr[s];

const int btnPin = 7;
const int sensorPin = A0;  // sensor pin

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

  // init tmparr
  for(int i=0;i<s;i++){
    tmparr[i] = 0;
  }
}

void waitForButton(int btnPin){
  Serial.println("Waiting...");
  while(digitalRead(btnPin) != 1){
    continue;
    }
  Serial.println("Button has been pressed!");
}

void loop() {  // code that loops forever

  int i = 0;
  unsigned long curTime = micros();
  unsigned long prevTime, startTime;
  prevTime = curTime;
  startTime = curTime;
  while(curTime - startTime <= ONESEC){ // sofar the time between the current and the start time is less than 1 second, keep recording data
    if(curTime - prevTime < dly){ // sofar the current and the previous time stamp has a differene of less than N seconds, do not record anything
      curTime = micros();
      continue;
    }
    sensorValue[i++] = analogRead(sensorPin);

    if(i > size){
      break;
    }
    prevTime = curTime;
    curTime = micros();
  }

  ///////////////////////
  ///////////////////////
  // Data processing ////
  ///////////////////////
  ///////////////////////

  // filter the signal and find maximum/minimum and avg

  for(int i=0;i<size;i++){
    int v = sensorValue[i];
    filteredValue = (v * Alpha) + (prevValue * (1-Alpha)); // exponential filtering
    sensorValue[i] = filteredValue; // re-writing the sensor data !! RAW DATA ARE BEING OVERWRITTEN !!
    avgsum = avgsum + filteredValue;
    prevValue = filteredValue;

    if(maxValue < filteredValue){
      maxValue = filteredValue;
    }
    if(minValue > filteredValue){
      minValue = filteredValue;
    }
  }
  avgsum = avgsum / size;

  // plotting and segregating the signal
  int peaks = 0;
  int prevState = -1;

  for(int i=0;i<rounds;i++){
    for(int j=0;j<s;j++){
      int v = sensorValue[(i*s)+j];
      total = total - tmparr[j];
      total = total + v;
      avgtotal = total / s;
      tmparr[j] = v;
      Serial.print(avgtotal); // new filtered value
      Serial.print(",");
      Serial.print(avgsum);
      Serial.print(",");
      Serial.println(v); // filtered value

      if(avgtotal > avgsum + (avgsum*0.01)){
        // Serial.println(1);
        if(prevState != 1){
          peaks++;
          prevState = 1;
        }
      }
      else{
        // Serial.println(0);
        prevState = 0;
      }
    }
  }
  Serial.print("peaks:");
  Serial.println(peaks);

}

So far I am getting somewhere close I guess.
Down are some of the recorded measurements. Filtering the signal, I suspect, is not optimal to make clear distinction between peaks and trough in the signal.
Also I am not sure if the shape of the signal is proper representation of the actual input signal given that the filtering influence that in a way or another based on the used parameters.
Any tips for what I should do and how I should proceed to make it more reliable and accurate?

Update 1:
Here is the Pi code:
import RPi.GPIO as GPIO # Import Raspberry Pi GPIO library
from time import sleep # Import the sleep function from the time module

GPIO.setwarnings(False) # Ignore warning for now
GPIO.setmode(GPIO.BOARD) # Use physical pin numbering
GPIO.setup(8, GPIO.OUT, initial=GPIO.LOW) # Set pin 8 to be an output pin and set initial value to low (off)

freq = 5.0 # Hz
cycle = 1.0/freq
hcycle = cycle / 2.0

while True: # Run forever
 GPIO.output(8, GPIO.HIGH) # Turn on
 sleep(hcycle) # Sleep for N second
 GPIO.output(8, GPIO.LOW) # Turn off
 sleep(hcycle)

Update 2:
After updating the code, for very low frequencies I get kinda nicely shaped-signal
example of 5 Hz signal

Things start to get messier with high frequency (not that high) at 30 Hz for instance, where trying to segregate the signal based on the total average line does not result in informative value for how many peaks and troughs there are, for several peaks can be under the lines and several troughs can be above the line. Output reads 25 peaks here.
so I am starting to think that the filtering technique I am using maybe is not the best. Any suggestions?

If you are seeing 1 extra peak at 15 Hz, and then 3 extra at 50 Hz (3x15 ~ 50), so at least it is consistent. You haven't posted your Pi code, which may or may not have an issue. Are you sure the Pi is flashing at 15 Hz and not 16 Hz? Maybe try 5 Hz to see if that is more accurate, and then slowly ramp up the rate. Have you tried flashing the LED using the Arduino (maybe by using interrupts) to see if the number of peaks change (or become more accurate)..?

I've just updated the question with some info, please check.
I am very new to all this circuitry and I was not sure how to use the LED and the sensor simultaneously to measure the LED flashing as both would be sequential in the same loop(), so I decided to use another circuit to control the LED.

Could you update the units on the figures? Are you sure you are taking measurements every second? Or what is your time-scale like?

Why are you doing an analog read on what is basically a digital input? The LED is on, or off isn't it?

@NickGammon I am not interested in the LED per se, it is here only as a mean to test how to do proper reading using a photodiode sensor which has an analogue input

@NickS. I have just updated the code using a different strategy for capturing data over EXACTLY one second. please have a look

What are we looking at here? What is that red line?

the legend is mentioned in the figure above each in thier corresponding color

Consider this loop:
for(int i=0; i< size;i++){
  // Read sensor value
  sensorValue[i] = analogRead(sensorPin);
  // wait between readings for N microseconds
  delayMicroseconds(dly);
}

The time taken by each iteration is the sum of the times taken by each
individual operation (compare i to size, read the ADC, delay,
increment i and jump to the start of the loop). Other than the delay,
the longest operation here is analogRead(), as it blocks in a busy
loop while the ADC performs its conversion. This can take anywhere
between 104 µs and 112 µs. Even neglecting everything but
analogRead() and delayMicroseconds(), you expect your loop to be
about 6–7% too slow.
You should get better timings if you use micros() instead of
delayMicroseconds(). Check the Arduino tutorial “Blink without delay”
to see how you can manage your timings without delaying. You still won't
get metrology-class timings though, as micros() is only as good as the
ceramic resonator clocking your Uno, which should be roughly 0.1%
accurate in its frequency. If you need anything better, you will have to
find a better frequency standard.

Edit: Addressing the updated question.
There are a few issues I would like to address:
First, the way the updated code handles the acquisition timing is a bit
convoluted. Furthermore, updating the time with prevTime = curTime; is
prone to timing drift: you cannot count on curTime being exactly the
time at which the ADC reading was scheduled, it can be a few
microseconds later. Actually, curTime will always be later, as the
acquisition period (1,666 µs) is not a multiple of the micros()
resolution (4 µs). This timing drift can be avoided by making
prevTime represent the time when the previous acquisition was
scheduled (not when it was performed):
// Data acquisition.
unsigned long prevTime = micros();
for (int i = 0; i < size; i++) {
    while (micros() - prevTime < dly) continue;  // wait until it's time
    prevTime += dly;                         // update scheduled time
    sensorValue[i] = analogRead(sensorPin);  // acquire data
}

The limited resolution of micros() will still cause some jitter, but
updating with prevTime += dly; ensures there is no systematic drift.
Second, I would avoid doing any kind of filtering on the Arduino itself.
If the data is meant to be transferred to the PC anyway, just transfer
the raw data. This gives you the chance of processing it on your PC,
interactively experimenting with different types of filters, with the
comfort of your favorite programming language or data-processing
package. If the complete project requires the filtering to be done on
the Arduino, do that later, once you have found the most appropriate
filter on the PC.
Third, as filtering goes, you seem to have a lot of 50 Hz noise
here. Maybe the noise is already present in the luminous flux, or maybe
it is introduced somewhere between the photodiode and the Arduino. I
would check the cabling to see whether there is a way to reduce
inductive noise pickup. Are you using long cables between the photodiode
and the Arduino? If so, is that a twisted pair? Is everything properly
grounded? Are there any ground loops?
If you cannot get rid of the mains noise at the source, it will be very
difficult to identify signals that are anywhere close to 50 Hz, as
your 30 Hz experiment shows. You may want to try a notch filter
specifically tuned to kill any 50 Hz component.
Fourth, you may want to try, at least once, to acquire at a faster rate:
let's say with a 200 µs period. If that acquisition reveals a lot
of high-frequency noise, then it may be worth using some decimating
filter. For example, you could store, in each array position, the sum of
eight samples taken at 200 µs intervals. That should give less
noisy data, with a period of 1.6 ms per array cell (round value
close to the current 1.666 ms). Note that this technique will be
absolutely useless against 50 Hz noise though.
Fifth, it is possible to trigger the ADC from a timer, which gives very
accurate and consistent timing. This, however, requires low-level
programming, and digging into the ATmega datasheet. I would not care
about perfect timings now, at least not until the above issues are
fixed. It is, however, a possibility you may want to keep in mind in
case in the future you want to get the best possible timings.

thanks for the tip. I have just updated the code using the suggested method for capturing data within 1 second. But my main inquiry about how to process the recorded signal so to make informative reading out of it is still confusing me

@wisdom This isn't really a forum, and making major edits to your question in response to answers is trying to turn it into one. I think your original question has been answered, and further questions about such things as processing the signal should really be turned into new questions in their own right. Otherwise this particular thread will become quite confusing to read. Amended questions / amended answers, don't make for a good reading flow.

Counting in a loop like that is fine if you have a very low frequency signal, and are getting the hang of how loops, and reading from input pins, work. But there will be a lot of overheads. As Edgar Bonet points out in his answer there can be an overhead of between 104 µs and 112 µs for doing an analogRead call. Plus the overhead of the loop. And the delay won't be accurate to the microsecond. All this adds up.
There are two ways you can find a frequency:

Count "ticks" over a known interval. For example, counting 50 ticks over a second would give you 50 Hz.

Measure the period. In other words, find out how long elapses between a rising edge and a falling edge (and double that time). For example for 50 Hz the period would be 20 ms (1 / 50).

As I mention on my page about timers there are ways of doing that. To avoid giving a link-only answer I'll paste some of that code.
Count pulses
// Timer and Counter example
// Author: Nick Gammon
// Date: 17th January 2012

// Input: Pin D5

// these are checked for in the main program
volatile unsigned long timerCounts;
volatile boolean counterReady;

// internal to counting routine
unsigned long overflowCount;
unsigned int timerTicks;
unsigned int timerPeriod;

void startCounting (unsigned int ms)
  {
  counterReady = false;         // time not up yet
  timerPeriod = ms;             // how many 1 ms counts to do
  timerTicks = 0;               // reset interrupt counter
  overflowCount = 0;            // no overflows yet

  // reset Timer 1 and Timer 2
  TCCR1A = 0;
  TCCR1B = 0;
  TCCR2A = 0;
  TCCR2B = 0;

  // Timer 1 - counts events on pin D5
  TIMSK1 = bit (TOIE1);   // interrupt on Timer 1 overflow

  // Timer 2 - gives us our 1 ms counting interval
  // 16 MHz clock (62.5 ns per tick) - prescaled by 128
  //  counter increments every 8 µs.
  // So we count 125 of them, giving exactly 1000 µs (1 ms)
  TCCR2A = bit (WGM21) ;   // CTC mode
  OCR2A  = 124;            // count up to 125  (zero relative!!!!)

  // Timer 2 - interrupt on match (ie. every 1 ms)
  TIMSK2 = bit (OCIE2A);   // enable Timer2 Interrupt

  TCNT1 = 0;      // Both counters to zero
  TCNT2 = 0;

  // Reset prescalers
  GTCCR = bit (PSRASY);        // reset prescaler now
  // start Timer 2
  TCCR2B =  bit (CS20) | bit (CS22) ;  // prescaler of 128
  // start Timer 1
  // External clock source on T1 pin (D5). Clock on rising edge.
  TCCR1B =  bit (CS10) | bit (CS11) | bit (CS12);
  }  // end of startCounting

ISR (TIMER1_OVF_vect)
  {
  ++overflowCount;               // count number of Counter1 overflows
  }  // end of TIMER1_OVF_vect

//******************************************************************
//  Timer2 Interrupt Service is invoked by hardware Timer 2 every 1 ms = 1000 Hz
//  16Mhz / 128 / 125 = 1000 Hz

ISR (TIMER2_COMPA_vect)
  {
  // grab counter value before it changes any more
  unsigned int timer1CounterValue;
  timer1CounterValue = TCNT1;  // see datasheet, page 117 (accessing 16-bit registers)
  unsigned long overflowCopy = overflowCount;

  // see if we have reached timing period
  if (++timerTicks < timerPeriod)
    return;  // not yet

  // if just missed an overflow
  if ((TIFR1 & bit (TOV1)) && timer1CounterValue < 256)
    overflowCopy++;

  // end of gate time, measurement ready

  TCCR1A = 0;    // stop timer 1
  TCCR1B = 0;

  TCCR2A = 0;    // stop timer 2
  TCCR2B = 0;

  TIMSK1 = 0;    // disable Timer1 Interrupt
  TIMSK2 = 0;    // disable Timer2 Interrupt

  // calculate total count
  timerCounts = (overflowCopy << 16) + timer1CounterValue;  // each overflow is 65536 more
  counterReady = true;              // set global flag for end count period
  }  // end of TIMER2_COMPA_vect

void setup ()
  {
  Serial.begin(115200);
  Serial.println("Frequency Counter");
  } // end of setup

void loop ()
  {
  // stop Timer 0 interrupts from throwing the count out
  byte oldTCCR0A = TCCR0A;
  byte oldTCCR0B = TCCR0B;
  TCCR0A = 0;    // stop timer 0
  TCCR0B = 0;

  startCounting (500);  // how many ms to count for

  while (!counterReady)
     { }  // loop until count over

  // adjust counts by counting interval to give frequency in Hz
  float frq = (timerCounts *  1000.0) / timerPeriod;

  Serial.print ("Frequency: ");
  Serial.print ((unsigned long) frq);
  Serial.println (" Hz.");

  // restart timer 0
  TCCR0A = oldTCCR0A;
  TCCR0B = oldTCCR0B;

  // let serial stuff finish
  delay(200);
  }   // end of loop

This is actually not so great for low frequencies because if the count is out by even one tick, your frequency is wrong by 2%. However it can count accurately (more or less) up to 5 kHz.
Measure the period
The other technique is to measure the period, like this:
// Frequency timer
// Author: Nick Gammon
// Date: 10th February 2012

// Input: Pin D2

volatile boolean first;
volatile boolean triggered;
volatile unsigned long overflowCount;
volatile unsigned long startTime;
volatile unsigned long finishTime;

// here on rising edge
void isr ()
{
  unsigned int counter = TCNT1;  // quickly save it

  // wait until we noticed last one
  if (triggered)
    return;

  if (first)
    {
    startTime = (overflowCount << 16) + counter;
    first = false;
    return;
    }

  finishTime = (overflowCount << 16) + counter;
  triggered = true;
  detachInterrupt(0);
}  // end of isr

// timer overflows (every 65536 counts)
ISR (TIMER1_OVF_vect)
{
  overflowCount++;
}  // end of TIMER1_OVF_vect

void prepareForInterrupts ()
  {
  // get ready for next time
  EIFR = bit (INTF0);  // clear flag for interrupt 0
  first = true;
  triggered = false;  // re-arm for next time
  attachInterrupt(0, isr, RISING);
  }  // end of prepareForInterrupts

void setup ()
  {
  Serial.begin(115200);
  Serial.println("Frequency Counter");

  // reset Timer 1
  TCCR1A = 0;
  TCCR1B = 0;
  // Timer 1 - interrupt on overflow
  TIMSK1 = bit (TOIE1);   // enable Timer1 Interrupt
  // zero it
  TCNT1 = 0;
  overflowCount = 0;
  // start Timer 1
  TCCR1B =  bit (CS10);  //  no prescaling

  // set up for interrupts
  prepareForInterrupts ();

  } // end of setup

void loop ()
  {

  if (!triggered)
    return;

  unsigned long elapsedTime = finishTime - startTime;
  float freq = F_CPU / float (elapsedTime);  // each tick is 62.5 ns at 16 MHz

  Serial.print ("Took: ");
  Serial.print (elapsedTime);
  Serial.print (" counts. ");

  Serial.print ("Frequency: ");
  Serial.print (freq);
  Serial.println (" Hz. ");

  // so we can read it
  delay (500);

  prepareForInterrupts ();
}   // end of loop

This is better for low frequencies. Since this uses hardware timers you need to connect your input up to a specific pin as noted in the code. No doing analog reads, the time taken to do that would swamp any accuracy that you might get.

There is a race in your isr() function: if the timer overflows right before you read TCNT1, TIMER1_OVF_vect will not be called right away (because we are already in interrupt context), and you will miss an overflow.

both codes work brilliantly for LED (though with margin of error up to 6% as I've noticed).... but maybe I was not too clear in my intentions that I strictly want to use a photodiode sensor to read frequencies off displays at the end,  and I am using an LED for now just as a mean of testing and experimenting for how to design the code.

also I am interested in the waveform for how the signal rise and fall regardless of what is the light source (e.g. PC monitor, LED, projector, ...etc.). So I need to use a photodiode for that as well

@EdgarBonet You mean in the second piece of posted code? It looks like you are right. I had the test in TIMER2_COMPA_vect in the first piece of code. You could add that test where it says if ((TIFR1 & bit (TOV1)) && timer1CounterValue < 256) ... into the second one.

@wisdom The measurements should be more accurate than 6%, possibly the test frequency you are sending it  is not all that accurate. You are again using a loop and not a hardware generated frequency, so that the overhead of the loop is likely to affect the overall result. You really want a proper hardware-generated signal for testing, not code running on a processor using a while loop.

ok I see.... last bit of question: am I able to run hardware-generated signal-reading for the photodiode sensor in a way or another? if so could you please just point me to the direction?

Er, other than the code I posted above? My tests of that (first one) had an error of 0.02%. Isn't that good enough?

I understood that your code to be used in place of the photodiode to estimate the frequeny of an incoming signal (i.e. the LED blinking), and when I connected the other end of the LED to the mentioned PIN in your code, your code gives me accurate reading of the frequency of the blinking LED. But I was not sure how to use the photodiode signal instead as input instead of the LED directly so that the sequence is (LED >> Photodiode >> Arduino Pin) for I need to use the photodiode, this is the whole purpose of the question.

A bit of hardware than can turn the photodiode into an on/off signal?


text:
Arduino_DebugUtils.h: No such file or directory
How to get rid of this error?
/storage/emulated/0/ArduinoDroid/userlibraries/Arduino_ConnectionHandler/src/Arduino_ConnectionHandler.h:26:34: fatal error: Arduino_DebugUtils.h: No such file or directory

You need to install the Arduino_DebugUtils library.
From Arduino_DebugUtils:

To use this library, open the Library Manager in the Arduino IDE and install it from there.

source: Stack Exchange

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

sort: votes


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...

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


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:
Problems with reacting to joystick button press
I am trying to use a joystick in a project for device control. Pressing a joystick button should cause incrementing a variable. INPUT_PULLUP mode is used for internal button.
As I understand it, when the button is not pressed there is a HIGH level on the GPIO pin, and there is a LOW level when the button is pressed. The signal read from the button in thd sketch is inverted to HIGH when the circuit is closed.
I used some sketches for eliminating debounce, but in all cases when the button is pressed a stream of incoherent symbols occurs on the serial port. It happens both in the simulator and the IDE.
What can cause this stream on the output when waiting for the message that button is pressed? The symbols also occured when I put a count-variable on the serial port. Does the button debounce look correct?
int Joystick_Y = A0;
int Joystick_X = A1;
int Joystick_but = 1;
int X;
int Y;
int X_prev = 0;
int Y_prev = 0;
int butt_flag = 0;
int butt;

const unsigned long debounceDelay = 50;
unsigned long last_press;

void setup() {
  Serial.begin(9600);
  pinMode(Joystick_but, INPUT_PULLUP);
}

void loop() {
  butt = !digitalRead(Joystick_but);

  if (butt == 1 && butt_flag == 0 && millis() - last_press > debounceDelay) {
    butt_flag = 1;
    last_press = millis();
    Serial.println("Button was pressed!");
  }

  if (butt == 0 && butt_flag == 1) {
    butt_flag = 0;
  }

  Y = analogRead(Joystick_Y);
  X = analogRead(Joystick_X);

  if (X < 512 && X > 485) {
    X = 512;
  }
  if (Y < 512 && Y > 485) {
    Y = 512;
  }

  if ((Y != Y_prev || X != X_prev) && (X != Y)) {
    Serial.print("X: ");
    Serial.print(X);
    Serial.print(" Y: ");
    Serial.println(Y);
  }

  Y_prev = Y;
  X_prev = X;
  delay(500);
}

What Arduino are you using exactly? On Uno/Nano pins 0 and 1 are used for the Serial interface. And the debouncedelay of 50ms won't work, when you delay for 500ms at the end of loop().

As was mentioned in @chrisl 's comment: pin 1 on an Arduino Uno/Nano is the TX (transmit) pin for the Serial port. See here. This is the pin that is used to transmit serial data to the host.
When the same pin is also used as the joystick button, pressing it will interfere with serial output, causing the incoherent symbols you see to be transmitted.
Solution: Use a different (unused) pin.
Another potential problem is the delay (500) at the end of your loop() which, as @chrisl also noted, interferes with your debounce and will cause your code to react to button presses and joystick movements very slowly.


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:
Can't upload to nano esp32
Recently bought a nano esp32 to play around with the small size and wifi module. However I'm plagued by the No DFU capable USB device available message.
My efforts and deductions:

I can connect to my Uno boards just fine.
I have reset the bootloader see here successfully, however it opens a new COM port that after reset is gone
Restarted the IDE, Redownloaded the IDE, made sure it's up to date
Tried numerous cabling (eg. cables for ssd's, charging, etc) nothing seems to work except on that one port  that is opened upon the bootloader reset.
The arduino IDE will identify a port (in my case COM 9) and recognize it, however returns this error
I have done the double tap on the RST button
I have made sure that the esp32 is selected and the dependencies for it is installed
I am using just a simple web server sketch
As far as I can tell theres the port that its being picked up as and the actual port it should be on, however the IDE rarely detects it and if it does its only for a moment and is incredibly inconsistent

I am new to this IoT world so there's most likely an oversight on my part but please try to be kind and not stack overflow me into oblivion :D
I should note that I am just trying to upload anything to the nano esp32without this error occurring
Sketch uses 721325 bytes (22%) of program storage space. Maximum is 3145728 bytes.
Global variables use 56580 bytes (17%) of dynamic memory, leaving 271100 bytes for local variables. Maximum is 327680 bytes.
dfu-util 0.11-arduino4

Copyright 2005-2009 Weston Schmidt, Harald Welte and OpenMoko Inc.
Copyright 2010-2021 Tormod Volden and Stefan Schmidt
This program is Free Software and has ABSOLUTELY NO WARRANTY
Please report bugs to http://sourceforge.net/p/dfu-util/tickets/

Cannot open DFU device 2341:0070 found on devnum 20 (LIBUSB_ERROR_NOT_FOUND)
No DFU capable USB device available
Failed uploading: uploading error: exit status 74


text:
Serial.println printing just after the previous string in same line
I wrote serial.println in my code but the string was printed in same line on serial moniter.
#include <WiFi.h>//for connecting esp32 to a wifi

#include <TinyGPS++.h>//to obtain gps data from neo-6m gps module

#define WIFI_SSID "Airtel_pawa_4182"//wifi name in simple words
#define WIFI_PWD "Ahuja6230"//wifi password

TinyGPSPlus GPS;//creating a gps object from tinygps++ library

void setup() {
 Serial.begin(9600);
  //wifi setup{
  WiFi.begin(WIFI_SSID, WIFI_PWD);
  Serial.println("connecting to wifi");
  while(WiFi.status() != WL_CONNECTED){
   Serial.println(".");
   delay(1000);
  }
  Serial.println("Successfully connected to ");
  Serial.print(WIFI_SSID);
  //}

  //gps setup{
  Serial2.begin(9600);
  delay(1000);
  Serial.println("ESP32-GPS Tracker");
  Serial.println("Initializing...");
  //}
}

void loop() {
}

In this code the string "esp32-gps tracker" is printing just after the previous string in same line on serial moniter.
I tried running code again and again but it didn't work...
I am using esp32 board(just a detail)
What do i do?

You need to be way more specific for your question to be answerable. Same line? Same as what? Please, post a minimal testable sketch showing the issue, tell us what you expected as an output, and tell us what the actual output was.

@EdgarBonet done

The previous print statements are these:
  Serial.println("Successfully connected to ");
  Serial.print(WIFI_SSID);

The SSID won't be terminated by a newline. Perhaps you meant:
  Serial.print("Successfully connected to ");
  Serial.println(WIFI_SSID);

?

To follow on from previous answer, your solution is to either:

change the previous Serial.print() to a Serial.println() so that that text is followed by a line end, or
add a \n to the front of the line you are having the problem with, so it starts with a new line, to make up for the "missing" new line in the previous Serial.print().

For consistency with what Serial.println() does, you should add "\r\n", not only '\n'. If you ever use a terminal emulator instead of the Arduino serial monitor, a bare '\n' will likely move the cursor one line down while staying on the same column.

Depends on your operating system. In Linux a newline advances to the start of a new line. On Windows YMMV. It's very common in Linux code to use \n for a newline when outputting and not \r\n, which may in fact put some weird character (the carriage-return character) in your terminal window.

@NickGammon: On a Linux terminal, a \n alone is a vertical-only cursor movement. When a program outputs \n, the tty driver converts it to \r\n before it reaches the terminal. This should become clear if you try to use a terminal with this output post-processing disabled (stty -opost). A serial communication program like picocom, by default, disables all tty driver processing: the bytes from the Arduino reach the terminal unaltered. This plays well with Serial.println(), as it ends the line with \r\n.

When sending text through a serial line, it is customary to
terminate each line with some sort of end-of-line marker: you print
some text, and immediately after it the EOL to signify that “this is
now a complete line”. Accordingly, the Serial.println() method prints
the requested text, immediately followed by the EOL marker (in this
case, CR+LF).
From your question, you seem to be thinking that the EOL immediately
precedes the text. This is not the case.
See JRobert's answer for the correct way to build a line from multiple
print statements: println() should be use on the last piece, not on
the first one.

Yes. Nice explanation. Now I know where I mistook. I thought that by using "print.ln()", the string will be printed in new line(I got this info from google). But it isn't like that print.ln is for terminating a line and starting a new line

Jrobert's comment was the first one to mark my mistake so I declared it as answer. But I also thank you for the explanation

@YugAhuja println not print.ln you need to be very specific when coding.


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:
GPS Module not catching signal

I am making a gps tracker with neo6m gps module and esp32 dev board.
I checked wiring and coding but still my module isn't catching a signal
I am already on roof of my house in case it require clear sky to connect
This is my code
#include <WiFi.h>//for connecting esp32 to a wifi

#include <TinyGPS++.h>//to obtain gps data from neo-6m gps module

#define WIFI_SSID "Airtel_pawa_4182"//wifi name in simple words
#define WIFI_PWD "Ahuja6230"//wifi password

TinyGPSPlus GPS;//creating a gps object from tinygps++ library

void setup() {
 Serial.begin(9600);
  //wifi setup{
  WiFi.begin(WIFI_SSID, WIFI_PWD);
  Serial.println("connecting to wifi");
  while(WiFi.status() != WL_CONNECTED){
   Serial.println(".");
   delay(100);
  }
  Serial.print("Successfully connected to ");
  Serial.println(WIFI_SSID);
  //}

  //gps setup{
  Serial2.begin(9600);
  delay(1000);
  Serial.println(".");
  Serial.println("ESP32-GPS Tracker");
  Serial.println("Initializing...");
  //}
}

void loop() {
  if(Serial2.available() > 0) {
    if(GPS.encode(Serial2.read())) {
      if(GPS.location.isValid()) {
        double latitude = GPS.location.lat();
        double longitude = GPS.location.lng();

        Serial.print(F("- latitude: "));
        Serial.println(latitude);

        Serial.print(F("- longitude: "));
        Serial.println(longitude);
      }
      else{
        Serial.println(F("- location: INVALID"));
      }
      Serial.println();
    }
  }
  if (millis() > 5000 && GPS.charsProcessed() < 10) {
    Serial.println(F("No GPS data received: check wiring"));
  }
}

The connection is simple
VCC(gps)--->3V3(esp32)

Gnd--->Gnd

Rx---->GPIO17(Tx)

Tx---->GPIO16(Rx)

This is what serial monitor reads:
connecting to wifi
.
.
.
.
.
Successfully connected to Airtel_pawa_4182
.
ESP32-GPS Tracker
Initializing...
No GPS data received: check wiring
No GPS data received: check wiring
No GPS data received: check wiring
No GPS data received: check wiring

How to resolve this issue?
Edit: the breadboard was initially wired wrong but later this was fixed.thanks to Starcat for correcting mistake
But still the gps module is taking very much time to catch signal. When it starts, it first print that no gps data recived for some time then it says location is invalid. Only then it prints the lat. and long.Also, the lat and long are not being updated on serial moniter on time. The delay is just one second but it is taking much more time...
If anybody has a solution then pls answer..

Could you include a picture or a schematic of how your ESP32 and GPS are connected and powered?

@StarCat added picture. I am currently powering it with my laptop

You're using the breadboard wrong. The parts on either side of the center bar of of the breadboard are not connected to each other (see here) so the white and orange wires and the black yellow and wires are not making a connection. Put the wires on the same side of the breadboard and you have a higher change of a working GPS.

@StarCat It worked... It was my first time using mini bread board. I have always used normal sized breadboard that are connected vertically (when placed as landscape), so didn't know that it didn't had connection across the middle bar....

But still the location is showing INVALID for some reason

Nevermind it worked after some tries. Thank you @StarCat but how can I mark your comment as answer?

I've posted my comment as an answer, so you can accept it.

The "No GPS detected" message means that 5 seconds have passed and less than 10 valid characters have arrived at the GPS serial port. Could be a baud rate mismatch.

The breadboard is wired wrong. The parts on either side of the center bar of of the breadboard are not connected to each other (see here), so the white and orange wires and the black yellow and wires are not making a connection.
Solution: Put the wires on the same side of the breadboard and you have a higher change of a working GPS.
You should now at least receive output from the GPS, even if it is just reporting the fact that it has not yet received a valid position. It may take some time (especially when using it for the first time) to get a fix. I would give it at least 30 minutes for the first fix.

It is working but every time I start it, It says no gps data recieved for some time then then the location is invalid and only then it output the latitude and longitude. Also the latitudes and longitudes are updated to serial moniter with much delay even I just added a delay of 1 second in my program... Do you have solution to this?


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