Cross-platform, Serial Port library written in C++

Related tags

Miscellaneous serial
Overview

Serial Communication Library

Build Status(Linux and OS X) Build Status(Windows)

This is a cross-platform library for interfacing with rs-232 serial like ports written in C++. It provides a modern C++ interface with a workflow designed to look and feel like PySerial, but with the speed and control provided by C++.

This library is in use in several robotics related projects and can be built and installed to the OS like most unix libraries with make and then sudo make install, but because it is a catkin project it can also be built along side other catkin projects in a catkin workspace.

Serial is a class that provides the basic interface common to serial libraries (open, close, read, write, etc..) and requires no extra dependencies. It also provides tight control over timeouts and control over handshaking lines.

Documentation

Website: http://wjwwood.github.com/serial/

API Documentation: http://wjwwood.github.com/serial/doc/1.1.0/index.html

Dependencies

Required:

  • catkin - cmake and Python based buildsystem
  • cmake - buildsystem
  • Python - scripting language
    • empy - Python templating library
    • catkin_pkg - Runtime Python library for catkin

Optional (for tests):

  • Boost - Boost C++ librairies

Optional (for documentation):

  • Doxygen - Documentation generation tool
  • graphviz - Graph visualization software

Install

Get the code:

git clone https://github.com/wjwwood/serial.git

Build:

make

Build and run the tests:

make test

Build the documentation:

make doc

Install:

make install

License

The MIT License

Copyright (c) 2012 William Woodall, John Harrison

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Authors

William Woodall [email protected] John Harrison [email protected]

Contact

William Woodall [email protected]

