/* 四个GPIO以不同频率输出闪烁,创建四个线程,分别输出不同的频率 */
#include <stdio.h> #include <fcntl.h> #include <unistd.h> #include <stdlib.h> #include <pthread.h> #include <string.h> #include <sys/types.h> #include <asm/hardware.h> #include <asm-arm/arch-s3c2410/gpio.h>
pthread_t tid1,tid2,tid3,tid4; unsigned char gpio_rd(int fd); int gpio_wr(int fd,unsigned char data); struct gpio { int fd; int data; int time; }; void *led_func(struct gpio *tmp) //线程复用函数 { struct gpio led_tmp; led_tmp=*tmp; while(1) { //sleep(1);
usleep(led_tmp.time); ioctl(led_tmp.fd,GPIO_SET_PIN,led_tmp.data); usleep(led_tmp.time); ioctl(led_tmp.fd,GPIO_CLR_PIN,led_tmp.data);
} pthread_exit(0); } int gpio_open(void) //打开文件 返回文件描述符 { int fd; if( (fd=open("/dev/gpf/0" ,O_RDWR))<0 ) { perror("open gpio error"); exit(1); } return fd; }
int gpio_set(int fd,unsigned char set_in,unsigned char set_out)//配置IO口的输入输出 { printf("set in port "); if( ioctl(fd,GPIO_SET_MULTI_PIN_IN,set_in)!=0 ) { perror("gpio ioctl error"); exit(1); } printf("[ok] \n set out port "); if( ioctl(fd,GPIO_SET_MULTI_PIN_OUT,set_out)!=0 ) { perror("gpio ioctl error"); exit(1); } printf("[ok] \n"); return 0; }
unsigned char gpio_rd(int fd) //IO口读 { unsigned char buf=0; if( read(fd,&buf,1)==-1 ) { perror("read error"); exit(1); } return buf; } int gpio_wr(int fd,unsigned char data) //IO读 { if( write(fd,&data,1)==-1 ) { perror("write error"); exit(1); } return 0; }
int main(void) { int fd; char cmd[8]; struct gpio led; fd=gpio_open(); gpio_set(fd,0x0f,0xf0); //配置输入输出口 led.fd=fd; led.data=4; led.time=100000; pthread_create(&tid1,NULL,led_func,&led);//通过结构体传递多参数 usleep(20); led.fd=fd; led.data=5; led.time=50000; pthread_create(&tid2,NULL,led_func,&led); //函数冲入,实现不同频率同步输出 usleep(20); led.fd=fd; led.data=6; led.time=200000; pthread_create(&tid3,NULL,led_func,&led); usleep(20); led.fd=fd; led.data=7; led.time=250000; pthread_create(&tid4,NULL,led_func,&led); usleep(20); while(1) { scanf("%s",cmd); if( strcmp(cmd,"exit")==0 ) // 父进程控制推出 { pthread_cancel(tid1); break; } usleep(20); } pthread_join(tid1,NULL); //父进程推出后,所属线程消亡 printf("exit"); return 0; }
|