简体   繁体   English

打开串行端口ANSI C.

[英]open serial port ANSI C

I have been googling my last couple of hours(days) to find a simple, working example of how one opens a serial port in ANSI C on Windows. 我一直在谷歌搜索我的最后几个小时(天),找到一个简单的工作示例,说明如何在Windows上打开ANSI C中的串行端口。 I try to open a txt file and send it to the serial port char by char. 我尝试打开一个txt文件并通过char将其发送到串口char。 (Also I would be happy if you could give me a hint how to send char by char with 1 second delay!) This is my code but somehow it won't work :( (如果你能给我一个提示如何通过char发送char,延迟1秒钟,我会很高兴!)这是我的代码但不知何故它不起作用:(

FILE *file;
file = fopen("text.txt", "r");
if (file)
{
    while ((c = getc(file)) != EOF)
    {
        FILE *fp;
        fp = open("COM1", O_RDWR | O_NOCTTY | O_NDELAY);
        if (fp == -1) puts("Couldn't open port!");
        else puts("Port opened!");
        fprintf(fp,c);  
    }
    fclose(file);
}
else puts("Couldn't find text.txt!");

The C standard does not know about serial ports. C标准不了解串口。 Your question is Windows specific. 您的问题是Windows特定的。 Perhaps you want to 也许你想

         fp = open("COM1:", O_RDWR | O_NOCTTY | O_NDELAY);
         if (fp<0) perror("open COM1:");

I'm not sure that open , O_NDELAY exist on Windows (looks like Posix or Linux code!) 我不确定Windows上是否存在open O_NDELAY (看起来像Posix或Linux代码!)

I don't think the code you have written will work in Windows, unless maybe you are using some POSIX library that I don't know about. 我不认为您编写的代码可以在Windows中运行,除非您使用的是某些我不了解的POSIX库。 Otherwise, you have to use the Windows API functions used for serial communication. 否则,您必须使用用于串行通信的Windows API函数。

All documentation and some examples are found at Microsoft's documentation site MSDN . 所有文档和一些示例都可以在Microsoft的文档站点MSDN中找到

Windows regards serial ports as files. Windows将串行端口视为文件。 You open them with CreateFile() and read/write with ReadFile() and WriteFile(). 用CreateFile()打开它们,用ReadFile()和WriteFile()读/​​写。 And then there are various functions used for setting up baudrate, handshaking, timeouts etc. 然后有各种功能用于设置波特率,握手,超时等。

How to do this in detail is quite a big topic, but at least the information on MSDN should get you started. 如何详细地执行此操作是一个非常重要的主题,但至少MSDN上的信息应该可以帮助您入门。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM