写入/读取命令到指定的端口

时间:2014-10-28 22:21:10

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

我使用this usb gpio device。它使用一些命令从输入/输出通道发送/接收数据。有一个guide解释了如何在numato网站上发送命令。 Windows上有C some sample code。但我使用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

1 个答案:

答案 0 :(得分:1)

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

打开()之后以及任何 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");