2013-04-09 53 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