使用串口实现接收和发送功能

本文介绍了如何在STM32F1开发板上使用串口USART1进行接收和发送功能的实现。内容涵盖硬件连接、串口配置、中断优先级设置、发送和接收函数的编写,以及中断处理。通过烧录代码并与串口调试助手配合,成功实现了串口通信。
摘要由CSDN通过智能技术生成

使用串口实现接收和发送功能

一、前言
本文以串口-USART1为例,初步实现接收和发送功能,使用的是stm32f1板子,基于火哥教学做的自我小结。电脑设备需要安装串口调试助手和USB转串口CH340G的驱动。

二、正文
1.硬件设计:
将 CH340G 的 TXD 引脚与 USART1 的 RX 引脚连接, CH340G 的 RXD 引脚与USART1 的 TX 引脚连接,此处已在开发板上配置好了,我们只需进行编程。
在这里插入图片描述

—————————————————————————————————
USART1的引脚重映射是PA9和PA10
在这里插入图片描述

2.软件设计:
编写的要点:①提前在头文件中写好需要的宏定义 ②初始化GPIO和USART1编写于一个函数中 ③串口中断优先级配置,包括配置接受中断 ④使能串口 ⑤编写中断函数 ⑥编写发送和接收函数
—————————————————————————————————

①编写头文件“bsp_usart.h”
在这里插入图片描述
若想使

public partial class Form1 : Form { public Form1() { InitializeComponent(); } SerialPort port1 = new SerialPort(); string InputData = String.Empty; delegate void SetTextCallback(string text); private void Port_Select() {//获取机器中的串口地址 string[] ports = SerialPort.GetPortNames(); foreach (string port in ports) { comboBox1.Items.Add(port); } } private void Form1_Load_1(object sender, EventArgs e) { Port_Select(); this.comboBox1.SelectedIndex = 0; this.comboBox2.SelectedIndex = 0; } private void button1_Click(object sender, EventArgs e) { if (button1.Text == "关闭串口") //当要关闭串口的时候 { port1.DiscardOutBuffer(); port1.DiscardInBuffer(); port1.Close(); button1.Text = "打开串口"; label3.Text = "串口当前状况:未打开"; comboBox1.Enabled = true; comboBox2.Enabled = true; } else if (button1.Text == "打开串口") //当要打开串口的时候 { try { port1.PortName = comboBox1.SelectedItem.ToString(); port1.BaudRate = Convert.ToInt32(comboBox2.SelectedItem); port1.DataBits = 8; port1.RtsEnable = true; port1.Open(); port1.DiscardOutBuffer(); port1.DiscardInBuffer(); button1.Text = "关闭串口"; comboBox1.Enabled = false; comboBox2.Enabled = false; label3.Text = "串口:" + comboBox1.SelectedItem.ToString() + " 波特率:" + comboBox2.SelectedItem.ToString() + " 数据位:8 "; } catch { button1.Text = "打开串口"; label3.Text = "串口:" + comboBox1.SelectedItem.ToString() + "打开失败"; MessageBox.Show("该串口无法打开"); } } } 资源中部分代码
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值