头文件TestMstarGpio.h
///
#ifndef _MSTAR__GPIO_KLSDJFAJLKAJKAL_H_
#define _MSTAR__GPIO_KLSDJFAJLKAJKAL_H_
#define MSTAR_GPIO_MAJOR 224
#define MSTAR_GPIO_MINOR 0
#define Cmd_GPIO_Write 221
#define Cmd_GPIO_Read 222
#define Cmd_GPIO_DirectionOut 223
#define Cmd_GPIO_DirectionIn 224
typedef struct _mstar_gpio_data_struct {
int num;
int value;
}mstar_gpio_data_struct;
int OpenGpio();
int WriteGpio(int fd,int num,int value);
int ReadGpio(int fd,int num);
int SetGpioIn(int fd,int num);
#endif
/
源文件TestMstarGpio.c
///
#include <stdio.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <sys/ioctl.h>
#include "MstarGpio.h"
void HexPrintf(char * buf ,int len)
{
int i;
printf("\r\n");
for(i=0;i<len;i++)
{
printf("0x%02x ",*(buf+i));
if(15==(i%16))
printf("\r\n");
}
printf("\r\n");
}
int OpenGpio()
{
int fd=0;
/*打开设备文件*/
fd = open("/dev/MstarGpio",O_RDWR);
if (fd < 0)
{
printf("Open Dev Mem0 Error!\n");
return -1;
}
return fd;
}
int WriteGpio(int fd,int num,int value)
{
mstar_gpio_data_struct Mymstar_gpio_data_struct;
Mymstar_gpio_data_struct.num=num;
Mymstar_gpio_data_struct.value=value;
if (ioctl(fd, Cmd_GPIO_Write, &Mymstar_gpio_data_struct) < 0)
{
printf("Call cmd MEMDEV_IOCPRINT fail\n");
return -1;
}
return 0;
}
int ReadGpio(int fd,int num)
{
mstar_gpio_data_struct Mymstar_gpio_data_struct;
Mymstar_gpio_data_struct.num=num;
if (ioctl(fd, Cmd_GPIO_Read, &Mymstar_gpio_data_struct) < 0)
{
printf("Call cmd MEMDEV_IOCPRINT fail\n");
return -1;
}
return Mymstar_gpio_data_struct.value;
}
int SetGpioIn(int fd,int num)
{
mstar_gpio_data_struct Mymstar_gpio_data_struct;
Mymstar_gpio_data_struct.num=num;
if (ioctl(fd, Cmd_GPIO_DirectionIn, &Mymstar_gpio_data_struct) < 0)
{
printf("Call cmd MEMDEV_IOCPRINT fail\n");
return -1;
}
return Mymstar_gpio_data_struct.value;
}
main(int argc,char *argv[])
{
int num;
int value;
int i;
int fd;
int ret=0;
if((3!=argc)&&(2!=argc))
{
printf("usage \r\n read demo: ./TestMstarGpio 62 \r\n write demo: ./TestMstarGpio 62 1 \r\n");
return 0;
}
num=atoi(argv[1]);
fd=OpenGpio();
if(argc==3)
{
printf("fd %d\r\n",fd);
value=atoi(argv[2]);
WriteGpio(fd,num,value);
printf("WriteGpio %d\r\n",value);
}
if(argc==2)
{
// SetGpioIn(fd,num);
// while(1)
{
ret=ReadGpio(fd,num);
printf("ReadGpio %d\r\n",ret);
// usleep(2000);
}
}
close(fd);
//printf("argc %d %d\r\n",argc,cycle);
return 0;
}
/
编译的Makefile
all:
arm-buildroot-linux-uclibcgnueabihf-gcc -o TestMstarGpio TestMstarGpio.c
# arm-linux-gnueabihf-gcc -o TestMstarGpio TestMstarGpio.c