The objectives of this steps are the following:
- Understand the execution semantics associated to the board;
- Use the
avr
standard C library to code the feature; - Use
make
to automate compilation & upload the program on the board.
Here is the pattern we will use to program the Arduino: The program to embed on the board implements an infinite loop, where the main behaviour will be called. The setup
method is used to initialize the board, e.g., specify which pin is used as input or output.
#include <avr/io.h>
#include <util/delay.h>
void setup(void) {}
int main(void)
{
setup();
while(1)
{
// Business code goes here
_delay_ms(1000);
}
}
The blinking LED example
To switch a led on and off on an Arduino, we need to
- configure the port/pin where the led is connected into a reading mode (in the setup procedure)
- write a 0 (off) or a 1 (on) into the same port when required.
Here is a code skeleton to kick off the lab
#include <avr/io.h>
#include <util/delay.h>
void init(void){
DDRB |= 0b00100000;
DDRD |= 0b11111110;
}
int main(void){
init();
while(1)
{
PORTB ^= 0b00100000;
_delay_ms(1000);
}
return 0;
}
Here is some explanation of the code:
-
As the led is linked to digital pin 13, the port to be manipulated is DDRB, here every single pin from 8 to 13 is set to “input” (0) excepting bit 5 which gives an “output” access to the led (1).
-
The instruction
PORTB ^= 0b00100000;
makes the led blink, as the xor operator permits us to toggle the 5th bit from 0 to 1 or 1 to 0 each time we enter a different loop. -
To control the other pins (from 1 to 7), one can use DDRD and PORTD in a similar way.
Expected work
- Look at the code in the step1 directory, compile the code and upload it to your hardware to see the led blink;
- Implement in plain C the behaviour for the “switch the light on!” part: the code needs to read on digital 10 (use
PINB
value and some boolean operators). Use themain
to control the led (switch it on to off or off to on if the button is pressed). Do not forget to update thesetup
function if required. Test. - Implement the “count to 9!” app: write a simple function that transforms a digit into the combination of the right signals, and use it to count to 9 and then back to zero.
Stepback questions
- What can we say about the readability of this code? What are the skills required to write such a program?
- Regarding the application domain, could you characterize the expressivity? The configurability of the code to change pins or behaviour? Its debugging capabilities?
- Regarding the performance of the output code, what kind of parallelism is expressed by the use of the DDRx registers?
- What if we add additional tasks in the micro-controller code, with the same frequency? With a different frequency?
- Next: Using the arduino library