新聞中心

ARM 與 51單片機通信

作者: 時間:2016-11-11 來源:網(wǎng)絡(luò) 收藏
硬件 mini2440核心板,另外一塊帶串口的單片機學(xué)習(xí)板(掛著DS18B20),學(xué)習(xí)板連續(xù)輸出DS18B20的溫度值,波特率19200。

在一個文件夾里新建一個文件,我的是voltage_set.c(以后用來調(diào)壓)

本文引用地址:http://butianyuan.cn/article/201611/316911.htm

#include
#include
#include
#include
#include
#include
#include
#include
#include

#define FALSE -1
#define TRUE1
int speed_arr[] = { B38400, B19200, B9600, B4800, B2400, B1200, B300, //
B38400, B19200, B9600, B4800, B2400, B1200, B300, };
int name_arr[] = {38400, 19200, 9600, 4800, 2400, 1200, 300,
38400, 19200, 9600, 4800, 2400, 1200, 300, };
void set_speed(int fd, int speed)
{
int i;
int status;
struct termios Opt;
tcgetattr(fd, &Opt);
for ( i= 0; i < sizeof(speed_arr) / sizeof(int); i++)
{
if (speed == name_arr[i])
{
tcflush(fd, TCIOFLUSH);
cfsetispeed(&Opt, speed_arr[i]);
cfsetospeed(&Opt, speed_arr[i]);
status = tcsetattr(fd, TCSANOW, &Opt);
if (status != 0)
perror("tcsetattr fd1");
return;
}
tcflush(fd,TCIOFLUSH); //????
}
}

int set_Parity(int fd,int databits,int stopbits,int parity)
{
struct termios options; //?¨???????á??
if ( tcgetattr( fd,&options) != 0) //?×???????????????è??options??,±???
{
perror("SetupSerial 1");
return(FALSE);
}
options.c_cflag &= ~CSIZE; //?????è??c_cflag??????°?????????????
switch (databits)
{
case 7:
options.c_cflag |= CS7; //?è??c_cflag????????????7??
break;
case 8:
options.c_cflag |= CS8; //?è??c_cflag????????????8??
break;
default:
fprintf(stderr,"Unsupported data sizen"); //???????????§??
return (FALSE);
}
switch (parity) //?è?????????é??c_cflag??c_iflag???§
{
case n:
case N:
options.c_cflag &= ~PARENB;
options.c_iflag &= ~INPCK;
break;
case o:
case O: options.c_cflag |= (PARODD | PARENB);
options.c_iflag |= INPCK;
break;
case e:
case E:
options.c_cflag |= PARENB;
options.c_cflag &= ~PARODD;
options.c_iflag |= INPCK;
break;
default:
fprintf(stderr,"Unsupported parityn");
return (FALSE);
}

switch (stopbits)
{
case 1:
options.c_cflag &= ~CSTOPB;
break;
case 2:
options.c_cflag |= CSTOPB;
break;
default:
fprintf(stderr,"Unsupported stop bitsn");
return (FALSE);
}

if (parity != n)
options.c_iflag |= INPCK;


options.c_cc[VTIME] = 150; // 15 seconds
options.c_cc[VMIN] = 0;

tcflush(fd,TCIFLUSH);
if (tcsetattr(fd,TCSANOW,&options) != 0)
{
perror("SetupSerial 3");
return (FALSE);
}
return (TRUE);
}

int OpenDev(char *Dev)
{
int fd = open( Dev, O_RDWR ); //| O_NOCTTY | O_NDELAY????·?????open????
if (-1 == fd)
{
perror("Cant Open Serial Port");
return -1;
}
else
return fd;
}

int main(int argc, char **argv)
{
int fd;
int nread;
char buff[512];
char *dev ="/dev/ttySAC1";
fd = OpenDev(dev);
if (fd>0)
{
printf("Open Serial succeedn");
set_speed(fd,19200);
}
else
{
printf("Cant Open Serial Port!n");
exit(0);
}
if (set_Parity(fd,8,1,N)== FALSE)
{
printf("Set Parity Errorn");
exit(1);
}

while(1)
{
int i;
//char buff1[2]={0x5a,0x5a};
//write(fd,buff1,1);
while((nread = read(fd,buff,512))>0)
{
printf("nLen %dn",nread);
buff[nread+1]=