user2362956
user2362956

Reputation:

Write/Read command to the specified port

I use this usb gpio device. It uses some command to send/receive data from input/output channel. There is a guide that explains how commands send on numato website. There are some sample code for C on Windows. But I use fedora and my code is below for read/write gpio. I can't read data.

Code sample for 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;
} 

My code for 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;

}

The output

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

Upvotes: 0

Views: 775

Answers (1)

sawdust
sawdust

Reputation: 17067

The "successful" write() s are false positives. The data was output, but not properly received by the device.

Your program has not properly configured the serial port using termios after the open() and before any write() or read(). You should configure the port for canonical rather than raw mode. You also need to configure the baud rate, character length, parity and number of stop bits.

Use the Serial Programming Guide for POSIX Operating Systems.

Workable(?) configuration code might look like (for 115200 baud rate, 8N1 and canonical input, i.e. read terminates on NL character):

#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 */
...

Additional comments on your code:

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

This is illogical code. If you could actually determine the string length of what's in bufferRecv, then that text would already be null terminated, and this assignment would not be necessary.
Secondly and much worse, the read() does not terminate the receive data with a null byte, so the strlen() could scan past the buffer end.

The read() does return the number of bytes stored in the buffer, and that value can be used to locate where a null byte should be written.
Workable code would look like (note the reduction in requested read length):

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);

The strings that you send to the USB device should be preceded and terminated with a carriage return just like the Win examples:

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

Upvotes: 1

Related Questions