读取连接电脑COM口的电子天枰数据
mrpmc 2010-10-29 11:52:04 using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
namespace 读取条形码
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//定义 SerialPort对象
SerialPort port1;
//初始化SerialPort对象方法.PortName为COM口名称,例如"COM1","COM2"等,注意是string类型
public void InitCOM(string PortName)
{
port1 = new SerialPort(PortName);
port1.BaudRate = 9600;//波特率
port1.Parity = Parity.None;//无奇偶校验位
port1.StopBits = StopBits.Two;//两个停止位
port1.Handshake = Handshake.RequestToSend;//控制协议
port1.ReceivedBytesThreshold = 4;//设置 DataReceived 事件发生前内部输入缓冲区中的字节数
port1.DataReceived += new SerialDataReceivedEventHandler(port1_DataReceived);//DataReceived事件委托
byte[] WriteBytes = Encoding.ASCII.GetBytes("AT+CGMI\r");
}
//DataReceived事件委托方法
private void port1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
try
{
StringBuilder currentline = new StringBuilder();
//循环接收数据
while (port1.BytesToRead > 0)
{
char ch = (char)port1.ReadByte();
currentline.Append(ch.ToString());
}
//在这里对接收到的数据进行处理
textBox2.Text = currentline.ToString();
currentline = new StringBuilder();
port1.Close();
}
catch (Exception ex)
{
textBox2.Text = ex.Message.ToString();
}
}
//打开串口的方法
public void OpenPort()
{
try
{
port1.Open();
}
catch { }
if (port1.IsOpen)
{
textBox3.Text = "the port is opened!";
}
else
{
textBox3.Text = "failure to open the port!";
}
}
//关闭串口的方法
public void ClosePort()
{
port1.Close();
if (!port1.IsOpen)
{
textBox3.Text = "the port is already closed!";
}
}
//向串口发送数据
public void SendCommand(string CommandString)
{
byte[] WriteBuffer = Encoding.ASCII.GetBytes(CommandString);
port1.Write(WriteBuffer, 0, WriteBuffer.Length);
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
string str = "";
textBox1.Text = str;
}
private void button1_Click(object sender, EventArgs e)
{
//我现在用的COM1端口,按需要可改成COM2,COM3
InitCOM("COM3");
OpenPort();
}
}
}
代码如上,读取来的信息并不是数值,请教大家代码有什么问题,大家也可以提点其他实现这个功能的好的方法给我,谢谢