做STC8G1K08A-8Pin芯片的485數據收發,使用STC官方的庫編程比較方便。調試的時候數據收發始終不正常,想達到的目的是外部發送兩個字節的數據,第一個是A6握手數據,另一個任意數據。芯片接收并識別到握手數據后,回送收到的字節數與第二個任意數據。就這么簡單的一個小程序,搞了半天都沒搞定。后來為了驗證程序的正確性干脆把程序移植到了STC8G1K08-16Pin管腳的芯片上數據收發卻 是正常的。這是為何?下面是STC8G1K08A-8Pin的程序仿真測試:程序執行發送“L、B、H”三個字符,調用發送函數實參裝入正確但到賦值給SBUF卻是零,另外中斷接收到的數據也是錯誤的,懷疑是波特率錯誤,特意把時鐘從P5.5輸出用示波器查看頻率有點小誤差是22.107M,但16Pin的芯片頻率也是如此。不知道 問題在什么地方。
單片機源程序如下:
- #include "config.h"
- #include "GPIO.h"
- #include "UART.h"
- /************************ 485通訊與IO口配置 ****************************/
- void GPIO_config(void)
- {
- GPIO_InitTypeDef GPIO_InitStructure; //結構定義
- //初始化串口管腳
- GPIO_InitStructure.Pin = GPIO_Pin_0|GPIO_Pin_1|GPIO_Pin_2; //指定要初始化的IO
- GPIO_InitStructure.Mode = GPIO_PullUp; //指定IO上拉準雙向輸入或輸出方式
- GPIO_Inilize(GPIO_P3,&GPIO_InitStructure); //初始化
- //初始化UART1映射管腳
- GPIO_InitStructure.Pin = GPIO_Pin_4|GPIO_Pin_5; //指定要初始化的IO, GPIO_Pin_4
- GPIO_InitStructure.Mode = GPIO_PullUp; //指定IO上拉準雙向輸入或輸出方式
- GPIO_Inilize(GPIO_P5,&GPIO_InitStructure); //初始化
- //初始化485芯片的使能控制管腳
- GPIO_InitStructure.Pin = GPIO_Pin_3; //指定要初始化的IO, GPIO_Pin_0 GPIO_Pin_1
- GPIO_InitStructure.Mode = GPIO_OUT_PP; //指定IO推挽的輸入或輸出方式
- GPIO_Inilize(GPIO_P3,&GPIO_InitStructure); //初始化
-
- }
- void UART_config(void)
- {
- COMx_InitDefine COMx_InitStructure; //結構定義
- COMx_InitStructure.UART_Mode = UART_8bit_BRTx; //模式,
- COMx_InitStructure.UART_BRT_Use = BRT_Timer1; //使用Timer1做波特率發生器,
- COMx_InitStructure.UART_BaudRate = 9600ul; //波特率, 一般 110 ~ 115200
- COMx_InitStructure.UART_RxEnable = ENABLE; //接收允許,
- COMx_InitStructure.BaudRateDouble = DISABLE; //波特率加倍,
- COMx_InitStructure.UART_Interrupt = ENABLE; //中斷允許,
- COMx_InitStructure.UART_Priority = Priority_0; //指定中斷優先級(低到高)
- UART_Configuration(UART1, &COMx_InitStructure); //初始化串口1
- }
- void delayms(unsigned int ms)
- {
- unsigned int i,j;
- for(i = 0; i < ms; i++)
- for(j = 0; j < 100; j++);
- }
- /******************** 主函數**************************/
- void main(void)
- {
- GPIO_config();
- UART_config();
- TX1_write2buff(0x4C); //"L"發送回送數據
- TX1_write2buff(0x42); //"B"發送回送數據
- TX1_write2buff(0x48); //"H"發送回送數據
-
- P_SW1 = 0x84; //UART1配置映射到P5.5與P5.4腳,SPI配置缺失
- RS485_EN = 0; //使485通訊使能在接收狀態
- EA = 1; //開放所有中斷
-
- while(1)
- {
- if(COM1.B_RX_OK == 1 && RX1_Buffer[0] == 0xa6) //判斷接收標志
- {
- delayms(200);
- TX1_write2buff(COM1.RX_Cnt); //回送收到的數據長度
- TX1_write2buff(RX1_Buffer[1]); //回送收到的數據
- COM1.B_RX_OK = 0; //清除標志
- COM1.RX_Cnt = 0; //清除數據長度
- }
- }
-
- }
復制代碼
485測試程序.rar
(205.25 KB, 下載次數: 7)
2023-3-11 13:25 上傳
點擊文件名下載附件
|