尝试 ioctl 调用 - 您可以指定任意波特率。那是,
ioctl(serialFileDescriptor, IOSSIOSPEED, &baudRate);
打开串口:
// 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);
从串口读取:
// 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]);
}
}
要写入串行端口:
uint8_t val = 'A';
write(serialFileDescriptor, val, 1);
列出可用的串行端口:
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);