PDA

View Full Version : Giao tiếp qua COM,RS232 bằng VC++6.0,EVC++4.0...


vuthuanbkvn
20-03-2008, 04:33 PM
em đang làm 1 project nhỏ mà chưa biết làm tiếp như nào mong anh em chỉ giáo thêm :
Đây là chương trình mở cổng COM :
/Opening and Configuring Serial Ports
void CSerialPort::Open()
{
//Windows CE doesn't support overlapped I/O for devices, so you can't pass the FILE_FLAG_OVERLAPPED flag in the dwFlagsAndAttributes parameter
//The handle returned is either the handle to the opened serial port or INVALID_HANDLE_VALUE. Remember that, unlike many of the Windows functions,
//CreateFile doesn't return a 0 for a failed open.


m_PortHandle = CreateFile (TEXT ("COM1:"), GENERIC_READ | GENERIC_WRITE,
0, NULL, OPEN_EXISTING, 0, NULL);

if (m_PortHandle != INVALID_HANDLE_VALUE)
{
AfxMessageBox(TEXT("Serial port could not be opened. Wrong port number?"), MB_OK);
m_PortHandle = NULL;
return; // error opening com port
}
else
//example turns off all flow control (such as XON/XOFF, CTS/RTS, and DSR/DTR) and sets the baud rate, data bits,
//and parity settings from the m_strBaud command string:
{
DCB dcb;
CString s;
dcb.DCBlength = sizeof(dcb);

// controlling the serial Port
//start a serial stream
SetCommState(m_PortHandle, &dcb);
//setting

dcb.BaudRate = CBR_115200;

dcb.Parity = EVENPARITY;
dcb.ByteSize = 8;
dcb.StopBits = ONESTOPBIT;
//The fParity field can be set to TRUE to enable parity checking.
dcb.fParity = false;
//The fDsrSensitivity field is set to TRUE, and the serial port
//ignores any incoming bytes unless the port DSR line is enabled
dcb.fDsrSensitivity = false;
//The fOutxCtsFlow field should be set to TRUE if the output of the serial port should be
//controlled by the port CTS line
dcb.fOutxCtsFlow = true;
//The fOutxDsrFlow field should be set to TRUE if the output of the serial port should be
//controlled by the DSR line of the serial port
dcb.fOutxDsrFlow = false;
//Setting the fOutX field to TRUE specifies that the XON/XOFF control is used to control the serial output.
//Setting the fInX field to TRUE specifies that the XON/XOFF control is used for the input serial stream.
dcb.fInX = false;
dcb.fOutX = false;
//Setting the fTXContinueOnXoff field to TRUE tells the driver to stop transmitting characters if its receive
//buffer has reached its limit and the driver has transmitted an XOFF character
dcb.fTXContinueOnXoff = false;
//The fDtrControl field can be set to one of three values: DTR_CONTROL_DISABLE,
//which disables the DTR (Data Terminal Ready) line and leaves it disabled; DTR_CONTROL_ENABLE,
//which enables the DTR line; or DTR_CONTROL_HANDSHAKE, which tells the serial driver to toggle
//the DTR line in response to how much data is in the receive buffer.

dcb.fDtrControl = DTR_CONTROL_DISABLE; //DTR and RTS 0
dcb.fRtsControl = RTS_CONTROL_DISABLE;
//stop a serial stream
//parameter for both these functions is the handle to the opened COM port
//When SetCommBreak is called, the COM port stops transmitting characters
//and places the port in a break state. Communication is resumed with the ClearCommBreak function.
//dcb.XonChar = EV_RXFLAG;

dcb.fAbortOnError = false;
dcb.fNull = true; //tells the serial driver to discard null bytes received.

GetCommState(m_PortHandle, &dcb);
if (SetCommState(m_PortHandle, &dcb) == 0)
{
AfxMessageBox(TEXT("Serial port could not be initialized. Error while setting communication state."), MB_OK);
CloseHandle(m_PortHandle);
m_PortHandle = NULL;
return; // error opening com port
}


////////////////////////////////////////
// do tim xac dinh toc do truyen
//The configuration functions enable you to configure the serial driver, but with varied implementations
//of serial ports you need to know just what features a serial port supports before you configure it. The
//function GetCommProperties provides just this service
// GetCommProperties (m_PortHandle, LPCOMMPROP lpCommProp);


//Setting the Port Timeout Values
//ReadFile returns immediately regardless of whether there is data to be read.
//Set ReadIntervalTimeout to MAXDWORD. Set ReadTotalTimeoutMultiplier
//and ReadTotalTimeoutConstant to 0.
COMMTIMEOUTS touts;
touts.ReadIntervalTimeout = 100;
touts.ReadTotalTimeoutMultiplier = MAXDWORD;
touts.ReadTotalTimeoutConstant = 50;
touts.ReadIntervalTimeout =MAXDWORD;
touts.WriteTotalTimeoutConstant = 100;
touts.WriteTotalTimeoutMultiplier = 100;
//ReadFile doesn't have a timeout. The function doesn't return until the proper number
//of bytes is returned or an error occurs. Set ReadIntervalTimeout,
//ReadTotalTimeoutMultiplier, and ReadTotalTimeoutConstant to 0.
if (SetCommTimeouts(m_PortHandle, &touts)==0) //Set communication timeouts
{
AfxMessageBox(TEXT("Serial port could not be initialized. Error while setting communication timeouts."), MB_OK);
CloseHandle(m_PortHandle);
m_PortHandle = NULL;
return; // error opening com port
}

SetCommMask (m_PortHandle, EV_CTS | EV_DSR | EV_RING | EV_RLSD);

//Controlling the Serial Port
//You can stop and start a serial stream using the following functions
SetCommBreak(m_PortHandle);
ClearCommBreak(m_PortHandle);
//You can clear out any characters in either the transmit or receive queues internal to
//the serial driver using this function:
//Since Windows CE doesn't support overlapped I/O, the flags PURGE_TXABORT and PURGE_RXABORT,
//used under Windows NT and Windows 98, are ignored.
PurgeComm(m_PortHandle, PURGE_TXABORT | PURGE_RXABORT);


///Clearing Errors and Querying Status
// ClearCommError (m_PortHandle, CE_OVERRUN ,COMSTAT);
// return TRUE;
}
//else
// {
// return FALSE; // Use GetLastError() to know the reason
// }
}


