Mbed writing library

From emboxit
Jump to: navigation, search
Step 1 - Refactoring....................................... Step 2 - Making it a Class

<cpp> //main.cpp

  1. include "mbed.h"

DigitalOut pin(LED2);

void flash(int n) {

   for(int i=0; i<n*2; i++) {
       pin = !pin;
       wait(0.2);
   }

}

int main() {

   // do something...
   // flash 5 times
   flash(5);
   // do something else
   // flash 2 times
   flash(2);
   // do another thing
   //
   //
   //

} </cpp>

<cpp> //main.cpp

  1. include "mbed.h"

class Flasher { public:

   Flasher(PinName pin) : _pin(pin) {  // _pin(pin) means pass pin to the DigitalOut constructor
       _pin = 0;                       // default the output to 0
   }
   void flash(int n) {
       for(int i=0; i<n*2; i++) {
           _pin = !_pin;
           wait(0.2);
       }
   }

private:

   DigitalOut _pin;

};

Flasher led(LED2); Flasher out(p6);

int main() {

   led.flash(5);
   led.flash(2);
   out.flash(10);

} </cpp>

Step 3 - Separating the code into files

<cpp> //Flasher.h

  1. ifndef MBED_FLASHER_H
  2. define MBED_FLASHER_H
  1. include "mbed.h"

class Flasher { public:

   Flasher(PinName pin);
   void flash(int n);
 

private:

   DigitalOut _pin;

};

  1. endif

</cpp>

<cpp> //Flasher.cpp

  1. include "Flasher.h"
  2. include "mbed.h"

Flasher::Flasher(PinName pin) : _pin(pin) {

   _pin = 0;

}

void Flasher::flash(int n) {

   for(int i=0; i<n*2; i++) {
       _pin = !_pin;
       wait(0.2);
   }

} // // </cpp>

<cpp> //main.cpp

  1. include "mbed.h"
  2. include "Flasher.h"

Flasher led(LED2);

int main() {

   led.flash(5);
   led.flash(2);

} // // // // // // </cpp>


TextLCD library

  • TextLCD Library uses more than one pin:






C++ classes

wikipedia C++ classes]