Merge branch 'master' of https://github.com/szmoore/MCTX3420.git
[matches/MCTX3420.git] / BBB code / pwm.c
1 #include "pwm.h"
2
3 /* Initialize PWM : 
4 1/ mmap /dev/mem to have write access to system clock 
5 2/ enable system clock (0x0 = disabled, 0x02 = enabled)
6 3/ set correct pin MUX 
7
8 can modify pwm variables through virtual filesystem:
9 "/sys/class/pwm/ehrpwm.1:0/..."
10
11 pwm drivers reference:
12 http://processors.wiki.ti.com/index.php/AM335x_PWM_Driver%27s_Guide */
13
14 static int pwminit = 0;
15 static int pwmstart = 0;
16
17 void pwm_init(void) {
18     FILE *pwm_mux;
19     int i;
20     volatile uint32_t *epwmss1;
21     
22     int fd = open("/dev/mem", O_RDWR);
23     
24     if(fd < 0)
25         {
26         printf("Can't open /dev/mem\n");
27         exit(1);
28         }
29
30     epwmss1 = (volatile uint32_t *) mmap(NULL, LENGTH, PROT_READ|PROT_WRITE, MAP_SHARED, fd, START);
31     if(epwmss1 == NULL)
32         {
33         printf("Can't mmap\n");
34         exit(1);
35         }
36     else
37         {
38                 epwmss1[OFFSET_1 / sizeof(uint32_t)] = 0x2;
39                 }
40     close(fd);
41     pwminit = 1;
42     pwm_mux = fopen(PWMMuxPath, "w");
43     fprintf(pwm_mux, "6");                                                      // pwm is mux mode 6
44     fclose(pwm_mux);
45 }
46
47 //can change filepath of pwm module "/ehrpwm.%d:0/" by passing %d as argument
48 //depends how many pwm modules we have to run
49 //TODO:
50
51 void pwm_start(void) {
52     FILE *pwm_run;
53     pwm_run = fopen(PWMRunPath, "w");
54     fprintf(pwm_run, "1");
55     fclose(pwm_run);
56         pwmstart = 1;
57 }
58
59 void pwm_stop(void) {
60     FILE *pwm_run;
61     pwm_run = fopen(PWMRunPath, "w");
62     fprintf(pwm_run, "0");
63     fclose(pwm_run);
64         pwmstart = 0;
65 }
66
67 //duty_percent is just a regular percentage (i.e. 50 = 50%)
68
69 void pwm_set_duty(int duty_percent) {
70     FILE *pwm_duty;
71     pwm_duty = fopen(PWMDutyPath, "w"); 
72     fprintf(pwm_duty, "%d", duty_percent);
73     fclose(pwm_duty);
74 }
75
76 //freq is just normal frequency (i.e. 100 = 100Hz)
77
78 void pwm_set_period(int freq) {
79     FILE *pwm_period;
80     pwm_period = fopen(PWMFreqPath, "w");
81     fprintf(pwm_period, "%d", freq);
82     fclose(pwm_period);
83 }

UCC git Repository :: git.ucc.asn.au