2009-05-24

HAL - Hardware Abstraction Library, or "Yes, I can do that, Dave."

Cheesy title aside, Hardware Abstraction Libraries are an attempt to bring the full power of Object Oriented Programming to bear on hardware interaction. In the Arduino world, the simplest example is HAL Class LED. Download the LED.zip file, and extract the LED folder to your Arduino/hardware/libraries folder. There are several other HAL classes available.

You can dispense with a lot of coding and pare it down to the basics.

First, include the library so you have access to the LED class.

#include<LED.h>

Declare an instance of the class (object) for the pin that controls the LED.

LED led0 = LED(6);

and then use attributes (data) to ask for information about the instance and methods (behaviors) to control the instance.

Class Attributes
  • .getState() returns current LED state
Class Methods
  • .on() turns LED on
  • .off() turns LED off
  • .toggle() changes current LED state
  • .blink() halt for millis and blink LED x times
  • .setValue() sets PWM 0-255 value
  • .fadeIn(millis) on PWM pin, fades in over millis time
  • .fadeOut(millis) on PWM pin, fades out over millis time


The sketch LEDLib demonstrates use of various LED class methods in controlling LEDs.

LEDLib
/***************************************************************
* LEDLib - Demonstrate HAL library for LED class by capt.tagon
*
* HAL Class LED library by Alexander Brevig (alphabeta)
* http://www.arduino.cc/playground/Code/LED
*
* Class Attributes
* .getState() returns current LED state
*
* Class Methods
* .on() turns LED on
* .off() turns LED off
* .toggle() changes current LED state
* .blink() halt for millis and blink LED x times
* .setValue() sets PWM 0-255 value
* .fadeIn(millis) on PWM pin, fades in over millis time
* .fadeOut(millis) on PWM pin, fades out over millis time
****************************************************************/

#include <LED.h>

//create instance of LED for each pin
LED led0 = LED(6);
LED led1 = LED(8);
LED led2 = LED(9);
LED led3 = LED(10);
LED led4 = LED(11);

void setup(){
led4.setValue(127); // LED setValue method - set PWM 50%
}

void loop(){
led0.blink(500, 10); // LED blink method -- signal start
ledDemo(); // run main demo
}

void ledDemo() {
for (int i = 0; i<6; i++) { // five iterations and then blink led0
led1.on(); // LED on method
delay(250);
led1.off(); // LED off method
delay(250);
led2.toggle(); // LED toggle method - flip LED state
led3.fadeIn(750); // LED fadeIn method - PWM to full on
led3.fadeOut(1000); // LED fadeOut method - PWM to full off
}
}

No comments:

Post a Comment