编写串口出了点问题,求解
问题一:我接收到的数据显示的是ASCII码编号而不是字符串。如发送1,接收到49,;发送a,接收到97。问题二:不管发送多少数据,只能接收2个。如发送12345678,接收4950;发送abcd,接收9798。
整个代码如下:
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;
namespace 串口小助手
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)//清空发送区按键
{
send.Text = ""; //清空发送区
}
private void button3_Click(object sender, EventArgs e)//清空接收区按键
{
get.Text = ""; //清空接收区
}
private void button4_Click(object sender, EventArgs e) //打开串口按键
{
if (comboBox1.Text != "" && comboBox2.Text != "" && comboBox3.Text != "")//确保串口参数已设定
{
string ser = this.comboBox1.Text;
int bo = Convert.ToInt32(this.comboBox2.Text); ;
string yan = this.comboBox3.Text; //保存串口参数
if (!serialPort.IsOpen) //如果串口是打开的
{
serialPort.BaudRate = bo; //设定波特率
serialPort.PortName = ser; //设定串口号
if (yan == "NONE")
serialPort.Parity = System.IO.Ports.Parity.None;
if (yan == "ODD")
serialPort.Parity = System.IO.Ports.Parity.Odd;
if (yan == "EVEN")
serialPort.Parity = System.IO.Ports.Parity.Even; //设定校验位
try
{
serialPort.Open(); //打开串口
button4.Text = "关闭串口"; //改变按键显示
comboBox1.Enabled = false;
comboBox2.Enabled = false;
comboBox3.Enabled = false; //将串口号、波特率和校验位选择控件关闭
}
catch
{
MessageBox.Show("打开串口失败\n\n串口被占用!", "错误警告", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
else //如果串口是打开的
{
serialPort.Close(); //关闭串口
button4.Text = "打开串口"; //改变按键显示
comboBox1.Enabled = true;
comboBox2.Enabled = true;
comboBox3.Enabled = true; //将串口号、波特率和校验位选择控件关闭
}
}
else
{
MessageBox.Show("请调整串口参数", "错误警告", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void button1_Click(object sender, EventArgs e) //发送数据按键
{
if (serialPort.IsOpen) //如果串口以打开
{
if (send.Text == "") //如果发送数据位空
{
MessageBox.Show("请输入数据", "错误警告", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
serialPort.Write(send.Text);//发送数据
}
}
else
{
MessageBox.Show("数据发送失败\n\n串口未打开", "错误警告",MessageBoxButtons.OK,MessageBoxIcon.Error);
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void serialPort_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
int SDateTemp = this.serialPort.ReadChar();
this.get.Invoke(
new MethodInvoker(
delegate
{
this.get.Text += Convert.ToString(SDateTemp);//输出到主窗口文本控件
}
)
);
}
}
}
--------------------编程问答-------------------- 缓冲区大小不够? --------------------编程问答-------------------- 既然你知道发送的是字符,那就按字符解析就行了
int SDateTemp = this.serialPort.ReadChar();
ReadChar,只读取Char,不是字符串 --------------------编程问答-------------------- 缓冲区大小够得
补充:.NET技术 , C#