c - 向指定端口写入/读取命令

标签 c serial-port usb linux-device-driver gpio

我使用this usb gpio device 。它使用一些命令从输入/输出 channel 发送/接收数据。有一个guide这解释了如何在 numato 网站上发送命令。有some sample code适用于 Windows 上的 C。但我使用 fedora,我的代码如下用于读/写 gpio。我无法读取数据。

Windows 代码示例

#include "stdafx.h"
#include "windows.h"
#include "string.h"


int _tmain(int argc, _TCHAR* argv[])
{

HANDLE hComPort;
char cmdBuffer[32];
char responseBuffer[32];
DWORD numBytesWritten;
DWORD numBytesRead;

/*
    Lookup the port name associated to your GPIO device and update the 
    following line accordingly. The port name should be in the format 
    "\\.\COM<port Number>". Notice the extra slaches to escape slashes
    themselves. Read http://en.wikipedia.org/wiki/Escape_sequences_in_C
    for more details.
*/

wchar_t PortName[] = L"\\\\.\\COM14";

/*
    Open a handle to the COM port. We need the handle to send commands and
    receive results.
*/

hComPort = CreateFile(PortName, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0);

if (hComPort == INVALID_HANDLE_VALUE)
{
    printf("Error: Unable to open the specified port\n");
    return 1;
}

/* EXAMPLE 1 - MANIPULATE GPIO0 BY SENDING COMMAND                        */
/************************************************************************** 
    Send a command to output a logic high at GPIO 0. The command that is 
    used to accomplish this acton is "gpio set 0". It is important to send 
    a Carriage Return character (ASCII value 0x0D) to emulate the ENTER 
    key. The command will be executed only when the GPIO module detects 
    Carriage Return character.
**************************************************************************/

/* Write a Carriage Return to make sure that any partial commands or junk
   data left in the command buffer is cleared. This step is optional.
*/
cmdBuffer[0] = 0x0D;

if(!WriteFile(hComPort, cmdBuffer, 1, &numBytesWritten, NULL))
{
    CloseHandle(hComPort);
    printf("Error: Unable to write to the specified port\n");
    return 1;
}

/* Copy the command to the command buffer */
strcpy(cmdBuffer, "gpio set 0");

/* Append 0x0D to emulate ENTER key */
cmdBuffer[10] = 0x0D;

/* Write the command to the GPIO module. Total 11 bytes including 0x0D  */

printf("Info: Writing command <gpio set 0> to the GPIO module\n");

if(!WriteFile(hComPort, cmdBuffer, 11, &numBytesWritten, NULL))
{
    CloseHandle(hComPort);
    printf("Error: Unable to write to the specified port\n");
    return 1;
}

printf("Info: <gpio set 0> Command sent successfuly\n");

/* EXAMPLE 2 - MANIPULATE GPIO10 BY SENDING COMMAND                        */
/************************************************************************** 
    Send a command to output a logic high at GPIO 0. The command that is 
    used to accomplish this acton is "gpio set 0". It is important to send 
    a Carriage Return character (ASCII value 0x0D) to emulate the ENTER 
    key. The command will be executed only when the GPIO module detects 
    Carriage Return character.
**************************************************************************/

/* Write a Carriage Return to make sure that any partial commands or junk
   data left in the command buffer is cleared. This step is optional.
*/
cmdBuffer[0] = 0x0D;

if(!WriteFile(hComPort, cmdBuffer, 1, &numBytesWritten, NULL))
{
    CloseHandle(hComPort);
    printf("Error: Unable to write to the specified port\n");
    return 1;
}

/* 
    Copy the command to the command buffer. GPIO number 10 and beyond are
    referenced in the command by using alphabets starting A. For example
    GPIO10 willbe A, GPIO11 will be B and so on. Please note that this is
    not intended to be hexadecimal notation so the the alphabets can go 
    beyond F.
*/
strcpy(cmdBuffer, "gpio set A");

/* Append 0x0D to emulate ENTER key */
cmdBuffer[10] = 0x0D;

/* Write the command to the GPIO module. Total 11 bytes including 0x0D  */

printf("Info: Writing command <gpio set A> to the GPIO module\n");

if(!WriteFile(hComPort, cmdBuffer, 11, &numBytesWritten, NULL))
{
    CloseHandle(hComPort);
    printf("Error: Unable to write to the specified port\n");
    return 1;
}

printf("Info: <gpio set A> Command sent successfuly\n");

/* EXAMPLE 3 - READ ADC 1                                                */
/************************************************************************** 
    Write "adc read 1" comamnd to the device and read back response. It is 
    important to note that the device echoes every single character sent to
    it and so when you read the response, the data that is read will 
    include the command itself, a carriage return, the response which you 
    are interested in, a '>' character and another carriage return. You 
    will need to extract the response from this bunch of data. 
/*************************************************************************/

/* Write a Carriage Return to make sure that any partial commands or junk
   data left in the command buffer is cleared. This step is optional.
*/
cmdBuffer[0] = 0x0D;

if(!WriteFile(hComPort, cmdBuffer, 1, &numBytesWritten, NULL))
{
    CloseHandle(hComPort);
    printf("Error: Unable to write to the specified port\n");
    return 1;
}

/* Flush the Serial port's RX buffer. This is a very important step*/
Sleep(10);
PurgeComm(hComPort, PURGE_RXCLEAR|PURGE_RXABORT);

/* Copy the command to the command buffer */
strcpy(cmdBuffer, "adc read 1");

/* Append 0x0D to emulate ENTER key */
cmdBuffer[10] = 0x0D;

/* Write the command to the GPIO module. Total 11 bytes including 0x0D  */

printf("Info: Writing command <adc read 1> to the GPIO module\n");

if(!WriteFile(hComPort, cmdBuffer, 11, &numBytesWritten, NULL))
{
    CloseHandle(hComPort);
    printf("Error: Unable to write to the specified port\n");
    return 1;
}

printf("Info: <adc read 1> Command sent successfuly\n");

/*Read back the response*/
if(!ReadFile(hComPort, responseBuffer, 16, &numBytesRead, NULL))
{
    CloseHandle(hComPort);
    printf("Error: Unable to write to the specified port\n");
    return 1;
}

/* Add a null character at the end of the response so we can use the buffer
   with string manipulation functions.
 */
responseBuffer[numBytesRead] = '\0';

printf("Info: ADC value read from the device = %.*s", 4, responseBuffer + 12);

/* Close the comm port handle */
CloseHandle(hComPort);

return 0;
} 

