Re: Serial port access from C / Objective C
Re: Serial port access from C / Objective C
- Subject: Re: Serial port access from C / Objective C
- From: "Vansickle, Greg" <email@hidden>
- Date: Mon, 15 Jun 2009 15:10:19 -0700
- Acceptlanguage: en-US
- Thread-topic: Serial port access from C / Objective C
I'm trying to communicate with a Photo Research Spectral photometer via USB. The device responds to simple ascii commands via a terminal program.
I have no problem accessing this via the screen command from Terminal. I need to get to the same capability from a Cocoa project.
>From terminal I'd enter:
> screen /dev/cu.usbmodem1a21
Once the screen utility starts, I simply type PHOTO (no carriage return) and the device would respond "REMOTE MODE" (no carriage return) and the spectro photometer displays "REMOTE" on it's panel.
Here's the C code I'm trying to make work. It's Apples SerialPortSample, stripped to it's minimum (so I understand what's important and what's fluff ...)
#include <fcntl.h>
#include <termios.h>
#include <string.h>
int main(void)
{
int fileDescriptor;
const char *bsdPath = "/dev/cu.usbmodem1a21";
const char *cmdString = "PHOTO";
int handshake, numBytes;
int result;
char buffer[256];
char *bufPtr;
fileDescriptor = open(bsdPath, O_RDWR | O_NOCTTY | O_NONBLOCK); // returns 3
if (fileDescriptor == -1) { return -1;}
result = ioctl(fileDescriptor, TIOCEXCL);
if (result == -1) { return -1; } // returns 0
result = ioctl(fileDescriptor, TIOCMGET, &handshake); // returns 0, handshake is 0x26
numBytes = write(fileDescriptor, cmdString, strlen(cmdString)); // returns 5
bufPtr = buffer;
numBytes = read(fileDescriptor, bufPtr, 15); // returns -1
close(fileDescriptor);
return 0;
}
If I remove the read and write, the USB device opens and closes properly, i.e. I can access the device successfully using the screen command again.
With the write / read in place, although the write appears to work (numbytes returns 5), the photometer does not respond (I get no "REMOTE" indication on the instrument panel. The subsequent read fails (returns -1).
I've never programmed at the device level like this, so please confirm my assumption - I do not need to set the baud rate, parity and all that as the device appears to default to a sane state. (Screen utility doesn't set it, I assume the default values are set in the device it self.)
FWIW, the complete SerialPortSample code, complete with setting up the terminal, baud, parity, ... and changing the command strings, behaved the same way. I stripped all this out in case the problem was setting this stuff up.
Any pointers appreciated.
Greg
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden