Page MenuHomec4science

uart.c
No OneTemporary

File Metadata

Created
Mon, Jun 10, 22:54
#include "uart.h"
uart_rxByteHandlerFunc uart_rxHandler;
/**
* @brief Initialize the UART module.
* @param f: a pointer to the function to be called each time a byte arrives.
*/
void uart_Init(uart_rxByteHandlerFunc f)
{
GPIO_InitTypeDef GPIO_InitStruct;
USART_InitTypeDef USART_InitStruct;
NVIC_InitTypeDef NVIC_InitStruct;
// Periph clock enable
RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2, ENABLE);
// GPIO (PC10 & PC11)
GPIO_InitStruct.GPIO_Pin = USART_TX_Pin;
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_AF;
GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStruct.GPIO_OType = GPIO_OType_PP;
GPIO_InitStruct.GPIO_PuPd = GPIO_PuPd_UP;
GPIO_Init(USART_TX_Port, &GPIO_InitStruct);
GPIO_PinAFConfig(USART_TX_Port, USART_TX_PinSource, GPIO_AF_USART2);
GPIO_InitStruct.GPIO_Pin = USART_RX_Pin;
GPIO_Init(USART_RX_Port, &GPIO_InitStruct);
GPIO_PinAFConfig(USART_RX_Port, USART_RX_PinSource, GPIO_AF_USART2);
// UART config
USART_InitStruct.USART_BaudRate = USART_BAUDRATE;
USART_InitStruct.USART_WordLength = USART_WordLength_8b;
USART_InitStruct.USART_StopBits = USART_StopBits_1; // 1 stop bit (standard)
USART_InitStruct.USART_Parity = USART_Parity_No;
USART_InitStruct.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
USART_InitStruct.USART_Mode = USART_Mode_Tx|USART_Mode_Rx; //Two way datas
USART_Init(USART2, &USART_InitStruct);
// USART Rx interrupt
USART_ITConfig(USART2, USART_IT_RXNE, ENABLE);
NVIC_InitStruct.NVIC_IRQChannel = USART2_IRQn;
NVIC_InitStruct.NVIC_IRQChannelPreemptionPriority = UART_RX_IRQ_PRIORIY;
NVIC_InitStruct.NVIC_IRQChannelSubPriority = 0;
NVIC_InitStruct.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStruct);
USART_Cmd(USART2, ENABLE);
// Function called when a byte arrives, to process it.
uart_rxHandler = f;
}
/**
* @brief Get the received byte, and send it to the specified RX handler.
* @note Called by the received byte interrupt.
*/
void USART2_IRQHandler(void)
{
if(USART_GetITStatus(USART2, USART_IT_RXNE))
{
uint8_t rxData = USART2->DR; // Read the DataRegister (also clears the RX interrupt pending bit).
// Call the external RX byte handler.
uart_rxHandler(rxData);
}
}
/**
* @brief Sent a byte through UART.
* @param data: byte to send through UART.
* @note This function blocks until the byte is sent.
*/
void uart_SendByte(uint8_t data)
{
while( !(USART_PC_COMM->SR & 0x00000040) ) // Wait until data register is empty.
;
USART_SendData(USART_PC_COMM, data);
}
/**
* @brief Sent an array of bytes through UART.
* @note This function blocks until all the bytes are sent.
* @param data: bytes array to send through UART.
* @param length: number of bytes in the array.
*/
void uart_SendBytes(uint8_t *data, int length)
{
int i;
for(i=0; i<length; i++)
uart_SendByte(data[i]);
}

Event Timeline