/* * switch.c * How to register an button and count this * author: Simon Wörner, Manuel Vögele, * Siegfried Kienzle * 24-March-2017 * * */ #define BUTTON "17" #define IN "in\n" #define OUT "out\n" #define HIGH "1\n" #define LOW "0\n" #define MAXBYTES 1 #include #include #include #include #include int writeIntoFile(char* value, char* path) { int fd; char buffer[3]; strcpy(buffer, value); if((fd=open(path, O_RDWR | O_CREAT | O_TRUNC)) == -1) { perror(NULL); return EXIT_FAILURE; } if((write(fd, &buffer, sizeof(buffer))) == -1) { perror("Cannot write into file"); return EXIT_FAILURE; } printf("Success"); close(fd); return EXIT_SUCCESS; } int reserve(char* gpioPort) { char str[3]; strcpy(str, gpioPort); strcat(str, "\n"); return writeIntoFile(str,"/sys/class/gpio/export"); } int setDirection(char* gpioPort, char* inOut) { char *direc = "/direction"; char *gpioPath = "/sys/class/gpio/gpio"; char path[32]; strcpy(path, gpioPath); strcat(path, gpioPort); strcat(path, direc); return writeIntoFile(inOut, path); } int setOutput(char* gpioPort, char* volt) { char *val = "/value"; char *gpioPath = "/sys/class/gpio/gpio"; char path[28]; strcpy(path, gpioPath); strcat(path, gpioPort); strcat(path, val); return writeIntoFile(volt, path); } int mainLoop(char* gpioPort) { int fid, portValue, count, countButton; char *val = "/value"; char *gpioPath = "/sys/class/gpio/gpio"; char path[28]; strcpy(path, gpioPath); strcat(path, gpioPort); strcat(path, val); while(true) { if( (fid=open(path, O_RDONLY)) == -1) perror("Fehler "); if(readInput(fid) == 1) { countButton++; printf("%d", countButton); } close(fid); } } char[] readInput(int fid) { char buffer[MAXBYTES]; read(fid, &buffer, MAXBYTES); return buffer; } int unexport(char* gpioport) { char str[3]; strcpy(str, gpioPort); strcat(str, "\n"); return writeIntoFile(str,"/sys/class/gpio/unexport"); } int main() { reserve(BUTTON); setDirection(BUTTON, IN); mainLoop(BUTTON); unexport(BUTTON); return 0; }