Skip to content

Commit f652e5e

Browse files
committed
Implement micros() based pulseIn
For Portenta and RP2040 targets Works in interrupts() / noInterrupts() section too
1 parent 8045678 commit f652e5e

File tree

1 file changed

+77
-3
lines changed

1 file changed

+77
-3
lines changed

cores/arduino/wiring_pulse.cpp

Lines changed: 77 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -190,6 +190,82 @@ unsigned long pulseIn(PinName pin, PinStatus state, unsigned long timeout)
190190
return pulseTime;
191191
}
192192

193+
194+
#elif defined(TARGET_RP2040)
195+
196+
unsigned long pulseIn(PinName pin, PinStatus state, unsigned long timeout)
197+
{
198+
unsigned long startMicros = micros();
199+
200+
// wait for any previous pulse to end
201+
while (gpio_get(pin) == state) {
202+
tight_loop_contents();
203+
if (micros() - startMicros > timeout)
204+
return 0;
205+
}
206+
207+
// wait for the pulse to start
208+
while (gpio_get(pin) != state) {
209+
tight_loop_contents();
210+
if (micros() - startMicros > timeout)
211+
return 0;
212+
}
213+
214+
unsigned long start = micros();
215+
// wait for the pulse to stop
216+
while (gpio_get(pin) == state) {
217+
tight_loop_contents();
218+
if (micros() - startMicros > timeout)
219+
return 0;
220+
}
221+
return micros() - start;
222+
}
223+
224+
#elif defined(TARGET_STM32H7)
225+
226+
extern "C" {
227+
#include "gpio_api.h"
228+
GPIO_TypeDef *Set_GPIO_Clock(uint32_t port_idx);
229+
}
230+
231+
#include "pinDefinitions.h"
232+
233+
unsigned long pulseIn(PinName pin, PinStatus state, unsigned long timeout)
234+
{
235+
236+
uint32_t port_index = STM_PORT(pin);
237+
GPIO_TypeDef *gpio = Set_GPIO_Clock(port_index);
238+
239+
volatile uint32_t *reg_in = &gpio->IDR;
240+
uint32_t mask = gpio_set(pin);
241+
242+
unsigned long startMicros = micros();
243+
244+
// wait for any previous pulse to end
245+
while ((*reg_in & mask) == state) {
246+
if (micros() - startMicros > timeout)
247+
return 0;
248+
}
249+
250+
// wait for the pulse to start
251+
while ((*reg_in & mask) != state) {
252+
if (micros() - startMicros > timeout)
253+
return 0;
254+
}
255+
256+
unsigned long start = micros();
257+
// wait for the pulse to stop
258+
while ((*reg_in & mask) == state) {
259+
if (micros() - startMicros > timeout)
260+
return 0;
261+
}
262+
return micros() - start;
263+
}
264+
265+
#endif
266+
267+
// generic, overloaded implementations
268+
193269
unsigned long pulseIn(uint8_t pin, uint8_t state, unsigned long timeout)
194270
{
195271
return pulseIn(digitalPinToPinName(pin), (PinStatus)state, timeout);
@@ -203,6 +279,4 @@ unsigned long pulseInLong(uint8_t pin, uint8_t state, unsigned long timeout)
203279
unsigned long pulseInLong(PinName pin, PinStatus state, unsigned long timeout)
204280
{
205281
return pulseIn(pin, state, timeout);
206-
}
207-
208-
#endif
282+
}

0 commit comments

Comments
 (0)