单片机之旅(串口)--1
来源:互联网 发布:数据库怎么删除表 编辑:程序博客网 时间:2024/06/14 15:52
如果说单写单片机什么最重要,我想应该就是串口了吧。
在我没有钱买仿真调试那玩意的时候,也在我发现手上就一块2块钱的单片机的时候串口可能就成为了唯一的调试手断了。
我喜欢用串口中断的方式来使用串口,一般的话我都是这样写的,可能用先入为主,因为看过很多串口相关的写法,但我还是觉得代码这样写要好看一些,因为这是我老大(后来才知道他是我学长)拿我的代码和他的对比了下,确实好像好看些,后来大就一直都这样写了:
以下是自收自发的测试程序(把串口的tx,rx线短在一起),用来debug还是可以的:
头文件:uart.h
#ifndef uart_h_
#define uart_h_
#define UART_RX_SIZE 128
#define UART_TX_SIZE 128
extern unsigned char uart_rx_byte;
extern unsigned char uart_tx_byte;
extern unsigned char xdata uart_rx_buffer[UART_RX_SIZE];
extern unsigned char *uart_tx_point;
void uart_init(void);
void uart_send_data(unsigned char *send_data_point, unsigned char length);
void uart_task(void);
extern void uart_init(void);
extern void uart_send_data(unsigned char *send_data_point, unsigned char length);
extern void uart_task(void);
#endif
源代码文件:uart.c
#include "../include/stc12c5a60s2.h"
#include "../include/uart.h"
unsigned char uart_rx_byte;
unsigned char uart_tx_byte;
unsigned char xdata uart_rx_buffer[UART_RX_SIZE];
unsigned char xdata uart_tx_buffer[UART_TX_SIZE];
unsigned char *uart_tx_point;
void uart_init(void)
{
PCON &= 0x7F; //波特率不倍速
SCON = 0x50; //8位数据,可变波特率
AUXR |= 0x04; //独立波特率发生器时钟为Fosc,即1T
BRT = 0xC4; //设定独立波特率发生器重装值 //外部晶振18.432M
AUXR |= 0x01; //串口1选择独立波特率发生器为波特率发生器
AUXR |= 0x10; //启动独立波特率发生器
ES = 1;
}
void uart_send_data(unsigned char *send_data_point, unsigned char length)
{
uart_tx_byte = length;
uart_tx_point = send_data_point;
SBUF = *uart_tx_point;
}
void uart_task(void)
{
if(uart_rx_byte > 0)
{
uart_send_data(uart_rx_buffer, uart_rx_byte);
uart_rx_byte = 0;
}
}
还有串口中断文件:interrupt.c
#include "../include/stc12c5a60s2.h"
#include "../include/uart.h"
void uart_0_isr(void) interrupt 4 using 3
{
if(1 == RI)
{
RI = 0;
uart_rx_buffer[uart_rx_byte] = SBUF;
if(uart_rx_byte >= UART_RX_SIZE)
{
uart_rx_byte = UART_RX_SIZE - 1;
}
else
{
uart_rx_byte += 1;
}
}
else if(TI)
{
TI = 0;
uart_tx_byte -=1;
if(uart_tx_byte > 0)
{
uart_tx_point += 1;
SBUF = *uart_tx_point;
}
}
}
主程序:main.c
#include "../include/stc12c5a60s2.h"
#include "../include/uart.h
void main(void)
{
uart_init(); //串口初始化
EA = 1;
while(1)
{
uart_task();
delay_100ms(); //一定要有这个否则会只收到前一两个数据。
}
}
也不知道这个还有没有漏洞,反正这样用着还行。
- 单片机之旅(串口)--1
- 51单片机之串口通信(一)
- 单片机之串口通信
- 单片机串口通信(1)
- 单片机串口程序1
- 51单片机之串口通讯
- 89C52单片机之串口
- 单片机之旅——串口、8*8点阵
- 【51单片机学习过程记录】14 中断之串口中断的应用1(查询方式)
- 单片机(十)__串口
- 51系列单片机之串口通信
- msp430单片机之串口通信模块
- 学习笔记之-51单片机串口通信
- 单片机C语言之串口通信协议
- 用软件模拟单片机串口程序(1)
- 单片机==串口-1~10字符串(16)
- 菜鸟单片机随写(51单片机串口通信)
- 菜鸟学51单片机之----在笔记本上模拟PC和51串口通信1
- 风气很好的公司也有不太那个的部门——北漂18年(87)
- 洗牌问题
- 综合界面
- YOLOv2训练自己的数据集(VOC格式)
- eclipse安装JAVA反编译插件
- 单片机之旅(串口)--1
- LeetCode 3. Longest Substring Without Repeating Characters
- bzoj2134: 单选错位
- invalidate、postInvalidat、 postInvalidateOnAnimation 区别
- ZJOI2017 游记
- PAT1014 福尔摩斯的约会
- idea 的pom文件添加 dependency 无法更新
- Alignment trap
- 基础指南:利用Sed Stream编辑器在Linux中处理文本