title: "Libaries and Inheritance" author: "Dan Goldsmith"
Libaries
Libaries
- Allow us to reuse code in multiple projects.
- Write the Code once
- Include the Libary to use it.
Example: Turning the Class into a Library
- Now we have gone to all the effort of creating our class.
- We should make it so it is usable by other programs.
- Break the code out into new files, which can be included.
- NOTE: WE cannot do this in the simulator.
Turning the code into a library
- We need two files here.
- Headerfile contains the definitions
- Source file contains the code to make things work
Libary: Header file (Flasher.h)
\scriptsize
#ifndef CUSTOM_FLASHER.H
#define CUSTOM_FLASHER.H
#include "mbed.h"
class Flasher{
private:
float delay;
DigitalOut pin;
public:
//Constructor
Flasher(PinName thePin, float delayTime);
void flash(int times);
};
endif
Library Source file (Flasher.c)
\scriptsize
#include "Flasher.h"
#include "mbed.h"
//Constructor
Flasher(PinName thePin, float delayTime) : pin(thePin) {
delay = delayTime;
}
void flash(int times){
for (int x = 0; x< times; x++){
pin= !pin;
wait(delay);
}
}
Main Program Code
\scriptsize
#include "mbed.h"
#include "Flasher.h"
int main() {
//Setup
Flasher ledOne = Flasher(LED1, 0.5)
Flasher ledTwo = Flasher(LED2, 0.25)
//Loop
while(1){
ledOne.flash(5);
ledTwo.flash(10);
}
Inheritance
Inheritance Example: A new type of Flasher.
- Lets build on the previous Flasher Example.
- Number of times the sequence happens based on some "State".
- This time we have multiple LED's
- Different types of Flasher will show different sequences.
UML Class Diagrams Inheritance
- What are our attributes?
- LED's that are attached.
- State the flasher object is in.
- What are the functions
- Flashing Sequence.
- Alternate Flashing Sequence
C++ Inheritance Implementation: Base Class
\scriptsize
class BaseFlasher{
private:
int state = 0; //Initialise the state variable
float delay;
public:
//Constructor
BaseFlasher(float delayTime) {
delay = delayTime;
}
//Run a sequence of flashes
void flash(int times){
for (int x=0; x < times; x++){
doFlash(); //Update the lights
}
}
//Note. Needs to be virtual otherwise we inherit the parent version.
virtual void doFlash(); //Actually toggle the lights
};
C++ Inheritance Implementation: Subclass
\scriptsize
class OneLedFlasher : public BaseFlasher{
public:
DigitalOut theLED; //Class Only Variable for the LED
OneLedFlasher(float delayTime, PinName thePin)
: BaseFlasher(delayTime), theLED(thePin) {
//Nothing needs to go here.
}
void doFlash() //Polymorphic
{
theLED = !theLED;
}
void alternateFlash()
{
for (int x=0; x< times; x++){
theLED = !=theLED;
wait(0.1);
theLED = != theLED;
wait(0.9);
}
};