Serial Port Programming

On Computer, a serial port is an hardware interface which used to communicate/transfer data bytes serially. Modern Computers and device use an interface called UART for serial communication.

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>
#include <errno.h>

#define SERIAL_PORT_DEV		"/dev/ttyUSB0"

int main(int argc, char *argv[])
{
	int sfd = -1;
	struct termios default_cfg;
	struct termios cfg;

	sfd = open(SERIAL_PORT_DEV, O_RDWR);
	if (sfd < 0) {
		fprintf(stderr, "Failed to open %s. error no:%d error:%s\n", SERIAL_PORT_DEV, errno, strerror(errno));
		return -1;
	}

	if (tcgetattr(sfd, &default_cfg) != 0) {
		fprintf(stderr, "Failed to get default attr. error no:%d error:%s\n", errno, strerror(errno));
		return -2;
	}
	memcpy(&cfg, &default_cfg, sizeof(struct termios));

	cfg.c_cflag &= ~PARENB;
	cfg.c_cflag &= ~CSTOPB;
	cfg.c_cflag &= ~CSIZE;
	cfg.c_cflag |= CS8;
	cfg.c_cflag &= ~CRTSCTS;
	cfg.c_cflag |= CREAD | CLOCAL;

	cfg.c_lflag &= ~ICANON; 	
	cfg.c_lflag &= ~ECHO;
	cfg.c_lflag &= ~ECHOE;
	cfg.c_lflag &= ~ECHONL;
	cfg.c_lflag &= -ISIG;
	cfg.c_lflag &= ~(IXON | IXOFF | IXANY);
	cfg.c_lflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL);

	cfg.c_oflag &= ~OPOST;
	cfg.c_oflag &= ~ONLCR;

	cfg.c_cc[VTIME] = 10;
	cfg.c_cc[VMIN] = 0;

	cfsetispeed(&cfg, B9600);
	cfsetospeed(&cfg, B9600);

	if (tcsetattr(sfd, TCSANOW, &cfg) != 0) {
		return -3;
	}

	return 0;
}

©2023-2024 rculock.com