- c-periphery
- https://github.com/vsergeev/c-periphery
文章目录
- NAME
- SYNOPSIS
- ENUMERATIONS
- 关于奇偶校验枚举类型
- DESCRIPTION
- serial_new()
- serial_open()
- 关于流控制
- 软件流控制(XON/XOFF)
- 硬件流控制(RTS/CTS)
- 选择流控制方法
- serial_open_advanced()
- serial_read()
- 关于非阻塞读
- 如何工作的?
- 使用场景
- 示例
- 关于VMIN和VTIME
- VMIN (Minimum number of characters to read)
- VTIME (Timer for read completion)
- 结合使用 VMIN 和 VTIME
- serial_write()
- serial_flush()
- serial_input_waiting()
- serial_output_waiting()
- serial_poll()
- serial_close()
- serial_free()
- serial_get_xxx()
- serial_get_baudrate()函数获取波特率流程
- serial_set_xxx()
- serial_get_vmin()、serial_get_vtime()、serial_set_vmin()、serial_set_vtime()
- serial_fd()
- serial_tostring()
- serial_errno()
- serial_errmsg()
- RETURN VALUE
- EXAMPLE
NAME
Serial wrapper functions for Linux userspace termios tty
devices.
SYNOPSIS
#include <periphery/serial.h>
/* Primary Functions */
serial_t *serial_new(void);
int serial_open(serial_t *serial, const char *path, uint32_t baudrate);
int serial_open_advanced(serial_t *serial, const char *path, uint32_t baudrate,
unsigned int databits, serial_parity_t parity,
unsigned int stopbits, bool xonxoff, bool rtscts);
int serial_read(serial_t *serial, uint8_t *buf, size_t len, int timeout_ms);
int serial_write(serial_t *serial, const uint8_t *buf, size_t len);
int serial_flush(serial_t *serial);
int serial_input_waiting(serial_t *serial, unsigned int *count);
int serial_output_waiting(serial_t *serial, unsigned int *count);
int serial_poll(serial_t *serial, int timeout_ms);
int serial_close(serial_t *serial);
void serial_free(serial_t *serial);
/* Getters */
int serial_get_baudrate(serial_t *serial, uint32_t *baudrate);
int serial_get_databits(serial_t *serial, unsigned int *databits);
int serial_get_parity(serial_t *serial, serial_parity_t *parity);
int serial_get_stopbits(serial_t *serial, unsigned int *stopbits);
int serial_get_xonxoff(serial_t *serial, bool *xonxoff);
int serial_get_rtscts(serial_t *serial, bool *rtscts);
/* Setters */
int serial_set_baudrate(serial_t *serial, uint32_t baudrate);
int serial_set_databits(serial_t *serial, unsigned int databits);
int serial_set_parity(serial_t *serial, enum serial_parity parity);
int serial_set_stopbits(serial_t *serial, unsigned int stopbits);
int serial_set_xonxoff(serial_t *serial, bool enabled);
int serial_set_rtscts(serial_t *serial, bool enabled);
/* Miscellaneous */
int serial_fd(serial_t *serial);
int serial_tostring(serial_t *serial, char *str, size_t len);
/* Error Handling */
int serial_errno(serial_t *serial);
const char *serial_errmsg(serial_t *serial);
ENUMERATIONS
serial_parity_t
PARITY_NONE
: No parityPARITY_ODD
: Odd parityPARITY_EVEN
: Even parity
关于奇偶校验枚举类型
“
serial_parity_t
”是一个枚举类型,用于定义串口通信中的奇偶校验选项。在串口通信中,奇偶校验是一种错误检测机制,它可以帮助检测数据传输中的单比特错误。这个枚举定义了三种可能的奇偶校验模式:
PARITY_NONE
:
- 无校验:在这种模式下,不进行奇偶校验。数据传输不会增加校验位,这是最基本的设置,用于当错误检测不是特别关键的情况。
PARITY_ODD
:
- 奇校验:在这种模式下,校验位设置为使得总的数据位(包括校验位)中1的数量为奇数。这意味着如果数据位中1的数量已经是奇数,则校验位为0;如果是偶数,则校验位为1。
PARITY_EVEN
:
- 偶校验:与奇校验相反,偶校验确保总的数据位中1的数量为偶数。如果数据位中1的数量已经是偶数,则校验位为0;如果是奇数,则校验位为1。
这些设置通常在串口配置时指定,依据你的通信协议和所需的数据完整性级别来选择。例如,如果你的通信环境较为嘈杂或对数据准确性有较高要求,可能会选择使用奇校验或偶校验来提高数据的可靠性。如果环境相对稳定,为了节省带宽,可以选择无校验。
DESCRIPTION
serial_new()
serial_t *serial_new(void);
Allocate a Serial handle.
Returns a valid handle on success, or NULL on failure.
serial_open()
int serial_open(serial_t *serial, const char *path, uint32_t baudrate);
Open the tty
device at the specified path (e.g. “/dev/ttyUSB0”), with the specified baudrate, and the defaults of 8 data bits, no parity, 1 stop bit, software flow control (xonxoff) off, hardware flow control (rtscts) off.
serial
should be a valid pointer to an allocated Serial handle structure.
Returns 0 on success, or a negative Serial error code on failure.
关于流控制
在串口通信中,流控制是一种用于管理数据传输速率和确保数据完整性的机制。流控制可以是软件实现的,也可以是硬件实现的,用于控制发送设备和接收设备之间的数据流,防止接收方的缓冲区溢出。以下是对软件和硬件流控制的详细解释:
软件流控制(XON/XOFF)
- 软件流控制,也称为 XON/XOFF 流控制,是通过发送特殊的控制字符来控制数据流的。
- XON(通常是 ASCII 字符
CTRL-Q
或十六进制0x11
)和 XOFF(通常是 ASCII 字符CTRL-S
或十六进制0x13
)分别用来恢复和暂停数据流。 - 当接收设备的缓冲区接近满时,它会发送 XOFF 字符给发送设备,指示其停止发送数据。当接收设备准备好接收更多数据时,它会发送 XON 字符,指示发送设备继续发送数据。
- 这种方法不需要额外的硬件支持,因为它使用标准的数据线来传输控制信号。
硬件流控制(RTS/CTS)
- 硬件流控制,通常涉及 RTS(Request to Send) 和 CTS(Clear to Send) 信号。
- RTS 是发送设备用来指示它准备好发送数据的信号。当接收设备准备好接收数据时,它会通过 CTS 信号来响应。
- 这种方式需要额外的硬件线路来传输 RTS 和 CTS 信号,因此对硬件的要求更高,但它可以提供更可靠的流控制,特别是在高速传输或长距离通信中。
- 与软件流控制相比,硬件流控制通常可以处理更大的数据流量和更快的速度,因为它不依赖于数据线本身来传递控制信号。
选择流控制方法
选择哪种类型的流控制取决于特定应用的需求、硬件配置和预期的数据传输速率。在一些简单或成本敏感的应用中,软件流控制可能是一个好的选择。对于需要高可靠性和高速数据传输的应用,硬件流控制可能更为适合。
serial_open_advanced()
int serial_open_advanced(serial_t *serial, const char *path, uint32_t baudrate,
unsigned int databits, serial_parity_t parity,
unsigned int stopbits, bool xonxoff, bool rtscts);
Open the tty
device at the specified path (e.g. “/dev/ttyUSB0”), with the specified baudrate, data bits, parity, stop bits, software flow control (xonxoff), and hardware flow control (rtscts) settings.
serial
should be a valid pointer to an allocated Serial handle structure. databits
can be 5, 6, 7, or 8. parity
can be PARITY_NONE
, PARITY_ODD
, or PARITY_EVEN
as defined above. stopbits
can be 1 or 2.
Returns 0 on success, or a negative Serial error code on failure.
serial_read()
int serial_read(serial_t *serial, uint8_t *buf, size_t len, int timeout_ms);
Read up to len
number of bytes from the serial port into the buf
buffer with the specified millisecond timeout. timeout_ms
can be positive for a blocking read with a timeout in milliseconds, zero for a non-blocking read, or negative for a blocking read that will block until length
number of bytes are read.
For a non-blocking or timeout-bound read, serial_read()
may return less than the requested number of bytes.
For a blocking read with the VMIN setting configured, serial_read()
will block until at least VMIN bytes are read. For a blocking read with both VMIN and VTIME settings configured, serial_read()
will block until at least VMIN bytes are read or the VTIME interbyte timeout expires after the last byte read. In either case, serial_read()
may return less than the requested number of bytes.
serial
should be a valid pointer to a Serial handle opened with serial_open()
or serial_open_advanced()
. timeout_ms
can be positive for a blocking read with a timeout in milliseconds, zero for a non-blocking read, or negative for a blocking read.
Returns the number of bytes read on success, 0 on timeout, or a negative Serial error code on failure.
关于非阻塞读
非阻塞读(non-blocking read)是指在读取数据时,如果没有数据可读,函数会立即返回而不是等待数据到达。这种模式在串口通信中非常有用,特别是在你需要程序在没有接收到数据的情况下继续执行其他任务时。
如何工作的?
当你对串口执行非阻塞读操作时:
- 如果串口的输入缓冲区中有数据,
serial_read()
会尽可能多地从缓冲区中读取数据,直到达到你请求的字节数(len
参数指定的数目)或缓冲区中的数据被全部读取完毕。 - 如果输入缓冲区中没有数据,函数将立即返回,并且返回值为0,表示没有读取到任何数据。
这与阻塞读取(blocking read)形成对比,后者会在没有足够的数据可读时使调用线程暂停执行,直到有足够的数据可读或达到某个特定的条件(如超时或特定数量的数据已经可用)。
使用场景
非阻塞读特别适用于以下几种场景:
- 多任务处理:当应用程序需要同时处理多种任务,如用户输入、数据处理和通信时,非阻塞读使程序能够在等待串口数据时继续执行其他任务。
- 实时系统:在实时数据处理或响应系统中,你可能不希望程序在等待串口数据时发生任何延迟。
- 事件驱动的程序:在事件驱动的设计中,非阻塞读可以用于轮询设备状态而不会阻塞程序的主循环。
示例
假设你有一个需要不断监测多个传感器数据,同时还需要响应用户命令的程序,使用非阻塞读可以让程序持续检查传感器数据,而不会因为某个传感器暂时没有数据而停滞不前。
在编程实践中,通常会结合使用非阻塞读和某种形式的事件通知或轮询机制,以有效地管理数据流和程序响应。
关于VMIN和VTIME
在串口编程中,VMIN
和 VTIME
是两个非常重要的设置,它们控制了阻塞读取(blocking read)行为,尤其是在使用 termios(在 UNIX 和类 UNIX 系统中控制终端 I/O 特性的编程接口)配置串口时。这两个参数通常一起使用来精确地定义串口读取操作的行为。
VMIN (Minimum number of characters to read)
VMIN
设置决定了 serial_read()
函数在返回前需要接收到的最小字符数。这是一个整数值,用于指定在阻塞模式下读取操作必须要读取的最少字节数。
- 如果
VMIN
被设置为 0,serial_read()
可能会立即返回,不管有无数据到达。 - 如果
VMIN
被设置为一个大于 0 的值,serial_read()
将会阻塞,直到至少有VMIN
个字节的数据可以被读取。
VTIME (Timer for read completion)
VTIME
设置定义了等待数据时的计时器。这个计时器的单位是十分之一秒(100 毫秒),用于指定在阻塞读取期间等待的时间长度。
- 如果
VTIME
设置为 0,则没有超时限制——serial_read()
将无限期等待,直到收到足够的数据。 - 如果
VTIME
设置为一个正值,这个值代表在收到首个字符后,再继续等待指定的时间,以接收更多的数据。如果在这段时间内没有新的数据到达,serial_read()
将返回已接收到的数据。
结合使用 VMIN 和 VTIME
VMIN
和 VTIME
可以根据需要组合设置来满足不同的读取需求:
VMIN > 0
且VTIME > 0
:在这种设置下,serial_read()
将阻塞直到收到VMIN
个字节的数据,或者在收到至少一个字节数据后,VTIME
计时器到期时返回。这可以用于确保在指定时间内尽可能多地读取数据,但不会无限期等待。VMIN = 0
且VTIME > 0
:在这种设置下,serial_read()
将在没有数据时立即返回,如果有数据到达,则在指定的VTIME
时间内等待更多数据。这种设置适合于非阻塞轮询。
这些参数的正确设置对于确保数据的有效和及时接收至关重要,特别是在实时系统或需要精确数据流控制的应用中。通过调整 VMIN
和 VTIME
,你可以根据具体的应用需求优化串口通信的效率和响应性。
serial_write()
int serial_write(serial_t *serial, const uint8_t *buf, size_t len);
Write len
number of bytes from the buf
buffer to the serial port.
serial
should be a valid pointer to a Serial handle opened with serial_open()
or serial_open_advanced()
.
Returns the number of bytes written on success, or a negative Serial error code on failure.
serial_flush()
int serial_flush(serial_t *serial);
Flush the write buffer of the serial port (i.e. force its write immediately).
serial
should be a valid pointer to a Serial handle opened with serial_open()
or serial_open_advanced()
.
Returns 0 on success, or a negative Serial error code on failure.
serial_input_waiting()
int serial_input_waiting(serial_t *serial, unsigned int *count);
Get the number of bytes waiting to be read from the serial port.
serial
should be a valid pointer to a Serial handle opened with serial_open()
or serial_open_advanced()
.
Returns 0 on success, or a negative Serial error code on failure.
serial_output_waiting()
int serial_output_waiting(serial_t *serial, unsigned int *count);
Get the number of bytes waiting to be written to the serial port.
serial
should be a valid pointer to a Serial handle opened with serial_open()
or serial_open_advanced()
.
Returns 0 on success, or a negative Serial error code on failure.
serial_poll()
bool serial_poll(serial_t *serial, int timeout_ms);
Poll for data available for reading from the serial port.
serial
should be a valid pointer to a Serial handle opened with serial_open()
or serial_open_advanced()
. timeout_ms
can be positive for a timeout in milliseconds, zero for a non-blocking poll, or negative for a blocking poll.
Returns 1 on success (data available for reading), 0 on timeout, or a negative Serial error code on failure.
serial_close()
int serial_close(serial_t *serial);
Close the tty
device.
serial
should be a valid pointer to a Serial handle opened with serial_open()
or serial_open_advanced()
.
Returns 0 on success, or a negative Serial error code on failure.
serial_free()
void serial_free(serial_t *serial);
Free a Serial handle.
serial_get_xxx()
int serial_get_baudrate(serial_t *serial, uint32_t *baudrate);
int serial_get_databits(serial_t *serial, unsigned int *databits);
int serial_get_parity(serial_t *serial, serial_parity_t *parity);
int serial_get_stopbits(serial_t *serial, unsigned int *stopbits);
int serial_get_xonxoff(serial_t *serial, bool *xonxoff);
int serial_get_rtscts(serial_t *serial, bool *rtscts);
Get the baudrate, data bits, parity, stop bits, software flow control (xonxoff), or hardware flow control (rtscts), respectively, of the underlying tty
device.
serial
should be a valid pointer to a Serial handle opened with serial_open()
or serial_open_advanced()
.
Returns 0 on success, or a negative Serial error code on failure.
serial_get_baudrate()函数获取波特率流程
serial_get_baudrate()
函数的工作流程涉及到读取串口配置,并从中提取当前的波特率设置。这个过程使用 POSIX 的 termios
结构,其步骤大致如下:
-
获取串口属性:
- 函数首先通过
tcgetattr()
调用获取串口(由文件描述符serial->fd
指向)当前的属性,并将其存储在一个termios
结构体中。这个调用可能失败(比如如果文件描述符不是一个有效的串口),此时会返回错误。
- 函数首先通过
-
解析波特率:
- 使用
cfgetospeed()
函数从termios
结构体中提取输出波特率(实际上这个函数通常返回一个比特掩码,而不是实际的波特率数字)。然后_serial_bits_to_baudrate()
函数将这个比特掩码转换成实际的整数波特率。这个转换通过一个switch
语句来匹配termios
定义的波特率常量,如B9600
、B115200
等。
- 使用
-
返回结果:
- 如果成功,波特率存储在
baudrate
指向的变量中,并返回0
表示成功。如果有任何错误发生,将返回一个非零值表示错误。
- 如果成功,波特率存储在
此过程确保了可以有效地读取和解析连接在计算机上的串口设备的当前配置。这对于调试或动态调整串口设置非常有用。
serial_set_xxx()
int serial_set_baudrate(serial_t *serial, uint32_t baudrate);
int serial_set_databits(serial_t *serial, unsigned int databits);
int serial_set_parity(serial_t *serial, enum serial_parity parity);
int serial_set_stopbits(serial_t *serial, unsigned int stopbits);
int serial_set_xonxoff(serial_t *serial, bool enabled);
int serial_set_rtscts(serial_t *serial, bool enabled);
Set the baudrate, data bits, parity, stop bits, software flow control (xonxoff), or hardware flow control (rtscts), respectively, on the underlying tty
device.
serial
should be a valid pointer to a Serial handle opened with serial_open()
or serial_open_advanced()
.
Returns 0 on success, or a negative Serial error code on failure.
serial_get_vmin()、serial_get_vtime()、serial_set_vmin()、serial_set_vtime()
int serial_get_vmin(serial_t *serial, unsigned int *vmin);
int serial_get_vtime(serial_t *serial, float *vtime);
int serial_set_vmin(serial_t *serial, unsigned int vmin);
int serial_set_vtime(serial_t *serial, float vtime);
Get or set the termios VMIN and VTIME settings, respectively, of the underlying tty
device.
VMIN specifies the minimum number of bytes returned from a blocking read. VTIME specifies the timeout in seconds of a blocking read.
When both VMIN and VTIME settings are configured, VTIME acts as an interbyte timeout that restarts on every byte received, and a blocking read will block until either VMIN bytes are read or the VTIME timeout expires after the last byte read. See the termios
man page for more information.
serial
should be a valid pointer to a Serial handle opened with serial_open()
or serial_open_advanced()
. vmin
can be between 0 and 255. vtime
can be between 0 and 25.5 seconds, with a resolution of 0.1 seconds.
Returns 1 on success, or a negative Serial error code on failure.
serial_fd()
int serial_fd(serial_t *serial);
Return the file descriptor (for the underlying tty
device) of the Serial handle.
serial
should be a valid pointer to a Serial handle opened with serial_open()
or serial_open_advanced()
.
This function is a simple accessor to the Serial handle structure and always succeeds.
serial_tostring()
int serial_tostring(serial_t *serial, char *str, size_t len);
Return a string representation of the Serial handle.
serial
should be a valid pointer to a Serial handle opened with serial_open()
or serial_open_advanced()
.
This function behaves and returns like snprintf()
.
serial_errno()
int serial_errno(serial_t *serial);
Return the libc errno of the last failure that occurred.
serial
should be a valid pointer to a Serial handle opened with serial_open()
or serial_open_advanced()
.
serial_errmsg()
const char *serial_errmsg(serial_t *serial);
Return a human readable error message of the last failure that occurred.
serial
should be a valid pointer to a Serial handle opened with serial_open()
or serial_open_advanced()
.
RETURN VALUE
The periphery Serial functions return 0 on success or one of the negative error codes below on failure.
The libc errno of the failure in an underlying libc library call can be obtained with the serial_errno()
helper function. A human readable error message can be obtained with the serial_errmsg()
helper function.
Error Code | Description |
---|---|
SERIAL_ERROR_ARG | Invalid arguments |
SERIAL_ERROR_OPEN | Opening serial port |
SERIAL_ERROR_QUERY | Querying serial port attributes |
SERIAL_ERROR_CONFIGURE | Configuring serial port attributes |
SERIAL_ERROR_IO | Reading/writing serial port |
SERIAL_ERROR_CLOSE | Closing serial port |
EXAMPLE
#include <stdio.h>
#include <stdlib.h>
#include "serial.h"
int main(void) {
serial_t *serial;
const char *s = "Hello World!";
char buf[128];
int ret;
serial = serial_new();
/* Open /dev/ttyUSB0 with baudrate 115200, and defaults of 8N1, no flow control */
if (serial_open(serial, "/dev/ttyUSB0", 115200) < 0) {
fprintf(stderr, "serial_open(): %s\n", serial_errmsg(serial));
exit(1);
}
/* Write to the serial port */
if (serial_write(serial, s, strlen(s)) < 0) {
fprintf(stderr, "serial_write(): %s\n", serial_errmsg(serial));
exit(1);
}
/* Read up to buf size or 2000ms timeout */
if ((ret = serial_read(serial, buf, sizeof(buf), 2000)) < 0) {
fprintf(stderr, "serial_read(): %s\n", serial_errmsg(serial));
exit(1);
}
printf("read %d bytes: _%s_\n", ret, buf);
serial_close(serial);
serial_free(serial);
return 0;
}