Skip to content

Commit d50e109

Browse files
jhmaloneysandeepmistry
authored andcommitted
Map pin number argument to internal pin number using digitalPinToPin
Adjust loop count to microsecond computations
1 parent 772990a commit d50e109

File tree

1 file changed

+13
-15
lines changed

1 file changed

+13
-15
lines changed

cores/nRF5/pulse.c

Lines changed: 13 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -27,27 +27,25 @@ extern unsigned long countPulseASM(const volatile uint32_t *port, uint32_t bit,
2727
* or LOW, the type of pulse to measure. Works on pulses from 2-3 microseconds
2828
* to 3 minutes in length, but must be called at least a few dozen microseconds
2929
* before the start of the pulse. */
30-
uint32_t pulseIn(uint32_t pin, uint32_t state, uint32_t timeout)
30+
uint32_t pulseIn(uint32_t ulPin, uint32_t state, uint32_t timeout)
3131
{
3232
// cache the port and bit of the pin in order to speed up the
3333
// pulse width measuring loop and achieve finer resolution. calling
3434
// digitalRead() instead yields much coarser resolution.
3535
// PinDescription p = g_APinDescription[pin];
36-
uint32_t bit = 1 << pin; //p.ulPin;
36+
uint32_t bit = 1 << digitalPinToPin(ulPin);
3737
uint32_t stateMask = state ? bit : 0;
3838

3939
// convert the timeout from microseconds to a number of times through
40-
// the initial loop; it takes (roughly) 13 clock cycles per iteration.
41-
uint32_t maxloops = microsecondsToClockCycles(timeout) / 13;
42-
43-
uint32_t width = countPulseASM(&(NRF_GPIO->IN), bit, stateMask, maxloops);
44-
45-
// convert the reading to microseconds. The loop has been determined
46-
// to be 13 clock cycles long and have about 16 clocks between the edge
47-
// and the start of the loop. There will be some error introduced by
48-
// the interrupt handlers.
49-
if (width)
50-
return clockCyclesToMicroseconds(width * 13 + 16);
51-
else
52-
return 0;
40+
// the initial loop; it takes (roughly) 10 clock cycles per iteration.
41+
uint32_t maxloops = microsecondsToClockCycles(timeout) / 10;
42+
43+
// count low-level loops during the pulse (or until maxLoops)
44+
// a zero loopCount means that a complete pulse was not detected within the timeout
45+
uint32_t loopCount = countPulseASM(&(NRF_GPIO->IN), bit, stateMask, maxloops);
46+
47+
// convert the reading to (approximate) microseconds. The loop time as measured with an
48+
// oscilloscope is 10 cycles on a BBC micro:bit 1.3 (nRF51822). There is error because the
49+
// time is quantized to an integral number of loops and because interrupt may steal cycles.
50+
return clockCyclesToMicroseconds(10 * loopCount);
5351
}

0 commit comments

Comments
 (0)