Comments
  • Reduce CPU usage for multi-byte reads

    Reduce CPU usage for multi-byte reads

    The way read/select are implemented in unix.cc means that block reads are typically still pulling data a few bytes at a time. This can consume a lot of CPU for reads of 20+ consecutive bytes.

    One of our customers has handled this by adding a lowlevel_read method, which gives the user a direct line to the underlying read() method: https://github.com/cedricpradalier/serial/blob/master/src/impl/unix.cc#L421

    Another alternative would be to introduce a usleep between the select and read calls. If you know how many bytes are expected and the baud rate, you can compute how long of a pause will allow the entire message to arrive. I don't know how well aligned such functionality would be with the design goals of Serial, but it's something to consider.

    As it stands, we have a sensor which mostly saturates a 115kbps serial line, and its Serial-based driver is still taking more CPU than we'd like.

    unix enhancement darwin 
    opened by mikepurvis 25
  • Timespec refactor (again)

    Timespec refactor (again)

    A simpler, gentler take on what was previously discussed in #42 and #43.

    • Everything is handled in ms, with a timespec_from_ms function providing last-minute conversion to timespecs for use in pselect.
    • A MillisecondTimer class is provided which handles the total_timeout functionality in read and write. Its set/remaining is in millis, but internally it stores the expiry point as a timespec for maximal resolution.
    • No funky math or operations on timespecs.
    opened by mikepurvis 18
  • Wait functions

    Wait functions

    ~~While the timespec PR is waiting on reviews, I want to get the ball rolling on this one, which is the actual change that one sets up for, based on the discussion in #37. Click here for a diff showing just the additional changes in this PR.~~

    Haven't had a chance to test much at this point, but it will be going into battle on two different peripheral drivers in the next day or two, so there will be some practical miles on it long before an actual merge happens.

    For the moment, it's also missing the stubs in the Windows implementation; compilation there will fail until those are added in.


    Okay, the timespec PR is merged, and this one has been rebased accordingly.

    opened by mikepurvis 17
  • Timespec refactor

    Timespec refactor

    This PR addresses #42. Summary:

    • Introduce a new unix-timespec.h header, which includes timespec operators for +, -, * by int, min, and conversion from millis. Rationale for new file is logical separation and better testability (though no tests at this point).
    • Cache the timeout values as timespecs in the SerialImpl, as that's the form in which they are exclusively used.
    • Call setTimeout() with a default Timeout obj from the constructor, to initialize the timespec caches to 0.
    • Simplify the timing logic in read and write methods to be based both around a fixed endtime, rather than timeout which is adjusted multiple times.
    • Introduce an available() check in read, to avoid going to the first select() if data is already waiting. This is important for devices which deliver a larger amount of data (eg, 5000+ bytes/sec), and is independent of the select/pselect switchover.

    Testing done has been against the um6 driver in Ubuntu Raring. The um6 driver uses both read and write.

    A followup will introduce the sleepByteTimes() and waitAvailable() functions to the external API.

    opened by mikepurvis 15
  • Problem with setting timout

    Problem with setting timout

    Hello,

    I am having a problem setting the timeout. I am using ROS Hydro. I've catkin installed serial, and used rosbuild to build serial_utils. In my program I have the line

    this->serial_port_->setTimeout(10);
    

    When I try to run this I get the error

    no matching function for call to 'serial::Serial::setTimeout(Int)'
    

    When I tried changing the line to

    this->serial_port_->setTimeout(10,10,10,10,10);
    

    This gives me

      ../lib/libax2550.so: undefined reference to serial::Serial::setBytesize(serial::bytesize_t)'
      ../lib/libax2550.so: undefined reference to `serial::Serial::setBaudrate(unsigned int)'
      ../lib/libax2550.so: undefined reference to `serial::Serial::setTimeout(serial::Timeout&)'
      ../lib/libax2550.so: undefined reference to `serial::utils::SerialListener::SerialListener(unsigned long)'
      ../lib/libax2550.so: undefined reference to `serial::Serial::Serial(std::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, unsigned int, serial::Timeout, serial::bytesize_t, serial::parity_t, serial::stopbits_t, serial::flowcontrol_t)'
      ../lib/libax2550.so: undefined reference to `serial::utils::SerialListener::startListening(serial::Serial&)'
      ../lib/libax2550.so: undefined reference to `serial::Serial::open()'
      ../lib/libax2550.so: undefined reference to `serial::Serial::write(std::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)'
      ../lib/libax2550.so: undefined reference to `serial::utils::SerialListener::~SerialListener()'
      ../lib/libax2550.so: undefined reference to `serial::Serial::setPort(std::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)'
      ../lib/libax2550.so: undefined reference to `serial::utils::SerialListener::createBufferedFilter(boost::function<bool (std::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)>, unsigned long)'
      ../lib/libax2550.so: undefined reference to `serial::utils::SerialListener::stopListening()'
      ../lib/libax2550.so: undefined reference to `serial::Serial::setStopbits(serial::stopbits_t)'
      ../lib/libax2550.so: undefined reference to `serial::Serial::setParity(serial::parity_t)'
      ../lib/libax2550.so: undefined reference to `serial::utils::SerialListener::createFilter(boost::function<bool (std::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)>, boost::function<void (std::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)>)'
    
    opened by NCharabaruk 13
  • serial_example.cc Command Arguments

    serial_example.cc Command Arguments

    Hello,

    What could be a valid value argument for the serial port in order to run the example? I tried COM1,COM2,etc and keep receiving the following error: "unhandled exception: I/O Exception:specified port, port_name, doesn't exist."

    Any ideas?

    opened by ghost 12
  • List ports

    List ports

    Emulated the port enumeration functionality found in pyserial's list_ports.comports().

    Available in linux and windows only at the moment. The linux implementation uses standard c++ and some posix calls to scrape sysfs. So it will compile on most "unixy" systems but obviously, will only return results on linux.

    opened by naedanger 11
  • Serial library installation failed

    Serial library installation failed

    When I run "sudo make" for installing serial library I get following messages with error.

    Can you please tell me what has gone wrong? I'm stuck here for two days now.

    cd build && cmake -DCMAKE_INSTALL_PREFIX=/opt/ros/jade/ ..
    -- The C compiler identification is GNU 4.8.4
    -- The CXX compiler identification is GNU 4.8.4
    -- Check for working C compiler: /usr/bin/cc
    -- Check for working C compiler: /usr/bin/cc -- works
    -- Detecting C compiler ABI info
    -- Detecting C compiler ABI info - done
    -- Detecting C compile features
    -- Detecting C compile features - done
    -- Check for working CXX compiler: /usr/bin/c++
    -- Check for working CXX compiler: /usr/bin/c++ -- works
    -- Detecting CXX compiler ABI info
    -- Detecting CXX compiler ABI info - done
    -- Detecting CXX compile features
    -- Detecting CXX compile features - done
    -- Using CATKIN_DEVEL_PREFIX: /home/odroid/Downloads/serial-master/build/devel
    -- Using CMAKE_PREFIX_PATH: 
    -- Found PythonInterp: /usr/bin/python (found version "2.7.6") 
    -- Using PYTHON_EXECUTABLE: /usr/bin/python
    -- Using Debian Python package layout
    -- Using empy: /usr/bin/empy
    -- Using CATKIN_ENABLE_TESTING: ON
    -- Call enable_testing()
    -- Using CATKIN_TEST_RESULTS_DIR: /home/odroid/Downloads/serial-master/build/test_results
    -- Looking for include file pthread.h
    -- Looking for include file pthread.h - found
    -- Looking for pthread_create
    -- Looking for pthread_create - not found
    -- Looking for pthread_create in pthreads
    -- Looking for pthread_create in pthreads - not found
    -- Looking for pthread_create in pthread
    -- Looking for pthread_create in pthread - found
    -- Found Threads: TRUE  
    -- Found gtest sources under '/usr/src/gtest': gtests will be built
    -- Using Python nosetests: /usr/bin/nosetests-2.7
    -- catkin 0.6.14
    Traceback (most recent call last):
      File "/home/odroid/Downloads/serial-master/build/catkin_generated/generate_cached_setup.py", line 20, in <module>
        from catkin.environment_cache import generate_environment_script
    ImportError: No module named catkin.environment_cache
    CMake Error at /opt/ros/jade/share/catkin/cmake/safe_execute_process.cmake:11 (message):
      execute_process(/usr/bin/python
      "/home/odroid/Downloads/serial-master/build/catkin_generated/generate_cached_setup.py")
      returned error code 1
    Call Stack (most recent call first):
      /opt/ros/jade/share/catkin/cmake/all.cmake:186 (safe_execute_process)
      /opt/ros/jade/share/catkin/cmake/catkinConfig.cmake:20 (include)
      CMakeLists.txt:5 (find_package)
    
    
    -- Configuring incomplete, errors occurred!
    See also "/home/odroid/Downloads/serial-master/build/CMakeFiles/CMakeOutput.log".
    See also "/home/odroid/Downloads/serial-master/build/CMakeFiles/CMakeError.log".
    make: *** [serial] Error 1
    
    opened by htr99 10
  • cannot build

    cannot build

    Please forgive my ignorance. I am good on Arduino/Atmel AVR, but have never done C or C++ programming on a computer (vs microcontroller).

    I want to run your serial example to start. I am using Windows 8 with CodeBlocks, GNU GCC Compiler. I downloaded your library zip file, extracted it, navigated there using command prompt, and typed "make" and I got the following errors:

    image

    I can't figure out how to install and use the library to run your test file....

    opened by ElectricRCAircraftGuy 10
  • Made catkin optional with automatic selection if it is available

    Made catkin optional with automatic selection if it is available

    I made catkin optional so this wonderful library can be used without it (now only with cmake) - as when you just want to install it and not use it with ROS.

    The changes I made will only take effect if catkin is not found. If you have any comments or things I should fix, then lets discuss.

    Tested on: Arch Linux, Ubuntu (both in and outside ROS)

    opened by korken89 8
  • serialConfig.cmake not found

    serialConfig.cmake not found

    I was able to successfully build and install serial but I can't include it in my CMake project.

    This is the error I get:

    CMake Warning at src/CMakeLists.txt:21 (find_package):
      By not providing "Findserial.cmake" in CMAKE_MODULE_PATH this project has
      asked CMake to find a package configuration file provided by "serial", but
      CMake did not find one.
    
      Could not find a package configuration file provided by "serial" with any
      of the following names:
    
        serialConfig.cmake
        serial-config.cmake
    
      Add the installation prefix of "serial" to CMAKE_PREFIX_PATH or set
      "serial_DIR" to a directory containing one of the above files.  If "serial"
      provides a separate development package or SDK, be sure it has been
      installed.
    

    I believe it's because serial itself doesn't provide a package configuration file. Is there any solution to this problem?

    opened by costas290 8
  • Full duplex support on Windows.

    Full duplex support on Windows.

    Add full duplex communications support on Windows.

    When I use a separate thread to read the serial data, I notice that the write operation is blocked.

    Here is a simple program to illustrate this.

    #include <iostream>
    #include <chrono>
    #include <thread>
    #include "serial/serial.h"
    
    using namespace std;
    using namespace chrono;
    using namespace std::chrono_literals;
    using namespace serial;
    
    int main(int argc, char **argv) {
        Serial serial_port("COM5", 9600, Timeout::simpleTimeout(200));
    
        thread read_serial([&](){
            while (true) {
                uint8_t ch;
                serial_port.read(&ch, 1);
            }
        });
    
        while (true) {
            // Test write latency.
            auto start = high_resolution_clock::now();
            serial_port.write("Hello world!\n");
            auto end = high_resolution_clock::now();
            double dt = duration<double>(end - start).count();
    
            cout << "Write using " << (dt * 1000) << " ms" << endl;
    
            this_thread::sleep_for(500ms);
        }
    }
    

    Output:

    Write using 0.0576 ms
    Write using 314.211 ms
    Write using 325.428 ms
    Write using 299.138 ms
    Write using 524.347 ms
    Write using 702.12 ms
    Write using 513.909 ms
    ...
    

    This does not make sense because the serial port is supposed to communicate asynchronously. To fix this problem, I modified win.h and win.cc to enable asynchronous communication by adding the OVERLAPPED option. This also helps to solve the issue #150.

    This is the right result:

    Write using 0.0093 ms
    Write using 0.034 ms
    Write using 0.0564 ms
    Write using 0.012 ms
    Write using 0.0343 ms
    Write using 0.0494 ms
    Write using 0.0124 ms
    Write using 0.01 ms
    
    opened by chinaheyu 0
  • Serial Port Exception

    Serial Port Exception

    Serial::SerialImpl::close () { if (is_open_ == true) { if (fd_ != INVALID_HANDLE_VALUE) { int ret; ret = CloseHandle(fd_); if (ret == 0) { stringstream ss; ss << "Error while closing serial port: " << GetLastError(); THROW (IOException, ss.str().c_str()); } else { fd_ = INVALID_HANDLE_VALUE; } } is_open_ = false; } } Untitled000

    opened by manandogar 0
  • Maintainer: do you need help?

    Maintainer: do you need help?

    Hey!

    It seems there is a lot of PR/issues ongoing on this project, and no release has been made for a while.

    Are you looking for help for maintaining this project? Being alone on an open source project can be tedious, I might help on small PR if you wish, or roadmap.

    Thanks for this nice library BTW! Cheers!

    opened by lp35 1
  • Fix empty PortInfo.description/hardware_id on Mac M1

    Fix empty PortInfo.description/hardware_id on Mac M1

    on Mac M1, both PortInfo.description and PortInfo.hardware_id are always "n/a", because usb device type name was changed from "IOUSBDevice" to "IOUSBHostInterface".

    opened by Quotation 0
