一、前言
本次使用STM8S003F芯片,编译环境为IAR,至于新建工程什么的教程很多,这里就不多叙述了。
二、串口初始化
串口使用的485的方式,所以首先初始化串口和IO口
#define RS485_GPIO_PORT (GPIOD)
#define RS485_GPIO_PINS (GPIO_PIN_4)
#define RS485_SEND GPIO_WriteHigh(RS485_GPIO_PORT, (GPIO_Pin_TypeDef)RS485_GPIO_PINS);
#define RS485_RECEIVE GPIO_WriteLow(RS485_GPIO_PORT, (GPIO_Pin_TypeDef)RS485_GPIO_PINS);
GPIO_Init(RS485_GPIO_PORT, (GPIO_Pin_TypeDef)RS485_GPIO_PINS, GPIO_MODE_OUT_PP_LOW_FAST);
static void UART1_Config(void)
{
/* UART1 configured as follow:
- Word Length = 8 Bits
- 1 Stop Bit
- No parity
- BaudRate = 19200 baud
- UART1 Clock enabled
- Polarity Low
- Phase Middle
- Last Bit enabled
- Receive and transmit enabled
*/
/* Enable the UART1 peripheral */
// UART1_DeInit();
UART1_Init((uint32_t)BAUDRATE, UART1_WORDLENGTH_8D, UART1_STOPBITS_1, UART1_PARITY_NO,
(UART1_SyncMode_TypeDef)(UART1_SYNCMODE_CLOCK_DISABLE),
UART1_MODE_TXRX_ENABLE);
/* Enable the UART1 Receive interrupts */
UART1_ITConfig(UART1_IT_RXNE_OR, ENABLE);
UART1_ITConfig(UART1_IT_IDLE, ENABLE);
UART1_Cmd(ENABLE);
/* Enable general interrupts */
enableInterrupts();
}
串口使用接收中断+空闲中断的方式接收串口收到的信息。
三、串口发送接收
在串口中断里调用中断函数:
extern void UART1_IRQHandler(void);
INTERRUPT_HANDLER(UART1_RX_IRQHandler, 18)
{
UART1_IRQHandler();
/* In order to detect unexpected events during development,
it is recommended to set a breakpoint on the following instruction.
*/
}
在中断函数里实现发送接收,便于修改:
void UART1_IRQHandler(void)
{
if (UART1_GetITStatus(UART1_IT_RXNE) != RESET)
{
/* Read the received data */
RxBuffer[RxIndex] = UART1_ReceiveData8();
RxIndex++;
if (RxIndex == RxBufferSize)
{
RxIndex = 0;
}
UART1_ClearITPendingBit(UART1_IT_RXNE);
}
else if (UART1_GetITStatus(UART1_IT_IDLE) != RESET)
{
//这里处理接收到的信息
RxIndex = 0;
UART1->SR;//执行这两句可以,清除空闲中断 , //空闲中断没有单独的清除函数
UART1->DR;//执行这两句可以,清除空闲中断, //空闲中断没有单独的清除函数
//UART1_ClearITPendingBit(UART1_IT_IDLE);
/* Process the received data*/
//GPIO_WriteReverse(LED_GPIO_PORT, (GPIO_Pin_TypeDef)LED_GPIO_PINS);
}
}
对了,还有宏定义可以修改接收长度:
#define RxBufferSize 8
#define TxBufferSize 8
#define BAUDRATE 19200
uint8_t TxBuffer[TxBufferSize];
uint8_t RxBuffer[RxBufferSize];
uint8_t RxIndex = 0;
uint8_t TxIndex = 0;