The Arduino’s USB port is actually a serial port in disguise. To your computer it appears as a ‘virtual’ serial port. This is good news if you want to write custom code on your computer to talk with the Arduino, as talking to serial ports is a well-solved problem. (Unfortunately, so well-solved that there’s many ways of solving it.)
On the Arduino forum there’s been a few requests for some example C code of how to talk to Arduino. The nice thing about standard POSIX C code is that it works on every computer (Mac/Linux/PC) and doesn’t require any extra libraries (like what Java and Python need). The bad thing about C is that it can be pretty incomprehensible.
Here is arduino-serial.c, a command-line C program that shows how to send data to and receive data from an Arduino board. It attempts to be as simple as possible while being complete enough in the port configuration to let you send and receive arbitrary binary data, not just ASCII. It’s not a great example of C coding, but from it you should be able to glean enough tricks to write your own stuff.
Usage
laptop% gcc -o arduino-serial arduino-serial.claptop% ./arduino-serialUsage: arduino-serial -p [OPTIONS]
Options:-h, --help Print this help message-p, --port=serialport Serial port Arduino is on-b, --baud=baudrate Baudrate (bps) of Arduino-s, --send=data Send data to Arduino-r, --receive Receive data from Arduino & print it out-n --num=num Send a number as a single byte-d --delay=millis Delay for specified milliseconds
Note: Order is important. Set '-b' before doing '-p'.Used to make series of actions: '-d 2000 -s hello -d 100 -r'means 'wait 2secs, send 'hello', wait 100msec, get reply'
Example Use
laptop% ./arduino-serial -b 9600 -p /dev/tty.usbserial -s 6
laptop% ./arduino-serial -b 9600 -p /dev/cu.usbserial -s furby
laptop% ./arduino-serial -b 9600 -p /dev/cu.usbserial -rread: 15 Hello world!
laptop% ./arduino-serial -b 9600 -p /dev/cu.usbserial -s get -rread: d=0
Internals
There are three interesting functions that show how to implement talking to serial ports in C:
- int serialport_init(const char* serialport, int baud)— given a serial port name and a speed, return a file descriptor to the open serial port.
- int serialport_write(int fd, const char* str)– write out a string on the given a serial port file descriptor
- int serialport_read_until(int fd, char* buf, char until)– read from serial port into a buffer until a given character is received
You can and should write improved versions of the read and write functions that better match your application.