From fbd863ca39fb8be294d65c6521774a4737ec5d29 Mon Sep 17 00:00:00 2001 From: Thomas Ingleby Date: Mon, 14 Apr 2014 16:55:19 +0100 Subject: [PATCH] pwm: Fully Functional. * C++ example included Signed-off-by: Thomas Ingleby --- examples/CMakeLists.txt | 2 ++ examples/cycle-pwm3.cpp | 24 ++++++++++++++++++++++++ src/pwm/pwm.cxx | 11 ++++++----- 3 files changed, 32 insertions(+), 5 deletions(-) create mode 100644 examples/cycle-pwm3.cpp diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt index a0db23a..430c18e 100644 --- a/examples/CMakeLists.txt +++ b/examples/CMakeLists.txt @@ -1,7 +1,9 @@ add_executable (readi2c readi2c.cpp) add_executable (hellomaa hellomaa.cpp) +add_executable (cycle-pwm3 cycle-pwm3.cpp) include_directories(${PROJECT_SOURCE_DIR}/api ${PROJECT_SOURCE_DIR}/include) target_link_libraries (hellomaa maa) target_link_libraries (readi2c maa) +target_link_libraries (cycle-pwm3 maa) diff --git a/examples/cycle-pwm3.cpp b/examples/cycle-pwm3.cpp new file mode 100644 index 0000000..a24dce9 --- /dev/null +++ b/examples/cycle-pwm3.cpp @@ -0,0 +1,24 @@ +#include + +#include "maa.h" + +int +main () +{ + maa::PWM pwm(0, 3); + pwm.period_us(200); + pwm.enable(1); + + float value = 0.0f; + + while(1) { + value = value + 0.01f; + pwm.write(value); + usleep(50000); + if (value >= 1.0f) { + value = 0.0f; + } + float output = pwm.read(); + } + return 0; +} diff --git a/src/pwm/pwm.cxx b/src/pwm/pwm.cxx index ff0c700..bd1fecd 100644 --- a/src/pwm/pwm.cxx +++ b/src/pwm/pwm.cxx @@ -43,6 +43,7 @@ PWM::PWM(int chipin, int pinin) } else { fprintf(export_f, "%d", pin); fclose(export_f); + setup_duty_fp(); } } @@ -55,7 +56,8 @@ PWM::write(float percentage) float PWM::read() { - return get_duty() / get_period(); + float output = get_duty() / (float) get_period(); + return output; } void @@ -153,9 +155,9 @@ PWM::write_duty(int duty) if(duty_fp == NULL) { setup_duty_fp(); } - fseek(duty_fp, SEEK_SET, 0); fprintf(duty_fp, "%d", duty); - fseek(duty_fp, SEEK_SET, 0); + rewind(duty_fp); + fflush(duty_fp); } int @@ -178,8 +180,8 @@ PWM::get_period() FILE *period_f; char bu[64]; char output[16]; - sprintf(bu, "/sys/class/pwm/pwmchip%d/pwm%d/period", chipid, pin); + sprintf(bu, "/sys/class/pwm/pwmchip%d/pwm%d/period", chipid, pin); if((period_f = fopen(bu, "rb")) == NULL) { fprintf(stderr, "Failed to open period for reading!\n"); return 0; @@ -197,7 +199,6 @@ PWM::get_duty() setup_duty_fp(); } char output[16]; - fseek(duty_fp, SEEK_SET, 0); fgets(output, 16, duty_fp); fseek(duty_fp, SEEK_SET, 0); return atoi(output);