当前位置: 首页>>代码示例>>C++>>正文


C++ GetCommState函数代码示例

本文整理汇总了C++中GetCommState函数的典型用法代码示例。如果您正苦于以下问题:C++ GetCommState函数的具体用法?C++ GetCommState怎么用?C++ GetCommState使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了GetCommState函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: sizeof

}	
void    WinSerial::setupLink()
{

        int     ret;
        DCB     dcb = {0};
        COMMTIMEOUTS cto = {10,10,10,10,10};

        dcb.DCBlength = sizeof(DCB);

        cto.ReadIntervalTimeout = 100;

sprintf(logchunk, "opening com port <%s>\n", mDevName);
log(logchunk);
        mPortFh = CreateFile(mDevName, GENERIC_READ | GENERIC_WRITE,
                                         0,
                                         0,
                                         OPEN_EXISTING, 
                                         0,
                                         0
                                         );

   	if (mPortFh == INVALID_HANDLE_VALUE) 
   	{
       		// Handle the error.
       		printf ("CreateFile failed with error %ld.\n", GetLastError());
       		exit(1);
   	}

sprintf(logchunk, " port %d\n", mPortFh);
log(logchunk);
        assert(mPortFh);
        ret = GetCommState(mPortFh, &dcb);

        if (!ret)
        {
                fprintf(stderr, "GetCommState failed %d\n",
                                 GetLastError());
                exit(2);
        } 
 //       dcb.BaudRate = CBR_57600;
        dcb.BaudRate = CBR_256000;
    	dcb.ByteSize    = 8;
    	dcb.StopBits    = ONESTOPBIT;
    	dcb.Parity      = NOPARITY;
    	dcb.fDtrControl = DTR_CONTROL_DISABLE;
    	dcb.fOutX       = FALSE;
    	dcb.fInX        = FALSE;
    	dcb.fNull       = FALSE;
    	dcb.fRtsControl = RTS_CONTROL_DISABLE;

// need to send binary data
	dcb.fBinary = 1;

//    *  fInX, fOutX,fOutXDsrFlow, fOutXCtsFlow are set to FALSE
//    * fDtrControl is set to DTR_CONTROL_ENABLE
//    * fRtsControl is set to RTS_CONTROL_ENABLE

   
  

        ret = SetCommState(mPortFh, &dcb);
        if (!ret)
        {
                fprintf(stderr, "SetCommState failed %d\n",
                                GetLastError());
                exit(3);
        }

        ret = SetCommTimeouts(mPortFh, &cto);
        if (!ret)
        {
                fprintf(stderr, "SetCommTimeouts failed %d\n",
                                GetLastError());
                exit(3);
        }

	log("setup\n");
	mSetup = 1;
开发者ID:samanz,项目名称:Fribbler-PS-Driver,代码行数:79,代码来源:WinSerial.cpp

示例2: main

int main(void){

	/* I searched for this topic and found no real leads so i looked it up.
	 * Opening the serial port
	 * First point is to open a connection. Before opening any connection several informations must be acquired.
	 * 
	 * The name of the serial port.(Usually COM1-COM6 )
	 * The direction of communication.
	 * (It is possible to set the communication to an asynchronic mode but it is far mor complex and unintuitive than the synchronic mode used here)
	 */

	LPCSTR portname = "COM4";
	DWORD  accessdirection =GENERIC_READ | GENERIC_WRITE;
	HANDLE hSerial = CreateFile(portname,
		accessdirection,
		0,
		0,
		OPEN_EXISTING,
		0,
		0);
	if (hSerial == INVALID_HANDLE_VALUE) {
		//call GetLastError(); to gain more information
		printf("Error 1\n");
	}
	
	/*
	 * After opening the port further settings like Baudrate, Byte size, the number of stopbits and the Parity need to be set.
	 */
	 
	DCB dcbSerialParams = {0};
	dcbSerialParams.DCBlength=sizeof(dcbSerialParams);
	if (!GetCommState(hSerial, &dcbSerialParams)) {
		 //could not get the state of the comport
	}
	dcbSerialParams.BaudRate=9600;
	dcbSerialParams.ByteSize=8;
	dcbSerialParams.StopBits=ONESTOPBIT;
	dcbSerialParams.Parity=NOPARITY;
	if(!SetCommState(hSerial, &dcbSerialParams)){
		 //analyse error
		 printf("Error 2\n");
	}	
	
	/* Finally timeouts need to be set so that the program does not hang up when receiving nothing. */
	COMMTIMEOUTS timeouts={0};
	timeouts.ReadIntervalTimeout=50;
	timeouts.ReadTotalTimeoutConstant=50;
	timeouts.ReadTotalTimeoutMultiplier=10;
	timeouts.WriteTotalTimeoutConstant=50;
	timeouts.WriteTotalTimeoutMultiplier=10;
	if(!SetCommTimeouts(hSerial, &timeouts)){
		//handle error
		 printf("Error 3\n");
    }
	
	{
		uint8_t symbol = 'A';
		for(symbol = 'A'; symbol <= 'Z'; ++symbol){
			(void)writeToSerialPort(hSerial, &symbol, 1);
		}
	}
	
	/* Closing: when the serial port is not longer needed, it can be freed by closing the associated handle. */
	CloseHandle(hSerial);
	
	printf("Hello\n");
	
	
} /* main */
开发者ID:basejumpa,项目名称:theitkrauts,代码行数:69,代码来源:HelloCom.c

示例3: open_serial_source

serial_source open_serial_source(const char *device, int baud_rate,
				 int non_blocking,
				 void (*message)(serial_source_msg problem))
/* Effects: opens serial port device at specified baud_rate. If non_blocking
     is true, read_serial_packet calls will be non-blocking (writes are
     always blocking, for now at least)
   Returns: descriptor for serial forwarder at host:port, or
     NULL for failure (bad device or bad baud rate)
 */
{
#ifndef LOSE32
  struct termios newtio;
  int fd;
  tcflag_t baudflag = parse_baudrate(baud_rate);

  if (!baudflag)
    return NULL;

  fd = open(device, O_RDWR | O_NOCTTY | O_NONBLOCK);

  if (fd < 0)
    return NULL;

  /* Serial port setting */
  memset(&newtio, 0, sizeof(newtio));
  newtio.c_cflag = CS8 | CLOCAL | CREAD;
  newtio.c_iflag = IGNPAR | IGNBRK;
  cfsetispeed(&newtio, baudflag);
  cfsetospeed(&newtio, baudflag);

  /* Raw output_file */
  newtio.c_oflag = 0;

  if (tcflush(fd, TCIFLUSH) >= 0 &&
      tcsetattr(fd, TCSANOW, &newtio) >= 0)
    {
      serial_source src = malloc(sizeof *src);

      if (src)
	{
	  memset(src, 0, sizeof *src);
	  src->fd = fd;
	  src->non_blocking = non_blocking;
	  src->message = message;
	  src->send.seqno = 37;

	  return src;
	}
    }
  close(fd);

  return NULL;
#else // LOSE32
	LPCTSTR       ComName = (LPCTSTR)device;
    HANDLE        hComm;
	DCB           dcb;
    serial_source src;

	int buflen = MultiByteToWideChar(CP_ACP,0,(PCSTR)device,-1,(LPWSTR)ComName,0);
	MultiByteToWideChar(CP_ACP,0,(PCSTR)device,-1,(LPWSTR)ComName,buflen);
	
	//syncronize
	hComm = CreateFile(ComName,  GENERIC_READ | GENERIC_WRITE,  0,  NULL,  OPEN_EXISTING,
					FILE_ATTRIBUTE_NORMAL, NULL);

    if (hComm == INVALID_HANDLE_VALUE) {
        return NULL;
    }

    PurgeComm(hComm, PURGE_RXCLEAR);

	GetCommState(hComm, &dcb); 
	dcb.BaudRate = baud_rate;
	dcb.ByteSize = 8;
	dcb.Parity = NOPARITY;
	dcb.fParity = FALSE;
	dcb.StopBits = ONESTOPBIT;
    if (SetCommState(hComm, &dcb) == 0) {
        return NULL;
    }

    src = malloc(sizeof *src);

    if (src) {
	  memset(src, 0, sizeof *src);
	  src->hComm = hComm;
	  src->non_blocking = non_blocking;
	  src->message = message;
	  src->send.seqno = 37;

	}

	return src;

#endif // LOSE32
}
开发者ID:mszczodrak,项目名称:otf,代码行数:96,代码来源:serialsource.c

示例4: setAttributes

	int setAttributes(int baudRate, Parity parity, int dataBits, StopBits bits, Handshake hs, int readTimeout, int writeTimeout)
	{
		DCB dcb;
		if (!GetCommState(this->handle, &dcb))
		{
			return GetLastError();
		}

		dcb.BaudRate = baudRate;
		dcb.Parity = (byte)parity;
		dcb.ByteSize = (byte)dataBits;

        switch (bits)
        {
        case StopBits_10:
            dcb.StopBits = ONESTOPBIT;
            break;
        case StopBits_15:
            dcb.StopBits = ONE5STOPBITS;
            break;
        case StopBits_20:
            dcb.StopBits = TWOSTOPBITS;
            break;
        default:
            break;
        }

		// Clear Handshake flags
		dcb.fOutxCtsFlow = 0;
		dcb.fOutX = 0;
		dcb.fInX = 0;
		dcb.fRtsControl = 0;

		// Set Handshake flags
		switch (hs)
		{
		case Handshake_None:
			break;
		case Handshake_XonXoff:
			dcb.fOutX = 1;
			dcb.fInX = 1;
			break;
		case Handshake_RequestToSend:
			dcb.fOutxCtsFlow = 1;
			dcb.fRtsControl = 1;
			break;
		case Handshake_RequestToSendXonXoff:
			dcb.fOutX = 1;
			dcb.fInX = 1;
			dcb.fOutxCtsFlow = 1;
			dcb.fRtsControl = 1;
			break;
		default: // Shouldn't happen
			break;
		}

		if (!SetCommState(handle, &dcb))
		{
			return GetLastError();
		}
		return S_OK;
	}
开发者ID:Nakul,项目名称:AirSim,代码行数:62,代码来源:SerialPort.cpp

示例5: SEQUENCER_ERRORV

void serialDriver::open(std::string com_port, long baud_rate, int databits, sdff_serial_paritymodes parity, double stopbits, sdff_serial_handshaking handshaking){
    std::string par="NO_PARITY";
    if (parity==sdffserEVEN) par="EVEN_PARITY";
    if (parity==sdffserODD) par="ODD_PARITY";
    std::string name="serialDriver::open(port="+com_port+", baud_rate="+inttostr(baud_rate)+", databits="+inttostr(databits)+", stopbits="+floattostr(stopbits)+" parity="+par+")";
    if (ports.find(com_port)!=ports.end()) {
        SEQUENCER_ERRORV(SEQUENCER_SERERROR_PORTALREADYOPEN_NUM, name, com_port.c_str());
    }

    BOOL fSuccess;
    DCB dcb;      /* device control block */
    BYTE StopBits;
    if (stopbits==1) {
        StopBits=ONESTOPBIT;
    } else if (stopbits==1.5) {
        StopBits=ONE5STOPBITS;
    } else if (stopbits==2) {
        StopBits=TWOSTOPBITS;
    } else {
        SEQUENCER_ERRORV(SEQUENCER_SERERROR_IMPOSSIBLEARG_NUM, name, com_port.c_str(), floattostr(stopbits).c_str(), "stop_bits", "1, 1.5, 2");
    }
    BYTE Parity=NOPARITY;
    DWORD fParity;
    if (parity==sdffserEVEN) {
        Parity=EVENPARITY;
        fParity=TRUE;
    } else if (parity==sdffserODD) {
        Parity=ODDPARITY;
        fParity=TRUE;
    } else if (parity==sdffserNOPARITY) {
        Parity=NOPARITY;
        fParity=FALSE;
    }

    ports[com_port] = CreateFileA(com_port.c_str(), GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
    if (ports[com_port]==INVALID_HANDLE_VALUE) {
        ports.erase(com_port);
        win32_error(name);
    }
    fSuccess = GetCommState(ports[com_port], &dcb);
    if (!fSuccess) {
        CloseHandle(ports[com_port]);
        ports.erase(com_port);
        win32_error(name);
    }

    /* configure the port */

    dcb.BaudRate = baud_rate;
    dcb.ByteSize = databits;
    dcb.Parity = Parity;
    dcb.StopBits = StopBits;

    /* configure handshaking */
	switch (handshaking) {
	case sdffserNOHANDSHAKING:
		dcb.fOutxCtsFlow = false;					// Disable CTS monitoring
		dcb.fOutxDsrFlow = false;					// Disable DSR monitoring
		dcb.fDtrControl = DTR_CONTROL_DISABLE;		// Disable DTR monitoring
		dcb.fOutX = false;							// Disable XON/XOFF for transmission
		dcb.fInX = false;							// Disable XON/XOFF for receiving
		dcb.fRtsControl = RTS_CONTROL_DISABLE;		// Disable RTS (Ready To Send)
		break;

	case sdffserHARDWARE:
		dcb.fOutxCtsFlow = true;					// Enable CTS monitoring
		dcb.fOutxDsrFlow = true;					// Enable DSR monitoring
		dcb.fDtrControl = DTR_CONTROL_HANDSHAKE;	// Enable DTR handshaking
		dcb.fOutX = false;							// Disable XON/XOFF for transmission
		dcb.fInX = false;							// Disable XON/XOFF for receiving
		dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;	// Enable RTS handshaking
		break;

	case sdffserXONXOFF:
		dcb.fOutxCtsFlow = false;					// Disable CTS (Clear To Send)
		dcb.fOutxDsrFlow = false;					// Disable DSR (Data Set Ready)
		dcb.fDtrControl = DTR_CONTROL_DISABLE;		// Disable DTR (Data Terminal Ready)
		dcb.fOutX = true;							// Enable XON/XOFF for transmission
		dcb.fInX = true;							// Enable XON/XOFF for receiving
		dcb.fRtsControl = RTS_CONTROL_DISABLE;		// Disable RTS (Ready To Send)
		break;
	}
    fSuccess = SetCommState(ports[com_port], &dcb);
    if (!fSuccess) {
        CloseHandle(ports[com_port]);
        ports.erase(com_port);
        win32_error(name);
    }


    COMMTIMEOUTS commTimeout;

    if(GetCommTimeouts(ports[com_port], &commTimeout))
    {
        commTimeout.ReadIntervalTimeout     = 500;
        commTimeout.ReadTotalTimeoutConstant     = 100;
        commTimeout.ReadTotalTimeoutMultiplier     = 500;
        commTimeout.WriteTotalTimeoutConstant     = 100;
        commTimeout.WriteTotalTimeoutMultiplier = 500;
    } else {
//.........这里部分代码省略.........
开发者ID:jkriege2,项目名称:sdfflib,代码行数:101,代码来源:serialdriver.cpp

示例6: cmserial_create

COMMNG cmserial_create(UINT port, UINT8 param, UINT32 speed) {

	TCHAR	commstr[16];
	HANDLE	hdl;
	DCB		dcb;
	UINT	i;
	COMMNG	ret;
	CMSER	serial;

	wsprintf(commstr, _T("COM%u"), port);
	hdl = CreateFile(commstr, GENERIC_READ | GENERIC_WRITE,
												0, 0, OPEN_EXISTING, 0, NULL);
	if (hdl == INVALID_HANDLE_VALUE) {
		goto cscre_err1;
	}
	GetCommState(hdl, &dcb);
	for (i=0; i<NELEMENTS(cmserial_speed); i++) {
		if (cmserial_speed[i] >= speed) {
			dcb.BaudRate = cmserial_speed[i];
			break;
		}
	}
	dcb.ByteSize = (UINT8)(((param >> 2) & 3) + 5);
	switch(param & 0x30) {
		case 0x10:
			dcb.Parity = ODDPARITY;
			break;

		case 0x30:
			dcb.Parity = EVENPARITY;
			break;

		default:
			dcb.Parity = NOPARITY;
			break;
	}
	switch(param & 0xc0) {
		case 0x80:
			dcb.StopBits = ONE5STOPBITS;
			break;

		case 0xc0:
			dcb.StopBits = TWOSTOPBITS;
			break;

		default:
			dcb.StopBits = ONESTOPBIT;
			break;
	}
	SetCommState(hdl, &dcb);
	ret = (COMMNG)_MALLOC(sizeof(_COMMNG) + sizeof(_CMSER), "SERIAL");
	if (ret == NULL) {
		goto cscre_err2;
	}
	ret->connect = COMCONNECT_MIDI;
	ret->read = serialread;
	ret->write = serialwrite;
	ret->getstat = serialgetstat;
	ret->msg = serialmsg;
	ret->release = serialrelease;
	serial = (CMSER)(ret + 1);
	serial->hdl = hdl;
	return(ret);

cscre_err2:
	CloseHandle(hdl);

cscre_err1:
	return(NULL);
}
开发者ID:perabuss,项目名称:np2wii,代码行数:70,代码来源:cmserial.cpp

示例7: MRPT_UNUSED_PARAM

//////////////////////////////////////////////////////////////////////////////////////////
// Open a communication channel to the given serial port name.
XsensResultValue Cmt1s::open(  const char *portName,
						const uint32_t baudRate,
						uint32_t readBufSize,
						uint32_t writeBufSize)
{
	MRPT_UNUSED_PARAM(readBufSize); MRPT_UNUSED_PARAM(writeBufSize);
	m_endTime = 0;

	CMT1LOG("L1: Open port %s at %d baud\n", portName, baudRate);

	if (m_isOpen)
	{
		CMT1LOG("L1: Port already open\n");
		return (m_lastResult = XRV_ALREADYOPEN);
	}
	m_baudrate = baudRate;

#ifdef _WIN32
	char winPortName[32];

	// Open port
	sprintf(winPortName, "\\\\.\\%s", portName);
	m_handle = CreateFileA(winPortName, GENERIC_READ | GENERIC_WRITE, 0, NULL,
									OPEN_EXISTING, 0, NULL);
	if (m_handle == INVALID_HANDLE_VALUE)
	{
		CMT1LOG("L1: Port cannot be opened\n");
		return (m_lastResult = XRV_INPUTCANNOTBEOPENED);
	}

	// Once here, port is open
	m_isOpen = true;

	//Get the current state & then change it
	GetCommState(m_handle, &m_commState);	// Get current state

	m_commState.BaudRate = baudRate;			// Setup the baud rate
	m_commState.Parity = NOPARITY;				// Setup the Parity
	m_commState.ByteSize = 8;					// Setup the data bits
	m_commState.StopBits = TWOSTOPBITS;			// Setup the stop bits
	m_commState.fDsrSensitivity = FALSE;		// Setup the flow control
	m_commState.fOutxCtsFlow = FALSE;			// NoFlowControl:
	m_commState.fOutxDsrFlow = FALSE;
	m_commState.fOutX = FALSE;
	m_commState.fInX = FALSE;
	if (!SetCommState(m_handle, (LPDCB)&m_commState)) {// Set new state
		// Bluetooth ports cannot always be opened with 2 stopbits
		// Now try to open port with 1 stopbit.
		m_commState.StopBits = ONESTOPBIT;
		if (!SetCommState(m_handle, (LPDCB)&m_commState)) {
			CloseHandle(m_handle);
			m_handle = INVALID_HANDLE_VALUE;
			m_isOpen = false;
			return (m_lastResult = XRV_INPUTCANNOTBEOPENED);
		}
	}
	m_port = atoi(&portName[3]);
	sprintf(m_portname, "%s", portName);

	setTimeout(m_timeout);

	// Other initialization functions
	EscapeCommFunction(m_handle, SETRTS);		// Enable RTS (for Xbus Master use)
	// Set DTR (Calibration sensors need DTR to startup, won't hurt otherwise
	EscapeCommFunction(m_handle, SETDTR);
	SetupComm(m_handle,readBufSize,writeBufSize);	// Set queue size

	// Remove any 'old' data in buffer
	//PurgeComm(m_handle, PURGE_TXCLEAR | PURGE_RXCLEAR);
	PurgeComm(m_handle, PURGE_TXABORT | PURGE_RXABORT | PURGE_TXCLEAR | PURGE_RXCLEAR);
#else // !_WIN32
	// Open port
	m_handle = ::open(portName, O_RDWR | O_NOCTTY);
	// O_RDWR: Read+Write
	// O_NOCTTY: Raw input, no "controlling terminal"
	// O_NDELAY: Don't care about DCD signal

	if (m_handle < 0) {
		// Port not open
		return m_lastResult = XRV_INPUTCANNOTBEOPENED;
	}

	// Once here, port is open
	m_isOpen = true;

	/* Start configuring of port for non-canonical transfer mode */
	// Get current options for the port
	tcgetattr(m_handle, &m_commState);

	// Set baudrate.
	cfsetispeed(&m_commState, baudRate);
	cfsetospeed(&m_commState, baudRate);

	// Enable the receiver and set local mode
	m_commState.c_cflag |= (CLOCAL | CREAD);
	// Set character size to data bits and set no parity Mask the characte size bits
	m_commState.c_cflag &= ~(CSIZE|PARENB);
	m_commState.c_cflag |= CS8;		// Select 8 data bits
//.........这里部分代码省略.........
开发者ID:GYengera,项目名称:mrpt,代码行数:101,代码来源:cmt1.cpp

示例8: CreateFile

Serial::Serial(char *portName)
{
    //We're not yet connected
    this->connected = false;

    //Try to connect to the given port through CreateFile
    this->hSerial = CreateFile(portName,
            GENERIC_READ | GENERIC_WRITE,
            0,
            NULL,
            OPEN_EXISTING,
            FILE_ATTRIBUTE_NORMAL,
            NULL);

    //Check if the connection was successfull
    if(this->hSerial==INVALID_HANDLE_VALUE)
    {
        //If not successful display an Error
        if(GetLastError()==ERROR_FILE_NOT_FOUND){

            //Print Error if neccessary
            printf("ERROR: Handle was not attached. Reason: %s not available.\n", portName);

        }
        else
        {
            printf("ERROR!!!");
        }
    }
    else
    {
        //If connected we try to set the comm parameters
        DCB dcbSerialParams = {0};

        //Try to get the current
        if (!GetCommState(this->hSerial, &dcbSerialParams))
        {
            //If impossible, show an error
            printf("failed to get current serial parameters!");
        }
        else
        {
            //Define serial connection parameters for the arduino board
            dcbSerialParams.BaudRate=CBR_9600;
            dcbSerialParams.ByteSize=8;
            dcbSerialParams.StopBits=ONESTOPBIT;
            dcbSerialParams.Parity=NOPARITY;

             //Set the parameters and check for their proper application
             if(!SetCommState(hSerial, &dcbSerialParams))
             {
                printf("ALERT: Could not set Serial Port parameters");
             }
             else
             {
                 //If everything went fine we're connected
                 this->connected = true;
                 //We wait 2s as the arduino board will be reseting
                 Sleep(ARDUINO_WAIT_TIME);
             }
        }
    }

}
开发者ID:billlipeng,项目名称:ECEN489-Fall2013,代码行数:64,代码来源:Serial.cpp

示例9: memset

/*
打开串口
*/
HANDLE CComInit::OpenComm(int ncom)
{
	memset( &m_read_os, 0, sizeof( OVERLAPPED ) ) ;    
	memset( &m_write_os, 0, sizeof( OVERLAPPED ) ) ;
	
	CString Com;
	Com.Format(_T("COM%d"),ncom);
	HANDLE hCom = CreateFile(Com,GENERIC_READ | GENERIC_WRITE,
		0,NULL,OPEN_EXISTING,FILE_FLAG_OVERLAPPED,NULL);

	if(INVALID_HANDLE_VALUE==hCom)
	{
		CloseHandle(hCom);
		return hCom;
	}
	//创建事件
	m_read_os.hEvent = CreateEvent(NULL,TRUE,FALSE,NULL);
	m_write_os.hEvent = CreateEvent(NULL,TRUE,FALSE,NULL);
	if(NULL == m_read_os.hEvent || NULL == m_write_os.hEvent){
		CloseHandle(hCom);
		CloseHandle(m_read_os.hEvent);
		CloseHandle(m_write_os.hEvent);
		hCom = INVALID_HANDLE_VALUE;
		return hCom;
	}
	//设置com事件类型,参见msdn
	SetCommMask(hCom,EV_RXCHAR | EV_TXEMPTY);
	SetupComm( hCom, 1024,512 );//设置缓冲区大小;
	PurgeComm( hCom, PURGE_TXABORT | PURGE_RXABORT | PURGE_TXCLEAR
		| PURGE_RXCLEAR ); //清干净输入、输出缓冲区

	DCB dcb={0};
	dcb.DCBlength=sizeof(dcb);
	BOOL bres=GetCommState(hCom,&dcb);
	if(!bres)
	{
		CloseHandle(hCom);
		hCom=INVALID_HANDLE_VALUE;
		return hCom;
	}
	dcb.ByteSize=8;//后改
	dcb.fParity=0;
	dcb.BaudRate=CBR_9600;
	dcb.StopBits=ONESTOPBIT;

	bres=SetCommState(hCom,&dcb);
	if(!bres)
	{
		CloseHandle(hCom);
		hCom=INVALID_HANDLE_VALUE;
		return hCom;
	}
	COMMTIMEOUTS comm_time={0};
	comm_time.ReadIntervalTimeout=MAXDWORD;
	bres=SetCommTimeouts(hCom,&comm_time);
//	SetupComm(m_hComWndScreen, 4096, 1024);

	if(!bres)
	{
		CloseHandle(hCom);
		CloseHandle(m_read_os.hEvent);
		CloseHandle(m_write_os.hEvent);
		hCom = INVALID_HANDLE_VALUE;
		return hCom;
	}
	return hCom;
}
开发者ID:Forlearngit,项目名称:HallQueFront,代码行数:70,代码来源:ComInit.cpp

示例10: coserial_main

static co_rc_t coserial_main(int argc, char *argv[])
{
	co_rc_t rc;
	co_module_t module;
	HANDLE out_handle, in_handle;
	int select_time;

	rc = handle_parameters(&g_daemon_parameters, argc, argv);
	if (!CO_OK(rc))
		return rc;

	rc = co_reactor_create(&g_reactor);
	if (!CO_OK(rc))
		return rc;

	co_debug("connecting to monitor");

	module = CO_MODULE_SERIAL0 + g_daemon_parameters.index;
	rc = co_user_monitor_open(g_reactor, monitor_receive,
				  g_daemon_parameters.instance,
				  &module, 1,
				  &g_monitor_handle);
	if (!CO_OK(rc))
		return rc;

	if (g_daemon_parameters.filename_specified == PTRUE) {
		char name [strlen(g_daemon_parameters.filename) + 4+1];
		DCB dcb;
		COMMTIMEOUTS commtimeouts = {
			1,	/* ReadIntervalTimeout */
			0,	/* ReadTotalTimeoutMultiplier */
			0,	/* ReadTotalTimeoutConstant */
			0,	/* WriteTotalTimeoutMultiplier */
			0 };	/* WriteTotalTimeoutConstant */

		if (g_daemon_parameters.filename[0] != '\\') {
			/* short windows name */
			if (strncasecmp(g_daemon_parameters.filename, "COM", 3) != 0)
				co_terminal_print("warning: host serial device '%s' is not a COM port\n",
						    g_daemon_parameters.filename);
			snprintf(name, sizeof(name), "\\\\.\\%s", g_daemon_parameters.filename);
		} else {
			/* windows full name device */
			strncpy(name, g_daemon_parameters.filename, sizeof(name));
		}

		co_debug("open device '%s'", name);
		out_handle = \
		in_handle = CreateFile (name,
				GENERIC_READ | GENERIC_WRITE, 0, NULL,
				OPEN_EXISTING,
				FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL);
		if (in_handle == INVALID_HANDLE_VALUE) {
			co_terminal_print_last_error(g_daemon_parameters.filename);
			return CO_RC(ERROR);
		}

		if (g_daemon_parameters.mode_specified == PTRUE) {
			co_debug("set mode: %s", g_daemon_parameters.mode);

			if (!GetCommState(in_handle, &dcb)) {
				co_terminal_print_last_error("GetCommState");
				return CO_RC(ERROR);
			}

			/* Set defaults. user can overwrite ot */
			dcb.fOutxCtsFlow = FALSE; /* Disable Handshake */
			dcb.fDtrControl = DTR_CONTROL_ENABLE;
			dcb.fRtsControl = RTS_CONTROL_ENABLE;

			if (!BuildCommDCB(g_daemon_parameters.mode, &dcb)) {
				/*co_terminal_print_last_error("colinux-serial-daemon: BuildCommDCB");*/
				co_terminal_print("colinux-serial-daemon: error in mode parameter '%s'\n",
							g_daemon_parameters.mode);
				return CO_RC(ERROR);
			}

			if (!SetCommState(in_handle, &dcb)) {
				co_terminal_print_last_error("SetCommState");
				return CO_RC(ERROR);
			}
		} else {
			if (!EscapeCommFunction(in_handle, SETDTR)) {
				co_terminal_print_last_error("Warning EscapeCommFunction DTR");
				/* return CO_RC(ERROR); */
			}

			if (!EscapeCommFunction(in_handle, SETRTS)) {
				co_terminal_print_last_error("Warning EscapeCommFunction RTS");
				/* return CO_RC(ERROR); */
			}
		}

		if (!SetCommTimeouts(in_handle, &commtimeouts)) {
			co_terminal_print_last_error("SetCommTimeouts");
			return CO_RC(ERROR);
		}

		if (!SetupComm(in_handle, 2048, 2048)) {
			co_terminal_print_last_error("SetupComm");
//.........这里部分代码省略.........
开发者ID:gvsurenderreddy,项目名称:CoLinux64,代码行数:101,代码来源:main.c

示例11: Disconnect

bool PrinterSerial::RawConnect( string device, int baudrate ) {
#ifdef WIN32
  if ( IsConnected() || device_handle != INVALID_HANDLE_VALUE ) {
    Disconnect();
    if ( device_handle != INVALID_HANDLE_VALUE )
      return false;
  }

  device_handle = CreateFile( device.c_str(),
			      GENERIC_READ | GENERIC_WRITE,
			      0,
			      NULL,
			      OPEN_EXISTING,
			      FILE_ATTRIBUTE_NORMAL,
			      NULL );
  if ( device_handle == INVALID_HANDLE_VALUE ) {
    char err_str[ 256 ];
    snprintf( err_str, 256, _("Error opening port %s"), device.c_str() );
    err_str[ 256 ] = '\0';

    ostringstream os;
    os << err_str << " (" << GetLastError() << ")"<< endl;
    LogError( os.str().c_str() );
    return false;
  }

  DCB dcb = { 0 };
  dcb.DCBlength = sizeof( dcb );

  if ( ! GetCommState( device_handle, &dcb ) ) {
    CloseHandle( device_handle );
    device_handle = INVALID_HANDLE_VALUE;
    char err_str[ 256 ];
    snprintf( err_str, 256, _("Error getting port %s state"), device.c_str() );
    err_str[ 255 ] = '\0';

    ostringstream os;
    os << err_str << " (" << GetLastError() << ")"<< endl;
    LogError( os.str().c_str() );
    return false;
  }

  dcb.BaudRate = baudrate;
  dcb.fBinary = 1;
  dcb.fParity = 0;
  dcb.fOutxCtsFlow = 0;
  dcb.fOutxDsrFlow = 0;
  dcb.fDtrControl = DTR_CONTROL_ENABLE;
  dcb.fDsrSensitivity = 0;
  dcb.fOutX = 0;
  dcb.fInX = 0;
  dcb.fNull = 0;
  dcb.fRtsControl = RTS_CONTROL_ENABLE;
  dcb.ByteSize = 8;
  dcb.Parity = NOPARITY;
  dcb.StopBits = ONESTOPBIT;

  if ( ! SetCommState( device_handle, &dcb ) ) {
    CloseHandle( device_handle );
    device_handle = INVALID_HANDLE_VALUE;
    char err_str[ 256 ];
    snprintf( err_str, 256, _("Error setting port %s state"), device.c_str() );
    err_str[ 255 ] = '\0';

    ostringstream os;
    os << err_str << " (" << GetLastError() << ")"<< endl;
    LogError( os.str().c_str() );
    return false;
  }

  COMMTIMEOUTS ct;

  if ( ! GetCommTimeouts( device_handle, &ct ) ) {
    CloseHandle( device_handle );
    device_handle = INVALID_HANDLE_VALUE;
    char err_str[ 256 ];
    snprintf( err_str, 256, _("Error getting port %s timeouts"), device.c_str() );
    err_str[ 255 ] = '\0';

    ostringstream os;
    os << err_str << " (" << GetLastError() << ")"<< endl;
    LogError( os.str().c_str() );
    return false;
  }

  ct.ReadIntervalTimeout = 5;
  ct.ReadTotalTimeoutConstant = max_recv_block_ms;
  ct.ReadTotalTimeoutMultiplier = 0;
  ct.WriteTotalTimeoutConstant = max_recv_block_ms;
  ct.WriteTotalTimeoutMultiplier= 0;

  if ( ! SetCommTimeouts( device_handle, &ct ) ) {
    CloseHandle( device_handle );
    device_handle = INVALID_HANDLE_VALUE;
    char err_str[ 256 ];
    snprintf( err_str, 256, _("Error setting port %s timeouts"), device.c_str() );
    err_str[ 255 ] = '\0';
    ostringstream os;
    os << err_str << " (" << GetLastError() << ")"<< endl;
    LogError( os.str().c_str() );
//.........这里部分代码省略.........
开发者ID:YassineEraman,项目名称:repsnapper,代码行数:101,代码来源:printer_serial.cpp

示例12: SerialOpen

BOOL SerialOpen(int port, int baud) {
	HANDLE Comport;
	DCB myDCB;
	COMMTIMEOUTS CTout;
	char str[100];

	if (port > 9)
		sprintf(str, "\\\\.\\COM%d", port);
	else
		sprintf(str, "COM%d", port);

	// Open the serial port
	if ((Comport = CreateFile(str, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL)) == INVALID_HANDLE_VALUE)
		return FALSE;

	// Configure Serial port (Setup Comm)

	// Buffer sizes
	if (!SetupComm(Comport, 128, 128))
		return FALSE;

	// Setup DCB using current values
	if (!GetCommState(Comport, &myDCB))
		return FALSE;

	myDCB.fInX = FALSE;     // Turn off xon/xoff handler
	myDCB.fOutX = FALSE;
	myDCB.fOutxDsrFlow = FALSE;
	myDCB.fOutxCtsFlow = FALSE;    // no hardware flow control.
	myDCB.BaudRate = baud;
	myDCB.DCBlength = sizeof(DCB);
	myDCB.fBinary = 1;
	myDCB.fParity = 0;
	myDCB.fDtrControl = DTR_CONTROL_DISABLE;
	myDCB.fDsrSensitivity = 0;
	myDCB.fTXContinueOnXoff = 1;
	myDCB.fNull = 0;
	myDCB.fRtsControl = RTS_CONTROL_DISABLE;
	myDCB.fDummy2 = 0;
	myDCB.wReserved = 0;
	myDCB.Parity = NOPARITY;
	myDCB.StopBits = ONESTOPBIT;
	myDCB.wReserved1 = 0;
	myDCB.ByteSize = 8;

	if (!SetCommState(Comport, &myDCB))
		return FALSE;

	// Set timeouts
	CTout.ReadIntervalTimeout = 0xffffffff;
	CTout.ReadTotalTimeoutMultiplier = 0;
	CTout.ReadTotalTimeoutConstant = 0;
	CTout.WriteTotalTimeoutMultiplier = 0;
	CTout.WriteTotalTimeoutConstant = 5000;         // don't hang if CTS is locked, for example

	SetCommTimeouts(Comport, &CTout);
	EscapeCommFunction(Comport, SETDTR);
	PurgeComm(Comport, PURGE_TXCLEAR | PURGE_RXCLEAR);

	SerialPort = Comport;

	return TRUE;
}
开发者ID:CatalystG,项目名称:fceu-next,代码行数:63,代码来源:__serial.c

示例13: SHOWTIP

// 打开串口
HANDLE CMySerialPort::OpenPort()
{
    if (IsOpen())
    {
        return m_portHandle;
    }

    if (0 >= m_strComName.GetLength())
    {
        LOG.err_log("请先设置串口参数");
        CString strTip = "请先设置串口参数";
        SHOWTIP(strTip);
        return INVALID_HANDLE_VALUE;
    }

    // 以重叠方式打开串口
    m_strComName = "\\\\.\\" + m_strComName;
    m_portHandle = CreateFile(m_strComName,
        GENERIC_READ|GENERIC_WRITE,
        0,
        NULL,
        OPEN_EXISTING,
        0, //FILE_ATTRIBUTE_NORMAL|FILE_FLAG_OVERLAPPED,
        NULL);

    if (INVALID_HANDLE_VALUE == m_portHandle)
    {
        CString strTip;
        LOG.err_log("打开串口[%s]失败", (LPCSTR)m_strComName);
        strTip.Format("打开串口[%s]失败", m_strComName);
        SHOWTIP(strTip);
        return INVALID_HANDLE_VALUE;
    }

    // 设置串口参数
    DCB dcb;
    BOOL ret = GetCommState(m_portHandle, &dcb);
    if (FALSE == ret)
    {
        LOG.err_log("获取串口默认配置参数失败");
        CString strTip("获取串口默认配置参数失败");
        SHOWTIP(strTip);
        return INVALID_HANDLE_VALUE;
    }
    dcb.BaudRate = m_baud;
    dcb.StopBits = m_stopbits;
    dcb.Parity = m_check;
    dcb.ByteSize = m_databits;
    //dcb.fParity = FALSE; // 禁止奇偶检查
    //dcb.fBinary = TRUE;//是否允许传二进制 
    if (FALSE == SetCommState(m_portHandle,&dcb))
    {
        LOG.err_log("配置串口参数失败!");
        CString strTip("配置串口参数失败!");
        SHOWTIP(strTip);
        return INVALID_HANDLE_VALUE;
    }
    
    // 设置缓冲区大小
    if (FALSE == SetupComm(m_portHandle, 1024, 1024))
    {
        LOG.err_log("缓冲区设置失败!");
        CString strTip("缓冲区设置失败!");
        SHOWTIP(strTip);
        return INVALID_HANDLE_VALUE;
    }

    // 设置串口超时时间
    COMMTIMEOUTS CommTimeOuts;
    CommTimeOuts.ReadIntervalTimeout = 100;
    CommTimeOuts.ReadTotalTimeoutMultiplier = 100;
    CommTimeOuts.ReadTotalTimeoutConstant = 100;

    CommTimeOuts.WriteTotalTimeoutMultiplier = 500;
    CommTimeOuts.WriteTotalTimeoutConstant = 2000;
    if(false == SetCommTimeouts(m_portHandle,&CommTimeOuts))
    {
        LOG.err_log("设置读写超时时间失败!");
        CString strTip("设置读写超时时间失败!");
        SHOWTIP(strTip);
        return INVALID_HANDLE_VALUE;
    }

    // 清空发送和接收缓冲区
    PurgeComm(m_portHandle, PURGE_TXCLEAR|PURGE_RXCLEAR);

    m_bClosePort = false;

    return m_portHandle;
}
开发者ID:jeyochen,项目名称:MyCodingRes,代码行数:91,代码来源:MySerialPort.cpp

示例14: printf

//open
//	Opens the serial port using stored information
//	Sets the baud rate to the stored baud rate
//	8 data bits, no parity, one stop bit
bool serial_port::serial_open()
{
    printf("SerialPort: Opening serial port %s at baud rate %d.\n", port_name, baud_rate);

#ifdef WINDOWS
    file_descriptor = CreateFile(port_name, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);

    if((int)file_descriptor < 0)
    {
        printf("SerialPort: Port %s could not be opened: %d.\n", port_name, file_descriptor);
        return false;
    }

    SetupComm(file_descriptor, 1, 128);
    GetCommState(file_descriptor, &dcb);

    dcb.BaudRate = baud_rate;                   //Set baud rate
    dcb.ByteSize = 8;                           //8 data bits
    dcb.Parity = NOPARITY;                      //Parity = none
    dcb.StopBits = ONESTOPBIT;                  //One stop bit
    dcb.fAbortOnError = TRUE;                   //Abort on error
    dcb.fOutX = FALSE;                          //XON/XOFF off for transmit
    dcb.fInX = FALSE;                           //XON/XOFF off for receive
    dcb.fOutxCtsFlow = FALSE;                   //Turn off CTS flow control
    dcb.fRtsControl = RTS_CONTROL_DISABLE;      //Options DISABLE, ENABLE, HANDSHAKE
    dcb.fOutxDsrFlow = FALSE;                   //Turn off DSR flow control
    dcb.fDtrControl = DTR_CONTROL_DISABLE;      //Disable DTR control

    SetCommState(file_descriptor, &dcb);

    COMMTIMEOUTS timeouts = {0};
    timeouts.ReadIntervalTimeout = 50;
    timeouts.ReadTotalTimeoutConstant=50;
    timeouts.ReadTotalTimeoutMultiplier=10;
    timeouts.WriteTotalTimeoutConstant=50;
    timeouts.WriteTotalTimeoutMultiplier=10;
    SetCommTimeouts(file_descriptor, &timeouts);
#endif

#ifdef LINUX
    file_descriptor = open(port_name, O_RDWR | O_NOCTTY | O_NDELAY);

    if(file_descriptor < 0)
    {
        printf("SerialPort: Port %s could not be opened: %d.\n", port_name, file_descriptor);
        return false;
    }

    serial_struct ss;
    ioctl(file_descriptor, TIOCGSERIAL, &ss);
    ss.flags = (ss.flags & ~ASYNC_SPD_MASK) | ASYNC_SPD_CUST | ASYNCB_LOW_LATENCY;
    ss.custom_divisor = (ss.baud_base + (baud_rate / 2)) / baud_rate;
    int closestSpeed = ss.baud_base / ss.custom_divisor;

    if((float)closestSpeed < ((float)baud_rate * (98.0f/100.0f)) || (float)closestSpeed > ((float)baud_rate * (102.0f/100.0f)))
    {
        printf("SerialPort: Cannot set %s to %d.  Closest possible speed is %d.\n", port_name, baud_rate, closestSpeed);
    }
    else
    {
        printf("SerialPort: %s speed set to %d.\n", port_name, baud_rate);
    }

    fcntl(file_descriptor, F_SETFL, 0);
#endif

    printf("SerialPort: Serial port %s opened successfully.\n", port_name);
    return true;
}
开发者ID:CalcProgrammer1,项目名称:FanBus-Fan-Controller,代码行数:73,代码来源:serial_port.cpp

示例15: defined

ATMO_BOOL CAtmoClassicConnection::OpenConnection() {
#if defined(_ATMO_VLC_PLUGIN_)
     char *serdevice = m_pAtmoConfig->getSerialDevice();
     if(!serdevice)
        return ATMO_FALSE;
#else
     int portNummer = m_pAtmoConfig->getComport();
     m_dwLastWin32Error = 0;
	 if(portNummer < 1) return ATMO_FALSE; // make no real sense;-)
#endif

	 CloseConnection();

#if !defined(_ATMO_VLC_PLUGIN_)
     char serdevice[16];  // com4294967295
     sprintf(serdevice,"com%d",portNummer);
#endif

#if defined(WIN32)

     m_hComport = CreateFile(serdevice, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
     if(m_hComport == INVALID_HANDLE_VALUE) {
//      we have a problem here can't open com port... somebody else may use it?
//	    m_dwLastWin32Error = GetLastError();
	    return ATMO_FALSE;
     }
     /* change serial settings (Speed, stopbits etc.) */
     DCB dcb; // für comport-parameter
     dcb.DCBlength = sizeof(DCB);
     GetCommState (m_hComport, &dcb); // ger current serialport settings
     dcb.BaudRate  = 38400;        // set speed
     dcb.ByteSize  = 8;            // set databits
     dcb.Parity    = NOPARITY;     // set parity
     dcb.StopBits  = ONESTOPBIT;   // set one stop bit
     SetCommState (m_hComport, &dcb);    // apply settings

#else

     int bconst = B38400;
     m_hComport = open(serdevice,O_RDWR |O_NOCTTY);
     if(m_hComport < 0) {
	    return ATMO_FALSE;
     }

     struct termios tio;
     memset(&tio,0,sizeof(tio));
     tio.c_cflag = (CS8 | CREAD | HUPCL | CLOCAL);
     tio.c_iflag = (INPCK | BRKINT);
     cfsetispeed(&tio, bconst);
     cfsetospeed(&tio, bconst);
     if(!tcsetattr(m_hComport, TCSANOW, &tio)) {
         tcflush(m_hComport, TCIOFLUSH);
     } else {
         // can't change parms
        close(m_hComport);
        m_hComport = -1;
        return false;
     }

#endif

     return true;
}
开发者ID:CSRedRat,项目名称:vlc,代码行数:63,代码来源:AtmoClassicConnection.cpp


注:本文中的GetCommState函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。