刚开始听到“上位机程序”这词时以为很难,感觉好高大上的样子,其实做起来也没那么难。本文的上位机程序就是电脑通过数据线来连接51单片机串口,并且通过C#程序来发送字节数据给51单片机.
首先。打开VS2010→新建项目→其他语言→C#→Windows→Windows窗体应用程序,然后输入文件名,点击确认就创建好工程了。
然后在Form1.cs(设计)界面下,点右边点击工具箱,找到Button,ComboBox,SerialPort(串口)这三个组件,并且把它拉到设计的窗体下。
然后在button1右键选择属性,找到Text,改为发送,在ComboBox1右键选择属性,找到DropDownStyle,改为DropDownList(下拉列表),在SerialPort右键选择属性,找到PortName,改为COM3(根据自己的USB接口号来改),
最后双击设计窗口,编写程序运行,连上单片机,便可以发送数据给单片机了。
下面是程序,具体操作,上B站搜索“上位机”,查看教学视频.
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;
namespace chuangkou
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
int i;
string str;
for (i = 0; i < 256; i++)
{
str = i.ToString("X").ToUpper();
if (str.Length == 1)
str = "0" + str;
comboBox1.Items.Add("0X" + str);
}
}
private void button1_Click(object sender, EventArgs e)
{
string data = comboBox1.Text;
string condata = data.Substring(2, 2);
byte[] buffer = new byte[1];
buffer[0] = Convert.ToByte(condata, 16);
try
{
serialPort1.Open(); //打开串口
serialPort1.Write(buffer, 0, 1);//发送数据
serialPort1.Close(); //关闭串口
}
catch
{
serialPort1.Close();
MessageBox.Show("端口错误", "错误");
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}