看了两周C#,还是什么都不会,只能改程序。参考了网上几份代码,修改了下,弄成这样。还有很多不好使,比如在接收数据时突然关闭串口会死,向电脑发回车时好像“\n”就行了。下载了原子哥串口实验,有的地方打不出来,把"\r\n"改成"\n"会好点。贴上来这个半成品都算不上的东西首先是为了给更多像我一样的上位机新手一个参考,再就是让大家帮助我一起学习!把这些问题解决喽~~~
代码如下::: 大家一定帮我解决这些啊!!!谢谢啦
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 SerialCOM
{
public partial class Form1 : Form
{
SerialPort serialPort = new SerialPort();
public Form1()
{
InitializeComponent();
this.toolStripStatusLabel1.Text = "端口号:端口未打开";
this.toolStripStatusLabel2.Text = "波特率:端口未打开";
this.toolStripStatusLabel3.Text = "数据位:端口未打开";
this.toolStripStatusLabel4.Text = "停止位:端口未打开";
}
/// <summary>
/// 串口检测
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnCheckCOM_Click(object sender, EventArgs e)
{
comboBox1.Items.Clear();
for (int i = 0; i < 20; i++)
{
try
{
SerialPort serialPort = new SerialPort("COM" + (i + 1).ToString());
serialPort.Open();
serialPort.Close();
comboBox1.Items.Add("COM" + (i + 1).ToString());
}
catch (Exception)
{
comboBox1.Text = "COM" + (i + 1).ToString() + "不可用";
continue;
}
}
comboBox1.SelectedIndex = 0; //串口号
comboBox2.SelectedIndex = 3; //波特率
comboBox3.SelectedIndex = 0; //数据位
comboBox4.SelectedIndex = 0; //停止位
}
/// <summary>
/// 关闭串口按钮
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnCloseCom_Click(object sender, EventArgs e)
{
try
{
if (btnOpenCom.Enabled == false)
{
btnOpenCom.Enabled = true;
btnCheckCOM.Enabled = true;
comboBox1.Enabled = true;
comboBox2.Enabled = true;
comboBox3.Enabled = true;
comboBox4.Enabled = true;
serialPort.Close();
//MessageBox.Show("串口关闭成功!");
this.toolStripStatusLabel1.Text = "端口号:端口未打开";
this.toolStripStatusLabel2.Text = "波特率:端口未打开";
this.toolStripStatusLabel3.Text = "数据位:端口未打开";
this.toolStripStatusLabel4.Text = "停止位:端口未打开";
}
else
{
MessageBox.Show("请先打开串口哦亲~~!");
}
}
catch (Exception)
{
MessageBox.Show("串口关闭失败"); return;
}
}
/// <summary>
/// 打开串口按钮
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnOpenCom_Click(object sender, EventArgs e)
{
try
{
String str1 = comboBox1.Text;
String str2 = comboBox2.Text;
String str3 = comboBox3.Text;
String str4 = comboBox4.Text;
Int32 int2 = Convert.ToInt32(str2);
Int32 int3 = Convert.ToInt32(str3);
if (str1 == null)
{
MessageBox.Show("请先选择串口!", "Error");
return;
}
serialPort.PortName = str1;
serialPort.BaudRate = int2;
serialPort.DataBits = int3;
switch (comboBox4.Text)
{
case "1":
serialPort.StopBits = StopBits.One;
break;
case "1.5":
serialPort.StopBits = StopBits.OnePointFive;
break;
case "2":
serialPort.StopBits = StopBits.Two;
break;
default:
MessageBox.Show("参数不正确哦", "Error");
break;
}
serialPort1.ReadBufferSize = 1;//设置串口读缓冲区大小数值
serialPort1.WriteBufferSize = 1;//设置串口写缓冲区大小数值
if (serialPort.IsOpen == true)
{
serialPort.Close();
}
serialPort.Open();
//MessageBox.Show("串口打开成功!", str1);
Control.CheckForIllegalCrossThreadCalls = false;
serialPort.DataReceived += new SerialDataReceivedEventHandler(serialPort_DataReceived);
this.toolStripStatusLabel1.Text = "端口号:" + serialPort.PortName + " ";
this.toolStripStatusLabel2.Text = "波特率:" + serialPort.BaudRate + " ";
this.toolStripStatusLabel3.Text = "数据位:" + serialPort.DataBits + " ";
this.toolStripStatusLabel4.Text = "停止位:" + serialPort.StopBits + " ";
btnOpenCom.Enabled = false;
btnCheckCOM.Enabled = false;
comboBox1.Enabled = false;
comboBox2.Enabled = false;
comboBox3.Enabled = false;
comboBox4.Enabled = false;
}
catch (Exception)
{
MessageBox.Show("没发现串口设备,请检测串口!");
return;
}
}
/// <summary>
/// 清除接收区
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnCleanRec_Click(object sender, EventArgs e)
{
// tbRec.Text = "";
tbRec.Clear();
// serialPort.DiscardInBuffer();
}
/// <summary>
/// 退出软件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnExit_Click(object sender, EventArgs e)
{
try
{
serialPort.Close();
}
catch (Exception we)
{
MessageBox.Show("串口关闭异常"+we.Message);
}
Application.Exit();
}
private void btSendData_Click(object sender, EventArgs e)
{
if (serialPort.IsOpen==false) //如果没打开
{
MessageBox.Show("请先打开串口!", "Error");
return;
}
string strSend = tbSend.Text;
if (radio1.Checked == true) //“HEX发送” 按钮
{
//处理数字转换
string sendBuf = strSend;
string sendnoNull = sendBuf.Trim();
string sendNOComma = sendnoNull.Replace(',', ' '); //去掉英文逗号
string sendNOComma1 = sendNOComma.Replace(',', ' '); //去掉中文逗号
string strSendNoComma2 = sendNOComma1.Replace("0x", " "); //去掉0x
strSendNoComma2.Replace("0X"," "); //去掉0X
string[] strArray = strSendNoComma2.Split(' ');
int byteBufferLength = strArray.Length;
for (int i = 0; i < strArray.Length; i++)
{
if (strArray == "")
{
byteBufferLength--;
}
}
// int temp = 0;
byte[] byteBuffer = new byte[byteBufferLength];
int ii = 0;
for (int i = 0; i < strArray.Length; i++) //对获取的字符做相加运算
{
Byte[] bytesOfStr = Encoding.Default.GetBytes(strArray);
int decNum = 0;
if (strArray == "")
{
continue;
}
else
{
decNum = Convert.ToInt32(strArray, 16);
}
try //防止输错,使其只能输入一个字节的字符
{
byteBuffer[ii] = Convert.ToByte(decNum);
}
catch (Exception qw)
{
MessageBox.Show("输入多了!"+qw.Message);
tbSend.Enabled = false;
return;
}
ii++;
}
serialPort.Write(byteBuffer, 0, byteBuffer.Length);
}
else //以字符串形式发送时
{
serialPort.WriteLine(strSend+"\r\n"); //写入数据
}
}
void serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
if (serialPort.IsOpen)
{
//输出当前时间
//DateTime dt = DateTime.Now;
//tbRec.Text += dt.GetDateTimeFormats('f')[0].ToString() + "\r\n";
// tbRec.SelectAll();
//tbRec.SelectionColor = Color.Blue; //改变字体的颜色
byte[] byteRead = new byte[serialPort.BytesToRead]; //BytesToRead:sp1接收的字符个数
if (radio2.Checked == false) //'发送字符串'单选按钮
{
serialPort.Encoding = System.Text.Encoding.Default;//
tbRec.Text += serialPort.ReadLine() + "\r\n";
this.tbRec.SelectionStart = this.tbRec.TextLength;
this.tbRec.ScrollToCaret();
serialPort.DiscardInBuffer();
}
else //接收16进制按钮'
{
try
{
serialPort.Encoding = System.Text.Encoding.ASCII;
Byte[] receivedData = new Byte[serialPort.BytesToRead]; //创建接收字节数组
serialPort.Read(receivedData, 0, receivedData.Length); //读取数据
serialPort.DiscardInBuffer(); //清空SerialPort控件的Buffer
string strRcv = null;
for (int i = 0; i < receivedData.Length; i++) //窗体显示
{
strRcv += receivedData.ToString("X2")+" "; //16进制显示
}
tbRec.Text += strRcv;
this.tbRec.SelectionStart = this.tbRec.TextLength;
this.tbRec.ScrollToCaret();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "出错提示");
tbSend.Text = "";
}
}
}
else
{
MessageBox.Show("请打开某个串口", "错误提示");
}
}
}
}
|