Winform serial communication card reader and winform Serial Communication
The first hardware the boss gave me was a card reader,
Let me give it a try, so I checked it online and wrote it, which is quite simple.
But then there was another weighbridge serial communication. I had a whole day.
Write in the Form class Constructor
Form. checkforillegalcrossthreadcils = false;
You can update the form outside the thread so that you can always receive data and update the ui.
Open the serial port button:
1 // instantiate 2 SerialPort Myport = new SerialPort (); 3 // set the serial port 4 Myport. portName = cbxPortName. text; 5 // set the bit rate of 6 Myport. baudRate = Convert. toInt32 (cmbbaud. text); 7 // set the data bit 8 Myport. dataBits = Convert. toInt32 (cmbBits. text); 9 // Based on the selected data, set the stop bit 10 // if (cmbStop. selectedIndex = 0) 11 // Myport. stopBits = StopBits. none; 12 if (cmbStop. selectedIndex = 1) 13 Myport. stopBits = StopBits. one; 14 if (cmbStop. selectedIndex = 2) 15 Myport. stopBits = StopBits. onePointFive; 16 if (cmbStop. selectedIndex = 3) 17 Myport. stopBits = StopBits. two; 18 19 // set the 20 if (cmbParity. selectedIndex = 0) 21 Myport. parity = Parity. even; 22 if (cmbParity. selectedIndex = 1) 23 Myport. parity = Parity. mark; 24 if (cmbParity. selectedIndex = 2) 25 Myport. parity = Parity. none; 26 if (cmbParity. selectedIndex = 3) 27 Myport. parity = Parity. odd; 28 if (cmbParity. selectedIndex = 4) 29 Myport. parity = Parity. space; 30 31 // This delegate should be a trigger to asynchronously retrieve data, that is, trigger 32 Myport when data is transmitted through the serial port. dataReceived + = new SerialDataReceivedEventHandler (portequaldatareceived); // DataReceived event Delegate 33 // METHOD 34 try35 {36 Myport. open (); 37 if (Myport. isOpen) 38 {39 MessageBox. show ("Serial Port enabled"); 40} 41 else42 {43 MessageBox. show ("failed to enable serial port"); 44} 45} 46 catch (Exception ex) 47 {48 MessageBox. show ("unable to enable serial port" + ex. toString (); 49}
Use Myport. Close () when you Close the function. The problem does not occur during serial communication of the card reader.
DataReceived event delegation Method
1 private void port1_DataReceived (object sender, SerialDataReceivedEventArgs e) 2 {3 try 4 {5 string currentline = ""; 6 // cyclically receives data from the serial port 7 while (Myport. bytesToRead> 0) 8 {9 char ch = (char) Myport. readByte (); 10 currentline + = ch. toString (); 11} 12 // display the received data here. 13 // if it is not in the Form loading event, write: Form. checkforillegalcrossthreadcils = false; an error is returned.) 14 this.txt Receive. text = currentline; 15} 16 catch (Exception ex) 17 {18 Console. writeLine (ex. message. toString (); 19} 20}