Skip to content

Commit 4f80fe1

Browse files
committed
Added pulseIn function to measure pulse durations.
1 parent c6d860e commit 4f80fe1

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

Diff for: targets/arduino/wiring.c

+33
Original file line numberDiff line numberDiff line change
@@ -366,6 +366,39 @@ void delayMicroseconds(unsigned int us)
366366
sei();
367367
}
368368

369+
/*
370+
unsigned long pulseIn(int pin, int state)
371+
{
372+
unsigned long width = 0;
373+
374+
while (digitalRead(pin) == !state)
375+
;
376+
377+
while (digitalRead(pin) != !state)
378+
width++;
379+
380+
return width * 17 / 2; // convert to microseconds
381+
}
382+
*/
383+
384+
unsigned long pulseIn(int pin, int state)
385+
{
386+
unsigned long width = 0;
387+
int r = port_to_input[digitalPinToPort(pin)];
388+
int bit = digitalPinToBit(pin);
389+
int mask = 1 << bit;
390+
391+
state = (!!state) << bit;
392+
393+
while ((_SFR_IO8(r) & mask) != state)
394+
;
395+
396+
while ((_SFR_IO8(r) & mask) == state)
397+
width++;
398+
399+
return width * (16000000UL / F_CPU) * 20 / 23;
400+
}
401+
369402
int main(void)
370403
{
371404
// this needs to be called before setup() or some functions won't

Diff for: targets/arduino/wiring.h

+1
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,7 @@ unsigned long millis(void);
8282
void delay(unsigned long);
8383
void delay_ms(unsigned short ms);
8484
void delayMicroseconds(unsigned int us);
85+
unsigned long pulseIn(int pin, int state);
8586

8687
void setup(void);
8788
void loop(void);

0 commit comments

Comments
 (0)