K
K
kyurem_bog2019-04-20 09:39:50
C++ / C#
kyurem_bog, 2019-04-20 09:39:50

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);
            }
        }

This is the data
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");
        }
    }

5cbabe6f38af8452635532.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
C
CHolfield, 2019-04-20
@CHolfield

the line which you catch port.ReadLine()contains in the end two bytes invisible to you {0x0d, 0x0a}.
so do this:
port.ReadLine().Trim()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question