日期:2014-05-16 浏览次数:20679 次
// send.c ..........................................
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <termios.h>
#include <assert.h>
#include <errno.h>
#include <stdlib.h>
#define TTYS0 /dev/ttyS0
#define TTYS1 /dev/ttyS1
#define MAX_BUF_SIZE 1024*20 // define maxinum buffer length
int open_serial_port(int device)
{
int serial_port;
if (0 == device)
{
if (serial_port = open("dev/ttyS0",O_RDWR | O_NOCTTY | O_NDELAY) < 0)
{
perror("open /dev/ttyS0 encouter an error\n");
exit(1);
}
printf("open /dev/ttyS0 success.serial_port is %d..\n",serial_port);
}
else
{
if (serial_port = open("/dev/ttyS1",O_RDWR | O_NOCTTY | O_NDELAY) < 0 )
{
perror("open /dev/ttyS1 encouter an error\n");
exit(1);
}
printf("open /dev/ttyS1 success.serial_port is %d..\n",serial_port);
}
return serial_port;
}
int main(int argc,char *argv[])
{
char *msg = "hi,everyone...";
int sendlen = strlen(msg);
int serial_port = open_serial_port(1); // open /dev/ttyS0
struct termios opt;
tcgetattr(serial_port,&opt);
cfmakeraw(&opt);// sets the structure specified by opt to raw mode.
// there is no effect on the hardware until a subsequent successful call to tcsetattr()...
cfsetispeed(&opt,B38400); // set input baud as 38400 bps
cfsetospeed(&opt,B38400);
opt.c_cc[VMIN] = 1;
opt.c_cc[VTIME] = 1;
tcsetattr(serial_port,TCSANOW,&opt); //change attr as soon as possible
while (1)
{
int ret_val = write(serial_port,msg,sendlen);
assert(ret_val != -1);
printf("write %d bytes to serial_port %d successfully...\n",ret_val,serial_port);
sleep(3);
}
if (close(serial_port) == -1)
{
printf("close serial_port error\n");
(1);
}
printf("leave...\n");
return 0;
}