Sunday, December 15, 2013

Arduino and Mac OSX communication through serial port

I have been digging around to find a simple working example of Arduino and Mac OSX communication. To my surprise, it turned out to be not easy! There is an example for working with a serial port with Mac, but I found it overwhelming to grasp all the concepts there. Not to mention the confusion of working with Arduino (confess: I am an Arduino noob).

So here is a really, really basic sample.

Concept:
You'll need to communicate with Arduino through a serial port. Just read/write operations. If you want to do any fancy task like reading from/controlling a sensor/camera, you'll need to handle them in your Arduino sketch.
Code:
So let's get started. First, create an Arduino sketch to write to a serial port:
int randNumber;

void setup() {
  Serial.begin(9600);
  randomSeed(analogRead(0));
}

void loop() {
  randNumber = random(65,128);
  Serial.write(32);
  delay(1000);
  Serial.write(randNumber);  
  delay(1000);
}
So this sketch just writes random numbers to a serial port, interlaced with a space character. Load to Arduino and open the Arduino Serial Monitor (Tools/Serial Monitor) to see the outputs. You should be able to see random characters separated by space.

Now move on to the Mac. First, you can read the input with this Python snippet:

(You'll need to install the pySerial package, also remember to use the right serial port for your environment).

 
import Serial
ser = serial.Serial('/dev/tty.usbmodemfd121',9600)
while True:
      print ser.read()
Ok, now the real stuff with Mac. Forget about the SerialPortSample for now, all you need to do is to just open that port and read it.
     int main() {
     int fd = open('/dev/tty.usbmodemfd121', O_RDONLY | O_NONBLOCK);
     if (fd!=-1) {
        int rsize;
        char buf[100];
        memset(&buf,0, 100);
        while (true) {
            rsize = read(fd,&buf,1);
            if (rsize>0) {
                for (int i=0; i < rsize; i++ ) {
                    printf("%d ",buf[i]);
                }
            }
        }
     } else printf("Unable to open the serial port\n");
}

That's it!

No comments:

Post a Comment