// Dong cong

void CSerialPort::Close()
{
if (m_PortHandle != INVALID_HANDLE_VALUE)
{
CloseHandle(m_PortHandle);
m_PortHandle = INVALID_HANDLE_VALUE;
}
}

//// Reading and Writing to a Serial Port

DWORD CSerialPort::Read(LPVOID Buffer, DWORD BufferSize)
{
INT rc;
DWORD Res(0);
if (m_PortHandle != INVALID_HANDLE_VALUE)
{
rc = ReadFile(m_PortHandle, Buffer, BufferSize, &Res, NULL);

if ()
{
}
}
return Res;
}

DWORD CSerialPort::Write(LPVOID Buffer, DWORD BufferSize)
{
INT rc;
DWORD Res(0);
if (m_PortHandle != INVALID_HANDLE_VALUE)
{
rc = WriteFile(m_PortHandle, Buffer, BufferSize, &Res, NULL);
}
return Res;
}

//The difference between TransmitCommChar and WriteFile is that TransmitCommChar puts
// the character to be transmitted at the front of the transmit queue. When you call WriteFile,
//the characters are queued up after any characters that haven't yet been transmitted by the serial
//driver. TransmitCommChar allows you to insert control characters quickly in the stream without
// having to wait for the queue to empty.

DWORD CSerialPort::Transmit(LPVOID Buffer, char cChar)
{
INT rc;
DWORD Res(0);
if (m_PortHandle!= INVALID_HANDLE_VALUE)
{
rc =TransmitCommChar(m_PortHandle,cChar);

}
return Res;
}
///////////////////////////////////////

vuthuanbkvn
20-03-2008, 04:35 PM
đây là phần DATA em cần gủi :
char err_buff[10];

CString msg = "Forward";

//
// Gui lenh data
//

int ret = send( Port_Socket, (const char *) "be", 2, MSG_DONTROUTE);

if ( ret == SOCKET_ERROR)
{
int last_error = WSAGetLastError();

_itoa(last_error, &err_buff[0], 10);

msg = "socket error";
msg += err_buff;
this->m_status_window.SetWindowText( (LPCTSTR) msg);
return;
}

ngohaibac
28-04-2008, 11:18 PM
Bó tay với bạn. Code thì bạn phải đính kèm file Project của bạn chứ.

Bạn phải nêu mục đích của Project của bạn, đã làm được gì, và khó khăn ở bước nào??

Nếu bạn không đính kèm project thì không có ai có thời gian đọc code VC++ như thế đâu bạn ạ. Vì chẳng biết thử thế nào nữa. Vì ngoài code còn có resource như Dialog,...

Chú ý: viết code trong tag code.

Chúc bạn thành công.

nguyentienhung
11-06-2009, 10:01 AM
Thanks !!
de em xem lai

18031984
16-11-2009, 09:55 AM
anh hải bắc ơi?
anh cho em hỏi cách truyền dữ liệu dạng BYTE xuống cổng COM. em dùng C++ ..anh giúp em với. em đang rất cần.anh có thể gửi cho em một project đê em tham khảo được không
thank