Skip to content

Commit 5fcfbfe

Browse files
committed
FEAT pwm sensor can be blocking or nonblocking
1 parent a3741bf commit 5fcfbfe

File tree

2 files changed

+17
-6
lines changed

2 files changed

+17
-6
lines changed

src/sensors/MagneticSensorPWM.cpp

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -14,15 +14,19 @@ MagneticSensorPWM::MagneticSensorPWM(uint8_t _pinPWM, int _min_raw_count, int _m
1414
min_raw_count = _min_raw_count;
1515
max_raw_count = _max_raw_count;
1616

17-
pinMode(pinPWM, INPUT);
17+
// define if the sensor uses interrupts
18+
is_interrupt_based = false;
1819

19-
// init last call
20+
// define as not set
2021
last_call_us = _micros();
2122
}
2223

2324

2425
void MagneticSensorPWM::init(){
2526

27+
// initial hardware
28+
pinMode(pinPWM, INPUT);
29+
2630
// velocity calculation init
2731
angle_prev = 0;
2832
velocity_calc_timestamp = _micros();
@@ -66,10 +70,9 @@ float MagneticSensorPWM::getVelocity(){
6670

6771
// read the raw counter of the magnetic sensor
6872
int MagneticSensorPWM::getRawCount(){
69-
#if defined(__AVR_ATmega328P__) || defined(__AVR_ATmega168__) || defined(__AVR_ATmega328PB__) || defined(__AVR_ATmega2560__) // if mcu is not atmega328 && if mcu is not atmega2560
70-
pulse_length_us = pulseIn(pinPWM, HIGH);
71-
#endif
72-
73+
if (!is_interrupt_based){ // if it's not interrupt based read the value in a blocking way
74+
pulse_length_us = pulseIn(pinPWM, HIGH);
75+
}
7376
return pulse_length_us;
7477
}
7578

@@ -83,11 +86,15 @@ void MagneticSensorPWM::handlePWM() {
8386

8487
// save the currrent timestamp for the next call
8588
last_call_us = now_us;
89+
is_interrupt_based = true; // set the flag to true
8690
}
8791

8892
// function enabling hardware interrupts of the for the callback provided
8993
// if callback is not provided then the interrupt is not enabled
9094
void MagneticSensorPWM::enableInterrupt(void (*doPWM)()){
95+
// declare it's interrupt based
96+
is_interrupt_based = true;
97+
9198
#if !defined(__AVR_ATmega328P__) && !defined(__AVR_ATmega168__) && !defined(__AVR_ATmega328PB__) && !defined(__AVR_ATmega2560__) // if mcu is not atmega328 && if mcu is not atmega2560
9299
// enable interrupts on pwm input pin
93100
attachInterrupt(digitalPinToInterrupt(pinPWM), doPWM, CHANGE);

src/sensors/MagneticSensorPWM.h

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,10 @@ class MagneticSensorPWM: public Sensor{
3838
int min_raw_count;
3939
int max_raw_count;
4040
int cpr;
41+
42+
// flag saying if the readings are interrupt based or not
43+
bool is_interrupt_based;
44+
4145
int read();
4246

4347
/**

0 commit comments

Comments
 (0)