Cześć, chciałbym napisać program do komunikacji poprzez UART. Dobrym pomysłem wydaje się wykorzystanie wątku tak, aby aplikacja była responsywna podczas komunikacji.
Chciałbym zapytać Was o to czy powinno to tak wyglądać? W Visual studio mam błędy (tylko w postaci informacji, a nie wywalenia programu) System.InvalidOperationException.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
namespace ssss
{
public partial class Form1 : Form
{
int x;
int PortCOMOtwarty;
string PortSzeregowyCaly;
static SerialPort serial;
static bool Continue;
public Form1()
{
InitializeComponent();
}
public void UruchomWatek()
{
Thread readThread = new Thread(Odczyt);
Continue = true;
readThread.Start();
}
public void Odczyt()
{
while (Continue)
{
Thread.Sleep(1000);
x++;
try
{
this.Invoke(new Action(() => { label13.Text = "Odebrane dane z UART: " + serial.ReadExisting(); }));
this.Invoke(new Action(() => { label14.Text = "Sygnalizacja pracy wątku: " + x.ToString(); }));
}
catch
{
}
}
}
private void button3_Click(object sender, EventArgs e)
{
try
{
Continue = false;
serial.Close();
this.Close();
}
catch (Exception ex)
{
MessageBox.Show("Błąd: " + ex.Message, "Błąd");
return;
}
}
private void button1_Click(object sender, EventArgs e)
{
if (PortCOMOtwarty == 0)
{
PortSzeregowyCaly = "COM" + comboBox1.SelectedIndex;
serial = new SerialPort(); // Inicjalizacja obiektu
serial.PortName = PortSzeregowyCaly; // Nazwa portu COM - DevKit!
serial.BaudRate = int.Parse(comboBox2.Text); // Prędkość
serial.Parity = Parity.None; // Brak bitu parzystości
serial.DataBits = 8; // 8 bitów danych
serial.StopBits = StopBits.One; // 1 bit stopu
serial.Handshake = Handshake.None;
serial.ReadTimeout = 500;
serial.WriteTimeout = 500;
try
{
serial.Open(); // Otwiera port szeregowy
}
catch (Exception ex)
{
MessageBox.Show("Błąd: " + ex.Message, "Błąd");
return;
}
button1.Text = "Zamknij połączenie";
PortCOMOtwarty = 1;
UruchomWatek();
return;
}
if (PortCOMOtwarty == 1)
{
Continue = false;
try
{
serial.Close(); // Zamyka port COM
}
catch (Exception ex)
{
MessageBox.Show("Błąd: " + ex.Message, "Błąd");
return;
}
button1.Text = "Nawiąż połączenie";
PortCOMOtwarty = 0;
return;
}
}
private void button2_Click(object sender, EventArgs e)
{
try
{
serial.WriteLine(textBox1.Text + "x" + textBox2.Text + "x" + textBox3.Text + "x" + textBox4.Text + "x" + textBox5.Text + "x" + textBox6.Text + "x" + textBox7.Text + "x" + textBox8.Text + "x" + textBox9.Text);
}
catch (Exception ex)
{
MessageBox.Show("Błąd: " + ex.Message, "Błąd");
return;
}
}
}
}