C#与51单片机串口通信
2019-04-15 17:25发布
生成海报
C#与51单片机串口通信
51接受数据,PC发送数据。
通过单片机的数码管将PC发送的16进制数据显示出来。
51接受数据代码:
-
#include
-
#include
-
#include
-
-
sbit LS138A = P2^2;
-
sbit LS138B = P2^3;
-
sbit LS138C = P2^4;
-
-
unsigned char ch;
-
bit read_flag= 0 ;
-
-
unsigned char code Disp_Tab[] = {0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f,0x40};
-
void delay(unsigned int i);
-
void init_serialcom( void )
-
-
{
-
-
SCON = 0x50 ;
-
-
-
-
TMOD |= 0x20 ;
-
-
-
-
PCON |= 0x80 ;
-
-
TH1 = 0xF3;
-
-
IE |= 0x90 ;
-
-
TR1 = 1 ;
-
-
TI=1;
-
-
-
-
}
-
-
-
-
-
-
void send_char_com( unsigned char ch)
-
-
{
-
SBUF=ch;
-
while (TI== 0);
-
TI= 0 ;
-
-
}
-
-
-
-
-
-
void serial () interrupt 4 using 3
-
-
{
-
if (RI)
-
{
-
-
RI = 0 ;
-
-
ch=SBUF;
-
-
read_flag= 1 ;
-
-
}
-
-
}
-
-
-
-
main()
-
-
{
-
int LedNumVal = 0;
-
unsigned char LedOut[3];
-
int i = 0;
-
-
init_serialcom();
-
-
while ( 1 )
-
{
-
-
if (read_flag)
-
-
{
-
-
read_flag= 0 ;
-
send_char_com(ch);
-
LedNumVal = ch;
-
}
-
-
LedOut[0]=Disp_Tab[LedNumVal / 100];
-
LedOut[1]=Disp_Tab[(LedNumVal / 10) % 10];
-
LedOut[2]=Disp_Tab[LedNumVal % 10]|0x80;
-
-
-
for( i=0; i<3; i++)
-
{
-
P0 = LedOut[i];
-
-
switch(i)
-
{
-
case 0:LS138A=0; LS138B=0; LS138C=0; break;
-
case 1:LS138A=1; LS138B=0; LS138C=0; break;
-
case 2:LS138A=0; LS138B=1; LS138C=0; break;
-
}
-
delay(100);
-
}
-
}
-
}
-
-
void delay(unsigned int i)
-
{
-
char j;
-
for(i; i > 0; i--)
-
for(j = 200; j > 0; j--);
-
}
C#发送数据代码:
-
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;
-
using System.IO.Ports;
-
-
namespace 交通灯串口通信
-
{
-
public partial class Form1 : Form
-
{
-
public Form1()
-
{
-
InitializeComponent();
-
}
-
-
private SerialPort com;
-
-
private void button1_Click(object sender, EventArgs e)
-
{
-
-
com = new SerialPort();
-
com.BaudRate = 4800;
-
com.PortName = "COM4";
-
com.DataBits = 8;
-
com.Open();
-
Byte[] data = new Byte[4];
-
data[0] = 0x10;
-
com.Write(data, 0, 1);
-
com.Close();
-
}
-
}
-
}
-
OR
打开微信“扫一扫”,打开网页后点击屏幕右上角分享按钮