The function is based on MQTT. When the original serial of ESP8266/ESP32 cannot be used, it can replace serial print.

MqttPrint and MqttMonitor The function is based on MQTT. When the original serial of ESP8266/ESP32 cannot be used, it can replace serial print. MqttPr

fw-box 4 Sep 28, 2022
John Walker 24 Dec 15, 2022
KeePassXC is a cross-platform community-driven port of the Windows application “Keepass Password Safe”.

KeePassXC KeePassXC is a modern, secure, and open-source password manager that stores and manages your most sensitive information. You can run KeePass

KeePassXC 14.7k Jan 2, 2023
A modern port of Turbo Vision 2.0, the classical framework for text-based user interfaces. Now cross-platform and with Unicode support.

Turbo Vision A modern port of Turbo Vision 2.0, the classical framework for text-based user interfaces. Now cross-platform and with Unicode support. I

null 1.4k Dec 31, 2022
The Leap Motion cross-format, cross-platform declarative serialization library

Introduction to LeapSerial LeapSerial is a cross-format, declarative, serialization and deserialization library written and maintained by Leap Motion.

Leap Motion (Ultraleap) 15 Jan 17, 2022
monome serial library for teensy development boards

monome-teensy allows teensy development boards to communicate with monome grids via monome serial protocol works with teensy 3.6, 4.0 and 4.1 (when us

Josh Ruihley 9 Oct 5, 2022
A cross platform shader language with multi-threaded offline compilation or platform shader source code generation

A cross platform shader language with multi-threaded offline compilation or platform shader source code generation. Output json reflection info and c++ header with your shaders structs, fx-like techniques and compile time branch evaluation via (uber-shader) "permutations".

Alex Dixon 286 Dec 14, 2022
Free,Open-Source,Cross-platform agent and Post-exploiton tool written in Golang and C++, the architecture and usage like Cobalt Strike

Khepri Free,Open-Source,Cross-platform agent and Post-exploiton tool written in Golang and C++ Description Khepri is a Cross-platform agent, the archi

Young 1.4k Jan 3, 2023
A fully-featured, cross platform XO-CHIP/S-CHIP/CHIP-8 emulator written in C and SDL.

JAXE (Just Another XO-CHIP/CHIP-8 Emulator) Brix Space Invaders (In Debug Mode) Black Rainbow DVN8 Super Neat Boy Chicken Scratch CHIP-8 was a virtual

Kurtis Dinelle 21 Nov 12, 2022
A cross-platform,lightweight,scalable game server framework written in C++, and support Lua Script

Current building status Moon Moon is a lightweight online game server framework implement with multithread and multi-luaVM. One thread may have 1-N lu

Bruce 467 Dec 29, 2022
Cross-platform sandbox RPG game written in C++ with OpenGL and SDL2.

Forradia test Forradia is a cross-platform sandbox survival/RPG game written in C++ with OpenGL and SDL2. The engine loads 3D models in Wavefront-form

Andreas Åkerberg 7 Nov 9, 2022
A cross-platform,lightweight,scalable game server framework written in C++, and support Lua Script

hive Distributed game server framework based on CPP 17 && LUA 5.4 框架(hive)+逻辑(server) 支持跨平台开发(windows,linux,mac) oop模式的lua开发,支持lua热更新 protobuf协议 pbc修改

toney 82 Jan 1, 2023
experiments with the Gameboy Advance serial interface

(I'm hedging my bets with this repo name. I'd want to add more serial setup tutorials. For example, I bought a bunch of Gameboy Advance wireless adapt

Ties Stuij 32 Jan 6, 2023
CRServoF - The CSRF serial protocol to PWM servo converter

CRServoF - The CSRF serial protocol to PWM servo converter I wanted to create a small project to mess around with PWM servo output for ExpressLRS, and

Bryan Mayland 107 Dec 28, 2022
Synology DSM 7 USB serial drivers

Missing USB serial drivers for DSM 7 Supported drivers cp210x ch341 Supported platforms apollolake (linux-4.4.x) armada38x (linux-3.10.x-bsp) armadaxp

Robert Klep 176 Dec 31, 2022
A handy little system information monitor using and ESP32 + ILI9488 TFT. Receives data over Serial Bluetooth.

Bluetooth-System-Monitor A handy little system information monitor using and ESP32 + ILI9488 TFT. Receives data over Serial Bluetooth and thus giving

Dustin Watts 32 Dec 22, 2022
An OLED gauge for the Speeduino ECU. Uses UART (secondary serial) for communication.

speeduino-ardugauge An OLED gauge for the Speeduino ECU. Uses UART (secondary serial) for communication. See demo video. See screenshots. NOTE: The ga

null 15 Dec 18, 2022
A software serial driver package by using the hardware timer capture / comparison functionality.

Soft serial 1.简介 Soft serial 是利用硬件定时器捕获/比较功能实现软件模拟串口的软件包。 1.1目录结构 Soft serial 软件包目录结构如下所示: soft_serial ├───inc // 头文件目录 │

齐永忠 2 Jul 14, 2022
USB serial TTY for the Arduino Uno with ILI9341 LCD screen shield

ILI9341TTY USB serial TTY for the Arduino Uno with ILI9341 LCD screen shield [video] Semigraphics, ANSI, unicode, and an Arduino LCD-screen terminal I

M Rule 72 Sep 30, 2022