mcs51 串口通信 单片机发 pc收
pc代码:csharp串口接收.7z
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using System.Threading;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
// SerialPort SpSMS = new SerialPort("COM3", 300, 0, 8, StopBits.One);
SerialPort serialPort1 = new SerialPort();
public Form1()
{
InitializeComponent();
}
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
int num; //获取缓冲数据个数
num = serialPort1.BytesToRead;
byte[] data = new byte[num];
serialPort1.Read(data, 0, num); //读数
}
private void button1_Click(object sender, EventArgs e)
{
serialPort1.PortName = "COM3"; //端口号
serialPort1.BaudRate = 1200; //比特率
serialPort1.Parity = Parity.None;//奇偶校验
serialPort1.StopBits = StopBits.One;//停止位
serialPort1.ReadTimeout = 1000; //读超时,即在1000内未读到数据就引起超时异常
serialPort1.Open();//端口打开
serialPort1.DataReceived += new SerialDataReceivedEventHandler(serialPort1_DataReceived);//过程注册
}
private void button2_Click(object sender, EventArgs e)
{
serialPort1.Close();//关闭串口
}
}
}
mcs51代码:C语言串口通讯.7z
/* 11.0592MHz, 波特率1200 */
#include<reg51.h>
#include<stdio.h>//头文件
void main(void)//主程序
{
SCON=0x50;//串口方式1,允许接收
TMOD=0x20;//定时器1,定时方式2
TCON=0x40;//设定时器1开始计数
TH1=0xE8;//11.0592MHz, 1200波特率
TL1=0xE8;
TI=1;
TR1=1;
while(1)
{
printf("Hello ni hao!");
}
}