Example #1
0
void
Serial::SerialImpl::setDTR (bool level)
{
  if (is_open_ == false) {
    throw PortNotOpenedException ("Serial::setDTR");
  }

  int command = TIOCM_DTR;

  if (level) {
    if (-1 == ioctl (fd_, TIOCMBIS, &command))
    {
      stringstream ss;
      ss << "setDTR failed on a call to ioctl(TIOCMBIS): " << errno << " " << strerror(errno);
      throw(SerialException(ss.str().c_str()));
    }
  } else {
    if (-1 == ioctl (fd_, TIOCMBIC, &command))
    {
      stringstream ss;
      ss << "setDTR failed on a call to ioctl(TIOCMBIC): " << errno << " " << strerror(errno);
      throw(SerialException(ss.str().c_str()));
    }
  }
}
void main() {
  char data; //To store the character to send
  printf("Enter character to be sent"); //User prompt
  scanf("%c",&data); //User input

  comm.startDevice("COM2", 9600);
  /* “COM 2” refers to the com port in which the USB to SERIAL port is attached. It is shown by right clicking on my computer, then going to properties and then device manager
  9600 is the baud-rate in bits per second */

  comm.send_data(data); //The data is sent through the port
  comm.stopDevice(); //The device is closed down

}
Example #3
0
void
Serial::SerialImpl::open ()
{
  if (port_.empty ()) {
    throw invalid_argument ("Empty port is invalid.");
  }
  if (is_open_ == true) {
    throw SerialException ("Serial port already open.");
  }

  fd_ = ::open (port_.c_str(), O_RDWR | O_NOCTTY | O_NONBLOCK);

  if (fd_ == -1) {
    switch (errno) {
    case EINTR:
      // Recurse because this is a recoverable error.
      open ();
      return;
    case ENFILE:
    case EMFILE:
      THROW (IOException, "Too many file handles open.");
    default:
      THROW (IOException, errno);
    }
  }

  reconfigurePort();
  is_open_ = true;
}
Example #4
0
void
Serial::SerialImpl::open ()
{
  if (port_.empty ()) {
    throw invalid_argument ("Empty port is invalid.");
  }
  if (is_open_ == true) {
    throw SerialExecption ("Serial port already open.");
  }

  fd_ = CreateFile(port_.c_str(),
                   GENERIC_READ | GENERIC_WRITE,
                   0,
                   0,
                   OPEN_EXISTING,
                   FILE_ATTRIBUTE_NORMAL,
                   0);

  if (fd_ == INVALID_HANDLE_VALUE) {
    DWORD errno_ = GetLastError();
	stringstream ss;
    switch (errno_) {
    case ERROR_FILE_NOT_FOUND:
      ss << "Specified port, " << port_ << ", does not exist.";
      THROW (IOException, ss.str().c_str());
    default:
      ss << "Unknown error opening the serial port: " << errno;
      THROW (IOException, ss.str().c_str());
    }
  }

  reconfigurePort();
  is_open_ = true;
}
Example #5
0
/*
int c;
 do { c = inportb(PORT1 + 5);
      if (c & 1) {buffer[bufferin] = inportb(PORT1);
		  bufferin++;
		  if (bufferin == 1024) {bufferin = 0;}}
    }while (c & 1);
 outportb(0x20,0x20);
*/
EXTERNC void handle_serial()
{
	//display("?");
	unsigned int result = 0;
	result = inportb(COM1_PORT + INT_ID);
	unsigned int status;	//stores the status of whatever needs checking
	if ((result & IID_NO_INT) != IID_NO_INT)
	{	//interrupt pending
		//display("\nInterrupt pending: ");
		//PrintNumber(result);
		//display("\n");
		if ((result & 0x06) == IID_MODEM)
		{
			
		}
		if ((result & 0x06) == IID_REC_STAT)
		{
			//status = inportb(COM1_PORT);
			
		}
		if ((result & 0x06) == IID_TRANSMIT)
		{
			
		}
		if ((result & 0x06) == IID_RECEIVED)
		{
			add_me_serial.data1 = kellogs.read_serial();
			add_system_event(&add_me_serial);
		}
	}
	outportb(0x20,0x20);	//signal end of interrupt
	//display("+");
}
Example #6
0
// bii:#entry_point()
void loop() {

	msg = serialport.read(); //read a message
	if(msg != "")
	{
		serialport.writeOpen();
		serialport.writeString(msg); //send a message
		serialport.writeEnd();

		if(premsg=="servo"){
			int n;
			n = atoi(msg.c_str());
			myservo.write(n);
		}
		premsg = msg;
	}
}
Example #7
0
void
Serial::SerialImpl::sendBreak (int duration)
{
  if (is_open_ == false) {
    throw PortNotOpenedException ("Serial::sendBreak");
  }
  tcsendbreak (fd_, static_cast<int> (duration / 4));
}
Example #8
0
void
Serial::SerialImpl::flushOutput ()
{
  if (is_open_ == false) {
    throw PortNotOpenedException ("Serial::flushOutput");
  }
  tcflush (fd_, TCOFLUSH);
}
Example #9
0
void
Serial::SerialImpl::flush ()
{
  if (is_open_ == false) {
    throw PortNotOpenedException ("Serial::flush");
  }
  tcdrain (fd_);
}
Example #10
0
void
Serial::SerialImpl::flush ()
{
  if (is_open_ == false) {
    throw PortNotOpenedException ("Serial::flush");
  }
  FlushFileBuffers (fd_);
}
Example #11
0
bool
Serial::SerialImpl::waitForChange ()
{
#ifndef TIOCMIWAIT

while (is_open_ == true) {

    int status;

    if (-1 == ioctl (fd_, TIOCMGET, &status))
    {
        stringstream ss;
        ss << "waitForChange failed on a call to ioctl(TIOCMGET): " << errno << " " << strerror(errno);
        throw(SerialException(ss.str().c_str()));
    }
    else
    {
        if (0 != (status & TIOCM_CTS)
         || 0 != (status & TIOCM_DSR)
         || 0 != (status & TIOCM_RI)
         || 0 != (status & TIOCM_CD))
        {
          return true;
        }
    }

    usleep(1000);
  }

  return false;
#else
  int command = (TIOCM_CD|TIOCM_DSR|TIOCM_RI|TIOCM_CTS);

  if (-1 == ioctl (fd_, TIOCMIWAIT, &command)) {
    stringstream ss;
    ss << "waitForDSR failed on a call to ioctl(TIOCMIWAIT): "
       << errno << " " << strerror(errno);
    throw(SerialException(ss.str().c_str()));
  }
  return true;
#endif
}
Example #12
0
bool
Serial::SerialImpl::getRI ()
{
  if (is_open_ == false) {
    throw PortNotOpenedException ("Serial::getRI");
  }

  int status;

  if (-1 == ioctl (fd_, TIOCMGET, &status))
  {
    stringstream ss;
    ss << "getRI failed on a call to ioctl(TIOCMGET): " << errno << " " << strerror(errno);
    throw(SerialException(ss.str().c_str()));
  }
  else
  {
    return 0 != (status & TIOCM_RI);
  }
}
Example #13
0
void
Serial::SerialImpl::setBreak (bool level)
{
  if (is_open_ == false) {
    throw PortNotOpenedException ("Serial::setBreak");
  }
  if (level) {
    EscapeCommFunction (fd_, SETBREAK);
  } else {
    EscapeCommFunction (fd_, CLRBREAK);
  }
}
Example #14
0
void
Serial::SerialImpl::setDTR (bool level)
{
  if (is_open_ == false) {
    throw PortNotOpenedException ("Serial::setDTR");
  }
  if (level) {
    EscapeCommFunction (fd_, SETDTR);
  } else {
    EscapeCommFunction (fd_, CLRDTR);
  }
}
Example #15
0
bool
Serial::SerialImpl::getCD()
{
  if (is_open_ == false) {
    throw PortNotOpenedException ("Serial::getCD");
  }
  DWORD dwModemStatus;
  if (!GetCommModemStatus(fd_, &dwModemStatus))
    // Error in GetCommModemStatus;
    THROW (IOException, "Error getting the status of the DSR line.");

  return (bool) (MS_RLSD_ON & dwModemStatus);
}
Example #16
0
bool
Serial::SerialImpl::getRI()
{
  if (is_open_ == false) {
    throw PortNotOpenedException ("Serial::getRI");
  }
  DWORD dwModemStatus;
  if (!GetCommModemStatus(fd_, &dwModemStatus)) {
    THROW (IOException, "Error getting the status of the RI line.");
  }

  return (MS_RING_ON & dwModemStatus) != 0;
}
Example #17
0
void
Serial::SerialImpl::setBreak (bool level)
{
  if (is_open_ == false) {
    throw PortNotOpenedException ("Serial::setBreak");
  }

  if (level) {
    if (-1 == ioctl (fd_, TIOCSBRK))
    {
        stringstream ss;
        ss << "setBreak failed on a call to ioctl(TIOCSBRK): " << errno << " " << strerror(errno);
        throw(SerialException(ss.str().c_str()));
    }
  } else {
    if (-1 == ioctl (fd_, TIOCCBRK))
    {
        stringstream ss;
        ss << "setBreak failed on a call to ioctl(TIOCCBRK): " << errno << " " << strerror(errno);
        throw(SerialException(ss.str().c_str()));
    }
  }
}
Example #18
0
size_t
Serial::SerialImpl::write (const uint8_t *data, size_t length)
{
  if (is_open_ == false) {
    throw PortNotOpenedException ("Serial::write");
  }
  DWORD bytes_written;
  if (!WriteFile(fd_, data, static_cast<DWORD>(length), &bytes_written, NULL)) {
    stringstream ss;
    ss << "Error while writing to the serial port: " << GetLastError();
    THROW (IOException, ss.str().c_str());
  }
  return (size_t) (bytes_written);
}
Example #19
0
size_t
Serial::SerialImpl::read (uint8_t *buf, size_t size)
{
  if (!is_open_) {
    throw PortNotOpenedException ("Serial::read");
  }
  DWORD bytes_read;
  if (!ReadFile(fd_, buf, static_cast<DWORD>(size), &bytes_read, NULL)) {
    stringstream ss;
    ss << "Error while reading from the serial port: " << GetLastError();
    THROW (IOException, ss.str().c_str());
  }
  return (size_t) (bytes_read);
}
Example #20
0
bool
Serial::SerialImpl::waitForChange ()
{
  if (is_open_ == false) {
    throw PortNotOpenedException ("Serial::waitForChange");
  }
  DWORD dwCommEvent = 0;

  if (!SetCommMask(fd_, EV_CTS | EV_DSR | EV_RING | EV_RLSD)) {
    // Error setting communications mask
    return false;
  }

  if (!WaitCommEvent(fd_, &dwCommEvent, NULL)) {
    // An error occurred waiting for the event.
    return false;
  } else {
    // Event has occurred.
    return true;
  }
}
Example #21
0
size_t
Serial::SerialImpl::available ()
{
   if (!is_open_) {
    throw PortNotOpenedException ("Serial::available");
   }

    DWORD dwBytesInQueue = 0;
   // If the port is open and the device is not NULL
 
 
	DWORD   dwErrorFlags = 0;
	COMSTAT ComStat;
	ClearCommError (fd_, 
	&dwErrorFlags,           // 指向接收错误码的变量
	&ComStat );            // 指向通讯状态缓冲区
	dwBytesInQueue = (DWORD)ComStat.cbInQue; // COMSTAT结构包含串口的信息,该成员变量的值代表输入缓冲区的字节数
   
	return (dwBytesInQueue);


}
Example #22
0
void
Serial::SerialImpl::open ()
{
  if (port_.empty ()) {
    throw invalid_argument ("Empty port is invalid.");
  }
  if (is_open_ == true) {
    throw SerialException ("Serial port already open.");
  }

  // See: https://github.com/wjwwood/serial/issues/84
  wstring port_with_prefix = _prefix_port_if_needed(port_);
  LPCWSTR lp_port = port_with_prefix.c_str();
  fd_ = CreateFileW(lp_port,
                    GENERIC_READ | GENERIC_WRITE,
                    0,
                    0,
                    OPEN_EXISTING,
                    FILE_ATTRIBUTE_NORMAL,
                    0);

  if (fd_ == INVALID_HANDLE_VALUE) {
    DWORD errno_ = GetLastError();
	stringstream ss;
    switch (errno_) {
    case ERROR_FILE_NOT_FOUND:
      // Use this->getPort to convert to a std::string
      ss << "Specified port, " << this->getPort() << ", does not exist.";
      THROW (IOException, ss.str().c_str());
    default:
      ss << "Unknown error opening the serial port: " << errno;
      THROW (IOException, ss.str().c_str());
    }
  }

  reconfigurePort();
  is_open_ = true;
}
Example #23
0
size_t
Serial::SerialImpl::write (const uint8_t *data, size_t length)
{
  if (is_open_ == false) {
    throw PortNotOpenedException ("Serial::write");
  }
  fd_set writefds;
  size_t bytes_written = 0;

  // Calculate total timeout in milliseconds t_c + (t_m * N)
  long total_timeout_ms = timeout_.write_timeout_constant;
  total_timeout_ms += timeout_.write_timeout_multiplier * static_cast<long> (length);
  MillisecondTimer total_timeout(total_timeout_ms);

  while (bytes_written < length) {
    int64_t timeout_remaining_ms = total_timeout.remaining();
    if (timeout_remaining_ms <= 0) {
      // Timed out
      break;
    }
    timespec timeout(timespec_from_ms(timeout_remaining_ms));

    FD_ZERO (&writefds);
    FD_SET (fd_, &writefds);

    // Do the select
    int r = pselect (fd_ + 1, NULL, &writefds, NULL, &timeout, NULL);

    // Figure out what happened by looking at select's response 'r'
    /** Error **/
    if (r < 0) {
      // Select was interrupted, try again
      if (errno == EINTR) {
        continue;
      }
      // Otherwise there was some error
      THROW (IOException, errno);
    }
    /** Timeout **/
    if (r == 0) {
      break;
    }
    /** Port ready to write **/
    if (r > 0) {
      // Make sure our file descriptor is in the ready to write list
      if (FD_ISSET (fd_, &writefds)) {
        // This will write some
        ssize_t bytes_written_now =
          ::write (fd_, data + bytes_written, length - bytes_written);
        // write should always return some data as select reported it was
        // ready to write when we get to this point.
        if (bytes_written_now < 1) {
          // Disconnected devices, at least on Linux, show the
          // behavior that they are always ready to write immediately
          // but writing returns nothing.
          throw SerialException ("device reports readiness to write but "
                                 "returned no data (device disconnected?)");
        }
        // Update bytes_written
        bytes_written += static_cast<size_t> (bytes_written_now);
        // If bytes_written == size then we have written everything we need to
        if (bytes_written == length) {
          break;
        }
        // If bytes_written < size then we have more to write
        if (bytes_written < length) {
          continue;
        }
        // If bytes_written > size then we have over written, which shouldn't happen
        if (bytes_written > length) {
          throw SerialException ("write over wrote, too many bytes where "
                                 "written, this shouldn't happen, might be "
                                 "a logical error!");
        }
      }
      // This shouldn't happen, if r > 0 our fd has to be in the list!
      THROW (IOException, "select reports ready to write, but our fd isn't"
                          " in the list, this shouldn't happen!");
    }
  }
  return bytes_written;
}
Example #24
0
void setup() {
	myservo.attach(9);
	serialport.init();
}
Example #25
0
size_t
Serial::SerialImpl::read (uint8_t *buf, size_t size)
{
  // If the port is not open, throw
  if (!is_open_) {
    throw PortNotOpenedException ("Serial::read");
  }
  size_t bytes_read = 0;

  // Calculate total timeout in milliseconds t_c + (t_m * N)
  long total_timeout_ms = timeout_.read_timeout_constant;
  total_timeout_ms += timeout_.read_timeout_multiplier * static_cast<long> (size);
  MillisecondTimer total_timeout(total_timeout_ms);

  // Pre-fill buffer with available bytes
  {
    ssize_t bytes_read_now = ::read (fd_, buf, size);
    if (bytes_read_now > 0) {
      bytes_read = bytes_read_now;
    }
  }

  while (bytes_read < size) {
    int64_t timeout_remaining_ms = total_timeout.remaining();
    if (timeout_remaining_ms <= 0) {
      // Timed out
      break;
    }
    // Timeout for the next select is whichever is less of the remaining
    // total read timeout and the inter-byte timeout.
    uint32_t timeout = std::min(static_cast<uint32_t> (timeout_remaining_ms),
                                timeout_.inter_byte_timeout);
    // Wait for the device to be readable, and then attempt to read.
    if (waitReadable(timeout)) {
      // If it's a fixed-length multi-byte read, insert a wait here so that
      // we can attempt to grab the whole thing in a single IO call. Skip
      // this wait if a non-max inter_byte_timeout is specified.
      if (size > 1 && timeout_.inter_byte_timeout == Timeout::max()) {
        size_t bytes_available = available();
        if (bytes_available + bytes_read < size) {
          waitByteTimes(size - (bytes_available + bytes_read));
        }
      }
      // This should be non-blocking returning only what is available now
      //  Then returning so that select can block again.
      ssize_t bytes_read_now =
        ::read (fd_, buf + bytes_read, size - bytes_read);
      // read should always return some data as select reported it was
      // ready to read when we get to this point.
      if (bytes_read_now < 1) {
        // Disconnected devices, at least on Linux, show the
        // behavior that they are always ready to read immediately
        // but reading returns nothing.
        throw SerialException ("device reports readiness to read but "
                               "returned no data (device disconnected?)");
      }
      // Update bytes_read
      bytes_read += static_cast<size_t> (bytes_read_now);
      // If bytes_read == size then we have read everything we need
      if (bytes_read == size) {
        break;
      }
      // If bytes_read < size then we have more to read
      if (bytes_read < size) {
        continue;
      }
      // If bytes_read > size then we have over read, which shouldn't happen
      if (bytes_read > size) {
        throw SerialException ("read over read, too many bytes where "
                               "read, this shouldn't happen, might be "
                               "a logical error!");
      }
    }
  }
  return bytes_read;
}
Example #26
0
 void __irq_dma1_channel4(void) {
     //DMA_ClearITPendingBit(DMA1_IT_TC4);
     serial1.txIsr();
 }
