我正在开发一个项目,它将从COM端口读取数据,将其保存到数据表中,在图表中显示,并允许通过csv保存/加载数据。到目前为止,已实现串行通信和文件操作。
目前我正在使用arduino对其进行测试,该代码发送<uint16>
(包括'&lt;&gt;'符号,uint16为任意数字)。
不幸的是,DataRecievedHandler似乎永远不会被调用,我已经通过在接收到数据时将其打印到GUI中的文本框进行了测试。 Arduino的TX灯在发送数据时正常闪烁,并与arduino串行监视器配合使用。 COM端口似乎连接正常,因为它使串行线路忙,因此arduino软件无法同时连接到它。
关于我哪里出错的任何想法?我觉得这一定是蠢事。为了以防万一,我附上了完整的代码。
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;
using System.Threading;
using System.Text.RegularExpressions;
namespace FieldProbe
{
public partial class MainForm : Form
{
SerialPort _port = new SerialPort();
DataTable dt = new DataTable(); //set up datatable to hold output
int numSamples = 0;
public MainForm()
{
InitializeComponent();
}
private void MainForm_Load(object sender, EventArgs e)
{
var ports = SerialPort.GetPortNames(); //get list of ports connected to PC
cmbSerialPorts.DataSource = ports; //use list of ports as combobox options
_port.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler); //create pointer to datareceived event handler
dt.Clear(); //Clear datatable on start
dt.Columns.Add("index", typeof(int)); //index
dt.Columns.Add("dutyCycle", typeof(float)); //0.5 means equal on/off, 1.0 means permanently on
dt.Columns.Add("frequency", typeof(float)); //probe can go from 40MHz to 10GHz
dt.Columns.Add("distance", typeof(float)); //antenna to radiator distance in metres (usually 1m)
dt.Columns.Add("pulseWidth", typeof(float)); //calculated from duty cycle and frequency
dt.Columns.Add("level", typeof(int)); //output in V/m
chChart.Series["series1"].XValueMember = "level";
chChart.Series["series1"].YValueMembers = "index";
chChart.DataSource = dt;
chChart.DataBind();
}
private void btnConnect_Click(object sender, EventArgs e)
{
if (btnConnect.Text == "Connect") //if user clicks connect button
{
if (cmbSerialPorts.SelectedIndex > -1) //if port valid
{
MessageBox.Show(String.Format("You selected port '{0}'", cmbSerialPorts.SelectedItem));
Connect(cmbSerialPorts.SelectedItem.ToString()); //go to connect function
}
else
{
MessageBox.Show("Please select a port first");
}
}
else //if user clicks disconnect button
{
btnConnect.Text = "Connect";
_port.Close();
}
}
private void Connect(string portName)
{
_port = new SerialPort(portName); //set up serial port using static values (make editable in a config file?)
if (!_port.IsOpen)
{
_port.BaudRate = 9600; //CHANGE ME AFTER ARDUINO TESTING!!!!!!!!!!!!!!
_port.DataBits = 8;
_port.StopBits = StopBits.One;
_port.Parity = Parity.None;
_port.Handshake = Handshake.None;
_port.RtsEnable = true; //CHANGE ME AFTER ARDUINO TESTING!!!!!!!!!!!!!!
_port.DtrEnable = true; //CHANGE ME AFTER ARDUINO TESTING!!!!!!!!!!!!!!
try
{
_port.Open(); //connect to port
btnConnect.Text = "Disconnect";
}
catch
{
MessageBox.Show("ERROR: Port invalid or in use!");
btnConnect.Text = "Connect";
}
}
}
private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
string indata = sp.ReadExisting(); //read data from port
string indataString = Regex.Match(indata, @"\d+").Value; //extract number (still a string)
int indataInt = Int32.Parse(indataString); //convert string to int
teIncomingData.AppendText(indata); //append number to text box for testing
teIncomingData.AppendText("test1"); //show text in textbox if this function is called
numSamples++;
var pulseWidth = nudDutyCycle.Value / (nudFrequency.Value * 100);
object[] o = {numSamples, nudDutyCycle.Value, nudFrequency.Value, nudDistance.Value, pulseWidth, indataInt};
dt.Rows.Add(o);
chChart.DataBind();
}
private void btnSave_Click(object sender, EventArgs e)
{
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "csv files (*.csv)|*.csv*";
saveFileDialog1.RestoreDirectory = true;
saveFileDialog1.DefaultExt = "csv";
saveFileDialog1.AddExtension= true;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
File.WriteAllText(saveFileDialog1.FileName, dtToCSV());
}
}
private string dtToCSV()
{
string file = "";
foreach (DataColumn col in dt.Columns)
file = string.Concat(file, col.ColumnName, ",");
file = file.Remove(file.LastIndexOf(','), 1);
file = string.Concat(file, "\r\n");
foreach (DataRow row in dt.Rows)
{
foreach (object item in row.ItemArray)
file = string.Concat(file, item.ToString(), ",");
file = file.Remove(file.LastIndexOf(','), 1);
file = string.Concat(file, "\r\n");
}
return file;
}
public void saveFileDialog1_FileOk(object sender, CancelEventArgs e)
{ //do not delete me, this needs to exist for some reason for saving to work
}
}
}