用C控制GPIO的代码[可以直接看CPU占用率了]
http://forum.cubietech.com/forum.php?mod=viewthread&tid=405
#include <stdlib.h>
#include <stdio.h>#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
/**
* Here we use the GPIO expansion near the SATA connector, from PD1 ~ PD7
* */
#define MIN_PIN 1
#define MAX_PIN 7
/**
* Binary value that GPIO pins could accept
* */
typedef enum{
LOW=0,
HIGH=1
}value_t;
/**
* GPIO pins get/set direction
* */
typedef enum{
IN=0,
OUT=1
}direction_t;
FILE* value_fp[MAX_PIN+1];
/**
* @brief Initialize the GPIO ports' value file pointers
*
* */
void gpio_init()
{
int i;
for(i=MIN_PIN;i<=MAX_PIN;i++)
value_fp[i]=NULL;
}
/**
* @brief Uninitialize the GPIO ports, unexport those exported and close files.
*
* */
int gpio_uninit()
{
int i;
FILE *unexport_fp=fopen("/sys/class/gpio/unexport","w");
if(!unexport_fp) return -1;
for(i=MIN_PIN;i<=MAX_PIN;i++){
if(value_fp[i]){
fclose(value_fp[i]);
fprintf(unexport_fp,"%d",i);
fflush(unexport_fp);
}
}
fclose(unexport_fp);
return 0;
}
/**
* @brief Set the GPIO pins to specified direction
*
* @param pin: GPIO pin to set direction
* @param dir: IN or OUT
*
* */
int pinMode(int pin, direction_t dir)
{
char direction_file[64];
char value_file[64];
FILE *export_fp=fopen("/sys/class/gpio/export","w");
if(!export_fp) return -1;
fprintf(export_fp,"%d",pin);
sleep(1);
fclose(export_fp);
sprintf(direction_file,"/sys/class/gpio/gpio%d_pd%d/direction", pin, pin);
FILE *direction_fp=fopen(direction_file,"w");
if(!direction_fp) return -2;
if(dir==OUT){
fprintf(direction_fp,"out");
}else fprintf(direction_fp,"in");
fclose(direction_fp);
sprintf(value_file,"/sys/class/gpio/gpio%d_pd%d/value", pin, pin);
value_fp[pin]=fopen(value_file,"w");
if(!value_fp[pin]) return -3;
return 0;
}
/**
* @brief Set the GPIO pins to specified binary value
*
* @param pin: GPIO pin to set value
* @param value: LOW or HIGH
*
* */
int digitalWrite(int pin, value_t value)
{
if(!value_fp[pin])return -1;
if(pin<MIN_PIN) pin=MIN_PIN;
if(pin>MAX_PIN) pin=MAX_PIN;
fprintf(value_fp[pin],"%d", value);
fflush(value_fp[pin]);
return 0;
}
/**
* @brief A demo to alternately set two GPIO pin's power level (LOW or HIGH),
* to flash a LED connected between the two pins.
* */
int main()
{
gpio_init();
pinMode(1,OUT);
pinMode(2,OUT);
int i;
for(i=0;i<10;i++){
digitalWrite(1,HIGH);
digitalWrite(2,LOW);
sleep(1);
digitalWrite(1,LOW);
digitalWrite(2,HIGH);
sleep(1);
}
gpio_uninit();
}