How to use the SerialPort->Write function
-
What I need to do is this: To take a structure (or a class that contains only variables) then convert it somehow to an array of bytes, so i will be able to send it with the Write function of the SerialPort Control. On the other side of the port i need to do backward process Can anyone help me with this one? thanks
-
What I need to do is this: To take a structure (or a class that contains only variables) then convert it somehow to an array of bytes, so i will be able to send it with the Write function of the SerialPort Control. On the other side of the port i need to do backward process Can anyone help me with this one? thanks
Call createfile to get a valid handle to the port:
hPort = CreateFile(lpszPortName, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL); // NT wants overlapped
Then set the device control block with appropriate baude rate and parity bit settings and other settings.DCB dcb; dcb.DCBlength = sizeof( DCB ) ; GetCommState( ufp, &dcb ) ; //change settings as required by the device connected the serial port. dcb.BaudRate = baud; //set the new value back SetCommState(ufp, &dcb);
Now you can start writing to the device.WriteFile(hPort, bfr2write, dwBytestoWrite, &dwBytesWritten, &OVERLAPPEDWrite);
To Readfrom the file:ClearCommError( hPort, &dwErrorFlags, &ComStat ) ; // Clear error flag dwLength = min( (DWORD) MaxLength, ComStat.cbInQue ); // # of bytes to get if (dwLength > 0) { fReadStat = ReadFile( hPort, lpzBlock, // Do the READ dwLength, &dwLength, &osRead ) ; if (!fReadStat) { Err("ReadSPort"); dwLength = 0 ; ClearCommError( hPort, &dwErrorFlags, &ComStat ) ; } }
cheers...milton. -
Call createfile to get a valid handle to the port:
hPort = CreateFile(lpszPortName, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL); // NT wants overlapped
Then set the device control block with appropriate baude rate and parity bit settings and other settings.DCB dcb; dcb.DCBlength = sizeof( DCB ) ; GetCommState( ufp, &dcb ) ; //change settings as required by the device connected the serial port. dcb.BaudRate = baud; //set the new value back SetCommState(ufp, &dcb);
Now you can start writing to the device.WriteFile(hPort, bfr2write, dwBytestoWrite, &dwBytesWritten, &OVERLAPPEDWrite);
To Readfrom the file:ClearCommError( hPort, &dwErrorFlags, &ComStat ) ; // Clear error flag dwLength = min( (DWORD) MaxLength, ComStat.cbInQue ); // # of bytes to get if (dwLength > 0) { fReadStat = ReadFile( hPort, lpzBlock, // Do the READ dwLength, &dwLength, &osRead ) ; if (!fReadStat) { Err("ReadSPort"); dwLength = 0 ; ClearCommError( hPort, &dwErrorFlags, &ComStat ) ; } }
cheers...milton. -
Thanks, But in this way I don’t really use the SerialPort Control that .net 2 gave me. Do u know how to do it with the SerialPort Control?
sorry, not yet used.