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 ReadWieght
{
public partial class Form1 : Form
{
public delegate void UpdateTextCallback(string text);
private void Form1_Load(object sender, EventArgs e)
{
ReadSP();
}
void ReadSP()
{
SerialPort mySerialPort = null;
mySerialPort = new SerialPort("COM1");
mySerialPort.BaudRate = 2400;
mySerialPort.Parity = Parity.None;
mySerialPort.StopBits = StopBits.One;
mySerialPort.DataBits = 8;
mySerialPort.Handshake = Handshake.RequestToSend;
mySerialPort.DtrEnable = true;
mySerialPort.RtsEnable = true;
mySerialPort.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
try
{
mySerialPort.Open();
// mySerialPort.Write(str.Trim());
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
mySerialPort.Close();
}
// Updates the textbox text.
private void UpdateText(string text)
{
// Set the textbox text.
label1.Text = text;
}
//static string text = null;
private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
this.Invoke(new UpdateTextCallback(this.UpdateText), new object[] { "DATA RECIEVED" });
try
{
SerialPort sp = (SerialPort)sender;
byte[] comBuffer = new byte[sp.BytesToRead];
sp.Read(comBuffer, 0, sp.BytesToRead);
Console.WriteLine(Encoding.ASCII.GetString(comBuffer));
// char[] chr = Encoding.ASCII.GetString(comBuffer);
string str = Encoding.ASCII.GetString(comBuffer);
if (str.Length > 7)
{
str = str.Substring(2, 6);
this.Invoke((MethodInvoker)delegate
{
label1.Text = str; // runs on UI thread
});
}
Encoding.ASCII.GetString(comBuffer);
}
catch (Exception ex)
{
// MessageBox.Show(ex.Message);
this.Invoke((MethodInvoker)delegate
{
label1.Text = ex.Message; // runs on UI thread
});
}
}
public Form1()
{
InitializeComponent();
}
}
}
问问题
373 次
2 回答
2
将mySerialPort
变量放在函数之外,ReadSP
否则当该函数完成时它将被销毁。在另一个函数中关闭端口。
于 2013-06-16T08:21:36.040 回答
0
You've commented out the line that writes to the serial port, so it looks to me like you're not sending any data down the serial port so maybe that's why a request isn't being received?
For testing I'd recommend a "loop back" which is basically linking the rx & tx lines on your serial port. You can use a metal paper clip for this - just stick each end in pins 2 & 3.
于 2013-06-16T08:26:04.363 回答