该楼层疑似违规已被系统折叠 隐藏此楼查看此楼
#define DEV_NAME "/dev/ttySP1"
#define EXPORT_PATH "/sys/class/gpio/export" //GPIO 设备导出设备
#define GPIO "77" //76:GPIO2.12 77:GPIO2.13 78:GPIO2.14
#define DEV_PATH "/sys/class/gpio/gpio77/value" //输入输出电平值设备
#define DIRECT_PATH "/sys/class/gpio/gpio77/direction" //GPIO 输入输出控制设备
int main(void)
{
int fd_export, fd_dev, fd_dir;
int ret;
char value;
int iFd, i;
int len;
int fd;
unsigned char SenducBuf[8]={0x02,0x03,0x00,0x56,0x00,0x01,0x64,0x29};
unsigned char RecucBuf[15]={0};
struct termios opt;
iFd = open(DEV_NAME, O_RDWR | O_CREAT| O_SYNC);
if (iFd < 0) {
perror(DEV_NAME);
return -1;
}
tcgetattr(iFd, &opt);
cfsetispeed(&opt, B9600);
cfsetospeed(&opt, B9600);
if (tcgetattr(iFd, &opt) < 0) {
return -1;
}
opt.c_lflag &= ~(ECHO | ICANON | ECHOE | ISIG);
opt.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
opt.c_oflag &= ~(OPOST);
opt.c_cflag &= ~(CSIZE | PARENB);
//opt.c_cflag &= ~CSTOPB;
opt.c_cflag |= CS8;
opt.c_cc[VMIN] = 5;
opt.c_cc[VTIME] = 50;
if (tcsetattr(iFd, TCSANOW, &opt) < 0) {
return -1;
}
tcflush(iFd, TCIOFLUSH);
fd_export = open(EXPORT_PATH, O_WRONLY); //打开 GPIO 设备导出设备
if (fd_export < 0) {
perror(EXPORT_PATH);
}
ret = write(fd_export,GPIO,strlen(GPIO)); //向export文件写入GPIO排列序号字符串
fd_dir = open(DIRECT_PATH,O_RDWR); //打开 GPIO 输入输出控制设备
if (fd_dir < 0) {
perror(DIRECT_PATH);
}
ret = write(fd_dir, "in", sizeof("in")); //写入 GPIO 输入(out)方向
fd_dev = open(DEV_PATH, O_RDWR); //打开输入输出电平值设备
if (fd_dev < 0) {
perror(DEV_PATH);
}
while(1)
{
lseek(fd_dev, 0, SEEK_SET);
write(fd_dev, "1", sizeof("1")); //向 GPIO 写入电平值
write(iFd, SenducBuf, 8);
sleep(3);
lseek(fd_dev, 0, SEEK_SET);
write(fd_dev, "0", sizeof("0")); //向 GPIO 写入电平值
len = read(iFd, RecucBuf, 7);
printf("error is : %d\n",errno);
printf("get date: %d \n", len);
for (i = 0; i < len; i++) {
printf(" %x", RecucBuf[i]);
}
printf("\n");
}
close(iFd);
close(fd_dev);
close(fd_dir);
close(fd_export);
return 0;
}