Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't send data to my Arduino Uno using Cocoa (IOKit)

I'm currently trying to send data to my Arduino via a Mac application. The code in my Arduino Uno looks like this:

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);
    }
}

Here is my code in the XCode project:

// 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");

So when I run the application, it waits the five seconds, but then it freezes. The output in the console is this:

before
after

So, what am I doing wrong here?

UPDATE: So, when I comment this line out

fcntl(serialFileDescriptor, F_SETFL, 0);

the program doesn't freeze, but my Arduino still doesnt get any data.

like image 479
Jan Avatar asked Nov 03 '22 00:11

Jan


1 Answers

1) The second parameter of the call to write() is incorrect - write() expects a pointer to the byte(s) to be written. To write the value of a numerical variable as bytes, pass the address of the variable, not the variable itself:

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

More info on write(): https://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man2/write.2.html

2) Changes to the local termios variable, options - such as the call to cfmakeraw() - don't affect the terminal settings; In order to update the terminal settings with the changed options, call tcsetattr():

cfmakeraw(&options);

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

tcsetattr(serialFileDescriptor, TCSANOW, &options);

More info on Mac OS X serial communication: http://developer.apple.com/library/mac/#documentation/DeviceDrivers/Conceptual/WorkingWSerial/WWSerial_SerialDevs/SerialDevices.html

like image 172
Josh Freeman Avatar answered Nov 10 '22 01:11

Josh Freeman