Press enter to see results or esc to cancel.

PWM read

This is a short continuation of an article about PWM. Here we will upgrade our knowledge and see how microcontrollers read PWM signals.

There are some devices such as drone controllers that output a PWM signal which we would like to read. As mentioned in article about PWM, it works based on timers which control when GPIO output is high or low. We can reverse this logic and use timers to count how long the signal is high or low. In the world of Arduino there is a function that can help with some basic projects. It is called pulseIn() and it only measures how long a signal is high or low – not the whole duty cycle. Its capability is to measure signals from 10 microseconds to 3 minutes and its outputs result in microseconds.

Give me the code

The example below shows how simple this function is. All you have to do is connect the PWM device to Arduino “analog” pin, e.g. pin 7 and define if you would like to measure high or low values of the PWM signal. It is good to know the frequency of the measured signal: if you don’t know it then use an oscilloscope or read the value using Arduino when you expect it to be at its maximum level.

Arduino PWM read example:

int pin = 7;  // we are using pin 7 to read PWM
unsigned long length;

void setup() {
  Serial.begin(9600);  // set up serial monitor
  pinMode(pin, INPUT);  // set pin 7 as input
}

void loop() {
  length= pulseIn(pin, HIGH);  // read high value of PWM signal
  // bonus -> 1000 = how long should it wait for new pulse
  // duration = pulseIn(pin, HIGH,1000);
  Serial.println(length);
}

That was short and sweet wasn’t it? Now go ahead and get your teeth into timers. 🙂

I promise no spam. 😉