Browse Source

OOP for LED class OK

master
parent
commit
d528ba902a
3 changed files with 115 additions and 0 deletions
  1. +57
    -0
      LED.cpp
  2. +25
    -0
      LED.h
  3. +33
    -0
      main.cpp

+ 57
- 0
LED.cpp View File

@ -0,0 +1,57 @@
/*led.cpp*/
#include"LED.h"
#include<iostream>
#include<fstream>
#include<string>
#include<sstream>
#define LED_PATH "/sys/class/leds/beaglebone:green:usr"
LED::LED(int number){
this->number = number;
std::ostringstream s;
s << LED_PATH << number; // LED number to the Path
path = std::string(s.str()); // convert to string
}
void LED::writeLED(std::string filename, std::string value){
std::ofstream fs;
fs.open((path + filename).c_str());
fs << value;
fs.close();
}
void LED::removeTrigger(){
writeLED("/trigger", "none");
}
void LED::turnOn(){
std::cout << "Turning LED" << number << "on" << std::endl;
removeTrigger();
writeLED("/brightness", "1");
}
void LED::turnOff(){
std::cout << "Turning LED" << number << "off" << std::endl;
removeTrigger();
writeLED("/brightness", "0");
}
void LED::flash(std::string delayms ="50"){
std::cout << "Making LED" << number << "flash" << std::endl;
writeLED("/trigger", "timer");
writeLED("/delay_on", delayms);
writeLED("/delay_off", delayms);
}
void LED::outputState(){
std::ifstream fs;
fs.open((path + "/trigger").c_str());
std::string line;
while(getline(fs,line)) std::cout << line <<std::endl;
fs.close();
}
LED::~LED(){
std::cout << "!!Destroying the LED with path: " << path << std::endl;
}

+ 25
- 0
LED.h View File

@ -0,0 +1,25 @@
/*led.h
Gerardo Marx April/19/2020*/
#ifndef LED_H
#define LED_H
#include<iostream>
#include<fstream>
#include<string>
#include<sstream>
class LED{
private:
std::string path;
int number;
virtual void writeLED(std::string filename, std::string value);
virtual void removeTrigger();
public:
LED(int number);
virtual void turnOn();
virtual void turnOff();
virtual void flash(std::string delayms);
virtual void outputState();
virtual ~LED();
};
#endif

+ 33
- 0
main.cpp View File

@ -0,0 +1,33 @@
/*OOP in C++ example for LEDs
Gerardo Marx April/20/2020
g++ main.cpp -o main LED.cpp*/
#include<string>
#include"LED.h"
using namespace std;
int main(int argc, char* argv[]){
if(argc!=2){
cout << "The usage is main <command>" << endl;
cout << "<command> is on, off flash or status" << endl;
cout << "e.g. main on" << endl;
return 2;
}
cout << "Starting program ..." << endl;
string cmd(argv[1]);
LED leds[4] = {LED(0), LED(1), LED(2), LED(3)};
for(int i=0; i<=3; i++){
if(cmd=="on")
leds[i].turnOn();
else if(cmd=="off")
leds[i].turnOff();
else if(cmd=="flash")
leds[i].flash("100");
else if(cmd=="status")
leds[i].outputState();
else
cout << "invalid command, please type main" << endl;
}
cout << "Program done, Thanks." << endl;
return 0;
}

Loading…
Cancel
Save