我的 Ubuntu 代码

#include <string.h>
#include <fcntl.h>
#include <errno.h>
#include <termios.h>
#include <unistd.h>

#define MAXBUFFER 32

int main(int argc, char* argv[])
{

struct termios serialSettings;
char *deviceName = "/dev/ttyACM0";
char bufferRecv[MAXBUFFER], bufferSend[MAXBUFFER];
int readInt, sendInt;
int fd = open(deviceName, O_RDWR | O_NOCTTY | O_NDELAY);
if(fd == -1) {

    printf("\n %s\n", deviceName);
    perror("unable to open port");
}
else {
    printf("port is opened!\n");

    bufferSend[0] = 0x0D; /* clear buffer */
    strcpy(bufferSend, "gpio set 0"); /* */
    sendInt = write(fd, bufferSend, strlen(bufferSend));
    if(sendInt <= 0){
        printf("Unable to write to the port\n");
        return -1;
    }

    printf("<gpio set 0> : Command sent successfuly\n");


    strcpy(bufferSend, "gpio read 0"); /* */
    sendInt = write(fd, bufferSend, strlen(bufferSend));
    if(sendInt <= 0){
        printf("Unable to write to the port\n");
        return -1;
    }

    printf("<gpio read 0> : Command sent successfuly\n");

    readInt = read(fd, bufferRecv, sizeof(bufferRecv));
    if(readInt < 0){
        printf("Unable to read to the port\n");
        return -1;
    }

    bufferRecv[strlen(bufferRecv)] = '\0';
    printf("read=%c-\n", bufferRecv[0]);
}
close(fd);
return 0;

}

