2024-01-04 02:14 AM
Sharing the snippets of code related to UART from code generated using motor profiler, motor pilot and stmcube ide
uint16_t motor1Faults;
uint16_t rxbuffer[5] = {0};
uint16_t flag = 0;
HAL_UART_Receive_IT(&huart2, (uint8_t*)rxbuffer, 5);
while (1)
{
if(flag == 1)
{
MC_StartMotor1();
}
else
{
MC_StopMotor1();
}
}
void setMotorSpeed(uint16_t target_speed)
{
static uint16_t previous_speed = DEFAULT_TARGET_SPEED_RPM;
static uint16_t duration = 0;
const uint16_t slope = 3000;
if (target_speed > MAX_APPLICATION_SPEED_RPM)
{
HAL_UART_Transmit(&huart2, (uint8_t*)"Target speed exceeds the max", 29, 100);
return;
}
else
{
if(target_speed < previous_speed)
{
duration = (previous_speed - target_speed) / slope;
duration = duration * 1000;
}
else
{
duration = (target_speed - previous_speed) / slope;
duration = duration * 1000;
}
MC_ProgramSpeedRampMotor1_F(target_speed, duration);
previous_speed = target_speed;
}
}
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
HAL_UART_Transmit(&huart2, (uint8_t*)rxbuffer, 5, 100);
HAL_UART_Receive_IT(&huart2, (uint8_t*)rxbuffer, 5);
if (strncmp((const char*)rxbuffer, "start", sizeof("start") - 1) == 0)
{
flag = 1;
//MC_StartMotor1();
}
else if (strncmp((const char*)rxbuffer, "stop", sizeof("stop") - 1) == 0)
{
flag = 0;
//MC_StopMotor1();
}
else
{
rxbuffer[4] = '\0';
uint16_t rpmValue = atoi((char*)rxbuffer);
if (500 <= rpmValue && rpmValue <= 3000)
{
setMotorSpeed(rpmValue);
}
else
{
HAL_UART_Transmit(&huart2, (uint8_t*)"Invalid command or RPM value\r\n", 30, 100);
}
}
}
OUTPUT I AM RECEIVING:
Please help me to rectify this error
2024-01-04 06:29 AM
> uint16_t rxbuffer[5] = {0};
Should almost certainly be uint8_t, not uint16_t.
Debug the code, set a breakpoint and examine the contents of rxbuffer when HAL_UART_RxCpltCallback is called.
2024-01-04 06:44 AM
Bit of a mess.
Couple of thing that would be better as subroutines.
Don't call long blocking functions in interrupt / callback context.
Review why the echo back gives nonsense. ie wrong baud rates, clocks, or RS232 vs CMOS levels.
Ponder how you might recover or resync the stream if it shifts.