Try the ioctl call - you can specify an arbitrary baud rate. That is,
ioctl(serialFileDescriptor, IOSSIOSPEED, &baudRate);
To open the serial port:
// Open the serial like POSIX C
serialFileDescriptor = open(
"/dev/tty.usbserial-A6008cD3",
O_RDWR |
O_NOCTTY |
O_NONBLOCK );
// Block non-root users from using this port
ioctl(serialFileDescriptor, TIOCEXCL);
// Clear the O_NONBLOCK flag, so that read() will
// block and wait for data.
fcntl(serialFileDescriptor, F_SETFL, 0);
// Grab the options for the serial port
tcgetattr(serialFileDescriptor, &options);
// Setting raw-mode allows the use of tcsetattr() and ioctl()
cfmakeraw(&options);
// Specify any arbitrary baud rate
ioctl(serialFileDescriptor, IOSSIOSPEED, &baudRate);
To read from the serial port:
// This selector will be called as another thread
- (void)incomingTextUpdateThread: (NSThread *) parentThread {
char byte_buffer[100]; // Buffer for holding incoming data
int numBytes=1; // Number of bytes read during read
// Create a pool so we can use regular Cocoa stuff.
// Child threads can't re-use the parent's autorelease pool
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
// This will loop until the serial port closes
while(numBytes>0) {
// read() blocks until data is read or the port is closed
numBytes = read(serialFileDescriptor, byte_buffer, 100);
// You would want to do something useful here
NSLog([NSString stringWithCString:byte_buffer length:numBytes]);
}
}
To write to the serial port:
uint8_t val = 'A';
write(serialFileDescriptor, val, 1);
To list availble serial ports:
io_object_t serialPort;
io_iterator_t serialPortIterator;
// Ask for all the serial ports
IOServiceGetMatchingServices(
kIOMasterPortDefault,
IOServiceMatching(kIOSerialBSDServiceValue),
&serialPortIterator);
// Loop through all the serial ports
while (serialPort = IOIteratorNext(serialPortIterator)) {
// You want to do something useful here
NSLog(
(NSString*)IORegistryEntryCreateCFProperty(
serialPort, CFSTR(kIOCalloutDeviceKey),
kCFAllocatorDefault, 0));
IOObjectRelease(serialPort);
}
IOObjectRelease(serialPortIterator);
stty
doesn't work because it checks the baud rate with some hard-coded values. Interestinglyserserial
allows to set 307200 and doesn't report an error. But when I try to read from the serial port it doesn't work. – cairolBOTHER
approach and IOCTLs from termios2.h. – 0andriy