Blinking LED

Summary

Blink an LED connected to Arduino pin 13.

Code

// Bring in the MHV IO header
#include <MHV_io.h>

// Bring in the AVR delay header (needed for _delay_ms)
#include <util/delay.h>
#include <avr/power.h>

int main() {
// Disable all peripherals and enable just what we need
	power_all_disable();

// Enable output on pin 13 of the Arduino - this normally has an LED connected
	mhv_setOutput(MHV_ARDUINO_PIN_13);

	while (true) {
// Turn off the LED
		mhv_pinOff(MHV_ARDUINO_PIN_13);

// Sleep for 1/3 sec
		_delay_ms(333);

// Turn on the LED
		mhv_pinOn(MHV_ARDUINO_PIN_13);

// Sleep for 1/3 sec
		_delay_ms(333);
	}

// Main must return an int, even though we never get here
	return 0;
}

 

How it works

Line 2

The MHV_io.h header contains basic I/O functionality for MHVLib. It is needed for mhv_setOutput(), mhv_pinOff() and mhv_pinOn().

Line 5

The delay.h header belongs to AVR LibC, and contains functions for busy-loop delays, such as _delay_ms().

Line 6

The power.h header belongs to AVR LibC, and contains power management functions, such as power_all_disable().

Line 8

This declares the start of the program.

"int" tells the compiler that the function returns a signed integer, "main" is the name of the function, and "()" is the parameter list (there are no parameters in this case).

The open curly bracket "{" denotes the start of the block of code, while the closing bracket "}" on line 31 marks the end of it.

Line 10

The AVR microcontroller has a number of additional peripherals, such as timers, ADCs, etc, which consume power. Calling power_all_disable() turns off all peripherals, saving power.

Line 13

In order to enable writing to an I/O pin, it must be set to output. the function mhv_setOutput() does this. As a parameter, it takes a MHV_PIN_* (or MHV_ARDUINO_PIN_*) macro as a parameter. In this case, we set pin 13 on an Arduino compatible board to be an output pin (these commonly have an onboard LED connected to it).

Line 15

This declares a loop.

"while" tells the compiler to repeat the loop while the condition (in parentheses) evaluates to true. In this case, the value is always true, so the loop is executed indefinitely. The closing curly bracket for the loop is on line 27.

Line 17

The first operation we perform in the loop is to set Arduino pin 13 low. This will turn off the LED connected to it.

Line 20

The _delay_ms() function will perform a busy-wait for the specified number of milliseconds, in this case, 1/3 of a second.

Line 23

After waiting, we set Arduino pin 13 high, turning on the attached LED.

Line 26

We sleep for another 1/3 of a second.

Line 27

We end the loop, going back to the start.

Line 30

Since we declared the program to return an int, we must actually do so, even if it is never executed.

Line 31

This curly bracket marks the end of the program, and matches the opening bracket on line 8.