Skip to content

Commit f5ddfa8

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

File tree

1 file changed

+79
-3
lines changed

1 file changed

+79
-3
lines changed

Diff for: cores/arduino/wiring_pulse.cpp

+79-3
Original file line numberDiff line numberDiff line change
@@ -190,6 +190,84 @@ unsigned long pulseIn(PinName pin, PinStatus state, unsigned long timeout)
190190
return pulseTime;
191191
}
192192

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

0 commit comments

Comments
 (0)