Answer the question
In order to leave comments, you need to log in
C# how to work with com port?
I found on one forum a code for working with a com port. In theory, it should display data with a certain key. But that doesn't happen. He says there is no such data. I send data through the console. It is not entirely clear what data is the key, and what to write to the console.
Working with a com port
private SerialPort port;
public PersonsController(string COM5) {
this.WorkerReportsProgress = true;
this.WorkerSupportsCancellation = true;
port = new SerialPort("COM5", 9600, Parity.None, 8, StopBits.One);
}
protected override void OnDoWork(DoWorkEventArgs e) {
try {
port.Open();
StartListen(e);
}
catch (Exception ex) {
throw ex;
}
finally {
port.Close();
}
}
void StartListen(DoWorkEventArgs e) {
this.ReportProgress(0, "Listen started!");
while (true) {
if (this.CancellationPending) {
this.ReportProgress(0, "Listen stopped!");
e.Cancel = true;
return;
}
if (port.BytesToRead != 0) {
string key = port.ReadLine();
if (Program.persons.Keys.Contains(key)) {
this.ReportProgress(0, Program.persons[key]);
}
else {
this.ReportProgress(0, "Unknown person!");
this.ReportProgress(1, DateTime.Now.ToString("HH:mm:ss"));
this.ReportProgress(2, key);
}
}
Thread.Sleep(500);
}
}
public static Dictionary<string, string> persons =
new Dictionary<string, string>();
/// <summary>
/// Главная точка входа для приложения.
/// </summary>
[STAThread]
static void Main() {
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
}
static void FillPersons() {
persons.Add("101", "Antony");
persons.Add("102", "Oleg");
persons.Add("103", "Katrine");
persons.Add("104", "Evelina");
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question