c - 使用 C 建立与 RS232 的串行连接

标签 c serial-port serial-communication

我正在尝试通过 RS232 和 C 代码与设备建立串行连接。目的是稍后将arduino连接到计算机并在LED屏幕上显示从设备检索到的IP地址。

通常我通过RS232将设备连接到计算机,打开PuTTY并以115200波特率建立串行连接。然后我按 Enter 键,输入登录名,按 Enter 键,输入密码,按 Enter 键,输入“ip show”,然后检索 IP 地址。

问题是我不擅长C编程(大学只学了一年)。我想出的代码(复制粘贴和编辑)附在下面。问题是:

1) 如何获取终端屏幕上打印的信息。例如,我输入login然后按回车键后,有一句话说输入您的密码。如何将其检索到 IDE 控制台? 2)最后一步(获取ip),如何获取ip?它是文本格式的,显示后我需要将其复制并粘贴到另一个文档中)。

就目前而言,我对 C 的了解有限,无法进一步深入。

任何类型的帮助(甚至是有用的函数的名称)都将受到赞赏!

//
// serial.c / serial.cpp
// A simple serial port writing example
// Written by Ted Burke - last updated 13-2-2013
//
// To compile with MinGW:
//
//      gcc -o serial.exe serial.c
//
// To compile with cl, the Microsoft compiler:
//
//      cl serial.cpp
//
// To run:
//
//      serial.exe
//

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

int main()
{
    // Define the five bytes to send ("hello")
    char bytes_to_send[15];
    bytes_to_send[0] = '\n';
    bytes_to_send[1] = 'a';
bytes_to_send[2] = 'd';
bytes_to_send[3] = 'm';
bytes_to_send[4] = 'i';
bytes_to_send[5] = 'n';
bytes_to_send[6] = '\n';
bytes_to_send[7] = 's';
bytes_to_send[8] = 'h';
bytes_to_send[9] = 'o';
bytes_to_send[10] = 'w';
bytes_to_send[11] = ' ';
bytes_to_send[12] = 'i';
bytes_to_send[13] = 'p';
bytes_to_send[14] = '\n';
// Declare variables and structures
HANDLE hSerial;
DCB dcbSerialParams = {0};
COMMTIMEOUTS timeouts = {0};

// Open the highest available serial port number
fprintf(stderr, "Opening serial port...");
hSerial = CreateFile(
            "\\\\.\\COM6", GENERIC_READ|GENERIC_WRITE, 0, NULL,
            OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL );
if (hSerial == INVALID_HANDLE_VALUE)
{
        fprintf(stderr, "Error\n");
        return 1;
}
else fprintf(stderr, "OK\n");

// Set device parameters (38400 baud, 1 start bit,
// 1 stop bit, no parity)
dcbSerialParams.DCBlength = sizeof(dcbSerialParams);
if (GetCommState(hSerial, &dcbSerialParams) == 0)
{
    fprintf(stderr, "Error getting device state\n");
    CloseHandle(hSerial);
    return 1;
}

dcbSerialParams.BaudRate = CBR_115200;
dcbSerialParams.ByteSize = 8;
dcbSerialParams.StopBits = ONESTOPBIT;
dcbSerialParams.Parity = NOPARITY;
if(SetCommState(hSerial, &dcbSerialParams) == 0)
{
    fprintf(stderr, "Error setting device parameters\n");
    CloseHandle(hSerial);
    return 1;
}

// Set COM port timeout settings
timeouts.ReadIntervalTimeout = 50;
timeouts.ReadTotalTimeoutConstant = 50;
timeouts.ReadTotalTimeoutMultiplier = 10;
timeouts.WriteTotalTimeoutConstant = 50;
timeouts.WriteTotalTimeoutMultiplier = 10;
if(SetCommTimeouts(hSerial, &timeouts) == 0)
{
    fprintf(stderr, "Error setting timeouts\n");
    CloseHandle(hSerial);
    return 1;
}

// Send specified text (remaining command line arguments)
DWORD bytes_written, total_bytes_written = 0;
fprintf(stderr, "Sending bytes...");
if(!WriteFile(hSerial, bytes_to_send, sizeof(bytes_to_send), &bytes_written, NULL))
{
    fprintf(stderr, "Error\n");
    CloseHandle(hSerial);
    return 1;
}

fprintf(stderr, "%d bytes written\n", bytes_written);

// Close serial port
fprintf(stderr, "Closing serial port...");
if (CloseHandle(hSerial) == 0)
{
    fprintf(stderr, "Error\n");
    return 1;
}
fprintf(stderr, "OK\n");
fprintf(stderr, "the sent sentence is: ");
for(int i=0;i<sizeof(bytes_to_send);i++){
    fprintf(stderr,"%c",bytes_to_send[i]);
}

// exit normally
return 0;
}

最佳答案

要设置端口和读/写命令,您可以使用 this answer 中的代码。 然后您只需担心发送和接收的内容。

Putty实际上是在后台读取串口,然后打印在控制台上,这样你就可以看到。您必须在您的应用程序中执行相同的操作。读取数据后,您必须打印它。

例如,对于登录,正如您所描述的:

write (fd, "login\r\n", 7);          // send 7 character login command
                                     // (similar to writing login + enter in Putty)

usleep ((7 + 25) * 100);             // allow time for sending & receiving
                                     // (sleep enough to transmit the 7 plus
                                     // receive 25:  approx 100 uS per char transmit)

char buf [100];
int n = read (fd, buf, sizeof(buf)); // read rx characters (Putty does this automatically)
                                     // expect to have "the sentence saying type your password" in this buffer
                                     // 100 characters are read, adjust it if you expect a longer answer

printf("Rx:");                       // display the rx data (Putty does this automatically)
for (int i = 0; i < sizeof(buf); i++) 
    printf("%c",buf[i]);            
printf("\n");

// continue with sending the password + reading the response
// then sending the ip command + reading the answer

关于c - 使用 C 建立与 RS232 的串行连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45726974/

相关文章:

c++ - 从串行设备上读取字节(并理解它们??)

c# - 在连接打开时更改串行端口波特率

C#串口精准时间戳

java - 使用 RXTX 同步 java 串口连接

python - Arduino与Python串口通信,使用十六进制值的问题

c - 在函数 C 中修改字符串

C-在执行过程中检查特定的内存地址

c - 在C中合并两个已排序的字符串数组

java - 从 C/C++ JNI 传递参数到 Java 并获取修改后的值

python - 使用 python Raspberry Pi 3 从串行设备检索数据时出现问题