我目前正在尝试通过 Mac 应用程序向我的 Arduino 发送数据。我的代码 Arduino Uno看起来像这样:
void setup()
{
pinMode (2, OUTPUT);
pinMode (3, OUTPUT);
pinMode (4, OUTPUT);
Serial.begin (9600);
}
void loop ()
{
digitalWrite (2, HIGH);
if (Serial.available () > 0)
{
int c = Serial.read();
if (c == 255)
{
digitalWrite (3, HIGH);
}
else
digitalWrite (4, HIGH);
}
}
这是我在 XCode 项目中的代码:
// Open the serial like POSIX C
serialFileDescriptor = open(
"/dev/tty.usbmodemfa131",
O_RDWR |
O_NOCTTY |
O_NONBLOCK );
struct termios options;
// 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);
speed_t baudRate = 9600;
// Specify any arbitrary baud rate
ioctl(serialFileDescriptor, IOSSIOSPEED, &baudRate);
NSLog (@"before");
sleep (5); // Wait for the Arduino to restart
NSLog (@"after");
int val = 255;
write(serialFileDescriptor, val, 1);
NSLog (@"after2");
因此,当我运行该应用程序时,它会等待五秒钟,但随后会停止运行。控制台中的输出是这样的:
before
after
那么,我做错了什么?
更新:所以,当我注释掉这一行时
fcntl(serialFileDescriptor, F_SETFL, 0);
程序没有卡住,但我的 Arduino 仍然没有得到任何数据。
最佳答案
1) write() 调用的第二个参数不正确 - write() 需要一个指向要写入的字节的指针。要将数值变量的值写入字节,请传递变量的地址,而不是变量本身:
write(serialFileDescriptor, (const void *) &val, 1);
关于 write() 的更多信息: https://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man2/write.2.html
2) 对本地 termios 变量和选项的更改 - 例如对 cfmakeraw() 的调用 - 不会影响终端设置;为了使用更改后的选项更新终端设置,请调用 tcsetattr():
cfmakeraw(&options);
// ...other changes to options...
tcsetattr(serialFileDescriptor, TCSANOW, &options);
有关 Mac OS X 串行通信的更多信息: http://developer.apple.com/library/mac/#documentation/DeviceDrivers/Conceptual/WorkingWSerial/WWSerial_SerialDevs/SerialDevices.html
关于objective-c - 无法使用 Cocoa (IOKit) 将数据发送到我的 Arduino Uno,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15903747/