Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Kc868 Read Pwm input
#8
on the TOP-RIGHT photo, there label IO-1 and IO-2 you can use. they are GPIO32, GPIO33.

To read a PWM signal on a specific pin of the ESP32, you can't directly capture the PWM signal as an input in hardware. However, you can use the pulseIn() function in code to measure the high and low durations of the PWM signal, and from there, calculate the frequency and duty cycle.

Method: Use pulseIn() to Capture the PWM Signal
ESP32 offers the pulseIn() function, which allows you to measure the duration of a high or low pulse on a pin. By measuring both the high and low durations, you can calculate the PWM duty cycle and frequency.

Example Code
Here's a simple code example using pulseIn() to measure the PWM signal:
Code:
int pwmPin = 32; // Assume PWM input is connected to GPIO 32

void setup() {
  Serial.begin(115200);
  pinMode(pwmPin, INPUT);
}

void loop() {
  // Measure the high time (in microseconds)
  unsigned long highDuration = pulseIn(pwmPin, HIGH);
  // Measure the low time (in microseconds)
  unsigned long lowDuration = pulseIn(pwmPin, LOW);
 
  // Calculate the total period
  unsigned long period = highDuration + lowDuration;

  // Calculate the duty cycle (percentage)
  float dutyCycle = (float)highDuration / period * 100;

  // Calculate the frequency (Hz)
  float frequency = 1000000.0 / period;

  // Print the results
  Serial.print("Frequency: ");
  Serial.print(frequency);
  Serial.print(" Hz, Duty Cycle: ");
  Serial.print(dutyCycle);
  Serial.println(" %");

  delay(1000); // Print every second
}
Explanation of the Code
pulseIn(pwmPin, HIGH): Measures the duration the pin stays HIGH in microseconds.
pulseIn(pwmPin, LOW): Measures the duration the pin stays LOW.
Adding both high and low durations gives the total period, from which you can calculate the frequency.
The duty cycle is computed by dividing the high duration by the total period and multiplying by 100 to get a percentage.
Reply


Messages In This Thread
Kc868 Read Pwm input - by huntleight - 09-30-2024, 09:42 PM
RE: Kc868 Read Pwm input - by admin - 10-01-2024, 02:42 AM
RE: Kc868 Read Pwm input - by huntleight - 10-01-2024, 04:45 AM
RE: Kc868 Read Pwm input - by admin - 10-01-2024, 05:40 AM
RE: Kc868 Read Pwm input - by huntleight - 10-01-2024, 07:46 AM
RE: Kc868 Read Pwm input - by admin - 10-01-2024, 08:32 AM
RE: Kc868 Read Pwm input - by huntleight - 10-01-2024, 03:41 PM
RE: Kc868 Read Pwm input - by admin - 10-01-2024, 10:20 PM

Forum Jump:


Users browsing this thread:
1 Guest(s)