/*! \fn bool Win_QextSerialPort::open(OpenMode mode) Opens a serial port. Note that this function does not specify which device to open. If you need to open a device by name, see Win_QextSerialPort::open(const char*). This function has no effect if the port associated with the class is already open. The port is also configured to the current settings, as stored in the Settings structure. */ bool Win_QextSerialPort::open(OpenMode mode) { unsigned long confSize = sizeof(COMMCONFIG); Win_CommConfig.dwSize = confSize; DWORD dwFlagsAndAttributes = 0; if (queryMode() == QextSerialBase::EventDriven) dwFlagsAndAttributes += FILE_FLAG_OVERLAPPED; LOCK_MUTEX(); if (mode == QIODevice::NotOpen) return isOpen(); if (!isOpen()) { /*open the port*/ Win_Handle = CreateFileA(port.toLatin1(), GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_ALWAYS, dwFlagsAndAttributes, NULL); if (Win_Handle!=INVALID_HANDLE_VALUE) { /*configure port settings*/ GetCommConfig(Win_Handle, &Win_CommConfig, &confSize); GetCommState(Win_Handle, &(Win_CommConfig.dcb)); /*set up parameters*/ Win_CommConfig.dcb.fBinary=TRUE; Win_CommConfig.dcb.fInX=FALSE; Win_CommConfig.dcb.fOutX=FALSE; Win_CommConfig.dcb.fAbortOnError=FALSE; Win_CommConfig.dcb.fNull=FALSE; setBaudRate(Settings.BaudRate); setDataBits(Settings.DataBits); setStopBits(Settings.StopBits); setParity(Settings.Parity); setFlowControl(Settings.FlowControl); setTimeout(Settings.Timeout_Millisec); SetCommConfig(Win_Handle, &Win_CommConfig, sizeof(COMMCONFIG)); //init event driven approach if (queryMode() == QextSerialBase::EventDriven) { Win_CommTimeouts.ReadIntervalTimeout = MAXDWORD; Win_CommTimeouts.ReadTotalTimeoutMultiplier = 0; Win_CommTimeouts.ReadTotalTimeoutConstant = 0; Win_CommTimeouts.WriteTotalTimeoutMultiplier = 0; Win_CommTimeouts.WriteTotalTimeoutConstant = 0; SetCommTimeouts(Win_Handle, &Win_CommTimeouts); if (!SetCommMask( Win_Handle, EV_TXEMPTY | EV_RXCHAR | EV_DSR)) { qWarning("Failed to set Comm Mask. Error code: %ld", GetLastError()); UNLOCK_MUTEX(); return false; } overlapThread->start(); } QIODevice::open(mode); } } else { UNLOCK_MUTEX(); return false; } UNLOCK_MUTEX(); return isOpen(); }
Serial::Serial() : Serial("/dev/ttyUSB0", 9600, false, false, 0, 0) { #else Serial::Serial() : Serial("\\\\.\\COM1", 9600, false, false, 0, 0) { #endif } #ifndef _WIN32 Serial::Serial(const char *file, int baudRate, bool useParity, bool extraStopBit, unsigned char readMinChars, unsigned char readTimeout) : fd(0), tty{0} { //Set up serial interface //http://linux.die.net/man/3/termios fd = open(file, O_RDWR | O_NOCTTY); if(fd < 0) { Log::logf(Log::ERR, "Serial connection initialization failed!\n"); throw std::runtime_error("serial initialization failed"); } //Input/output flags tty.c_iflag = 0; //No input processing if(useParity) { tty.c_iflag |= INPCK; //Enable input parity checking } tty.c_oflag = 0; //No output processing //Control flags tty.c_cflag = CSIZE; //Character size mask tty.c_cflag |= CS8; //8 data bits if(useParity) { tty.c_cflag &= PARENB; //Enable output parity generation and input parity checking } else { tty.c_cflag &= ~PARENB; //Disable parity generation } if(extraStopBit) { tty.c_cflag &= CSTOPB; //2 stop bits } else { tty.c_cflag &= ~CSTOPB; //1 stop bit } tty.c_cflag |= CREAD; //Enable read tty.c_cflag |= CLOCAL; //Ignore control lines tty.c_cflag &= ~PARODD; //Even parity, if used //Local flags tty.c_lflag = 0; //No local processing: use non-canonical (raw) mode, disable echo, etc. //Control characters tty.c_cc[VMIN] = readMinChars; //Block on read until specified number of characters have been read tty.c_cc[VTIME] = readTimeout; //Time-based read, or timeout for blocking read //Set intial baud rate setBaudRate(baudRate, false); //Flush serial port and apply settings if(tcsetattr(fd, TCSAFLUSH, &tty) != 0) { Log::logf(Log::ERR, "Error applying serial port settings: %s\n", strerror(errno)); throw std::runtime_error("serial initialization failed"); } Log::logf(Log::INFO, "Serial connection initialized!\n"); }
/*! \brief SerialDevice::stopDevice Is the serial interface's implementation of setDefaults. * Sets the serial devices to the default values. (Rate=9600, Parity=None, Flow=None, Data=8, Stop=1) */ void SerialDevice::setDefaults() { statusReady = false; setBaudRate(9600); setParity(0); setFlowControl(0); setDataBits(8); setStopBits(1); }
/*! Opens the serial port associated to this class. This function has no effect if the port associated with the class is already open. The port is also configured to the current settings, as stored in the Settings structure. */ bool QextSerialPort::open(OpenMode mode) { QMutexLocker lock(mutex); if (mode == QIODevice::NotOpen) return isOpen(); if (!isOpen()) { qDebug() << "trying to open file" << port.toAscii(); //note: linux 2.6.21 seems to ignore O_NDELAY flag if ((fd = ::open(port.toAscii() ,O_RDWR | O_NOCTTY | O_NDELAY)) != -1) { qDebug("file opened succesfully"); setOpenMode(mode); // Flag the port as opened tcgetattr(fd, &old_termios); // Save the old termios Posix_CommConfig = old_termios; // Make a working copy /* the equivelent of cfmakeraw() to enable raw access */ #ifdef HAVE_CFMAKERAW cfmakeraw(&Posix_CommConfig); // Enable raw access #else Posix_CommConfig.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IXON); Posix_CommConfig.c_oflag &= ~OPOST; Posix_CommConfig.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN); Posix_CommConfig.c_cflag &= ~(CSIZE | PARENB); Posix_CommConfig.c_cflag |= CS8; #endif /*set up other port settings*/ Posix_CommConfig.c_cflag|=CREAD|CLOCAL; Posix_CommConfig.c_lflag&=(~(ICANON|ECHO|ECHOE|ECHOK|ECHONL|ISIG)); Posix_CommConfig.c_iflag&=(~(INPCK|IGNPAR|PARMRK|ISTRIP|ICRNL|IXANY)); Posix_CommConfig.c_oflag&=(~OPOST); Posix_CommConfig.c_cc[VMIN]= 0; #ifdef _POSIX_VDISABLE // Is a disable character available on this system? // Some systems allow for per-device disable-characters, so get the // proper value for the configured device const long vdisable = fpathconf(fd, _PC_VDISABLE); Posix_CommConfig.c_cc[VINTR] = vdisable; Posix_CommConfig.c_cc[VQUIT] = vdisable; Posix_CommConfig.c_cc[VSTART] = vdisable; Posix_CommConfig.c_cc[VSTOP] = vdisable; Posix_CommConfig.c_cc[VSUSP] = vdisable; #endif //_POSIX_VDISABLE setBaudRate(Settings.BaudRate); setDataBits(Settings.DataBits); setParity(Settings.Parity); setStopBits(Settings.StopBits); setFlowControl(Settings.FlowControl); setTimeout(Settings.Timeout_Millisec); tcsetattr(fd, TCSAFLUSH, &Posix_CommConfig); if (queryMode() == QextSerialPort::EventDriven) { readNotifier = new QSocketNotifier(fd, QSocketNotifier::Read, this); connect(readNotifier, SIGNAL(activated(int)), this, SIGNAL(readyRead())); }
/*! Opens a serial port. Note that this function does not specify which device to open. If you need to open a device by name, see QextSerialPort::open(const char*). This function has no effect if the port associated with the class is already open. The port is also configured to the current settings, as stored in the Settings structure. */ bool QextSerialPort::open(OpenMode mode) { unsigned long confSize = sizeof(COMMCONFIG); Win_CommConfig.dwSize = confSize; DWORD dwFlagsAndAttributes = 0; if (queryMode() == QextSerialPort::EventDriven) dwFlagsAndAttributes += FILE_FLAG_OVERLAPPED; QMutexLocker lock(mutex); if (mode == QIODevice::NotOpen) return isOpen(); if (!isOpen()) { /*open the port*/ Win_Handle=CreateFileA(port.toAscii(), GENERIC_READ|GENERIC_WRITE, 0, NULL, OPEN_EXISTING, dwFlagsAndAttributes, NULL); if (Win_Handle!=INVALID_HANDLE_VALUE) { QIODevice::open(mode); /*configure port settings*/ GetCommConfig(Win_Handle, &Win_CommConfig, &confSize); GetCommState(Win_Handle, &(Win_CommConfig.dcb)); /*set up parameters*/ Win_CommConfig.dcb.fBinary=TRUE; Win_CommConfig.dcb.fInX=FALSE; Win_CommConfig.dcb.fOutX=FALSE; Win_CommConfig.dcb.fAbortOnError=FALSE; Win_CommConfig.dcb.fNull=FALSE; setBaudRate(Settings.BaudRate); setDataBits(Settings.DataBits); setStopBits(Settings.StopBits); setParity(Settings.Parity); setFlowControl(Settings.FlowControl); setTimeout(Settings.Timeout_Millisec); SetCommConfig(Win_Handle, &Win_CommConfig, sizeof(COMMCONFIG)); //init event driven approach if (queryMode() == QextSerialPort::EventDriven) { Win_CommTimeouts.ReadIntervalTimeout = MAXDWORD; Win_CommTimeouts.ReadTotalTimeoutMultiplier = 0; Win_CommTimeouts.ReadTotalTimeoutConstant = 0; Win_CommTimeouts.WriteTotalTimeoutMultiplier = 0; Win_CommTimeouts.WriteTotalTimeoutConstant = 0; SetCommTimeouts(Win_Handle, &Win_CommTimeouts); if (!SetCommMask( Win_Handle, EV_TXEMPTY | EV_RXCHAR | EV_DSR)) { qWarning() << "failed to set Comm Mask. Error code:", GetLastError(); return false; } winEventNotifier = new QWinEventNotifier(overlap.hEvent, this); connect(winEventNotifier, SIGNAL(activated(HANDLE)), this, SLOT(onWinEvent(HANDLE))); WaitCommEvent(Win_Handle, &eventMask, &overlap); } } } else { return false; } return isOpen(); }
/*! \fn Posix_QextSerialPort::Posix_QextSerialPort(const char* name, const PortSettings& settings) Constructs a port with specified name and settings. */ Posix_QextSerialPort::Posix_QextSerialPort(const char* name, const PortSettings& settings) :QextSerialBase(name) { construct(); setBaudRate(settings.BaudRate); setDataBits(settings.DataBits); setStopBits(settings.StopBits); setParity(settings.Parity); setFlowControl(settings.FlowControl); setTimeout(settings.Timeout_Sec, settings.Timeout_Millisec); }
void SpiUartDevice::configureUart(unsigned long baudrate) { setBaudRate(baudrate); writeRegister(LCR, 0xBF); // access EFR register writeRegister(EFR, SPI_Uart_config.Flow); // enable enhanced registers writeRegister(LCR, SPI_Uart_config.DataFormat); // 8 data bit, 1 stop bit, no parity writeRegister(FCR, 0x06); // reset TXFIFO, reset RXFIFO, non FIFO mode writeRegister(FCR, 0x01); // enable FIFO mode }
/*! \fn Win_QextSerialPort::Win_QextSerialPort(const QString & name, const PortSettings& settings) Constructs a port with specified name and settings. */ Win_QextSerialPort::Win_QextSerialPort(const QString & name, const PortSettings& settings) { Win_Handle=INVALID_HANDLE_VALUE; setPortName(name); setBaudRate(settings.BaudRate); setDataBits(settings.DataBits); setStopBits(settings.StopBits); setParity(settings.Parity); setFlowControl(settings.FlowControl); setTimeout(settings.Timeout_Sec, settings.Timeout_Millisec); }
/*! \fn bool Posix_QextSerialPort::open(OpenMode mode) Opens the serial port associated to this class. This function has no effect if the port associated with the class is already open. The port is also configured to the current settings, as stored in the Settings structure. */ bool Posix_QextSerialPort::open(OpenMode mode) { LOCK_MUTEX(); if (mode == QIODevice::NotOpen) { UNLOCK_MUTEX(); return isOpen(); } if (!isOpen()) { /*open the port*/ Posix_File->setFileName(port); QueueReceiveSignals = 10; if (Posix_File->open(QIODevice::ReadWrite | QIODevice::Unbuffered)) { /*set open mode*/ QIODevice::open(mode); /*configure port settings*/ tcgetattr(Posix_File->handle(), &Posix_CommConfig); /*set up other port settings*/ Posix_CommConfig.c_cflag|=CREAD|CLOCAL; Posix_CommConfig.c_lflag&=(~(ICANON|ECHO|ECHOE|ECHOK|ECHONL|ISIG)); Posix_CommConfig.c_iflag&=(~(INPCK|IGNPAR|IGNBRK|PARMRK|ISTRIP|ICRNL|IXANY)); Posix_CommConfig.c_oflag&=(~OPOST); Posix_CommConfig.c_cc[VMIN]=0; Posix_CommConfig.c_cc[VINTR] = _POSIX_VDISABLE; Posix_CommConfig.c_cc[VQUIT] = _POSIX_VDISABLE; Posix_CommConfig.c_cc[VSTART] = _POSIX_VDISABLE; Posix_CommConfig.c_cc[VSTOP] = _POSIX_VDISABLE; Posix_CommConfig.c_cc[VSUSP] = _POSIX_VDISABLE; setBaudRate(Settings.BaudRate); setDataBits(Settings.DataBits); setParity(Settings.Parity); setStopBits(Settings.StopBits); setFlowControl(Settings.FlowControl); //setTimeout(Settings.Timeout_Sec, Settings.Timeout_Millisec); setTimeout(Settings.Timeout_Millisec); tcsetattr(Posix_File->handle(), TCSAFLUSH, &Posix_CommConfig); handle = Posix_File->handle(); readerThread->handle = handle; readerThread->shutdown = false; readerThread->start(); } else { qDebug("Could not open File! Error code : %d", Posix_File->error()); } } UNLOCK_MUTEX(); return isOpen(); }
/*! * \brief SerialDev::configPort - Parametri per configurare la porta seriale * \return true se riesce a configurare correttamente la porta seriale */ bool SerialDev::configPort (const QString &name) { bool debugVal = m_debug; m_debug = true; setPortName(name); if (!open(QIODevice::ReadWrite)) { QString testo = QString("Can't open %1, error code %2") .arg(portName()).arg(error()); debug(testo); return false; } if (!setBaudRate(QSerialPort::Baud115200)) { QString testo = QString("Can't set rate 115200 baud to port %1, error code %2") .arg(portName()).arg(error()); debug(testo); return false; } if (!setDataBits(QSerialPort::Data8)) { QString testo = QString("Can't set 8 data bits to port %1, error code %2") .arg(portName()).arg(error()); debug(testo); return false; } if (!setParity(QSerialPort::NoParity)) { QString testo = QString("Can't set no patity to port %1, error code %2") .arg(portName()).arg(error()); debug(testo); return false; } if (!setStopBits(QSerialPort::OneStop)) { QString testo = QString("Can't set 1 stop bit to port %1, error code %2") .arg(portName()).arg(error()); debug(testo); return false; } if (!setFlowControl(QSerialPort::NoFlowControl)) { QString testo = QString("Can't set no flow control to port %1, error code %2") .arg(portName()).arg(error()); debug(testo); return false; } connect(this, SIGNAL(error(QSerialPort::SerialPortError)), this, SLOT(errorSlot(QSerialPort::SerialPortError))); connect(this, SIGNAL(readyRead()), this, SLOT(fromDeviceSlot())); m_debug = debugVal; return true; }
JNIEXPORT jboolean JNICALL Java_com_fazecast_jSerialComm_SerialPort_configPort(JNIEnv *env, jobject obj, jlong serialPortFD) { if (serialPortFD <= 0) return JNI_FALSE; struct termios options = { 0 }; // Get port parameters from Java class int baudRate = (*env)->GetIntField(env, obj, baudRateField); int byteSizeInt = (*env)->GetIntField(env, obj, dataBitsField); int stopBitsInt = (*env)->GetIntField(env, obj, stopBitsField); int parityInt = (*env)->GetIntField(env, obj, parityField); tcflag_t byteSize = (byteSizeInt == 5) ? CS5 : (byteSizeInt == 6) ? CS6 : (byteSizeInt == 7) ? CS7 : CS8; tcflag_t stopBits = ((stopBitsInt == com_fazecast_jSerialComm_SerialPort_ONE_STOP_BIT) || (stopBitsInt == com_fazecast_jSerialComm_SerialPort_ONE_POINT_FIVE_STOP_BITS)) ? 0 : CSTOPB; tcflag_t parity = (parityInt == com_fazecast_jSerialComm_SerialPort_NO_PARITY) ? 0 : (parityInt == com_fazecast_jSerialComm_SerialPort_ODD_PARITY) ? (PARENB | PARODD) : (parityInt == com_fazecast_jSerialComm_SerialPort_EVEN_PARITY) ? PARENB : (parityInt == com_fazecast_jSerialComm_SerialPort_MARK_PARITY) ? (PARENB | CMSPAR | PARODD) : (PARENB | CMSPAR); // Clear any serial port flags if (isatty(serialPortFD)) fcntl(serialPortFD, F_SETFL, 0); // Set raw-mode to allow the use of ioctl() if (isatty(serialPortFD)) ioctl(serialPortFD, TCGETS, &options); else return JNI_FALSE; cfmakeraw(&options); // Set updated port parameters options.c_cflag = (byteSize | stopBits | parity | CLOCAL | CREAD); if (parityInt == com_fazecast_jSerialComm_SerialPort_SPACE_PARITY) options.c_cflag &= ~PARODD; options.c_iflag &= ~(INPCK | IGNPAR | PARMRK | ISTRIP); if (byteSizeInt < 8) options.c_iflag |= ISTRIP; if (parityInt != 0) options.c_iflag |= (INPCK | IGNPAR); // Set baud rate unsigned int baudRateCode = getBaudRateCode(baudRate); if (baudRateCode != 0) { cfsetispeed(&options, baudRateCode); cfsetospeed(&options, baudRateCode); } // Apply changes int retVal = -1; if (isatty(serialPortFD)) retVal = ioctl(serialPortFD, TCSETS, &options); else return JNI_FALSE; if (baudRateCode == 0) // Set custom baud rate setBaudRate(serialPortFD, baudRate); return ((retVal == 0) ? JNI_TRUE : JNI_FALSE); }
/*! \fn Win_QextSerialPort::Win_QextSerialPort(const PortSettings& settings) Constructs a port with default name and specified settings. */ Win_QextSerialPort::Win_QextSerialPort(const PortSettings& settings, QextSerialBase::QueryMode mode) { Win_Handle=INVALID_HANDLE_VALUE; setBaudRate(settings.BaudRate); setDataBits(settings.DataBits); setStopBits(settings.StopBits); setParity(settings.Parity); setFlowControl(settings.FlowControl); setTimeout(settings.Timeout_Millisec); setQueryMode(mode); init(); }
/*! \fn Posix_QextSerialPort::Posix_QextSerialPort(const PortSettings& settings) Constructs a port with default name and specified settings. */ Posix_QextSerialPort::Posix_QextSerialPort(const PortSettings& settings) : QextSerialBase() { setBaudRate(settings.BaudRate); setDataBits(settings.DataBits); setParity(settings.Parity); setStopBits(settings.StopBits); setFlowControl(settings.FlowControl); Posix_File=new QFile(); setTimeout(settings.Timeout_Sec, settings.Timeout_Millisec); }
bool D2xxSerial::open(string who, int baudRate) { FT_STATUS err = FT_OpenEx((void*)who.c_str(), FT_OPEN_BY_SERIAL_NUMBER, &handle); if (err != FT_OK) { // FT_OpenEx failed printf("Error connecting to '%s': %s\n", who.c_str(), getError(err)); return false; } setBaudRate(baudRate); return true; }
bool D2xxSerial::open(int which, int baudRate) { FT_STATUS err = FT_Open(0,&handle); if (err != FT_OK) { // FT_OpenEx failed printf("Error connecting to [%d]: %s\n", which, getError(err)); return false; } setBaudRate(baudRate); return true; }
void QextSerialPortPrivate::setPortSettings(const PortSettings &settings, bool update) { setBaudRate(settings.BaudRate, false); setDataBits(settings.DataBits, false); setStopBits(settings.StopBits, false); setParity(settings.Parity, false); setFlowControl(settings.FlowControl, false); setTimeout(settings.Timeout_Millisec, false); settingsDirtyFlags = DFE_ALL; if (update && q_func()->isOpen()) updatePortSettings(); }
bool UartDev::init(unsigned int pclk, unsigned int baudRate, int rxQSize, int txQSize) { mPeripheralClock = pclk; // Configure UART Hardware: Baud rate, FIFOs etc. if (LPC_UART0_BASE == (unsigned int) mpUARTRegBase) { lpc_pconp(pconp_uart0, true); NVIC_EnableIRQ(UART0_IRQn); } /* else if(LPC_UART1_BASE == (unsigned int)mpUARTRegBase) { lpc_pconp(pconp_uart1, true); NVIC_EnableIRQ(UART1_IRQn); } */ else if (LPC_UART2_BASE == (unsigned int) mpUARTRegBase) { lpc_pconp(pconp_uart2, true); NVIC_EnableIRQ(UART2_IRQn); } else if (LPC_UART3_BASE == (unsigned int) mpUARTRegBase) { lpc_pconp(pconp_uart3, true); NVIC_EnableIRQ(UART3_IRQn); } else { return false; } // Enable & Reset FIFOs and set 4 char timeout for Rx mpUARTRegBase->FCR = (1 << 0) | (1 << 6); mpUARTRegBase->FCR |= (1 << 1) | (1 << 2); setBaudRate(baudRate); // Set minimum queue size? if (rxQSize < 9) rxQSize = 8; if (txQSize < 9) txQSize = 8; // Create the receive and transmit queues if (!mRxQueue) mRxQueue = xQueueCreate(rxQSize, sizeof(char)); if (!mTxQueue) mTxQueue = xQueueCreate(txQSize, sizeof(char)); // Enable Rx/Tx and line status Interrupts: mpUARTRegBase->IER = (1 << 0) | (1 << 1) | (1 << 2); // B0:Rx, B1: Tx return (0 != mRxQueue && 0 != mTxQueue); }
/*! \fn Posix_QextSerialPort::Posix_QextSerialPort(const PortSettings& settings) Constructs a port with default name and specified settings. */ Posix_QextSerialPort::Posix_QextSerialPort(const PortSettings& settings, QextSerialBase::QueryMode mode) : QextSerialBase() { setBaudRate(settings.BaudRate); setDataBits(settings.DataBits); setParity(settings.Parity); setStopBits(settings.StopBits); setFlowControl(settings.FlowControl); setTimeout(settings.Timeout_Millisec); setQueryMode(mode); init(); }
/*! Constructs a port with default name and specified settings. */ QextSerialPort::QextSerialPort(const PortSettings& settings, QextSerialPort::QueryMode mode) : QIODevice() { construct(); setBaudRate(settings.BaudRate); setDataBits(settings.DataBits); setParity(settings.Parity); setStopBits(settings.StopBits); setFlowControl(settings.FlowControl); setTimeout(settings.Timeout_Millisec); setQueryMode(mode); platformSpecificInit(); }
//Functions //Increase device-side connection speed from 2400 baud to 38400 baud void Parallax::setBaudRate(bool increase) { unsigned char command[8] = {'!','S', 'C', 'S', 'B', 'R', increase, '\r'}; //3 preamble bytes, 3 command bytes, baud rate byte, command terminator if(serialWrite(&command, sizeof(command)) != sizeof(command)) { Log::logf(Log::ERR, "Error writing to Parallax servo controller!\n"); } //Remove remote echo from input buffer, ignore any errors serialRead(&command, sizeof(command)); //Set local baud rate if(increase) { setBaudRate(38400); } else { setBaudRate(2400); } //Check if a response was received if(!serialSelect(100000)) { //1 decisecond //No response received; wrong baud rate? Log::logf(Log::ERR, "Error communicating with Parallax servo controller!\n"); throw std::runtime_error("parallax speed increase failed"); } //Verify new baud rate unsigned char data[3] = {0}; //Response is "BR#", where # is the device's current baud rate setting (0x00 or 0x01) //FIXME: First character of response is sometimes dropped on baud rate increase, so check the second byte if the third is missing if((unsigned int)serialRead(&data, sizeof(data)) <= (ssize_t)sizeof(data) - 1) { Log::logf(Log::ERR, "Error reading from Parallax servo controller!\n"); } if(data[2] == increase || data[1] == increase) { Log::logf(Log::INFO, "Parallax serial connection baud rate changed successfully!\n"); } else { Log::logf(Log::ERR, "Error setting Parallax servo controller baud rate!\n"); throw std::runtime_error("parallax speed increase failed"); } }
SerialPortSettings::SerialPortSettings(QSerialPortInfo serialPortInfo, QSerialPort::DataBits dataBits, QSerialPort::StopBits stopBits, QSerialPort::Parity parityBits, QSerialPort::BaudRate baudRate, QSerialPort::FlowControl flowControl) { setSerialPortInfo(serialPortInfo); setDataBits(dataBits); setStopBits(stopBits); setParityBits(parityBits); setBaudRate(baudRate); setFlowControl(flowControl); }
void vexLcdInit( int port ) { // init the lcd structure vexLcdData.port = port; vexLcdData.flags = 0; vexLcdData.buttons = 0; // Init the baud rate setBaudRate( port, baudRate19200 ); // start task slightly higher priority then default StartTask( vexLcdPollTask, kDefaultTaskPriority + 1 ); }
/*! \fn Posix_QextSerialPort::construct(void) Common constructor function, called by all versions of Posix_QextSerialPort::Posix_QextSerialPort(). Sets up default port settings (115200 8N1 Hardware flow control where supported, otherwise no flow control, and 500 ms timeout). */ void Posix_QextSerialPort::construct(void) { QextSerialBase::construct(); #ifdef NOQFILE m_fdFile=-1; #else Posix_File=new QFile(); #endif setBaudRate(BAUD115200); setDataBits(DATA_8); setStopBits(STOP_1); setParity(PAR_NONE); setFlowControl(FLOW_HARDWARE); setTimeout(0, 500); }
task main() { bLCDBacklight = true; configureSerialPort(UART1, uartUserControl); //Configure Port Two For UART manually setBaudRate(UART1, baudRate115200); while (getChar(UART1) != -1) // Purge existing chars from buffer {} startTask(UARTReceive); while(true) {} }
void SpiUartDevice::configureUart(unsigned long baudrate) { /* * Configure the settings of the UART. */ // TODO: Improve with use of constants and calculations. setBaudRate(baudrate); writeRegister(LCR, 0xBF); // access EFR register writeRegister(EFR, SPI_Uart_config.Flow); // enable enhanced registers writeRegister(LCR, SPI_Uart_config.DataFormat); // 8 data bit, 1 stop bit, no parity writeRegister(FCR, 0x06); // reset TXFIFO, reset RXFIFO, non FIFO mode writeRegister(FCR, 0x01); // enable FIFO mode }
// ------------------------------------------------------------------------------ // Initialize, set the baudrate and enable RX // ------------------------------------------------------------------------------ void gSoftSerial::begin(uint16_t baudRate) { pinMode(rxPin, INPUT_PULLUP); pinMode(txPin, OUTPUT); *txPort |= txBitMask; // high = idle delay(1); // need some idle time rxBitMask = digitalPinToBitMask(rxPin); rxPort = portInputRegister(digitalPinToPort(rxPin)); txBitMask = digitalPinToBitMask(txPin); txPort = portOutputRegister(digitalPinToPort(txPin)); setBaudRate(baudRate); listen(); }
/** * \brief Default constructor */ CanBus::CanBus(QString device, int baudRate) { printf("CanBus::CanBus: %s %d\n", device.toStdString().c_str(), baudRate); rDebug("CanBus initialize"); // Open and initialize the device devHandler = VSCAN_Open(device.toAscii().data(), VSCAN_MODE_NORMAL); if(devHandler < 0) { qFatal("Failed to open Can device "); return; } rDebug("Can device "+device+" oppened correctly"); if(setBaudRate(baudRate) != 0) rDebug("Failed setting baudRate"); }
bool CCommand::Open() { // Device is initialized with 9600 bauds ??? conection int retry = 0; bool opened = false; // If device open failed retry three times while ((retry < 3) && (!opened)) { if (m_device->open()) { opened = true; qDebug() << "Connected"; break; } sleep(1); m_device->close(); sleep(1); retry++; } // If not opened cancel qDebug() << "Opened ? " << opened; if (opened == false) return false; // Try to power it on retry = 0; while (retry < 3) { // Try to power it on qDebug() << "setPower();"; setPower(true); // If powered end loop if (getPower()) { qDebug() << "Power on is OK"; qDebug() << "so change baudrate"; sleep(3); qDebug() << "change it on computer side too"; //m_device->setBaudRate("38400"); setBaudRate(CCommand::b38400); getPower(); sleep(10); // Baud rate is now 38400 return true; } sleep(3); retry++; } setPower(false); return false; }
/*! \fn bool Posix_QextSerialPort::open(OpenMode mode) Opens the serial port associated to this class. This function has no effect if the port associated with the class is already open. The port is also configured to the current settings, as stored in the Settings structure. */ bool Posix_QextSerialPort::open(OpenMode mode) { LOCK_MUTEX(); if (mode == QIODevice::NotOpen) return isOpen(); if (!isOpen()) { /*open the port*/ qDebug("trying to open file"); //note: linux 2.6.21 seems to ignore O_NDELAY flag if ((fd = ::open(port.toAscii() ,O_RDWR | O_NOCTTY | O_NDELAY)) != -1) { qDebug("file opened succesfully"); setOpenMode(mode); // Flag the port as opened tcgetattr(fd, &old_termios); // Save the old termios Posix_CommConfig = old_termios; // Make a working copy cfmakeraw(&Posix_CommConfig); // Enable raw access /*set up other port settings*/ Posix_CommConfig.c_cflag|=CREAD|CLOCAL; Posix_CommConfig.c_lflag&=(~(ICANON|ECHO|ECHOE|ECHOK|ECHONL|ISIG)); Posix_CommConfig.c_iflag&=(~(INPCK|IGNPAR|PARMRK|ISTRIP|ICRNL|IXANY)); Posix_CommConfig.c_oflag&=(~OPOST); Posix_CommConfig.c_cc[VMIN]= 0; #ifdef _POSIX_VDISABLE // Is a disable character available on this system? // Some systems allow for per-device disable-characters, so get the // proper value for the configured device const long vdisable = fpathconf(fd, _PC_VDISABLE); Posix_CommConfig.c_cc[VINTR] = vdisable; Posix_CommConfig.c_cc[VQUIT] = vdisable; Posix_CommConfig.c_cc[VSTART] = vdisable; Posix_CommConfig.c_cc[VSTOP] = vdisable; Posix_CommConfig.c_cc[VSUSP] = vdisable; #endif //_POSIX_VDISABLE setBaudRate(Settings.BaudRate); setDataBits(Settings.DataBits); setParity(Settings.Parity); setStopBits(Settings.StopBits); setFlowControl(Settings.FlowControl); setTimeout(Settings.Timeout_Millisec); tcsetattr(fd, TCSAFLUSH, &Posix_CommConfig); } else { qDebug("could not open file: %s", strerror(errno)); } } UNLOCK_MUTEX(); return isOpen(); }
/*! * \brief Rs232DevicePrivate::configPort - Parametri per configurare la porta seriale * \return true se riesce a configurare correttamente la porta seriale */ bool Rs232DevicePrivate::configPort () { if (!open(QIODevice::ReadWrite)) { QString testo = QString("Can't open %1, error code %2") .arg(portName()).arg(error()); debug(testo); return false; } if (!setBaudRate(QSerialPort::Baud115200)) { QString testo = QString("Can't set rate 115200 baud to port %1, error code %2") .arg(portName()).arg(error()); debug(testo); return false; } if (!setDataBits(QSerialPort::Data8)) { QString testo = QString("Can't set 8 data bits to port %1, error code %2") .arg(portName()).arg(error()); debug(testo); return false; } if (!setParity(QSerialPort::NoParity)) { QString testo = QString("Can't set no patity to port %1, error code %2") .arg(portName()).arg(error()); debug(testo); return false; } if (!setStopBits(QSerialPort::OneStop)) { QString testo = QString("Can't set 1 stop bit to port %1, error code %2") .arg(portName()).arg(error()); debug(testo); return false; } if (!setFlowControl(QSerialPort::NoFlowControl)) { QString testo = QString("Can't set no flow control to port %1, error code %2") .arg(portName()).arg(error()); debug(testo); return false; } return true; }