2024-09-17 06:00 PM - last edited on 2024-09-18 02:29 AM by Andrew Neil
Hi all,
I am working on a motor control project using STM32, and I am trying to calculate the RPM of a BLDC motor using Hall sensor pulses. I have set up a SysTick timer to trigger an interrupt every 1 millisecond, which should increment a counter (sys_tick_count). This counter is then used in my millis() function to calculate elapsed time.
However, I am facing an issue where the RPM calculation doesn't seem to trigger because the time difference (time_diff) remains zero throughout the execution. It seems like the millis() function is not returning an incrementing system time, so the RPM is never calculated.
Here's the relevant portion of my code:
// SysTick timer initialization
void SysTick_Init(void)
{
SysTick_Config(SystemCoreClock / 1000); // Interrupt every 1ms
}
// SysTick Handler
void SysTick_Handler(void)
{
sys_tick_count++;
}
// Simple function to get the time in milliseconds
uint32_t millis(void)
{
return sys_tick_count; // Return system uptime in milliseconds
}
// Function to calculate speed (RPM)
float calculate_speed(void)
{
static uint32_t last_time = 0;
uint32_t current_time = millis();
float rpm = 0;
uint32_t time_diff = current_time - last_time;
printf("Time difference: %lu ms\n", time_diff); // Debugging output
if (time_diff >= 1000) {
rpm = (hall_pulse_count / 6.0) * 60.0; // Assuming 6 pulses per revolution
printf("RPM calculation, hall_pulse_count: %lu, RPM: %f\n",
hall_pulse_count,
rpm);
hall_pulse_count = 0;
last_time = current_time;
}
else
{
printf("Waiting to calculate RPM, time remaining: %lu ms\n", 1000 - time_diff);
}
return rpm;
}
Any help would be greatly appreciated!
2024-09-18 07:52 AM
Edit your posted code and use the </> and paste the code so it's properly formatted and readable.
2024-09-18 08:27 AM
Obviously, your first if statement is not being entered. If hall_pulse count is at least 1 and you compare is >= 200 then your rpm will return 10. So check your current_time is greater than last_time. Probably something wrong with getting millis value
float calculate_speed(void) {
static uint32_t last_time = 0;
uint32_t current_time = millis();
float rpm = 0;
if (current_time - last_time >= 200) {
if (hall_pulse_count > 0) {
rpm = (hall_pulse_count / 6.0) * 60.0;
}
hall_pulse_count = 0;
last_time = current_time;
}
return rpm;
}