SerialPort CurrentPort = null
current port = new serial port();
Current port. read buffer size = 128;
Current port. PortName = comName// port number
Current port. BaudRate = bandRate// bit rate
Current port. Parity = parity; //parity check
Current port. StopBits = stop; //Stop bit
Current port. Data bits = data bits; //data bits
Current port. read time out = 1000; //Read timeout, that is, if no data is read within 1000, it will cause timeout exception.
//Bind the data receiving event, because sending is passive, so you can't take the initiative to get the code sent by others, and you can only handle it through this event.
Current port. data received+= Sp _ data received;
Current port. open();
Define a variable byte[]receiveStr;;
//Bind the event handler
Private static void sp _ datareceived (object sender, system. IO . ports . serial datareceivedeventargs e)
{
serial port sp = sender as serial port;
if (sp == null)
Return;
Byte[] readBuffer = new byte [sp. read buffer size];
Species Read(readBuffer, 0, readBuffer. Length);
//assignment
ReceiveStr = readBuffer// byte[] can of course be converted into a string by conversion.
}
//The button event you requested can be written like this.
Private void button 1_Click (object sender, EventArgs e)
{
if(receiveStr! = empty)
{
Variable xxx = receiveStr
}
}