objective-c - 无法使用 Cocoa (IOKit) 将数据发送到我的 Arduino Uno

标签 objective-c cocoa serial-port arduino iokit

我目前正在尝试通过 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/

相关文章:

objective-c - 为什么大写的属性名称在 Objective-C/UITouch 中没有给出错误?

objective-c - 游戏开发中的日志统计

objective-c - OCMock - 是否需要调用 "verify"来断言在模拟对象上调用了一个方法?

android - Android 与其他设备之间的蓝牙 SPP、UUID 和 PIN 问题

java - RXTX 的稳定替代品

objective-c - 从另一个类访问发送者方法

cocoa - 更改 Cocoa 中的文本光标(插入符号)颜色?

cocoa - 有没有办法在 10.6 机器上获取/使用 OS X 10.3 Cocoa SDK?

iphone - cocoa touch : Displaying a structured document

使用 RS232 的 C 程序仅在启动 minicom 时有效