Example #27
0
int main(void)
{

	halInit();
	chSysInit();

	//kruciální řádky - odpojit jtag; nechat jenom swd - sou na nem piny pro SPI1
	//premapovat SPI1 na PB3;4;5
	RCC->APB2ENR |= RCC_APB2ENR_AFIOEN;
	AFIO->MAPR |= AFIO_MAPR_SPI1_REMAP;
	AFIO->MAPR |= 0b010 << 24;

#if 1
	spiStart(&SPID1, &config);
	palSetPadMode(config.ssport, config.sspad, PAL_MODE_OUTPUT_PUSHPULL);
	palSetPadMode(SPI_SCK_PORT, SPI_SCK_PIN, SPI_SCK_MODE);
	palSetPadMode(SPI_MISO_PORT, SPI_MISO_PIN, SPI_MISO_MODE);
	palSetPadMode(SPI_MOSI_PORT, SPI_MOSI_PIN, SPI_MOSI_MODE);

#else
	palSetPadMode(config.ssport, config.sspad, PAL_MODE_OUTPUT_PUSHPULL);
	palSetPadMode(SPI_SCK_PORT, SPI_SCK_PIN, PAL_MODE_OUTPUT_PUSHPULL);
	palSetPadMode(SPI_MISO_PORT, SPI_MISO_PIN, PAL_MODE_OUTPUT_PUSHPULL);
	palSetPadMode(SPI_MOSI_PORT, SPI_MOSI_PIN, PAL_MODE_OUTPUT_PUSHPULL);

	palClearPad(config.ssport, config.sspad);
	palClearPad(SPI_SCK_PORT, SPI_SCK_PIN);
	palClearPad(SPI_MISO_PORT, SPI_MISO_PIN);
	palClearPad(SPI_MOSI_PORT, SPI_MOSI_PIN);

	palSetPad(config.ssport, config.sspad);
	palClearPad(config.ssport, config.sspad);
	palClearPad(SPI_SCK_PORT, SPI_SCK_PIN);
	palClearPad(SPI_MISO_PORT, SPI_MISO_PIN);
	palClearPad(SPI_MOSI_PORT, SPI_MOSI_PIN);
	palSetPad(SPI_SCK_PORT, SPI_SCK_PIN);
	palClearPad(config.ssport, config.sspad);
	palClearPad(SPI_SCK_PORT, SPI_SCK_PIN);
	palClearPad(SPI_MISO_PORT, SPI_MISO_PIN);
	palClearPad(SPI_MOSI_PORT, SPI_MOSI_PIN);
	palSetPad(SPI_MISO_PORT, SPI_MISO_PIN);
	palClearPad(config.ssport, config.sspad);
	palClearPad(SPI_SCK_PORT, SPI_SCK_PIN);
	palClearPad(SPI_MISO_PORT, SPI_MISO_PIN);
	palClearPad(SPI_MOSI_PORT, SPI_MOSI_PIN);
	palSetPad(SPI_MOSI_PORT, SPI_MOSI_PIN);
	palClearPad(config.ssport, config.sspad);
	palClearPad(SPI_SCK_PORT, SPI_SCK_PIN);
	palClearPad(SPI_MISO_PORT, SPI_MISO_PIN);
	palClearPad(SPI_MOSI_PORT, SPI_MOSI_PIN);

	//
#endif

	palSetPadMode(TEST_LED_PORT, TEST_LED_PIN, PAL_MODE_INPUT);
	palSetPadMode(TEST_LED_PORT2, TEST_LED_PIN2, PAL_MODE_OUTPUT_PUSHPULL);

	palClearPad(TEST_LED_PORT, TEST_LED_PIN);
	palClearPad(TEST_LED_PORT2, TEST_LED_PIN2);

	s1.Register();

	palSetPadMode(GPIOA, 2, PAL_MODE_STM32_ALTERNATE_PUSHPULL);
//	palSetPad(GPIOA,2);
	//DBGMCU->CR |= DBGMCU_CR_DBG_TIM2_STOP;
	pwmStart(&PWMD2, &pwmcfg);
	pwmEnableChannel(&PWMD2,2,PWM_PERCENTAGE_TO_WIDTH(&PWMD2,5000));

	//setup watchdog
	DBGMCU->CR |= DBGMCU_CR_DBG_IWDG_STOP;
	IWDG->KR = 0x5555;
	IWDG->PR = 6;
	IWDG->RLR = 0xFFF;
	IWDG->KR = 0xCCCC;

#if 1
	ser.Init();

	rf.begin();
	rf.enableAckPayload();
	rf.enableDynamicPayloads();
	for (int i = 0; i < 5; i++)
		rf.openReadingPipe(i, pipe + i);
	rf.startListening();

#endif
	while (TRUE)
	{
		Scheduler::Play();
		ser.Loop();
		sysTime = chTimeNow();
	}

	return 1;
}