Arduino appears as a serial device. You should look at the open() and close() functions. I did it on Linux, but I'm sure it works the same on Mac. This is an example code snippet. The first fragment opens and sets the file descriptor.
int fd; // File descriptor // Open port fd = open("/dev/ttyACM0", O_RDWR | O_NOCTTY | O_NDELAY); if (fd == -1){ printf("Device cannot be opened.\n"); exit(-1); // If the device is not open, return -1 } struct termios options; fcntl(fd, F_SETFL, FNDELAY); // Open the device in nonblocking mode // Set parameters tcgetattr(fd, &options); // Get the current options of the port bzero(&options, sizeof(options)); // Clear all the options speed_t Speed; switch (baudRate) // Set the speed (baudRate) { case 110 : Speed=B110; break; case 300 : Speed=B300; break; case 600 : Speed=B600; break; case 1200 : Speed=B1200; break; case 2400 : Speed=B2400; break; case 4800 : Speed=B4800; break; case 9600 : Speed=B9600; break; case 19200 : Speed=B19200; break; case 38400 : Speed=B38400; break; case 57600 : Speed=B57600; break; case 115200 : Speed=B115200; break; default : exit(-4); } cfsetispeed(&options, Speed); // Set the baud rate at 115200 bauds cfsetospeed(&options, Speed); options.c_cflag |= ( CLOCAL | CREAD | CS8); // Configure the device : 8 bits, no parity, no control options.c_iflag |= ( IGNPAR | IGNBRK ); options.c_cc[VTIME]=0; // Timer unused options.c_cc[VMIN]=0; // At least on character before satisfy reading tcsetattr(fd, TCSANOW, &options); // Activate the settings
It just closes it:
close(fd);
To read from the actual file descriptor:
ioctl(fd, FIONREAD, &t1); if(t1 > 0) { // If the number of bytes read is equal to the number of bytes retrieved if(read(fd,pByte, t1) == t1) { for(int i =0; i < t1; i++) { if(pByte[i] != '\r'){ // Just makes sure you're not scanning new lines // TODO: Do what you want with this character } } } }
source share