C语言实现在Windows和Linux下的串口通信

C语言可以通过调用操作系统提供的串口API实现串口通信。常见的操作系统有Windows和Linux,在这两个操作系统中实现串口通信的方式略有不同。

在Windows系统中,可以使用Win32 API中的CreateFile函数来打开串口端口,使用ReadFile和WriteFile函数来读写串口数据。示例代码如下:

#include <windows.h>
#include <stdio.h>

int main()
{
    HANDLE hComm;
    DCB dcb = { 0 };
    COMMTIMEOUTS timeouts = { 0 };
    DWORD bytesRead, bytesWritten;
    char serialPort[] = "\\\\.\\COM1";

    hComm = CreateFile(serialPort, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
    if (hComm == INVALID_HANDLE_VALUE)
    {
        printf("Failed to open serial port.\n");
        return 1;
    }

    dcb.DCBlength = sizeof(DCB);
    if (!GetCommState(hComm, &dcb))
    {
        printf("Failed to get serial port settings.\n");
        CloseHandle(hComm);
        return 1;
    }

    dcb.BaudRate = CBR_9600;
    dcb.ByteSize = 8;
    dcb.Parity = NOPARITY;
    dcb.StopBits = ONESTOPBIT;

    if (!SetCommState(hComm, &dcb))
    {
        printf("Failed to set serial port settings.\n");
        CloseHandle(hComm);
        return 1;
    }

    timeouts.ReadIntervalTimeout = 10;
    timeouts.ReadTotalTimeoutConstant = 100;
    timeouts.ReadTotalTimeoutMultiplier = 10;
    timeouts.WriteTotalTimeoutConstant = 100;
    timeouts.WriteTotalTimeoutMultiplier = 10;

    if (!SetCommTimeouts(hComm, &timeouts))
    {
        printf("Failed to set serial port timeouts.\n");
        CloseHandle(hComm);
        return 1;
    }

    char data[] = "Hello, serial port!";
    if (!WriteFile(hComm, data, sizeof(data), &bytesWritten, NULL))
    {
        printf("Failed to write data to serial port.\n");
        CloseHandle(hComm);
        return 1;
    }

    char buffer[256];
    if (!ReadFile(hComm, buffer, sizeof(buffer), &bytesRead, NULL))
    {
        printf("Failed to read data from serial port.\n");
        CloseHandle(hComm);
        return 1;
    }

    printf("Received %d bytes: %s\n", bytesRead, buffer);

    CloseHandle(hComm);
    return 0;
}

在Linux系统中,可以使用标准的串口API函数来读写串口数据,例如open、tcgetattr、tcsetattr、read和write等函数。示例代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>
#include <string.h>

int main()
{
    int fd;
    struct termios options;
    char serialPort[] = "/dev/ttyS0";

    fd = open(serialPort, O_RDWR | O_NOCTTY);
    if (fd == -1)
    {
        printf("Failed to open serial port.\n");
        return 1;
    }

    tcgetattr(fd, &options);
    cfsetispeed(&options, B9600);
    cfsetospeed(&options, B9600);
    options.c_cflag |= CS8 | CLOCAL | CREAD;
    options.c_iflag |= IGNPAR;
    options.c_oflag = 0;
    options.c_lflag = 0;
    options.c_cc[VTIME] = 0;
    options.c_cc[VMIN] = 1;

    tcsetattr(fd, TCSANOW, &options);

    char data[] = "Hello, serial port!";
    int bytesWritten = write(fd, data, sizeof(data));
    if (bytesWritten == -1)
    {
        printf("Failed to write data to serial port.\n");
        close(fd);
        return 1;
    }

    char buffer[256];
    int bytesRead = read(fd, buffer, sizeof(buffer));
    if (bytesRead == -1)
    {
        printf("Failed to read data from serial port.\n");
        close(fd);
        return 1;
    }

    printf("Received %d bytes: %s\n", bytesRead, buffer);

    close(fd);
    return 0;
}
```C语言可以通过调用操作系统提供的串口API实现串口通信。常见的操作系统有Windows和Linux,在这两个操作系统中实现串口通信的方式略有不同。

在Windows系统中,可以使用Win32 API中的CreateFile函数来打开串口端口,使用ReadFile和WriteFile函数来读写串口数据。示例代码如下:

```c
#include <windows.h>
#include <stdio.h>

int main()
{
    HANDLE hComm;
    DCB dcb = { 0 };
    COMMTIMEOUTS timeouts = { 0 };
    DWORD bytesRead, bytesWritten;
    char serialPort[] = "\\\\.\\COM1";

    hComm = CreateFile(serialPort, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
    if (hComm == INVALID_HANDLE_VALUE)
    {
        printf("Failed to open serial port.\n");
        return 1;
    }

    dcb.DCBlength = sizeof(DCB);
    if (!GetCommState(hComm, &dcb))
    {
        printf("Failed to get serial port settings.\n");
        CloseHandle(hComm);
        return 1;
    }

    dcb.BaudRate = CBR_9600;
    dcb.ByteSize = 8;
    dcb.Parity = NOPARITY;
    dcb.StopBits = ONESTOPBIT;

    if (!SetCommState(hComm, &dcb))
    {
        printf("Failed to set serial port settings.\n");
        CloseHandle(hComm);
        return 1;
    }

    timeouts.ReadIntervalTimeout = 10;
    timeouts.ReadTotalTimeoutConstant = 100;
    timeouts.ReadTotalTimeoutMultiplier = 10;
    timeouts.WriteTotalTimeoutConstant = 100;
    timeouts.WriteTotalTimeoutMultiplier = 10;

    if (!SetCommTimeouts(hComm, &timeouts))
    {
        printf("Failed to set serial port timeouts.\n");
        CloseHandle(hComm);
        return 1;
    }

    char data[] = "Hello, serial port!";
    if (!WriteFile(hComm, data, sizeof(data), &bytesWritten, NULL))
    {
        printf("Failed to write data to serial port.\n");
        CloseHandle(hComm);
        return 1;
    }

    char buffer[256];
    if (!ReadFile(hComm, buffer, sizeof(buffer), &bytesRead, NULL))
    {
        printf("Failed to read data from serial port.\n");
        CloseHandle(hComm);
        return 1;
    }

    printf("Received %d bytes: %s\n", bytesRead, buffer);

    CloseHandle(hComm);
    return 0;
}

在Linux系统中,可以使用标准的串口API函数来读写串口数据,例如open、tcgetattr、tcsetattr、read和write等函数。示例代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>
#include <string.h>

int main()
{
    int fd;
    struct termios options;
    char serialPort[] = "/dev/ttyS0";

    fd = open(serialPort, O_RDWR | O_NOCTTY);
    if (fd == -1)
    {
        printf("Failed to open serial port.\n");
        return 1;
    }

    tcgetattr(fd, &options);
    cfsetispeed(&options, B9600);
    cfsetospeed(&options, B9600);
    options.c_cflag |= CS8 | CLOCAL | CREAD;
    options.c_iflag |= IGNPAR;
    options.c_oflag = 0;
    options.c_lflag = 0;
    options.c_cc[VTIME] = 0;
    options.c_cc[VMIN] = 1;

    tcsetattr(fd, TCSANOW, &options);

    char data[] = "Hello, serial port!";
    int bytesWritten = write(fd, data, sizeof(data));
    if (bytesWritten == -1)
    {
        printf("Failed to write data to serial port.\n");
        close(fd);
        return 1;
    }

    char buffer[256];
    int bytesRead = read(fd, buffer, sizeof(buffer));
    if (bytesRead == -1)
    {
        printf("Failed to read data from serial port.\n");
        close(fd);
        return 1;
    }

    printf("Received %d bytes: %s\n", bytesRead, buffer);

    close(fd);
    return 0;
}
  • 5
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

九点两刻

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值