-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpwm_set.c
96 lines (82 loc) · 2.19 KB
/
pwm_set.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
/*
* PWM test program
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <inttypes.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <signal.h>
#include <sys/time.h>
#include <stdarg.h>
#define PWMTMR_START (0x101)
#define PWMTMR_STOP (0x102)
#define PWMTMR_FUNC (0x103)
#define PWMTMR_TONE (0x104)
#define PWM_CONFIG (0x105)
#define HWPWM_DUTY (0x106)
#define PWM_FREQ (0x107)
#define MAX_DUTY (720)
#define MIN_DUTY (0)
#define MAX_FREQ (2000000)
#define MIN_FREQ (1)
static const char *pwm_dev = "/dev/pwmtimer";
typedef struct tagPWM_Config {
int channel;
int dutycycle;
} PWM_Config,*pPWM_Config;
typedef struct tagPWM_Freq {
int channel;
int step;
int pre_scale;
unsigned int freq;
} PWM_Freq,*pPWM_Freq;
void pabort(const char *s)
{
perror(s);
abort();
}
int main(int argc, char **argv)
{
if ( argc != 3 )
{
printf("Usage %s Frequency[%d-%d]Hz Duty Level [%d-%d]\n\n", argv[0], MIN_FREQ, MAX_FREQ, MIN_DUTY, MAX_DUTY);
exit(-1);
}
uint8_t pwm_pin = 5;// atoi(argv[1]);
unsigned int freq = atoi(argv[1]);
unsigned int duty = atoi(argv[2]);
int fd = -1;
if (duty < MIN_DUTY || duty > MAX_DUTY)
pabort("Invalid duty cycle");
if (freq < MIN_FREQ || freq > MAX_FREQ)
pabort("Invalid frequency");
//pwmfreq_set
PWM_Freq pwmfreq;
pwmfreq.channel = pwm_pin;
pwmfreq.freq = (unsigned int)((double)1000000000.0/freq);
pwmfreq.step = 0;
if ((fd = open(pwm_dev, O_RDONLY)) < 0)
pabort("open pwm device fail");
if (ioctl(fd, PWM_FREQ, &pwmfreq) < 0)
pabort("can't set PWM_FREQ");
if(fd)
close(fd);
//analogWrite
PWM_Config pwmconfig;
pwmconfig.channel = pwm_pin;
pwmconfig.dutycycle = duty;
if ((fd = open(pwm_dev, O_RDONLY)) < 0)
pabort("open pwm device fail");
if (ioctl(fd, PWM_CONFIG, &pwmconfig) < 0)
pabort("can't set PWM_CONFIG");
if (ioctl(fd, PWMTMR_START, &pwmconfig) < 0)
pabort("can't set PWMTMR_START");
if(fd)
close(fd);
printf("PWM%d: [%dHz, %d/%d]\n", pwm_pin, freq, duty, MAX_DUTY);
return 0;
}