Led-cpp BBB
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

97 lines
2.2 KiB

  1. /*OOP in C++ example for LEDs */
  2. #include<iostream>
  3. #include<fstream>
  4. #include<string>
  5. #include<sstream>
  6. using namespace std;
  7. #define LED_PATH "/sys/class/leds/beaglebone:green:usr"
  8. class LED{
  9. private:
  10. string path;
  11. int number;
  12. virtual void writeLED(string filename, string value);
  13. virtual void removeTrigger();
  14. public:
  15. LED(int number);
  16. virtual void turnOn();
  17. virtual void turnOff();
  18. virtual void flash(string delayms);
  19. virtual void outputState();
  20. virtual ~LED();
  21. };
  22. LED::LED(int number){
  23. this->number = number;
  24. ostringstream s;
  25. s << LED_PATH << number; // LED number to the Path
  26. path = string(s.str()); // convert to string
  27. }
  28. void LED::writeLED(string filename, string value){
  29. ofstream fs;
  30. fs.open((path + filename).c_str());
  31. fs << value;
  32. fs.close();
  33. }
  34. void LED::removeTrigger(){
  35. writeLED("/trigger", "none");
  36. }
  37. void LED::turnOn(){
  38. cout << "Turning LED" << number << "on" << endl;
  39. removeTrigger();
  40. writeLED("/brightness", "1");
  41. }
  42. void LED::turnOff(){
  43. cout << "Turning LED" << number << "off" << endl;
  44. removeTrigger();
  45. writeLED("/brightness", "0");
  46. }
  47. void LED::flash(string delayms ="50"){
  48. cout << "Making LED" << number << "flash" << endl;
  49. writeLED("/trigger", "timer");
  50. writeLED("/delay_on", delayms);
  51. writeLED("/delay_off", delayms);
  52. }
  53. void LED::outputState(){
  54. ifstream fs;
  55. fs.open((path + "/trigger").c_str());
  56. string line;
  57. while(getline(fs,line)) cout << line <<endl;
  58. fs.close();
  59. }
  60. LED::~LED(){
  61. cout << "!!Destroying the LED with path: " << path << endl;
  62. }
  63. int main(int argc, char* argv[]){
  64. if(argc!=2){
  65. cout << "The usage is main <command>" << endl;
  66. cout << "<command> is on, off flash or status" << endl;
  67. cout << "e.g. main on" << endl;
  68. }
  69. cout << "Starting program ..." << endl;
  70. string cmd(argv[1]);
  71. LED leds[4] = {LED(0), LED(1), LED(2), LED(3)};
  72. for(int i=0; i<=3; i++){
  73. if(cmd=="on")
  74. leds[i].turnOn();
  75. else if(cmd=="off")
  76. leds[i].turnOff();
  77. else if(cmd=="flash")
  78. leds[i].flash("100");
  79. else if(cmd=="status")
  80. leds[i].outputState();
  81. else
  82. cout << "invalid command, please type main" << endl;
  83. }
  84. cout << "Program done, Thanks." << endl;
  85. return 0;
  86. }