STM8串列埠通訊UART驅動
阿新 • • 發佈:2021-12-24
目錄
使用軟體:IAR FOR STM8
程式設計方式:韌體庫
硬體配套:STM8S105K4T6最小系統板
注意事項:需在IAR工程配置中:在 General Options->Library Configuration->Library 選擇 Full;在 General Options->Library Options->Printf formatter 選擇 Large,Math functions 選擇 Default;另外不能串列埠列印小數,需進一步處理資料
這是我在做課設時參考的程式碼,現記錄如下:
1. uart.h
#ifndef __UART_H #define __UART_H #include "stm8s.h" #include "stdio.h" #ifdef _RAISONANCE_ #define PUTCHAR_PROTOTYPE int putchar (char c) #define GETCHAR_PROTOTYPE int getchar (void) #elif defined (_COSMIC_) #define PUTCHAR_PROTOTYPE char putchar (char c) #define GETCHAR_PROTOTYPE char getchar (void) #else /* _IAR_ */ #define PUTCHAR_PROTOTYPE int putchar (int c) #define GETCHAR_PROTOTYPE int getchar (void) #endif /* _RAISONANCE_ */ void UART2_Config(void); void UART2_SendByte(u8 data); void UART2_SendStr(const unsigned char *p_str); void Delay(uint32_t nCount); #endif /* __UART_H */
2. uart.c
#include "UART.h" void UART2_Config(void) { CLK_PeripheralClockConfig(CLK_PERIPHERAL_UART2, ENABLE); UART2_DeInit(); /* * 將UART2配置為: * 波特率 = 115200 * 資料位 = 8 * 1位停止位 * 無校驗位 * 使能接收和傳送 * 使能接收中斷 */ UART2_Init((u32)115200, UART2_WORDLENGTH_8D, UART2_STOPBITS_1, UART2_PARITY_NO , UART2_SYNCMODE_CLOCK_DISABLE , UART2_MODE_TXRX_ENABLE); UART2_ITConfig(UART2_IT_RXNE_OR, ENABLE); UART2_Cmd(ENABLE); } void Delay(uint32_t nCount) { /* Decrement nCount value */ while (nCount != 0) { nCount--; } } void UART2_SendByte(u8 data) { UART2_SendData8((unsigned char)data); /* 等待傳輸結束 */ while (UART2_GetFlagStatus(UART2_FLAG_TXE) == RESET); } void UART2_SendStr(const unsigned char *p_str) { // u8 i = 0; while(*p_str != '\0') { UART2_SendByte(*p_str); // Delay(1000); p_str++; } } /**********************************printf*********************************************/ /** * @brief Retargets the C library printf function to the UART. * @param c Character to send * @retval char Character sent */ PUTCHAR_PROTOTYPE { /* Write a character to the UART2 */ UART2_SendData8(c); /* Loop until the end of transmission */ while (UART2_GetFlagStatus(UART2_FLAG_TXE) == RESET); return (c); } /** * @brief Retargets the C library scanf function to the USART. * @param None * @retval char Character to Read */ GETCHAR_PROTOTYPE { #ifdef _COSMIC_ char c = 0; #else int c = 0; #endif /* Loop until the Read data register flag is SET */ while (UART2_GetFlagStatus(UART2_FLAG_RXNE) == RESET); c = UART2_ReceiveData8(); return (c); }