c语言读取串口
⑴ C语言用read读取串口信息,按每字节读取和一次性读取一定长度效率上有区别吗
肯定有区别的,而且相差还比较大。
因为read是用户态程序,然后每read一次都对应一次系统调用 (从用户态切换到内核态,再切回到用户态),其实耗时最多的就是状态切换。
如果一次性读取5个字节,那么就只有一次系统调用(两个状态切换),
如果一次读一字节,需要读5次,就有5次系统调用 (10个状态切换)。
具体相差多大,跟实际的环境有关,测试的话要大量的数据才能看出来。
⑵ VS或者VC6.0编写的C语言程序,怎样能够实现串口数据的收发
1 、Windows API通信函数方法 。与通信有关的Windows API函数共有26个,但主要有关的有: CreateFile() 用 “comn”(n为串口号)作为文件名就可以打开串口。 ReadFile() 读串口。
2、WriteFile() 写串口。 CloseHandle() 关闭串口句柄。初始化时应注意CreateFile()函数中串兆键口共享方式应设为0,串口为不可共享设备,其它与一般文件读写类似。以下给出API实现的源代码。
3、利用端口函数直接操作 。这种方式主要是采用两个端口函数_inp(), _outp()实现对串口的读写,其中读端口函数的原型为: int _inp(unsigned shot port) 。该函数从端口读取一个字节,端口号为0~65535。 写端口的函数原型为: nt _outp(unsigned shot port, int databyte) 。
4、 MSComm控件 。MSComm控件是微软开发的专用通信控件,封装了串口的所有功能,使用很方便,但在实际应用中要小心对其属性进行配置。下面详细说明该类应用方法族坦巧。
⑶ c 获取串口号 c 自动获取串口号
用C怎么写获取串口的内容
看驱动程序的接口啊
一般是是open(“口名”)
用C/C++写一扒游个小程序读取串口接收到贺此销的数据
你太幸运了,刚好我有一个,你在禅游vc++6.0下测试一下。
/* serrecv.c */
/* Receives and saves a file over a serial port */
/* Last modified: Septemeber 21, 2005 */
/* [goman89] */
#include
#include
#include
/* Function to print out usage information */
void usage(void);
/* Function to set up the serial port settings with the specified baud rate,
no parity, and one stop bit */
void set_up_serial_port(HANDLE h, long baud);
/* Function to receive and save file from serial port */
void get_file_from_serial_port(HANDLE h, char *file_name, unsigned long file_length);
int main(int argc, char **argv)
{
HANDLE serial_port; /* Handle to the serial port */
long baud_rate = 9600; /* Baud rate */
char port_name[] = "COM1:"; /* Name of serial port */
unsigned long file_size; /* Size of file to receive in bytes */
unsigned long bytes_received; /* Bytes received from serial port */
unsigned long file_name_size; /* Size of file name in bytes */
char file_name[256]; /* Name of file to receive */
/* Check mand line */
if (argc == 3)
{
/* Read in baud rate */
if (argv[1][1] != 'b' || sscanf(argv[2], "%ld", &baud_rate) != 1)
{
usage;
exit(0);
}
}
else if (argc != 1)
{
usage;
exit(0);
}
/* Open up a handle to the serial port */
serial_port = CreateFile(port_name, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0);
/* Make sure port was opened */
if (serial_port == INVALID_HANDLE_VALUE)
{
fprintf(stderr, "Error opening port ");
CloseHandle(serial_port);
exit(0);
}
/* Set up the serial port */
set_up_serial_port(serial_port, baud_rate);
/* Receive file name size from serial port */
ReadFile(serial_port, (void *)&file_name_size, sizeof(unsigned long), &bytes_received, NULL);
if (bytes_received != sizeof(unsigned long))
{
fprintf(stderr, "Error getting file name size. ");
CloseHandle(serial_port);
exit(0);
}
/* Receive file name from serial port */
ReadFile(serial_port, (void *)file_name, file_name_size, &bytes_received, NULL);
if (bytes_received != file_name_size)
{
fprintf(stderr, "Error retrieving file name. ");
CloseHandle(serial_port);
exit(0);
}
/* Append NULL terminator to end of string */
file_name[bytes_received] = '