C# 从接收到的串行数据返回值到另一个函数
我正在通过Arduino从距离传感器获取串行数据到Visual Studio,我有另一台由另一个控制器控制的机器 从接收到的串行数据返回值到另一个函数 我的问题是:如何从函数返回值C# 从接收到的串行数据返回值到另一个函数,c#,serial-port,C#,Serial Port,我正在通过Arduino从距离传感器获取串行数据到Visual Studio,我有另一台由另一个控制器控制的机器 从接收到的串行数据返回值到另一个函数 我的问题是:如何从函数返回值 public void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e) 到函数内部的while循环 private void btnMove_Click(object sender, EventArgs e) 我的代码如
public void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
到函数内部的while循环
private void btnMove_Click(object sender, EventArgs e)
我的代码如下:
using System;
using System.Windows.Forms;
using PokeysLibSR;
using System.Drawing;
using System.Diagnostics;
using System.Threading;
using System.IO.Ports;
using System.Text.RegularExpressions;
namespace Melexis
{
public partial class Form1 : Form
{
PokeysLib pokeys;
public Form1()
{
InitializeComponent();
serialPort1.BaudRate = 9600;
serialPort1.PortName = "COM3";
}
}
private void button1_Click(object sender, EventArgs e)
{
serialPort1.Open();
}
public void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
try
{
string line = serialPort1.ReadLine();
string yourPortStringFormatted = Regex.Replace(line, @"\t|\n|\r", "");
string yourPortStringFormatted1 = yourPortStringFormatted.Trim();
double portNum = Double.Parse(yourPortStringFormatted1);
string line1 = Convert.ToString(portNum / 100);
this.BeginInvoke(new LineReceivedEvent(LineReceived), line1);
}
catch { }
finally
{
GC.Collect();
}
}
private delegate void LineReceivedEvent(string line1);
private void LineReceived(string line1)
{
textBox1.Text = line1;
}
private void btnMove_Click(object sender, EventArgs e)
{
double[] coords = new double[4] { 0, 0, 0, 0 };
byte axisMask = 0;
if (double.TryParse(tbX.Text, out coords[0])) axisMask = (byte)(axisMask + 1);
if (double.TryParse(tbY.Text, out coords[1])) axisMask = (byte)(axisMask + 2);
if (double.TryParse(tbZ.Text, out coords[2])) axisMask = (byte)(axisMask + 4);
while (true)
{
pokeys.StartMove(false, rbAbsolut.Checked, 1, coords);
Thread.Sleep(5000);
coords[0] = -coords[0];
pokeys.StartMove(false, rbAbsolut.Checked, 4, coords);
coords[2] = coords[2] + 10;
Thread.Sleep(5000);
}
}
}
目前,您有一个永无止境的while循环,我不推荐
serialPort1.ReadLine()代码>。我会使用serialPort1.ReadExisting()代码>但请注意,您必须跟踪字符串。您可能需要构建字符串,直到看到换行符,然后调用传递该字符串的函数。看见