2013-04-09 117 views
5

我目前正尝试通过Mac应用程序向我的Arduino发送数据。在我Arduino Uno的代码如下所示:无法使用Cocoa向我的Arduino Uno发送数据(IOKit)

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的得到犯规的任何数据。

+0

这不是由于IOKit代码,是吗? – 2013-04-09 14:51:45

+0

使用在这里提供的代码Im:http://playground.arduino.cc/Interfacing/Cocoa#IOKit – Jan 2013-04-09 15:00:38

+1

这不会直接回答你的问题(乔希弗里曼的答案是这样),但你可以看看[ORSSerialPort] (https://github.com/armadsen/ORSSerialPort),这使得在Objective-C/Cocoa中使用串口非常容易。 – 2013-04-12 15:30:19

回答

0

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

+0

改变它,但仍然无法正常工作。我在我的arduino上没有收到任何消息。 – Jan 2013-04-11 16:20:15

+0

嗯。从Xcode运行股票演示项目以及在我的Arduino作品上演示草图。时间开始区分他们。 – 2013-04-11 18:55:18

2

1)调用write()的第二个参数不正确 - write()需要一个指向要写入的字节的指针。写一个数值变量的字节的值,通过变量的地址,而不是变量本身:在写

write(serialFileDescriptor, (const void *) &val, 1); 

更多信息(): https://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man2/write.2.html

2)改变到本地的termios变量,选项 - 例如对cfmakeraw()的调用 - 不会影响终端设置;为了更新,更改的选项终端设置,调用tcsetattr():

Mac OS X上的串行通信
cfmakeraw(&options); 

// ...other changes to options... 

tcsetattr(serialFileDescriptor, TCSANOW, &options); 

更多信息: http://developer.apple.com/library/mac/#documentation/DeviceDrivers/Conceptual/WorkingWSerial/WWSerial_SerialDevs/SerialDevices.html

+0

你好,谢谢你的回答。不幸的是,它仍然不适合我(程序仍然冻结(我猜它等待回答或者因为它在写入时冻结)。这是我的新代码:http://pastebin.com/ax4tvLbg – Jan 2013-04-12 21:11:36