Bioscara
DALSA's DIY SCARA Robot Arm.
Loading...
Searching...
No Matches
uPWM.h
Go to the documentation of this file.
1
12#ifndef __RPIPWM
13#define __RPIPWM
14
15#include <stdio.h>
16#include <stdlib.h>
17#include <string.h>
18#include <unistd.h>
19#include <string>
20#include <iostream>
21#include <math.h>
22
34{
35public:
45 int start(int channel, int frequency, float duty_cycle = 0, int chip = 2)
46 {
47 chippath = "/sys/class/pwm/pwmchip" + std::to_string(chip);
48 pwmpath = chippath + "/pwm" + std::to_string(channel);
49 std::string p = chippath + "/export";
50 FILE *const fp = fopen(p.c_str(), "w");
51 if (NULL == fp)
52 {
53 std::cerr << "PWM device does not exist. Make sure to add 'dtoverlay=pwm-2chan' to /boot/firmware/config.txt.\n";
54 return -1;
55 }
56 const int r = fprintf(fp, "%d", channel);
57 fclose(fp);
58 if (r < 0)
59 return r;
60 usleep(100000); // it takes a while till the PWM subdir is created
61 per = (int)1E9 / frequency;
63 setDutyCycle(duty_cycle);
64 enable();
65 return r;
66 }
67
71 void stop()
72 {
73 disable();
74 }
75
83 {
84 disable();
85 }
86
92 inline int setDutyCycle(float v) const
93 {
94 const int dc = (int)round((float)per * (v / 100.0));
95 const int r = setDutyCycleNS(dc);
96 return r;
97 }
98
99private:
100
101 void setPeriod(int ns) const
102 {
103 writeSYS(pwmpath + "/" + "period", ns);
104 }
105
106 inline int setDutyCycleNS(int ns) const
107 {
108 const int r = writeSYS(pwmpath + "/" + "duty_cycle", ns);
109 return r;
110 }
111
112 void enable() const
113 {
114 writeSYS(pwmpath + "/" + "enable", 1);
115 }
116
117 void disable() const
118 {
119 writeSYS(pwmpath + "/" + "enable", 0);
120 }
121
122 int per = 0;
123
124 std::string chippath;
125 std::string pwmpath;
126
127 inline int writeSYS(std::string filename, int value) const
128 {
129 FILE *const fp = fopen(filename.c_str(), "w");
130 if (NULL == fp)
131 {
132 return -1;
133 }
134 const int r = fprintf(fp, "%d", value);
135 fclose(fp);
136 return r;
137 }
138};
139
140#endif
Class to create a Pulse Width Modulated (PWM) signal on the Raspberry PI 4 and 5.
Definition uPWM.h:34
void stop()
Stops the PWM.
Definition uPWM.h:71
std::string chippath
Definition uPWM.h:124
~RPI_PWM()
Destroy the RPI_PWM object.
Definition uPWM.h:82
std::string pwmpath
Definition uPWM.h:125
void setPeriod(int ns) const
Definition uPWM.h:101
int writeSYS(std::string filename, int value) const
Definition uPWM.h:127
int per
Definition uPWM.h:122
int start(int channel, int frequency, float duty_cycle=0, int chip=2)
Starts the PWM.
Definition uPWM.h:45
void enable() const
Definition uPWM.h:112
int setDutyCycle(float v) const
Sets the duty cycle in percent 0 - 100.
Definition uPWM.h:92
int setDutyCycleNS(int ns) const
Definition uPWM.h:106
void disable() const
Definition uPWM.h:117