How to pass an integer from an Arduino to a C application on Mac OS X
문제
What is the standard method to read values on an Arduino from a C application?
I have an accelerometer and a few poentiometers which I would like to bind to Cocoa controls, an NSSlider for example.
My arduino is currently connected to: /dev/cu.usbmodem26431
and I can read the values printed by the AnalogReadSerial code sample in the Serial Monitor.
How do I read from /dev/cu.usbmodem26431
?
해결책
Cocoa Serial (Edit)
Three methods of interfacing with Objective C are presented here
http://arduino.cc/playground/Interfacing/Cocoa
Arduino Serial
If you know how to establish a Serial/USB
connection then you can send the values as either string or binary to the Arduino.
In the setup()
method on the Arduino you establish as Serial
connection like this.
nb: using 115200
baud/speed for this example
Serial.begin(115200);
In the loop()
method on the Arduino you can read data from the c application. here is a full Arduino example including how to send data back to the c application using Serial.print()
int incomingByte = 0; // for incoming serial data
void setup() {
Serial.begin(115200); // opens serial port, sets data rate to 115200 bps
}
void loop() {
// send data only when you receive data:
if (Serial.available() > 0) {
// read the incoming byte:
incomingByte = Serial.read();
// say what you got:
Serial.print("I received: ");
Serial.println(incomingByte, DEC);
}
}
Source http://arduino.cc/en/Serial/read
The example above is very crude, you can use Serial.available() to see how much data is waiting to be read.
For strings
you might want to use a \n
line terminator or other type of terminator as an indicator for the end of a packet (to know when it has been fully received).
It is a good idea to design your own header and check sum
to ensure data integrity but I don't bother with check sums
for simple unimportant projects.
As an example, gps systems often send sentences when in string/text mode. If you look up the Arduino library called tinyGPS, you will see one way to read an entire sentence into different variables within an Arduino program.
This is an NMEA GPS sentence, do not use the same header in your projects, instead, design your own. This is just an example of how you might transmit multiple values (int, string, float etc) to an Arduino
$GPBWC,081837,,,,,,T,,M,,N,*13