本文实例为大家分享了c#基于serialport类实现串口通讯的具体代码,供大家参考,具体内容如下
最终效果
窗体设置:
using system; using system.collections.generic; using system.componentmodel; using system.data; using system.drawing; using system.linq; using system.text; using system.threading.tasks; using system.io.ports; using system.threading; using system.windows.forms; namespace serialcommunication { public partial class form1 : form { system.threading.synchronizationcontext m_synccontext = null; serialport serialport = null; tohexadecimalstring tohexadecimalstring = new tohexadecimalstring(); public form1() { m_synccontext = synchronizationcontext.current; initializecomponent(); } //data initialization private void form1_load(object sender, eventargs e) { string[] ports = serialport.getportnames(); serialportnumber.items.addrange(ports); serialportnumber.selectedindex = serialportnumber.items.count > 0 ? 0 : -1; baudratecom.text = "9600"; //set parameters checkbitcom.text = "none"; databitcom.text = "8"; stopbitcom.text = "one"; } //send data private void send_click(object sender, eventargs e) { try { //send data and handle exceptions byte[] bytes = new byte[sendmessage.text.length]; bytes = encoding.default.getbytes(sendmessage.text); serialport.write(bytes, 0, bytes.length); } catch (exception error) { messagebox.show(error.message); } } // byte to hexadecimal string //clear data private void clear_click(object sender, eventargs e) { receivemessage.text = ""; } private void open_click(object sender, eventargs e) { string portname = serialportnumber.text; int buadrate = int.parse(baudratecom.text); parity parity = 0; switch (checkbitcom.text) { case "none": parity = parity.none; break; case "odd": parity = parity.odd; break; case "even": parity = parity.even; break; case "mark": parity = parity.mark; break; case "space": parity = parity.space; break; } int databit = int.parse(databitcom.text); stopbits stopbits = 0; switch (stopbitcom.text) { case "none": stopbits = stopbits.none; break; case "one": stopbits = stopbits.one; break; case "tow": stopbits = stopbits.two; break; case "onepointfive": stopbits = stopbits.onepointfive; break; } try { if (open.text == "open") { serialport = new serialport(portname, buadrate, parity, databit, stopbits); serialport.open(); open.text = "close"; } else if (open.text == "close") { serialport.close(); open.text = "open"; } } catch (exception errror) { messagebox.show(errror.message); } serialport.datareceived = ondatareceived; } private void ondatareceived(object sender, serialdatareceivedeventargs e) { try { byte[] bytes = new byte[serialport.bytestoread]; serialport.read(bytes, 0, serialport.bytestoread); m_synccontext.post(new sendorpostcallback((obj) => { receivemessage.appendtext(encoding.default.getstring(bytes)); }), bytes); } catch (exception error) { messagebox.show(error.message); } } } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。