问题描述
我用serialPort做的串口读写, stringsend="Y0122570";serialPort1.BaudRate=115200;serialPort1.PortName="COM1";serialPort1.Open();serialPort1.Write(checksum_compute(send)+(char)13);发送完checksum_compute(send)+(char)13之后,就可以下指令来读设备的返回数据了,请大侠们扔两个读串口的代码。谢谢了。
解决方案
解决方案二:
C#串口通信编程类这是从网上down下来的一个串口通信类,发现close函数忘记了设置Opened属性为false还有后面string转byte[]和byte[]转string的函数有错误,索性删掉了修改后的串口通信类如下:下一篇将把我的测试程序主程序部分全部代码贴出来可以坚强勇敢的用来实现串口通信。usingSystem;usingSystem.Runtime.InteropServices;namespaceBusApp{///<summary>//////</summary>publicclassmycom{publicmycom(){////TODO:在此处添加构造函数逻辑//}publicintPortNum;//1,2,3,4publicintBaudRate;//1200,2400,4800,9600publicbyteByteSize;//8bitspublicbyteParity;//0-4=no,odd,even,mark,spacepublicbyteStopBits;//0,1,2=1,1.5,2publicintReadTimeout;//10//commportwin32filehandleprivateinthComm=-1;publicboolOpened=false;//win32apiconstantsprivateconstuintGENERIC_READ=0x80000000;privateconstuintGENERIC_WRITE=0x40000000;privateconstintOPEN_EXISTING=3;privateconstintINVALID_HANDLE_VALUE=-1;[StructLayout(LayoutKind.Sequential)]privatestructDCB{//takenfromcstructinplatformsdkpublicintDCBlength;//sizeof(DCB)publicintBaudRate;//currentbaudratepublicintfBinary;//binarymode,noEOFcheckpublicintfParity;//enableparitycheckingpublicintfOutxCtsFlow;//CTSoutputflowcontrolpublicintfOutxDsrFlow;//DSRoutputflowcontrolpublicintfDtrControl;//DTRflowcontroltypepublicintfDsrSensitivity;//DSRsensitivitypublicintfTXContinueOnXoff;//XOFFcontinuesTxpublicintfOutX;//XON/XOFFoutflowcontrolpublicintfInX;//XON/XOFFinflowcontrolpublicintfErrorChar;//enableerrorreplacementpublicintfNull;//enablenullstrippingpublicintfRtsControl;//RTSflowcontrolpublicintfAbortOnError;//abortonerrorpublicintfDummy2;//reservedpublicushortwReserved;//notcurrentlyusedpublicushortXonLim;//transmitXONthresholdpublicushortXoffLim;//transmitXOFFthresholdpublicbyteByteSize;//numberofbits/byte,4-8publicbyteParity;//0-4=no,odd,even,mark,spacepublicbyteStopBits;//0,1,2=1,1.5,2publiccharXonChar;//TxandRxXONcharacterpubliccharXoffChar;//TxandRxXOFFcharacterpubliccharErrorChar;//errorreplacementcharacterpubliccharEofChar;//endofinputcharacterpubliccharEvtChar;//receivedeventcharacterpublicushortwReserved1;//reserved;donotuse}[StructLayout(LayoutKind.Sequential)]privatestructCOMMTIMEOUTS{publicintReadIntervalTimeout;publicintReadTotalTimeoutMultiplier;publicintReadTotalTimeoutConstant;publicintWriteTotalTimeoutMultiplier;publicintWriteTotalTimeoutConstant;}[StructLayout(LayoutKind.Sequential)]privatestructOVERLAPPED{publicintInternal;publicintInternalHigh;publicintOffset;publicintOffsetHigh;publicinthEvent;}[DllImport("kernel32.dll")]privatestaticexternintCreateFile(stringlpFileName,//filenameuintdwDesiredAccess,//accessmodeintdwShareMode,//sharemodeintlpSecurityAttributes,//SDintdwCreationDisposition,//howtocreateintdwFlagsAndAttributes,//fileattributesinthTemplateFile//handletotemplatefile);[DllImport("kernel32.dll")]privatestaticexternboolGetCommState(inthFile,//handletocommunicationsdevicerefDCBlpDCB//device-controlblock);[DllImport("kernel32.dll")]privatestaticexternboolBuildCommDCB(stringlpDef,//device-controlstringrefDCBlpDCB//device-controlblock);[DllImport("kernel32.dll")]privatestaticexternboolSetCommState(inthFile,//handletocommunicationsdevicerefDCBlpDCB//device-controlblock);[DllImport("kernel32.dll")]privatestaticexternboolGetCommTimeouts(inthFile,//handletocommdevicerefCOMMTIMEOUTSlpCommTimeouts//time-outvalues);[DllImport("kernel32.dll")]privatestaticexternboolSetCommTimeouts(inthFile,//handletocommdevicerefCOMMTIMEOUTSlpCommTimeouts//time-outvalues);[DllImport("kernel32.dll")]privatestaticexternboolReadFile(inthFile,//handletofilebyte[]lpBuffer,//databufferintnNumberOfBytesToRead,//numberofbytestoreadrefintlpNumberOfBytesRead,//numberofbytesreadrefOVERLAPPEDlpOverlapped//overlappedbuffer);[DllImport("kernel32.dll")]privatestaticexternboolWriteFile(inthFile,//handletofilebyte[]lpBuffer,//databufferintnNumberOfBytesToWrite,//numberofbytestowriterefintlpNumberOfBytesWritten,//numberofbyteswrittenrefOVERLAPPEDlpOverlapped//overlappedbuffer);[DllImport("kernel32.dll")]privatestaticexternboolCloseHandle(inthObject//handletoobject);publicvoidOpen(){DCBdcbCommPort=newDCB();COMMTIMEOUTSctoCommPort=newCOMMTIMEOUTS();//OPENTHECOMMPORT.hComm=CreateFile("COM"+PortNum,GENERIC_READ|GENERIC_WRITE,0,0,OPEN_EXISTING,0,0);//IFTHEPORTCANNOTBEOPENED,BAILOUT.if(hComm==INVALID_HANDLE_VALUE){throw(newApplicationException("CommPortCanNotBeOpened"));}//SETTHECOMMTIMEOUTS.GetCommTimeouts(hComm,refctoCommPort);ctoCommPort.ReadTotalTimeoutConstant=ReadTimeout;ctoCommPort.ReadTotalTimeoutMultiplier=0;ctoCommPort.WriteTotalTimeoutMultiplier=0;ctoCommPort.WriteTotalTimeoutConstant=0;SetCommTimeouts(hComm,refctoCommPort);//SETBAUDRATE,PARITY,WORDSIZE,ANDSTOPBITS.//THEREAREOTHERWAYSOFDOINGSETTINGTHESEBUTTHISISTHEEASIEST.//IFYOUWANTTOLATERADDCODEFOROTHERBAUDRATES,REMEMBER//THATTHEARGUMENTFORBuildCommDCBMUSTBEAPOINTERTOASTRING.//ALSONOTETHATBuildCommDCB()DEFAULTSTONOHANDSHAKING.dcbCommPort.DCBlength=Marshal.SizeOf(dcbCommPort);GetCommState(hComm,refdcbCommPort);dcbCommPort.BaudRate=BaudRate;dcbCommPort.Parity=Parity;dcbCommPort.ByteSize=ByteSize;dcbCommPort.StopBits=StopBits;SetCommState(hComm,refdcbCommPort);Opened=true;}publicvoidClose(){if(hComm!=INVALID_HANDLE_VALUE){CloseHandle(hComm);Opened=false;}}publicbyte[]Read(intNumBytes){byte[]BufBytes;byte[]OutBytes;BufBytes=newbyte[NumBytes];if(hComm!=INVALID_HANDLE_VALUE){OVERLAPPEDovlCommPort=newOVERLAPPED();intBytesRead=0;ReadFile(hComm,BufBytes,NumBytes,refBytesRead,refovlCommPort);OutBytes=newbyte[BytesRead];Array.Copy(BufBytes,OutBytes,BytesRead);}else{throw(newApplicationException("CommPortNotOpen"));}returnOutBytes;}publicintWrite(byte[]WriteBytes){intBytesWritten=0;if(hComm!=INVALID_HANDLE_VALUE){OVERLAPPEDovlCommPort=newOVERLAPPED();WriteFile(hComm,WriteBytes,WriteBytes.Length,refBytesWritten,refovlCommPort);}else{throw(newApplicationException("CommPortNotOpen"));}returnBytesWritten;}}}