Jump to content
Search In
  • More options...
Find results that contain...
Find results in...
Sign in to follow this  
墨香年少

windows下c语言操作串口

Recommended Posts

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

// 打开串口
HANDLE open_serial_port(LPCSTR port_name, DWORD baud_rate) {
    HANDLE hSerial;
    DCB dcbSerialParams = {0};
    COMMTIMEOUTS timeouts = {0};

    // 打开串口
    hSerial = CreateFile(port_name,
                         GENERIC_READ | GENERIC_WRITE,
                         0,
                         0,
                         OPEN_EXISTING,
                         FILE_ATTRIBUTE_NORMAL,
                         0);
    if (hSerial == INVALID_HANDLE_VALUE) {
        fprintf(stderr, "Error opening serial port\n");
        return INVALID_HANDLE_VALUE;
    }

    // 获取当前串口配置
    dcbSerialParams.DCBlength = sizeof(dcbSerialParams);
    if (!GetCommState(hSerial, &dcbSerialParams)) {
        fprintf(stderr, "Error getting serial port state\n");
        CloseHandle(hSerial);
        return INVALID_HANDLE_VALUE;
    }

    // 配置串口
    dcbSerialParams.BaudRate = baud_rate;
    dcbSerialParams.ByteSize = 8;            // 数据位为8位
    dcbSerialParams.StopBits = ONESTOPBIT;   // 停止位为1
    dcbSerialParams.Parity = NOPARITY;       // 无奇偶校验位
    if (!SetCommState(hSerial, &dcbSerialParams)) {
        fprintf(stderr, "Error setting serial port state\n");
        CloseHandle(hSerial);
        return INVALID_HANDLE_VALUE;
    }

    // 设置超时
    timeouts.ReadIntervalTimeout = 50;
    timeouts.ReadTotalTimeoutConstant = 50;
    timeouts.ReadTotalTimeoutMultiplier = 10;
    timeouts.WriteTotalTimeoutConstant = 50;
    timeouts.WriteTotalTimeoutMultiplier = 10;
    if (!SetCommTimeouts(hSerial, &timeouts)) {
        fprintf(stderr, "Error setting timeouts\n");
        CloseHandle(hSerial);
        return INVALID_HANDLE_VALUE;
    }

    return hSerial;
}

// 写数据到串口
BOOL write_serial_port(HANDLE hSerial, LPCVOID data, DWORD size) {
    DWORD bytes_written;
    return WriteFile(hSerial, data, size, &bytes_written, NULL);
}

// 从串口读数据
BOOL read_serial_port(HANDLE hSerial, LPVOID buffer, DWORD size, DWORD *bytes_read) {
    return ReadFile(hSerial, buffer, size, bytes_read, NULL);
}

// 关闭串口
void close_serial_port(HANDLE hSerial) {
    CloseHandle(hSerial);
}

// 示例使用
int main() {
    HANDLE hSerial = open_serial_port("COM3", CBR_9600); // 以9600波特率打开COM3
    if (hSerial == INVALID_HANDLE_VALUE) return 1;

    char data_to_send[] = "Hello, serial port!";
    if (!write_serial_port(hSerial, data_to_send, sizeof(data_to_send))) {
        fprintf(stderr, "Error writing to serial port\n");
    }

    char read_buf[128];
    DWORD bytes_read;
    if (read_serial_port(hSerial, read_buf, sizeof(read_buf), &bytes_read)) {
        printf("Received: %.*s\n", (int)bytes_read, read_buf);
    } else {
        fprintf(stderr, "Error reading from serial port\n");
    }

    close_serial_port(hSerial);
    return 0;
}

这段代码中,open_serial_port函数用于打开指定的串口并进行配置,write_serial_port和read_serial_port函数分别用于向串口写数据和从串口读数据,最后通过close_serial_port函数关闭串口。注意,这段代码只是一个基础的示例,实际使用中可能需要根据具体需求进行调整,例如处理错误情况、调整超时设置等。在编译运行这段代码时,需要确保你的开发环境支持Windows API调用,并且链接了kernel32.lib库(如果使用Microsoft Visual C++,通常这是默认配置)。


目之所及,皆是回忆,心之所想,皆是过往

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

×
×
  • Create New...

Important Information

注册必须使用2-8个中文汉字作为账号