问题描述
publicForm1(){InitializeComponent();}SerialPortserialPort=newSerialPort("COM1",9600,Parity.Even,8,StopBits.One);privatevoidForm1_Load(objectsender,EventArgse){}voidcomm_DataReceived(objectsender,SerialDataReceivedEventArgse){if(!serialPort.IsOpen){label2.Text="串口已关关闭";}else{Thread.Sleep(500);byte[]ReadBytes=newbyte[serialPort.BytesToRead];serialPort.Read(ReadBytes,0,serialPort.BytesToRead);System.Text.UTF8Encodingutf8=newUTF8Encoding();stringReadStr=utf8.GetString(ReadBytes);label1.Text=ReadStr;}}privatevoidbutton1_Click(objectsender,EventArgse){if(serialPort.IsOpen){label2.Text="串口已打开";}else{serialPort.Open();label2.Text="串口已打开";}}
解决方案
解决方案二:
是comm_DataReceived没触发呢还是Read长度是0?Thread.Sleep(500);这个有什么作用?电源打开了吗?
解决方案三:
你这里无论串口打开成功与否都会提示串口已打开,你需要在serialPort.Open();处进行打开成功与否的判断,不然你的串口打开成功的提示可能只是假象,其实没有打开
解决方案四:
先用串口调试工具调试看看再排除是不是程序的错误。