c# - 使用定时器和任务的 Arduino 到 C# 实时数据传输
问题描述
问题:在 Form1 上声明的“str”变量未在Timer1_Tick()
方法中读取。输入来自连接到多个传感器的 Arduino。传感器输入组合成一个字符串(例如 [1,2,4,5,6])。对于这段代码,我只需要显示该字符串。非常感谢您对此事的任何帮助。
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
SerialPort currentPort = new SerialPort("COM5", 9600, Parity.None, 8, StopBits.One);
currentPort.Open();
string str = currentPort.ReadLine();
}
private void Timer1_Tick(object sender, EventArgs e)
{
Task.Run(() => {
this.BeginInvoke((Action)(() => { label1.Text = str; }));
});
}
private void Button1_Click(object sender, EventArgs e)
{//Start
timer1.Start();
}
private void Button2_Click(object sender, EventArgs e)
{//Stop
timer1.Stop();
}
}
}
解决方案
在 Form1 上声明的“str”变量未在 Timer1_Tick 中读取。
原因是:str
变量是在 上声明的Form1_Load
,所以它是一个局部变量。仅在类内部声明它Form1
,但在方法外部声明它。这样,它将是一个全局变量,可以从Form1
类中的任何方法访问,包括计时器方法。
推荐阅读
- python - Django Rest API - django-rest-auth
- reactjs - 参数更改时 useEffect 不会重新运行
- automation - 如何自动替换视频中的音轨?
- scala - Playframework 2.8 setSession 适用于 Postman,但不适用于浏览器
- docker-compose - 将卷添加到 SeaweedFS docker-compose 文件
- html - 如何让我的网站在放大和缩小时不变形?
- c# - REST 调用从 Oracle 数据库返回空列表
- c# - 无法加载 DLL 'Microsoft.WITDataStore32.dll':找不到指定的模块。(来自 HRESULT 的异常:0x8007007E)
- xslt - XSLT:选择性缩进可能吗?
- python - 如何使用 pygsheets 用数据更新工作表的底行(第一个空行)?