【问题标题】:Controlling DTR and RTS pin of serial port in C on Windows platformWindows平台用C语言控制串口的DTR和RTS管脚
【发布时间】:2013-08-30 18:14:41
【问题描述】:

如何在windows平台上控制串口的DTR和RTS引脚?我希望通过提高或降低其电压来对其进行 bitbanged 或操作。

【问题讨论】:

    标签: c windows serial-port


    【解决方案1】:

    您需要使用EscapeCommFunction 函数,如下所示:

    // winserial_io.cpp :  Win32 test program to control RTS and DTS output lines 
    // Originator: Steven Woon
    // Creation Date: 2007-12-15
    
    #include "stdafx.h"
    #include "windows.h"
    #include <conio.h>
    
    //#include "winbase.h"
    
    int main(int argc, char* argv[])
    {
        HANDLE hComm;
        char ch;
    
        for (int i = 0; i < argc; i++)
            printf("%s\n", argv[i]);
    
        hComm = CreateFileA( argv[1],GENERIC_READ | GENERIC_WRITE, 
                            0, 
                            0, 
                            OPEN_EXISTING,
                            NULL,
                            0);
    
        if (hComm == INVALID_HANDLE_VALUE)
        {
            printf("Cannot open %s\n", argv[1]);        //error occured alert user about error
            return -1;
        }
    
        printf("Press the following keys:\n");
        printf("1: Set DTR\n");
        printf("2: Clear DTR\n");
        printf("3: Set RTS\n");
        printf("4: Clear RTS\n");
        printf("q: End Program\n");
    
        do
        {   
            ch = _getch();
            switch (ch)
            {
            case '1':   if (EscapeCommFunction(hComm,SETDTR) == 0) 
                            printf ("Error Setting DTR\n");
                        break;
            case '2':   if (EscapeCommFunction(hComm,CLRDTR) == 0) 
                            printf ("Error Clearing DTR\n");
                        break;
            case '3':   if (EscapeCommFunction(hComm,SETRTS) == 0) 
                            printf ("Error Setting CTS\n");
                        break;
            case '4':   if (EscapeCommFunction(hComm,CLRRTS) == 0) 
                            printf ("Error Clearing CTS\n");
                        break;
            }
        }   while (ch != 'q');
    
    
        return 0;
    }
    

    【讨论】:

    • 不应该是“Error Clearing RTS”而不是“Error Clearing CTS”。还是因为反之连接命名?
    猜你喜欢
    • 1970-01-01
    • 2019-01-25
    • 2014-08-16
    • 2019-01-18
    • 1970-01-01
    • 2021-07-31
    • 1970-01-01
    • 2010-10-23
    • 2018-06-07
    相关资源
    最近更新 更多