输出

port is opened!
<gpio set 0> : Command sent successfuly
<gpio read 0> : Command sent successfuly
Unable to read to the port

最佳答案

“成功”的 write() 是误报。数据已输出,但设备未正确接收。

您的程序在open()之后和任何write()之前没有使用termios正确配置串行端口读取()。您应该将端口配置为规范模式而不是原始模式。您还需要配置波特率、字符长度、奇偶校验和停止位数。

使用Serial Programming Guide for POSIX Operating Systems

可行的(?)配置代码可能如下所示(对于 115200 波特率、8N1 和规范输入,即读取在 NL 字符处终止):

#include <termios.h>

struct termios  serialSettings;
speed_t     spd;
int fd;
int rc;

fd = open(deviceName, O_RDWR | O_NOCTTY);
if (fd == -1) {
    printf("\n %s\n", deviceName);
    perror("unable to open port");
    return -1;
}

rc = tcgetattr(fd, &serialSettings);
if (rc < 0) {
    perror("unable to get attributes");
    return -2;
}

spd = B115200;
cfsetospeed(&serialSettings, spd);
cfsetispeed(&serialSettings, spd);

serialSettings.c_cflag &= ~CSIZE;
serialSettings.c_cflag |= CS8;

serialSettings.c_cflag &= ~PARENB;
serialSettings.c_cflag &= ~CSTOPB;

serialSettings.c_cflag &= ~CRTSCTS;    /* no HW flow control? */
serialSettings.c_cflag |= CLOCAL | CREAD;

serialSettings.c_iflag &= ~(PARMRK | ISTRIP | IXON | IXOFF | INLCR);
serialSettings.c_iflag |= ICRNL;
serialSettings.c_oflag &= ~OPOST;
serialSettings.c_lflag &= ~(ECHO | ECHONL | ISIG | IEXTEN);
serialSettings.c_lflag |= ICANON;

rc = tcsetattr(fd, TCSANOW, &serialSettings);
if (rc < 0) {
    perror("unable to set attributes");
    return -2;
}
/* serial port is now configured and ready */
...
<小时/>

对您的代码的其他注释:

bufferRecv[strlen(bufferRecv)] = '\0';

这是不合逻辑的代码。如果您实际上可以确定 bufferRecv 中内容的字符串长度,那么该文本就已经以 null 结尾,并且不需要进行此分配。
其次,更糟糕的是,read() 不会以空字节终止接收数据,因此 strlen() 可能会扫描到缓冲区末尾。

read() 确实返回缓冲区中存储的字节数,并且该值可用于定位应写入空字节的位置。
可行的代码如下所示(请注意请求的读取长度的减少):

readInt = read(fd, bufferRecv, sizeof(bufferRecv) - 1);
if (readInt < 0){
    perror("Unable to read from the port\n");
    return -3;
}
bufferRecv[readInt] = '\0';
printf("ADC value read = %s\n", bufferRecv);
<小时/>

发送到 USB 设备的字符串应以回车符开头并以回车符结尾,就像 Win 示例一样:

strcpy(bufferSend, "\rgpio set 0\r");
...
strcpy(bufferSend, "\rgpio read 0\r");

关于c - 向指定端口写入/读取命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26619517/

相关文章:

c - 我如何发送测量温度的字符,以便在我的串行捕获程序中可以查看它(使用 Realterm 或 Putty)

java - 解析从 Arduino 上的多个传感器读取的数据

c# - c++ 或 c# 如何与 com 端口一起工作?

windows - 64 位驱动程序无法在 64 位 Windows 7/8 中运行

c++ - 像键盘一样向 cpu 发送中断?

c - C中的信号量和fork()

c - putchar()、putch()、fputchar() 之间的区别?

c - 访问内核模块中进程的预定指令

android - 任何人都可以确认任何平板电脑支持 USB 主机模式并且任何人都测试过代码实现

python - 为什么 Python "grouping"不适用于 C 中的正则表达式?