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

时间:2013-04-09 13:49:44

标签: 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仍然没有得到任何数据。

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:0)

你的Arduino草图应该是uint8_t,而不是int,你的IOKit调用write()也应该使用uint8_t。