#include <stdio.h> #include <stdlib.h> #include <stdbool.h> #define HIGH 1 #define LOW 0 #define ANALOG_PIN 0 // A0 #define PWM_PIN 0 #define PERIOD 1000000 bool pwmPin(int pin, int period, int duty_cycle, int enable){ FILE * fd; char fName[128]; if(( fd = fopen("/sys/class/pwm/pwmchip0/export", "w")) == NULL) { printf("Error: unable to export pin\n"); return false; } fprintf(fd, "%d\n", pin); fclose(fd); sprintf(fName, "/sys/class/pwm/pwmchip0/pwm%d/period", pin); if((fd = fopen(fName, "w")) == NULL) { printf("Error: can't open pin period\n"); return false; } fprintf(fd, "%d\n", period); fclose(fd); sprintf(fName, "/sys/class/pwm/pwmchip0/pwm%d/duty_cycle", pin); if((fd = fopen(fName, "w")) == NULL) { printf("Error: can't open pin duty_cycle\n"); return false; } fprintf(fd, "%d\n", duty_cycle); fclose(fd); sprintf(fName, "/sys/class/pwm/pwmchip0/pwm%d/enable", pin); if((fd = fopen(fName, "w")) == NULL) { printf("Error: can't open pin enable\n"); return false; } if(enable == HIGH) { fprintf(fd, "1\n"); } else { fprintf(fd, "0\n"); } fclose(fd); return true; } int analogRead(int pin) { FILE * fd; char fName[64]; char val[8]; // open value file sprintf(fName, "/sys/devices/12c0000.adc/iio:device0/in_voltage%d_raw", pin); if((fd = fopen(fName, "r")) == NULL) { printf("Error: can't open analog voltage value\n"); return 0; } fgets(val, 8, fd); fclose(fd); return atoi(val); } int Con_duty(int duty) { pwmPin(PWM_PIN, PERIOD, duty, 1); } int main(void) { long SenVal = 0; while(1) { SenVal = analogRead(ANALOG_PIN); printf("val : %d\n", SenVal); if (SenVal > 500) Con_duty(100000); // LED ON else if (SenVal <= 500) Con_duty(0); // LED OFF sleep(1); } return 0; } |
최신댓글