I'm trying to establish communication between two STM32F103 MCU's via UART. I'm using STMCubeMX to build peripheral initalization. I've logicaly named the MCU's as MASTER and SLAVE. Slave UART is configured as Transmit only, while MASTER uart is recieve only. I'm using HAL drivers to program the MCU in AtollicTRUEstudio IDE. I want to send uint32_t value, buffer_USART1_rx is declared as volatile uint8_t buffer_USART1_rx[10]. Basicly SLAVE UART transmit is being triggered by Systick timer every 1 second, while MASTER UART is defined in IT mode, and soon as the interrupt happens it read the transmited value.
I connected the osciloscope probe to the PA10 RX pin of MASTER and i noticed the UART signal is fine and transmiting over the wires. But the value being transmitted is always 0 and breakpoint in HAL_UART_RxCpltCallback is never activated. Since the osciloscope signal is correct, i'm thinking it's a software issue.
Image of RX PA10 pin of MASTER stm32
This is from MASTER STM (code is located in main file)
UART initialization:
static void MX_USART1_UART_Init(void)
{
huart1.Instance = USART1;
huart1.Init.BaudRate = 115200;
huart1.Init.WordLength = UART_WORDLENGTH_8B;
huart1.Init.StopBits = UART_STOPBITS_1;
huart1.Init.Parity = UART_PARITY_NONE;
huart1.Init.Mode = UART_MODE_RX;
huart1.Init.HwFlowCtl = UART_HWCONTROL_NONE;
huart1.Init.OverSampling = UART_OVERSAMPLING_16;
if (HAL_UART_Init(&huart1) != HAL_OK)
{
_Error_Handler(__FILE__, __LINE__);
}
}
static void MX_NVIC_Init(void)
{
/* USART1_IRQn interrupt configuration */
HAL_NVIC_SetPriority(USART1_IRQn, 0, 0);
HAL_NVIC_EnableIRQ(USART1_IRQn);
}
void HAL_UART_TxCpltCallback(UART_HandleTypeDef *huart)
{
__NOP();
}
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
/*UART1 water level from SLAVE */
if(huart->Instance==USART1)
{
water_level=getUSART1();
/* Water level change triggers LCD refresh */
if(water_level_prev!=water_level)
{
lcd_screen_refresh=true;
}
water_level_prev=water_level;
}
else
{
__NOP();
}
/*UART2 target level from NANOPI */
if(huart->Instance==USART2)
{
target_level_pi=getUSART2();
/* Target level change triggers LCD refresh */
if(target_level_pi!=target_level_prev)
{
lcd_screen_refresh=true;
}
}
else
{
__NOP();
}
}
UART deserialize function:
uint32_t getUSART1()
{
uint32_t num=0;
num |= buffer_USART1_rx[0] << 24;
num |= buffer_USART1_rx[1] << 16;
num |= buffer_USART1_rx[2] << 8;
num |= buffer_USART1_rx[3];
return num;
}
In main file initialization of UART in IT mode:
/* Initialize TIM/UART interrupts */
HAL_TIM_IC_Start_IT(&htim4, TIM_CHANNEL_1);
HAL_TIM_IC_Start_IT(&htim4, TIM_CHANNEL_2);
HAL_UART_Receive_IT(&huart1, buffer_USART1_rx, 4);
SLAVE MCU configuration :
// This is in while loop
if(send_USART==true)
{
buffer[0] = test ;
buffer[1] = test >>8;
buffer[2] = test >> 16;
buffer[3] = test >> 24;
HAL_UART_Transmit(&huart1,buffer,4,2000);
}
else
{
__NOP();
}
// Callback
void HAL_UART_TxCpltCallback(UART_HandleTypeDef *huart)
{
send_USART=false;
}
//Systick timer triggers UART transmit every 1 second
void HAL_SYSTICK_Callback()
{
sys_timer++;
if(sys_timer>=1000)
{
sys_timer=0;
send_USART=true;
}
else
{
__NOP();
}
}
//Global declaration of variables used
/* Timer variables */
uint8_t buffer[10];
volatile uint32_t sys_timer=0;
uint32_t test=10;
/* Boolean variables */
bool send_USART=false;
// UART initialization
/* USART1 init function */
static void MX_USART1_UART_Init(void)
{
huart1.Instance = USART1;
huart1.Init.BaudRate = 115200;
huart1.Init.WordLength = UART_WORDLENGTH_8B;
huart1.Init.StopBits = UART_STOPBITS_1;
huart1.Init.Parity = UART_PARITY_NONE;
huart1.Init.Mode = UART_MODE_TX;
huart1.Init.HwFlowCtl = UART_HWCONTROL_NONE;
huart1.Init.OverSampling = UART_OVERSAMPLING_16;
if (HAL_UART_Init(&huart1) != HAL_OK)
{
_Error_Handler(__FILE__, __LINE__);
}
}
static void MX_NVIC_Init(void)
{
/* USART1_IRQn interrupt configuration */
HAL_NVIC_SetPriority(USART1_IRQn, 1, 0);
HAL_NVIC_EnableIRQ(USART1_IRQn);
}
I expect the recieved value to be 10. (since i'm serializing "test" variable on SLAVE stm, and sending it on MASTER stm while deserializing it)
Nevermind, i've found the issue and what was causing it
void USART1_IRQHandler(void)
{
/* USER CODE BEGIN USART1_IRQn 0 */
/* USER CODE END USART1_IRQn 0 */
HAL_UART_IRQHandler(&huart1);
/* USER CODE BEGIN USART1_IRQn 1 */
if(huart1.RxState==HAL_UART_STATE_READY)
{
HAL_UART_Receive_IT(&huart1,buffer_USART1_rx,4);
uart1_received=4; //flag da je primljen podatak
__HAL_UART_FLUSH_DRREGISTER(&huart1);
__HAL_UART_CLEAR_FLAG(&huart1, UART_FLAG_RXNE);
}
else
{
__NOP();
}
/* USER CODE END USART1_IRQn 1 */
}
The code for handling was above the HAL_UART_IRQHandler(&huart1); . That's why it only recieved data once. When I copied it below like on the code above, everything works fine.
Related
Trying to make simple PWM transmitter i faced with a problem. I have TIM2 with Channel2 (in PWM Generation mode) on board NUCLEO F042K6 and USART1 connected to the board in Async mode (USART works in DMA).
I wanted to make a PWM transmitter that uses a circular buffer that can be filled with one character or several characters at once. The plan was that when the user enters a character (or several characters), the idle line callback is processed, in which a function is called that stores the data in a cyclic buffer. After saving, the data transferred to the buffer is passed to the function PWM_SendChar(...) to convert the data into bits and transfer them over the PWM line. But the problem is when the program goes into PWM_SendChar(...) the callback HAL_TIM_PWM_PulseFinishedCallback(...) isn't called and program stucks in infinite while loop because variable used as a flag for detecting the end of single pulse (PWM_data_sent_flag) wasn't set to value 1.
However, if I use HAL_UART_Recieve(...) func in while(1) loop (located in main(void)) to recieve a char from user program works fine without stucking in while loop in TIM callback. Ofc, for this method I don't use HAL_UARTEx_RxEventCallback(...) and cycle buffer.
Thats's why I think the problem is in USART idle line detection and please help me solve it.
Code Example
Global variable used for waiting the end of pulse:
volatile uint16_t PWM_data_sent_flag = 0;
PWM timer callback:
void HAL_TIM_PWM_PulseFinishedCallback(TIM_HandleTypeDef *htim) {
if (htim->Instance == TIM2) {
HAL_TIM_PWM_Stop(&htim2, TIM_CHANNEL_2);
PWM_data_sent_flag = 1;
}
}
Callback for USART idle line:
void HAL_UARTEx_RxEventCallback(UART_HandleTypeDef *huart, uint16_t Size) {
if (huart == &huart1) {
// Function_to_save_input_char_in_cycle_buffer() is called
}
}
Function used to send char as a PWM signal (emited after Function_to_save_input_char_in_cycle_buffer() completed):
void PWM_SendChar(char ch) {
for (int i = 0, mv = 7; i <= 7; ++i, --mv) {
uint8_t bit = (ch & (1 << mv)) ? 1 : 0;
// PWM_LOW_PERCENT encodes bit with zero value, PWM_HIGH_PERCENT encodes bit with value one
uint16_t duty_cycle = bit == 0 ? PWM_LOW_PERCENT : PWM_HIGH_PERCENT;
// Change TIM2 CCR2 value according to bit's value
__HAL_TIM_SET_COMPARE(&htim2, TIM_CHANNEL_2,
GET_PERCENT_VALUE(TIM2->ARR, duty_cycle));
HAL_TIM_PWM_Start_IT(&htim2, TIM_CHANNEL_2);
// Program comes to this cycle and doesn't leave it
while (!PWM_data_sent_flag)
;
PWM_data_sent_flag = 0;
}
}
USART receive to idle launch (half data transmitted callback disabled):
int main(void) {
// Init code
// ...
if (HAL_UARTEx_ReceiveToIdle_DMA(&huart1, (uint8_t*) ring_buf.buff,
ARRAY_LEN(ring_buf.buff)) != HAL_OK) {
Error_Handler();
}
// Disable half word transmitted callback
__HAL_DMA_DISABLE_IT(&hdma_usart1_rx, DMA_IT_HT);
while(1) {
}
}
TIM2 settings:
static void MX_TIM2_Init(void) {
/* USER CODE BEGIN TIM2_Init 0 */
/* USER CODE END TIM2_Init 0 */
TIM_ClockConfigTypeDef sClockSourceConfig = { 0 };
TIM_MasterConfigTypeDef sMasterConfig = { 0 };
TIM_OC_InitTypeDef sConfigOC = { 0 };
/* USER CODE BEGIN TIM2_Init 1 */
/* USER CODE END TIM2_Init 1 */
htim2.Instance = TIM2;
htim2.Init.Prescaler = 48000 - 1;
htim2.Init.CounterMode = TIM_COUNTERMODE_UP;
htim2.Init.Period = 100 - 1;
htim2.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
htim2.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE;
if (HAL_TIM_Base_Init(&htim2) != HAL_OK) {
Error_Handler();
}
sClockSourceConfig.ClockSource = TIM_CLOCKSOURCE_INTERNAL;
if (HAL_TIM_ConfigClockSource(&htim2, &sClockSourceConfig) != HAL_OK) {
Error_Handler();
}
if (HAL_TIM_PWM_Init(&htim2) != HAL_OK) {
Error_Handler();
}
sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET;
sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
if (HAL_TIMEx_MasterConfigSynchronization(&htim2, &sMasterConfig)
!= HAL_OK) {
Error_Handler();
}
sConfigOC.OCMode = TIM_OCMODE_PWM1;
sConfigOC.Pulse = 0;
sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH;
sConfigOC.OCFastMode = TIM_OCFAST_DISABLE;
if (HAL_TIM_PWM_ConfigChannel(&htim2, &sConfigOC, TIM_CHANNEL_2)
!= HAL_OK) {
Error_Handler();
}
/* USER CODE BEGIN TIM2_Init 2 */
/* USER CODE END TIM2_Init 2 */
HAL_TIM_MspPostInit(&htim2);
}
USART1 settings:
static void MX_USART1_UART_Init(void) {
/* USER CODE BEGIN USART1_Init 0 */
/* USER CODE END USART1_Init 0 */
/* USER CODE BEGIN USART1_Init 1 */
/* USER CODE END USART1_Init 1 */
huart1.Instance = USART1;
huart1.Init.BaudRate = 115200;
huart1.Init.WordLength = UART_WORDLENGTH_8B;
huart1.Init.StopBits = UART_STOPBITS_1;
huart1.Init.Parity = UART_PARITY_NONE;
huart1.Init.Mode = UART_MODE_TX_RX;
huart1.Init.HwFlowCtl = UART_HWCONTROL_NONE;
huart1.Init.OverSampling = UART_OVERSAMPLING_16;
huart1.Init.OneBitSampling = UART_ONE_BIT_SAMPLE_DISABLE;
huart1.AdvancedInit.AdvFeatureInit = UART_ADVFEATURE_NO_INIT;
if (HAL_UART_Init(&huart1) != HAL_OK) {
Error_Handler();
}
/* USER CODE BEGIN USART1_Init 2 */
/* USER CODE END USART1_Init 2 */
}
DMA settings:
static void MX_DMA_Init(void) {
/* DMA controller clock enable */
__HAL_RCC_DMA1_CLK_ENABLE();
/* DMA interrupt init */
/* DMA1_Channel4_5_IRQn interrupt configuration */
HAL_NVIC_SetPriority(DMA1_Channel4_5_IRQn, 0, 0);
HAL_NVIC_EnableIRQ(DMA1_Channel4_5_IRQn);
}
I am developing uart communication on STMicroelectronics NUCLEO-G474RE Board(stm32G474RETX MCU, 64pins) using MDK-v5, but run into a perplexing problem these several days, make no progress on it and have to reach out to seek some help. If anyone could give me a right way to go, it would be appreciated greatly.
Code is not complicated, I use cubeMX to initialize the code base with usart2 configured, and use two threads based on cmsis v2 api for receiving occassinally and transmiting periodically(in 2 seconds).
The auto-generated usart2 init code
static void MX_USART2_UART_Init(void)
{
/* USER CODE BEGIN USART2_Init 0 */
/* USER CODE END USART2_Init 0 */
/* USER CODE BEGIN USART2_Init 1 */
/* USER CODE END USART2_Init 1 */
huart2.Instance = USART2;
huart2.Init.BaudRate = 115200;
huart2.Init.WordLength = UART_WORDLENGTH_8B;
huart2.Init.StopBits = UART_STOPBITS_1;
huart2.Init.Parity = UART_PARITY_NONE;
huart2.Init.Mode = UART_MODE_TX_RX;
huart2.Init.HwFlowCtl = UART_HWCONTROL_RTS;
huart2.Init.OverSampling = UART_OVERSAMPLING_16;
huart2.Init.OneBitSampling = UART_ONE_BIT_SAMPLE_DISABLE;
huart2.Init.ClockPrescaler = UART_PRESCALER_DIV1;
huart2.AdvancedInit.AdvFeatureInit = UART_ADVFEATURE_NO_INIT;
if (HAL_UART_Init(&huart2) != HAL_OK)
{
Error_Handler();
}
if (HAL_UARTEx_SetTxFifoThreshold(&huart2, UART_TXFIFO_THRESHOLD_1_8) != HAL_OK)
{
Error_Handler();
}
if (HAL_UARTEx_SetRxFifoThreshold(&huart2, UART_RXFIFO_THRESHOLD_1_8) != HAL_OK)
{
Error_Handler();
}
if (HAL_UARTEx_DisableFifoMode(&huart2) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN USART2_Init 2 */
/* USER CODE END USART2_Init 2 */
}
Interrupt call back code
void HAL_UART_ErrorCallback(UART_HandleTypeDef *huart)
{
printf("Interrupt error occured(0x%x)!!!\r\n", huart->ErrorCode);
}
void HAL_UART_RxCpltCallback(UART_HandleTypeDef* huart)
{
UNUSED(huart);
if(huart == &huart2 || huart == &huart3){
uint8_t aEnterLine[] = "\r\n";
//HAL_UART_Transmit(huart, aEnterLine, sizeof(aEnterLine), 0xFFFF);
//HAL_UART_Transmit(huart, gRxBuffer, 11, 0xFFFF);
//HAL_UART_Transmit(huart, aEnterLine, sizeof(aEnterLine), 0xFFFF);
//printf("%s\r\n", gRxBuffer);
if(g_cmdExecuting == 0)
osEventFlagsSet(evt_id, 0x00000001U);
}else if(huart == &huart1){
}else{
}
HAL_UART_Receive_IT(huart, (unsigned char*)gRxBuffer, 11);
}
int8_t app_usart_transmit(uint8_t* buf, uint8_t len)
{
return 0;
}
int8_t app_usart_init(UART_HandleTypeDef* huart)
{
if(huart == NULL)
return -1;
if(huart == &huart2 || huart == &huart3){
uint8_t aTxStartMessage[] = "\r\n****UART-Hyperterminal commmunication based on IT****"
"\r\nEnter 10 characters using keyboard: \r\n";
HAL_UART_Transmit(huart, aTxStartMessage, sizeof(aTxStartMessage), 0xFFFF);
}
clear_rx_buffer();
HAL_UART_Receive_IT(huart, (uint8_t*)gRxBuffer, 11);
return 0;
}
rx & tx worker code
extern osMutexId_t myMutex01Handle;
extern osEventFlagsId_t evt_id;
extern osEventFlagsId_t evt_id1;
osTimerId_t timer_id;
static osThreadId gTask1Handle;
static const osThreadAttr_t gTask1Attrbutes = {
.name = "Task1",
.priority = (osPriority_t) osPriorityAboveNormal,
.stack_size = 512
};
static osThreadId gTask2Handle;
static const osThreadAttr_t gTask2Attrbutes = {
.name = "Task2",
.priority = (osPriority_t) osPriorityNormal,
.stack_size = 512
};
uint8_t g_cmdExecuting = 0;
uint8_t g_SemExec = 0;
uint32_t timer_cnt;
void update_stat_timer(void* argument)
{
timer_cnt++;
//osMutexAcquire(myMutex01Handle, osWaitForever);
printf("update_stat_timer executes %u times, ====++++====++++\r\n", timer_cnt);
//osMutexRelease(myMutex01Handle);
}
void update_stat_task_run(void* argument)
{
uint32_t count;
for(;;){
osDelay(2000);
count++;
osMutexAcquire(myMutex01Handle, osWaitForever);
printf("update_stat_task_run executes %d times, ====++++====++++\r\n", count);
osMutexRelease(myMutex01Handle);
}
}
void exec_cmd_task_run(void* argument)
{
uint32_t flags;
for(;;){
flags = osEventFlagsWait(evt_id, 0x00000001U, osFlagsWaitAny, osWaitForever);
g_cmdExecuting = 1;
osMutexAcquire(myMutex01Handle, osWaitForever);
osDelay(1000);
printf("exec_cmd_task Print\r\n");
osMutexRelease(myMutex01Handle);
g_cmdExecuting = 0;
}
}
int8_t app_task_init()
{
osStatus_t status;
gTask1Handle = osThreadNew(exec_cmd_task_run, NULL, &gTask1Attrbutes);
gTask2Handle = osThreadNew(update_stat_task_run, NULL, &gTask2Attrbutes);
//uint32_t exec = 1;
//timer_id = osTimerNew(update_stat_timer, osTimerPeriodic, &exec, NULL);
//if(status != osOK){
//;
//}
//osTimerStart(timer_id, 2000U);
return 0;
}
My Question:
It could receive and transmit msg at very begining, but after receiving three or four hundred times, it couldn't receive the msg anymore while the transmitting is ok, and I also use the timer api to replace the transmitting thread, the result is the same, it couldn't receive any msg after hundreds times.
the testing result pic
You can perform the HAL status and error checks using uint32_t HAL_UART_GetError(UART_HandleTypeDef * huart) and HAL_UART_StateTypeDef HAL_UART_GetState(UART_HandleTypeDef *huart) (http://www.disca.upv.es/aperles/arm_cortex_m3/llibre/st/STM32F439xx_User_Manual/group__uart__exported__functions__group4.html)
The source code for HAL_UART_Receive_IT(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size) and HAL_UART_RxCplt_Callback() is in https://github.com/ARMmbed/mbed-hal-st-stm32cubef4/blob/master/source/stm32f4xx_hal_uart.c
HAL_StatusTypeDef HAL_UART_Receive_IT(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size)
{
uint32_t tmp = 0;
tmp = huart->State;
if((tmp == HAL_UART_STATE_READY) || (tmp == HAL_UART_STATE_BUSY_TX))
{
if((pData == HAL_NULL ) || (Size == 0))
{
return HAL_ERROR;
}
/* Process Locked */
__HAL_LOCK(huart);
huart->pRxBuffPtr = pData;
huart->RxXferSize = Size;
huart->RxXferCount = Size;
huart->ErrorCode = HAL_UART_ERROR_NONE;
/* Check if a transmit process is ongoing or not */
if(huart->State == HAL_UART_STATE_BUSY_TX)
{
huart->State = HAL_UART_STATE_BUSY_TX_RX;
}
else
{
huart->State = HAL_UART_STATE_BUSY_RX;
}
/* Enable the UART Parity Error Interrupt */
__HAL_UART_ENABLE_IT(huart, UART_IT_PE);
/* Enable the UART Error Interrupt: (Frame error, noise error, overrun error) */
__HAL_UART_ENABLE_IT(huart, UART_IT_ERR);
/* Process Unlocked */
__HAL_UNLOCK(huart);
/* Enable the UART Data Register not empty Interrupt */
__HAL_UART_ENABLE_IT(huart, UART_IT_RXNE);
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
Note that the HAL mutually uses locking mechanisms (__HAL_LOCK, code line 107 in https://github.com/ARMmbed/mbed-os/blob/master/targets/TARGET_STM/TARGET_STM32L1/device/stm32l1xx_hal_def.h)
To get the UART status use i.e.
HAL_UART_StateTypeDef UARTStatus;
UARTStatus = HAL_UART_Receive_IT(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size);
The definition of HAL_UART_StateTypeDef is
typedef enum
{
HAL_UART_STATE_RESET = 0x00, /*!< Peripheral is not yet Initialized */
HAL_UART_STATE_READY = 0x01, /*!< Peripheral Initialized and ready for use */
HAL_UART_STATE_BUSY = 0x02, /*!< an internal process is ongoing */
HAL_UART_STATE_BUSY_TX = 0x12, /*!< Data Transmission process is ongoing */
HAL_UART_STATE_BUSY_RX = 0x22, /*!< Data Reception process is ongoing */
HAL_UART_STATE_BUSY_TX_RX = 0x32, /*!< Data Transmission and Reception process is ongoing */
HAL_UART_STATE_TIMEOUT = 0x03, /*!< Timeout state */
HAL_UART_STATE_ERROR = 0x04 /*!< Error */
}HAL_UART_StateTypeDef;
(https://github.com/synthetos/Motate/blob/master/MotateProject/motate/cmsis/TARGET_STM/TARGET_DISCO_F407VG/stm32f4xx_hal_uart.h code line 97)
The definition of HAL_StatusTypeDef (general HAL status) is
typedef enum
{
HAL_OK = 0x00,
HAL_ERROR = 0x01,
HAL_BUSY = 0x02,
HAL_TIMEOUT = 0x03
} HAL_StatusTypeDef;
You can print the HAL status (i.e. with UART transmit or SWO ITM_SendChar((*ptr++));, see https://ralimtek.com/stm32_debugging/ )
The HAL has its own reference manual, the HAL status is described in the reference manual https://www.st.com/content/ccc/resource/technical/document/user_manual/2f/71/ba/b8/75/54/47/cf/DM00105879.pdf/files/DM00105879.pdf/jcr:content/translations/en.DM00105879.pdf on page 54 in chapter 2.9 HAL common resources.
Debugging techniques are described in https://www.st.com/content/ccc/resource/technical/document/application_note/group0/3d/a5/0e/30/76/51/45/58/DM00354244/files/DM00354244.pdf/jcr:content/translations/en.DM00354244.pdf, also for your programming adapter, that you can directly integrate in CubeMX (i use Atollic with integrated CubeMX because Atollic is based on Eclipse IDE and is almost identical to use)
Another debugging tutorial is https://ardupilot.org/dev/docs/debugging-with-gdb-on-stm32.html (if you are on linux).
This could also be a race condition either of the HAL or the OS. The problem that i have is that you do not post your full code, especially not concerning your OS and this is possibly critical here
So maybe first check the HAL status and then focus on the OS part (race conditions, buffer, stack or heap overflow, ... https://www.st.com/content/ccc/resource/technical/document/user_manual/2d/60/ff/15/8c/c9/43/77/DM00105262.pdf/files/DM00105262.pdf/jcr:content/translations/en.DM00105262.pdf)
Stack overflows are always critical on embedded systems so here is links https://barrgroup.com/embedded-systems/how-to/prevent-detect-stack-overflow , https://www.iar.com/support/resources/articles/detecting-and-avoiding-stack-overflow-in-embedded-systems/
Also see Uart dma receive interrupt stops receiving data after several minutes and UART receive interrupt stops triggering after several hours of successful receive
Many developers avoid using the HAL because it is a bit buggy and not very transparent, i personally would also not use it when i want full control over the system behavior
I'm trying to implement communication between stm32f103 and SIM900A using FreeRTOS (mutexes and stream buffers), DMA and USART3.
I've enabled USART_IT_IDLE USART3 interrupt to be able to detect end of SIM900 transmittion and make force firing of DMA transmission complete interrupt to copy data from memory into FreeRtos's streamBuffer.
This article said that this is possible.
/**
* \brief Global interrupt handler for USART2
*/
void USART2_IRQHandler(void) {
/* Check for IDLE flag */
if (USART2->SR & USART_FLAG_IDLE) { /* We want IDLE flag only */
/* This part is important */
/* Clear IDLE flag by reading status register first */
/* And follow by reading data register */
volatile uint32_t tmp; /* Must be volatile to prevent optimizations */
tmp = USART2->SR; /* Read status register */
tmp = USART2->DR; /* Read data register */
(void)tmp; /* Prevent compiler warnings */
DMA1_Stream5->CR &= ~DMA_SxCR_EN; /* Disabling DMA will force transfer complete interrupt if enabled */
}
}
But my debugger says: no
Here is my code:
#define BUFF_SIZE 16
uint8_t RX_BUFFER[BUFF_SIZE] = {"\0"};
uint8_t TX_BUFFER[BUFF_SIZE] = {"\0"};
....
// USART TX channel
DMA_InitStruct.DMA_PeripheralBaseAddr = (uint32_t)&(USART3->DR);
DMA_InitStruct.DMA_MemoryBaseAddr = (uint32_t)&TX_BUFFER[0];
DMA_InitStruct.DMA_DIR = DMA_DIR_PeripheralDST;
DMA_InitStruct.DMA_BufferSize = sizeof(TX_BUFFER);
DMA_InitStruct.DMA_PeripheralInc = DMA_PeripheralInc_Disable;
DMA_InitStruct.DMA_MemoryInc = DMA_MemoryInc_Enable;
DMA_InitStruct.DMA_PeripheralDataSize = DMA_PeripheralDataSize_Byte;
DMA_InitStruct.DMA_MemoryDataSize = DMA_MemoryDataSize_Byte;
DMA_InitStruct.DMA_Mode = DMA_Mode_Normal;
DMA_InitStruct.DMA_Priority = DMA_Priority_Low;
DMA_InitStruct.DMA_M2M = DMA_M2M_Disable;
DMA_Init(DMA1_Channel2, &DMA_InitStruct);
DMA_InitStruct.DMA_MemoryBaseAddr = (uint32_t)&RX_BUFFER[0];
DMA_InitStruct.DMA_DIR = DMA_DIR_PeripheralSRC;
DMA_InitStruct.DMA_BufferSize = sizeof(RX_BUFFER);
DMA_Init(DMA1_Channel3, &DMA_InitStruct);
// USART RX channel
DMA_InitStruct.DMA_MemoryBaseAddr = (uint32_t)&RX_BUFFER[0];
DMA_InitStruct.DMA_DIR = DMA_DIR_PeripheralSRC;
DMA_InitStruct.DMA_BufferSize = sizeof(RX_BUFFER);
DMA_Init(DMA1_Channel3, &DMA_InitStruct);
// Interrupts
USART_ITConfig(USART3, USART_IT_IDLE, ENABLE);
USART_DMACmd(USART3, USART_DMAReq_Tx | USART_DMAReq_Rx, ENABLE);
USART_Cmd(USART3, ENABLE);
DMA_ITConfig(DMA1_Channel3, DMA_IT_TC, ENABLE);
DMA_Cmd(DMA1_Channel3, ENABLE);
NVIC_InitTypeDef NVIC_InitStructure;
NVIC_InitStructure.NVIC_IRQChannel = USART3_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = configMAX_SYSCALL_INTERRUPT_PRIORITY + 10;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 4;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
NVIC_InitStructure.NVIC_IRQChannel = DMA1_Channel3_IRQn;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 3;
NVIC_Init(&NVIC_InitStructure);
....
void USART3_IRQHandler() {
if (USART_GetITStatus(USART3, USART_IT_IDLE) == SET) {
volatile uint32_t tmp = USART3->SR;
tmp = USART3->DR;
(void) tmp;
// HERE interrupt should be fired!
DMA1_Channel3->CCR &= (uint16_t)(~DMA_CCR1_EN);
USART_ClearITPendingBit(USART3, USART_IT_IDLE);
}
}
void DMA1_Channel3_IRQHandler(void) {
if (DMA_GetITStatus(DMA1_IT_TC3) == SET) {
uint8_t len = BUFF_SIZE - DMA1_Channel3->CNDTR;
BaseType_t xHigherPriorityTaskWoken = pdFALSE;
xStreamBufferSendFromISR(xUSART3ReceiveStreamBuffer, &RX_BUFFER, len, &xHigherPriorityTaskWoken);
for (uint8_t i = 0; i < len; i++) {
RX_BUFFER[i] = '\0';
}
DMA1_Channel3->CNDTR = BUFF_SIZE;
DMA_Cmd(DMA1_Channel3, ENABLE);
DMA_ClearITPendingBit(DMA1_IT_TC3);
}
}
Why I can't force DMA1_IT_TC3 interrupt? Or can it be forced on STM32F103?
I have experienced a very strange problem in developing my application for the ST Microelectronics iNemo. My applications consists in:
Gyroscope reading with SPI
Accelerometer and Magnetometer (in the same device) reading with I2C
Attitude estimation algorithm
PD functions
Data receiving with USART, with interrupt without DMA
Sending of logging packet, with USART
The loop is triggered by a timer at 100Hz.
The program works well (I have tested it with some USART debug prints) until I start sending data with the USART: my initial guess was that, since this fact enables the receiving of interrupts, it causes problem with the I2C bus arbitrage mechanism. My guess is derived that when I have succeeded in debugging the problem (that is time dependent), with USART prints, I have detected that the last print is always before the accelerometer of magnetometer prints (the first that I call in my code).
Additionally, If I enable the verbose debug prints via USART that I have mentioned the problem occurs in fewer occasions, while if I disable it and I send only logging packet the problem occurs always and immediately. Anyone can give me an idea of what can be the cause of this problem? Thanks
EDIT: I attach my I2C code:
#define DMA_BUFFER_SIZE 196
#define FORCE_CRITICAL_SEC
/**
* #brief DMA initialization structure variable definition.
*/
DMA_InitTypeDef I2CDMA_InitStructure;
/**
* #brief Volatile variable definition for I2C direction.
*/
__IO uint32_t I2CDirection = I2C_DIRECTION_TX;
void iNemoI2CInit(I2C_TypeDef* I2Cx, uint32_t I2CxSpeed)
{
I2C_InitTypeDef I2C_InitStructure;
GPIO_InitTypeDef GPIO_InitStructure;
/* Enable GPIO clocks */
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB|RCC_APB2Periph_AFIO, ENABLE);
/* Configure I2C pins: SCL and SDA */
if(I2Cx==I2C2)
{
RCC_APB1PeriphClockCmd(RCC_APB1Periph_I2C2, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10 | GPIO_Pin_11;
}
else
{
GPIO_PinRemapConfig(GPIO_Remap_I2C1,ENABLE);
RCC_APB1PeriphClockCmd(RCC_APB1Periph_I2C1, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_8 | GPIO_Pin_9;
}
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_OD;
GPIO_Init(GPIOB, &GPIO_InitStructure);
/* I2C configuration */
I2C_InitStructure.I2C_Mode = I2C_Mode_I2C;
I2C_InitStructure.I2C_DutyCycle = I2C_DutyCycle_2;
I2C_InitStructure.I2C_OwnAddress1 = 0x00;
I2C_InitStructure.I2C_Ack = I2C_Ack_Enable;
I2C_InitStructure.I2C_AcknowledgedAddress = I2C_AcknowledgedAddress_7bit;
I2C_InitStructure.I2C_ClockSpeed = I2CxSpeed;
/* Apply I2C configuration after enabling it */
I2C_Init(I2Cx, &I2C_InitStructure);
/* I2C Peripheral Enable */
I2C_Cmd(I2Cx, ENABLE);
/* Enable DMA if required */
#if (defined(I2C1_USE_DMA_TX) || defined(I2C1_USE_DMA_RX))
if (I2Cx==I2C1)
iNemoI2CDMAInit(I2C1);
#endif
#if (defined(I2C2_USE_DMA_TX) || defined(I2C2_USE_DMA_RX))
if (I2Cx==I2C2)
iNemoI2CDMAInit(I2C2);
#endif
}
void iNemoI2CDMAInit(I2C_TypeDef* I2Cx)
{
/* Enable the DMA1 clock */
RCC_AHBPeriphClockCmd(RCC_AHBPeriph_DMA1, ENABLE);
/* I2C TX DMA Channel configuration */
I2CDMA_InitStructure.DMA_MemoryBaseAddr = (uint32_t)0; /* This parameter will be configured durig communication */
I2CDMA_InitStructure.DMA_DIR = DMA_DIR_PeripheralDST; /* This parameter will be configured durig communication */
I2CDMA_InitStructure.DMA_BufferSize = 0xFFFF; /* This parameter will be configured durig communication */
I2CDMA_InitStructure.DMA_PeripheralInc = DMA_PeripheralInc_Disable;
I2CDMA_InitStructure.DMA_MemoryInc = DMA_MemoryInc_Enable;
I2CDMA_InitStructure.DMA_PeripheralDataSize = DMA_MemoryDataSize_Byte;
I2CDMA_InitStructure.DMA_MemoryDataSize = DMA_MemoryDataSize_Byte;
I2CDMA_InitStructure.DMA_Mode = DMA_Mode_Normal;
I2CDMA_InitStructure.DMA_Priority = DMA_Priority_VeryHigh;
I2CDMA_InitStructure.DMA_M2M = DMA_M2M_Disable;
if(I2Cx==I2C2)
{
I2CDMA_InitStructure.DMA_PeripheralBaseAddr = (uint32_t)I2C2_DR_Address;
#ifdef I2C2_USE_DMA_TX
DMA_DeInit(I2C2_DMA_CHANNEL_TX);
DMA_Init(I2C2_DMA_CHANNEL_TX, &I2CDMA_InitStructure);
#endif
#ifdef I2C2_USE_DMA_RX
/* I2C2 RX DMA Channel configuration */
DMA_DeInit(I2C2_DMA_CHANNEL_RX);
DMA_Init(I2C2_DMA_CHANNEL_RX, &I2CDMA_InitStructure);
#endif
}
if(I2Cx==I2C1)
{
I2CDMA_InitStructure.DMA_PeripheralBaseAddr = (uint32_t)I2C1_DR_Address;
#ifdef I2C1_USE_DMA_TX
DMA_DeInit(I2C1_DMA_CHANNEL_TX);
DMA_Init(I2C1_DMA_CHANNEL_TX, &I2CDMA_InitStructure);
#endif
#ifdef I2C1_USE_DMA_RX
/* I2C1 RX DMA Channel configuration */
DMA_DeInit(I2C1_DMA_CHANNEL_RX);
DMA_Init(I2C1_DMA_CHANNEL_RX, &I2CDMA_InitStructure);
#endif
}
void iNemoI2CDMAConfig(I2C_TypeDef* I2Cx, uint8_t* pBuffer, uint32_t lBufferSize, uint32_t lDirection)
{
/* Initialize the DMA with the new parameters */
if (lDirection == I2C_DIRECTION_TX)
{
/* Configure the DMA Tx Channel with the buffer address and the buffer size */
I2CDMA_InitStructure.DMA_MemoryBaseAddr = (uint32_t)pBuffer;
I2CDMA_InitStructure.DMA_DIR = DMA_DIR_PeripheralDST;
I2CDMA_InitStructure.DMA_BufferSize = (uint32_t)lBufferSize;
if(I2Cx==I2C2)
{
I2CDMA_InitStructure.DMA_PeripheralBaseAddr = (uint32_t)I2C2_DR_Address;
DMA_Cmd(I2C2_DMA_CHANNEL_TX, DISABLE);
DMA_Init(I2C2_DMA_CHANNEL_TX, &I2CDMA_InitStructure);
DMA_Cmd(I2C2_DMA_CHANNEL_TX, ENABLE);
}
else
{
I2CDMA_InitStructure.DMA_PeripheralBaseAddr = (uint32_t)I2C1_DR_Address;
DMA_Cmd(I2C1_DMA_CHANNEL_TX, DISABLE);
DMA_Init(I2C1_DMA_CHANNEL_TX, &I2CDMA_InitStructure);
DMA_Cmd(I2C1_DMA_CHANNEL_TX, ENABLE);
}
}
else /* Reception */
{
/* Configure the DMA Rx Channel with the buffer address and the buffer size */
I2CDMA_InitStructure.DMA_MemoryBaseAddr = (uint32_t)pBuffer;
I2CDMA_InitStructure.DMA_DIR = DMA_DIR_PeripheralSRC;
I2CDMA_InitStructure.DMA_BufferSize = (uint32_t)lBufferSize;
if(I2Cx==I2C2)
{
I2CDMA_InitStructure.DMA_PeripheralBaseAddr = (uint32_t)I2C2_DR_Address;
DMA_Cmd(I2C2_DMA_CHANNEL_RX, DISABLE);
DMA_Init(I2C2_DMA_CHANNEL_RX, &I2CDMA_InitStructure);
DMA_Cmd(I2C2_DMA_CHANNEL_RX, ENABLE);
}
else
{
I2CDMA_InitStructure.DMA_PeripheralBaseAddr = (uint32_t)I2C1_DR_Address;
DMA_Cmd(I2C1_DMA_CHANNEL_RX, DISABLE);
DMA_Init(I2C1_DMA_CHANNEL_RX, &I2CDMA_InitStructure);
DMA_Cmd(I2C1_DMA_CHANNEL_RX, ENABLE);
}
}
}
void iNemoI2CBufferReadDma(I2C_TypeDef* I2Cx, uint8_t cAddr, uint8_t* pcBuffer, uint8_t cReadAddr, uint8_t cNumByteToRead)
{
__IO uint32_t temp = 0;
__IO uint32_t Timeout = 0;
/* Enable I2C errors interrupts */
I2Cx->CR2 |= I2C_IT_ERR;
/* Set the MSb of the register address in case of multiple readings */
if(cNumByteToRead>1)
cReadAddr |= 0x80;
#ifdef FORCE_CRITICAL_SEC
__disable_irq();
#endif
#ifdef USART_DEBUG2
USART1_Printf("FLAG BUSY\r\n");
#endif
Timeout = 0xFFFF;
/* While the bus is busy */
while(I2C_GetFlagStatus(I2Cx, I2C_FLAG_BUSY)){
if (Timeout-- == 0)
return;
}
/* Send START condition */
I2C_GenerateSTART(I2Cx, ENABLE);
#ifdef USART_DEBUG2
USART1_Printf("MASTER MODE\r\n");
#endif
Timeout = 0xFFFF;
/* Test on EV5 and clear it */
while(!I2C_CheckEvent(I2Cx, I2C_EVENT_MASTER_MODE_SELECT)){
if (Timeout-- == 0)
return;
}
/* Send LSM303DLH address for read */
I2C_Send7bitAddress(I2Cx, cAddr, I2C_Direction_Transmitter);
Timeout = 0xFFFF;
/* Test on EV6 and clear it */
while(!I2C_CheckEvent(I2Cx, I2C_EVENT_MASTER_TRANSMITTER_MODE_SELECTED)){
if (Timeout-- == 0)
return;
}
/* Clear EV6 by setting again the PE bit */
I2C_Cmd(I2Cx, ENABLE);
/* Send the LSM303DLH_Magn's internal address to write to */
I2C_SendData(I2Cx, cReadAddr);
#ifdef USART_DEBUG2
USART1_Printf("BYTE TRANSMITTED\r\n");
#endif
Timeout = 0xFFFF;
/* Test on EV8 and clear it */
while(!I2C_CheckEvent(I2Cx, I2C_EVENT_MASTER_BYTE_TRANSMITTED)){
if (Timeout-- == 0)
return;
}
/* Configure I2Cx DMA channel */
iNemoI2CDMAConfig(I2Cx, pcBuffer, cNumByteToRead, I2C_DIRECTION_RX);
/* Set Last bit to have a NACK on the last received byte */
I2Cx->CR2 |= 0x1000;
/* Enable I2C DMA requests */
I2C_DMACmd(I2Cx, ENABLE);
Timeout = 0xFFFF;
/* Send START condition */
I2C_GenerateSTART(I2Cx, ENABLE);
Timeout = 0xFFFF;
/* Wait until SB flag is set: EV5 */
while(!I2C_CheckEvent(I2Cx, I2C_EVENT_MASTER_MODE_SELECT))
{
if (Timeout-- == 0)
return;
}
Timeout = 0xFFFF;
/* Send LSM303DLH address for read */
I2C_Send7bitAddress(I2Cx, cAddr, I2C_Direction_Receiver);
Timeout = 0xFFFF;
/* Wait until ADDR is set: EV6 */
while(!I2C_CheckEvent(I2Cx, I2C_EVENT_MASTER_RECEIVER_MODE_SELECTED))
{
if (Timeout-- == 0)
return;
}
/* Clear ADDR flag by reading SR2 register */
temp = I2Cx->SR2;
if(I2Cx == I2C2)
{
Timeout = 0xFFFF;
/* Wait until DMA end of transfer */
while (!DMA_GetFlagStatus(DMA1_FLAG_TC5)){
if (Timeout-- == 0)
return;
}
/* Disable DMA Channel */
DMA_Cmd(I2C2_DMA_CHANNEL_RX, DISABLE);
/* Clear the DMA Transfer Complete flag */
DMA_ClearFlag(DMA1_FLAG_TC5);
}
else
{
/* Wait until DMA end of transfer */
#ifdef USART_DEBUG2
USART1_Printf("END TRANSFER\r\n");
#endif
Timeout = 0xFFFF;
while (!DMA_GetFlagStatus(DMA1_FLAG_TC7)){
if (Timeout-- == 0)
return;
}
/* Disable DMA Channel */
DMA_Cmd(I2C1_DMA_CHANNEL_RX, DISABLE);
/* Clear the DMA Transfer Complete flag */
DMA_ClearFlag(DMA1_FLAG_TC7);
}
/* Disable Ack for the last byte */
I2C_AcknowledgeConfig(I2Cx, DISABLE);
/* Send STOP Condition */
I2C_GenerateSTOP(I2Cx, ENABLE);
#ifdef USART_DEBUG2
USART1_Printf("STOP BIT\r\n");
#endif
Timeout = 0xFFFF;
/* Make sure that the STOP bit is cleared by Hardware before CR1 write access */
while ((I2Cx->CR1 & 0x0200) == 0x0200){
if (Timeout-- == 0)
return;
}
/* Enable Acknowledgement to be ready for another reception */
I2C_AcknowledgeConfig(I2Cx, ENABLE);
#ifdef FORCE_CRITICAL_SEC
__enable_irq();
#endif
}
void iNemoI2CBufferWriteDma(I2C_TypeDef* I2Cx, uint8_t cAddr, uint8_t* pcBuffer, uint8_t cWriteAddr, uint8_t cNumByteToWrite)
{
__IO uint32_t temp = 0;
__IO uint32_t Timeout = 0;
static uint8_t pcDmaBuffer[DMA_BUFFER_SIZE+1];
/* Set to 1 the MSb of the register address in case of multiple byte writing */
if(cNumByteToWrite>1)
cWriteAddr |= 0x80;
pcDmaBuffer[0]=cWriteAddr;
memcpy(&pcDmaBuffer[1],pcBuffer,cNumByteToWrite);
/* Enable Error IT */
I2Cx->CR2 |= I2C_IT_ERR;
Timeout = 0xFFFF;
/* Configure the DMA channel for I2Cx transmission */
iNemoI2CDMAConfig(I2Cx, pcDmaBuffer, cNumByteToWrite+1, I2C_DIRECTION_TX);
/* Enable DMA for I2C */
I2C_DMACmd(I2Cx, ENABLE);
/* Send START condition */
I2C_GenerateSTART(I2Cx, ENABLE);
/* Wait until SB flag is set: EV5 */
while(!I2C_CheckEvent(I2Cx, I2C_EVENT_MASTER_MODE_SELECT))
{
if (Timeout-- == 0)
return;
}
Timeout = 0xFFFF;
/* Send LSM303DLH address for write */
I2C_Send7bitAddress(I2Cx, cAddr, I2C_Direction_Transmitter);
/* Wait until ADDR is set: EV6 */
while(!I2C_CheckEvent(I2Cx, I2C_EVENT_MASTER_TRANSMITTER_MODE_SELECTED))
{
if (Timeout-- == 0)
return;
}
/* Clear ADDR flag by reading SR2 register */
temp = I2Cx->SR2;
/* Disable the DMA1 channel */
if(I2Cx == I2C2)
{
/* Wait until DMA end of transfer */
while (!DMA_GetFlagStatus(DMA1_FLAG_TC4));
/* Disable DMA Channel */
DMA_Cmd(I2C2_DMA_CHANNEL_TX, DISABLE);
/* Clear the DMA Transfer complete flag */
DMA_ClearFlag(DMA1_FLAG_TC4);
}
else
{
/* Wait until DMA end of transfer */
while (!DMA_GetFlagStatus(DMA1_FLAG_TC6));
/* Disable DMA Channel */
DMA_Cmd(I2C1_DMA_CHANNEL_TX, DISABLE);
/* Clear the DMA Transfer complete flag */
DMA_ClearFlag(DMA1_FLAG_TC6);
}
/* EV8_2: Wait until BTF is set before programming the STOP */
while(!I2C_CheckEvent(I2Cx, I2C_EVENT_MASTER_BYTE_TRANSMITTED));
/* Send STOP Condition */
I2C_GenerateSTOP(I2Cx, ENABLE);
/* Make sure that the STOP bit is cleared by Hardware before CR1 write access */
while ((I2Cx->CR1 & 0x0200) == 0x0200);
}
I see that for some while loops you have a timeout, but for some you don't:
while ((I2Cx->CR1 & 0x0200) == 0x0200);
Make all your loops timeout, and also make a note where the error condition occurs (it needs to be investigated - if you don't know the reason, it will come back to haunt you later).
Hardware can be a bit buggy at times, so it completely possible you're doing everything correctly, but it still doesn't work. Check errata (for STM32 I2C and your I2C slaves) for documented bugs.
A few years ago I came across an issue where I2C lines would stay low, and I had to reconfigure pins as GPIO, bit-bang some bits out, and then it I could switch back to I2C operation.
I am trying to start learning programming and I am trying to get this code to work: https://github.com/espruino/Espruino/blob/master/targetlibs/stm32f4/lib/stm32f4xx_can.c
I am using Atollic TruStudio Lite.
I did the basic LED blinking code with Discovery, but other than that. I have no clue how to do this.
I don't get how am i supposed to simulate CAN message (and other things) via STM32.
I am a total beginner, so please, don't rip my throat out.
Thanks
Here's an example of a CAN loopback you can try. It's a CAN loopback test. It's in the stm32f4 examples that you can download from the STM website. This is for an STM32439 eval board but it should work on a discovery. (Both are STM32F4 chips).
#define USE_CAN1
/* Uncomment the line below if you will use the CAN 2 peripheral */
/* #define USE_CAN2 */
#ifdef USE_CAN1
#define CANx CAN1
#define CAN_CLK RCC_APB1Periph_CAN1
#else /* USE_CAN2 */
#define CANx CAN2
#define CAN_CLK (RCC_APB1Periph_CAN1 | RCC_APB1Periph_CAN2)
#endif /* USE_CAN1 */
typedef enum {FAILED = 0, PASSED = !FAILED} TestStatus;
__IO uint32_t ret = 0; /* for return of the interrupt handling */
volatile TestStatus TestRx;
TestStatus CAN_Polling(void);
int main(void) {
/*!< At this stage the microcontroller clock setting is already configured,
this is done through SystemInit() function which is called from startup
files (startup_stm32f40_41xxx.s/startup_stm32f427_437xx.s/startup_stm32f429_439xx.s)
before to branch to application main.
To reconfigure the default setting of SystemInit() function, refer to
system_stm32f4xx.c file
*/
/* CANx Periph clock enable */
RCC_APB1PeriphClockCmd(CAN_CLK, ENABLE);
/* Initialize LEDs mounted on EVAL board */
STM_EVAL_LEDInit(LED1);
STM_EVAL_LEDInit(LED2);
/* CAN transmit at 125Kb/s and receive by polling in loopback mode */
TestRx = CAN_Polling();
if (TestRx != FAILED) { /* OK */
/* Turn on LED1 */
STM_EVAL_LEDOn(LED1);
} else { /* KO */
/* Turn on LED2 */
STM_EVAL_LEDOn(LED2);
}
/* Infinite loop */
while (1) { }
}
/**
* #brief Configures the CAN, transmit and receive by polling
* #param None
* #retval PASSED if the reception is well done, FAILED in other case
*/
TestStatus CAN_Polling(void) {
CAN_InitTypeDef CAN_InitStructure;
CAN_FilterInitTypeDef CAN_FilterInitStructure;
CanTxMsg TxMessage;
CanRxMsg RxMessage;
uint32_t uwCounter = 0;
uint8_t TransmitMailbox = 0;
/* CAN register init */
CAN_DeInit(CANx);
/* CAN cell init */
CAN_InitStructure.CAN_TTCM = DISABLE;
CAN_InitStructure.CAN_ABOM = DISABLE;
CAN_InitStructure.CAN_AWUM = DISABLE;
CAN_InitStructure.CAN_NART = DISABLE;
CAN_InitStructure.CAN_RFLM = DISABLE;
CAN_InitStructure.CAN_TXFP = DISABLE;
CAN_InitStructure.CAN_Mode = CAN_Mode_LoopBack;
CAN_InitStructure.CAN_SJW = CAN_SJW_1tq;
/* CAN Baudrate = 175kbps (CAN clocked at 42 MHz) */
CAN_InitStructure.CAN_BS1 = CAN_BS1_6tq;
CAN_InitStructure.CAN_BS2 = CAN_BS2_8tq;
CAN_InitStructure.CAN_Prescaler = 16;
CAN_Init(CANx, &CAN_InitStructure);
/* CAN filter init */
#ifdef USE_CAN1
CAN_FilterInitStructure.CAN_FilterNumber = 0;
#else /* USE_CAN2 */
CAN_FilterInitStructure.CAN_FilterNumber = 14;
#endif /* USE_CAN1 */
CAN_FilterInitStructure.CAN_FilterMode = CAN_FilterMode_IdMask;
CAN_FilterInitStructure.CAN_FilterScale = CAN_FilterScale_32bit;
CAN_FilterInitStructure.CAN_FilterIdHigh = 0x0000;
CAN_FilterInitStructure.CAN_FilterIdLow = 0x0000;
CAN_FilterInitStructure.CAN_FilterMaskIdHigh = 0x0000;
CAN_FilterInitStructure.CAN_FilterMaskIdLow = 0x0000;
CAN_FilterInitStructure.CAN_FilterFIFOAssignment = 0;
CAN_FilterInitStructure.CAN_FilterActivation = ENABLE;
CAN_FilterInit(&CAN_FilterInitStructure);
/* transmit */
TxMessage.StdId = 0x11;
TxMessage.RTR = CAN_RTR_DATA;
TxMessage.IDE = CAN_ID_STD;
TxMessage.DLC = 2;
TxMessage.Data[0] = 0xCA;
TxMessage.Data[1] = 0xFE;
TransmitMailbox = CAN_Transmit(CANx, &TxMessage);
uwCounter = 0;
while((CAN_TransmitStatus(CANx, TransmitMailbox) != CANTXOK) && (uwCounter != 0xFFFF)) {
uwCounter++;
}
uwCounter = 0;
while((CAN_MessagePending(CANx, CAN_FIFO0) < 1) && (uwCounter != 0xFFFF)) {
uwCounter++;
}
/* receive */
RxMessage.StdId = 0x00;
RxMessage.IDE = CAN_ID_STD;
RxMessage.DLC = 0;
RxMessage.Data[0] = 0x00;
RxMessage.Data[1] = 0x00;
CAN_Receive(CANx, CAN_FIFO0, &RxMessage);
if (RxMessage.StdId != 0x11) {
return FAILED;
}
if (RxMessage.IDE != CAN_ID_STD) {
return FAILED;
}
if (RxMessage.DLC != 2) {
return FAILED;
}
if ((RxMessage.Data[0]<<8|RxMessage.Data[1]) != 0xCAFE) {
return FAILED;
}
return PASSED; /* Test Passed */
}