所以我正在创建一个Windows窗体应用程序,它将通过串口连续显示来自我的Arduino微控制器的更新传感器数据。我也是C#的新手,更是如此,Arduino。我的问题是,当我尝试通过计时器显示更新的传感器数据时 - 应用程序崩溃。
arduino发送一个格式为 1; 25 的字符串 - 其中第一个数字 1 或 0 ,表示是否动议传感器检测到运动。另一个数字是温度。
class ArduinoComClass : SerialPort
{
public string receivedData;
private bool dataReady = false;
public ArduinoComClass(string comport, int baudrate)
{
PortName = comport;
BaudRate = baudrate;
DataReceived += new SerialDataReceivedEventHandler(dataReceived);
ReadTimeout = 2000;
Open();
}
~ArduinoComClass()
{
Close();
}
public void ConvertString(out string pirValue, out string tempValue)
{
string[] data = receivedData.Split(';');
string string1 = data[0];
if (string1 == "1")
{
pirValue = "Movement detected!";
}
else
{
pirValue = "No movement detected";
}
string string2 = data[1];
tempValue = string2;
}
public bool DataReady
{
get
{
return dataReady;
}
set
{
dataReady = value;
}
}
public void dataReceived(object sender, SerialDataReceivedEventArgs earg)
{
try
{
receivedData = ReadLine();
dataReady = true;
}
// catch(TimeoutException e)
catch (Exception e)
{
MessageBox.Show(e.Message);
dataReady = false;
}
}
}
现在这是我想要显示数据的表单的代码。由于我尝试并尝试不同的事情并且不断使其变得更糟,这是非常混乱的。我已尝试过任务/线程,但由于receivedData在另一个线程中,我收到错误。
static private ArduinoComClass ArduinoCom = new ArduinoComClass("COM3", 9600);
private string pirValue;
private string tempValue;
public Main()
{
InitializeComponent();
pirValue = "";
tempValue = "";
tmrAlarm.Start();
}
private void ShowSensorInfo()
{
while (true)
{
if (ArduinoCom.DataReady)
{
ArduinoCom.ConvertString(out pirValue, out tempValue);
txtShowTemp.Text = tempValue;
if (pirValue == "Movement detected!")
{
picPIR.BackColor = Color.Red;
}
else
{
picPIR.BackColor = Color.Lime;
}
//if (SystemInformation.PowerStatus.PowerLineStatus) <- Ignore for now
ArduinoCom.DataReady = false;
}
}
}
private async void tmrAlarm_Tick(object sender, EventArgs e)
{
try
{
Task myTask = Task.Run(() => ShowSensorInfo());
await myTask;
myTask.Wait(2000);
}
catch (Exception error)
{
Console.WriteLine(error.Message);
}
}
简而言之 - 我怎么能以简单有效的方式让我的程序显示这些实时数据而不会让应用程序崩溃?