11#include "ulEncoder.h"
22#include "drvEncoder.h"
3+ #include "Database/ulDatabase.h"
34
45#include "FreeRTOS.h"
56#include "cmsis_os2.h"
67
78
89#define TICKS_PER_REVOLUTION 820.0f
9- #define MOTORS_CONTROL_PERIOD_MS 20
1010#define MOTORS_COUNT 4
1111
12+ #define TIMER_16_BIT_MAX 0x10000
13+ #define OVERFLOW_THRESHOLD TIMER_16_BIT_MAX / 2
14+
1215
1316static uint32_t lastTicks_RPM [MOTORS_COUNT ];
1417static uint32_t lastTicks_Ethernet [MOTORS_COUNT ];
1518
19+ static uint16_t encoder_period_ms = 5 ;
20+
1621static osTimerId_t encoderTimerHandle ;
1722
1823
24+ static inline int32_t ulEncoder_CalculateDiff (uint32_t current , uint32_t last ) {
25+ int32_t diff = (int32_t )(current - last );
26+
27+ // overflow in 16-bit timer
28+ if (diff < - OVERFLOW_THRESHOLD ) {
29+ diff += TIMER_16_BIT_MAX ;
30+ }
31+ else if (diff > OVERFLOW_THRESHOLD ) {
32+ diff -= TIMER_16_BIT_MAX ;
33+ }
34+
35+ return diff ;
36+ }
37+
1938static void ulEncoder_TimerCallback (void * argument ) {
2039
2140 for (int i = 0 ; i < MOTORS_COUNT ; i ++ ) {
2241 uint32_t currentTicks = drvEncoder_Read (i );
2342 uint32_t lastTicks = lastTicks_RPM [i ];
2443
25- int32_t diff = ( int32_t ) ( currentTicks - lastTicks );
44+ int32_t diff = ulEncoder_CalculateDiff ( currentTicks , lastTicks );
2645
27- float ticks_per_sec = (float ) diff * (1000.0f / MOTORS_CONTROL_PERIOD_MS );
46+ float ticks_per_sec = (float ) diff * (1000.0f / encoder_period_ms );
2847 float rpm = ticks_per_sec * 60.0f / TICKS_PER_REVOLUTION ;
2948
30- // TODO: adding rpm to the database
49+ int32_t rpm_to_db = (int32_t )rpm ;
50+ ulDatabase_setInt32 (MOTOR_FL_RPM + i , rpm_to_db );
3151
3252 lastTicks_RPM [i ] = currentTicks ;
3353 }
@@ -37,6 +57,10 @@ void ulEncoder_Init(void) {
3757
3858 drvEncoder_Init ();
3959
60+ if (!ulDatabase_getUint16 (ENCODER_CONTROL_PERIOD_MS , & encoder_period_ms ) || encoder_period_ms == 0 ) {
61+ encoder_period_ms = 5 ;
62+ }
63+
4064 for (int i = 0 ; i < MOTORS_COUNT ; i ++ ) {
4165 uint32_t initialTicks = drvEncoder_Read (i );
4266 lastTicks_RPM [i ] = initialTicks ;
@@ -50,7 +74,7 @@ void ulEncoder_Init(void) {
5074 encoderTimerHandle = osTimerNew (ulEncoder_TimerCallback , osTimerPeriodic , NULL , & encoderTimer_attributes );
5175
5276 if (encoderTimerHandle != NULL ) {
53- osTimerStart (encoderTimerHandle , MOTORS_CONTROL_PERIOD_MS );
77+ osTimerStart (encoderTimerHandle , encoder_period_ms );
5478 }
5579}
5680
@@ -61,9 +85,10 @@ void ulEncoder_GetDiffForEthernet(int32_t *diffOutput) {
6185 uint32_t currentTicks = drvEncoder_Read (i );
6286 uint32_t lastTicks = lastTicks_Ethernet [i ];
6387
64- int32_t diff = ( int32_t )( currentTicks - lastTicks );
88+ int32_t diff = ulEncoder_CalculateDiff ( currentTicks , lastTicks );
6589
6690 diffOutput [i ] = diff ;
6791 lastTicks_Ethernet [i ] = currentTicks ;
6892 }
6993}
94+
0 commit comments