-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpwm_handler.cpp
More file actions
85 lines (65 loc) · 2.41 KB
/
pwm_handler.cpp
File metadata and controls
85 lines (65 loc) · 2.41 KB
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
#include "pwm_handler.h"
#include "at_handler.h"
#define MAX_ADC_NUMBER 7
#define PWM_SAMPLES 5
#define PWM_SAMPLE_TIMEOUT_US 1000000
chAT::CommandStatus PwmHandler::handle_read(chAT::Server &srv, chAT::ATParser &parser)
{
if(parser.args.size() != 1){
return write_error_message(srv, "Invalid number of arguments");
}
int adcChannel = atoi(parser.args[0].c_str());
if(adcChannel < 0 || adcChannel > MAX_ADC_NUMBER){
return write_error_message(srv, "Invalid ADC channel");
}
int pulseLenght = 0;
if(read_pwm_in(adcChannel, &pulseLenght) != 0){
return write_error_message(srv, "Error reading ADC");
}
return write_ok_message(srv, String(pulseLenght).c_str());
}
chAT::CommandStatus PwmHandler::handle_write(chAT::Server &srv, chAT::ATParser &parser)
{
if(parser.args.size() != 2){
return write_error_message(srv, "Invalid number of arguments");
}
int pwmChannel = atoi(parser.args[0].c_str());
int dutyCycle = atoi(parser.args[1].c_str());
if(set_pwm_out(pwmChannel, dutyCycle) != 0){
return write_error_message(srv, "Error writing PWM");
}
return write_ok_message(srv, ("#"+String(pwmChannel)+" DutyCycle %:"+String(dutyCycle)).c_str());
}
chAT::CommandStatus PwmHandler::handle_test(chAT::Server &srv, chAT::ATParser &parser)
{
String message = "\n";
message += "AT+PWM?<adc channel> - Read PWM input as pulse count\n";
message += "AT+PWM=<pwm channel>,<duty cycle in percentage> - Set Pwm output\n";
return write_ok_message(srv, message.c_str());
}
int PwmHandler::read_pwm_in(int adcChannel, int *output) {
float pulseLenght = 0;
if(adcChannel < 0 || adcChannel > 7){
return -EINVAL;
}
int adc_channel = A0+adcChannel;
for (int i=0; i<PWM_SAMPLES; i++){
pulseLenght += pulseIn(adc_channel, HIGH, PWM_SAMPLE_TIMEOUT_US);
delay(50);
}
*output = int(pulseLenght/PWM_SAMPLES);
return 0;
}
//TODO IMPROVE THIS STARTINH FROM HERE [https://github.com/arduino/ArduinoCore-mbed/blob/main/cores/arduino/wiring_analog.cpp#L45-L99]
int PwmHandler::set_pwm_out(int pwmChannel, int dutyCycle_percentage) {
if(pwmChannel < 2 ||
pwmChannel > 13 ||
dutyCycle_percentage < 0 ||
dutyCycle_percentage > 100)
{
return -EINVAL;
}
int dutyCycle = map(dutyCycle_percentage, 0, 100, 0, 255);
analogWrite(pwmChannel, dutyCycle);
return 0;
}