/*********************************************************************
* File£º test-uart.c
* Author£º Embest
* Desc£º
* History£º
* Program modify, 2005.06.05 Embest R.X.Huang <hungrx@embedinfo.com>
*********************************************************************/
#include <stdio.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/io.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <termios.h>
#include <sys/time.h>
#include <errno.h>
int uart_open(char *Port, int Baud);
#define TIMEOUT 30
#define UART_DEBUG
/* Uart open and setting fuction */
int uart_open(char *Port, int Baud)
{
struct termio SerialPara;
int i, fd;
/* We want to open the port in nodelay mode */
if ((fd = open (Port, O_RDWR)) == -1) {
#ifdef UART_DEBUG
fprintf (stderr, "uart_open: Cannot open port %s\n", Port);
#endif
return -1;
}
/* Now change the rest of the parameters - non-canonical input, etc. */
if (ioctl (fd, TCGETA, &SerialPara) == -1) {
#ifdef UART_DEBUG
fprintf (stderr, "uart_open: Cannot ioctl(TCGETA) on port %s. Errno = %d\n", Port, errno);
#endif
return -1;
}
SerialPara.c_cflag = Baud | CS8 | CLOCAL | CREAD | HUPCL;
SerialPara.c_lflag &= ~ICANON;
SerialPara.c_lflag = 0;
SerialPara.c_oflag = 0;
SerialPara.c_iflag = IGNBRK | IGNPAR;
for (i = 0; i < NCC; i++)
SerialPara.c_cc[i] = (unsigned char) 0;
SerialPara.c_cc[VMIN] = (unsigned char) 0;
SerialPara.c_cc[VTIME] = (unsigned char) TIMEOUT;
if(ioctl (fd, TCSETA, &SerialPara) == -1) {
#ifdef UART_DEBUG
fprintf (stderr, "uart_open: Cannot ioctl(TCSETA) on port %s. Errno = %d\n", Port, errno);
#endif
return -1;
}
return fd;
}
/* Main test program */
int main(void)
{
int i,err,fd,ret;
unsigned char ch;
char buf[] = "Write Something to Test...\n";
struct timeval timeout;
fd_set new_fd_set;
static char *driver = "/dev/ttyS0";
printf("UARTx test example base on Linux. \n");
timeout.tv_sec = 0;
timeout.tv_usec = 0;
fd = uart_open(driver,B115200);
/* print something to UARTx */
write(fd,buf,strlen(buf));
/* Wait input through UART0, or press Crtl+C or Enter to Exit */
while(!((ch==3)|(ch==0xd))){
FD_ZERO (&new_fd_set);
if (fd >= 0)
FD_SET (fd, &new_fd_set);
err = select (fd + 1, &new_fd_set, NULL, NULL, &timeout);
if (err > 0){
if (fd >= 0 && FD_ISSET (fd, &new_fd_set)){
FD_CLR(fd, &new_fd_set);
read(fd,&ch,1);
printf("ch = %c\n",ch);
}
}
}
printf("end.\n");
return 0;
#if 0 // simply test
/* open ttyS0 device file --- UART0 */
fd = open(driver, O_RDWR|O_NOCTTY|O_NDELAY);
if(fd == -1)
{
printf("Fail to open /dev/ttyS0\n");
return -1;
}
else
fcntl(fd, F_SETFL, 0);
/* write data to UART0 */
if(write(fd, buf, strlen(buf) != strlen(buf))
{
printf("Fail to open /dev/ttyS0\n");
return -1;
}
/* close ttyS0 */
close(fd);
return 0;
#endif
}