【UART.c】
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h> // UNIX Standard Function Definitions
#include <fcntl.h> // File Control Definitions
#include <errno.h> // File Control Definitions
#include <termios.h> // POSIX Terminal Control Definitions
#include "UART.h"
struct termios tty;
struct termios tty_old;
int UART_id = 0;
int UART_Open(void)
{
memset(&tty, 0, sizeof(tty));
UART_id = open(UART_PORT, O_RDWR | O_NOCTTY | O_NDELAY);
if (UART_id < 0)
{
printf("Warning: Cannot open the serial port!\n");
return 0;
}
/* Error Handling */
if (tcgetattr(UART_id, &tty) != 0)
{
printf("Error: %d from tcgetattr: %s \n", errno,strerror(errno));
return 0;
}
/* Save old tty parameters */
tty_old = tty;
/* Set Baud Rate */
cfsetospeed(&tty, (speed_t)B9600);
cfsetispeed(&tty, (speed_t)B9600);
/* Setting other Port Stuff */
tty.c_cflag &= ~PARENB; // Make 8n1
tty.c_cflag &= ~CSTOPB;
tty.c_cflag &= ~CSIZE;
tty.c_cflag |= CS8;
tty.c_cflag &= ~CRTSCTS; // no flow control
tty.c_cc[VMIN] = 1; // read doesn't block
tty.c_cc[VTIME] = 5; // 0.5 second read timeout
tty.c_cflag |= CREAD | CLOCAL; // turn on READ & ignore ctrl lines
/* Make raw */
cfmakeraw(&tty);
/* Flush Port, then applies attributes */
tcflush(UART_id, TCIFLUSH);
if (tcsetattr(UART_id, TCSANOW, &tty) != 0)
{
printf("Error: %d from tcgetattr\n", errno);
return 0;
}
return UART_id;
}
void UART_Send(unsigned char Byte)
{
write(UART_id, &Byte, 1);
// It was definitely not necessary to write byte per byte, also int n_written = write( UART_id, cmd, sizeof(cmd) -1) worked fine.
}
int UART_Receive(char* buf)
{
int len = read(UART_id, buf, 512);
buf[len] = '\0';
return len;
}
void UART_Close()
{
close(UART_id);
}