The objectives of this steps are the following:

  1. Understand the execution semantics associated to the board;
  2. Use the avr standard C library to code the feature;
  3. 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

  1. Look at the code in the step1 directory, compile the code and upload it to your hardware to see the led blink;
  2. 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 the main to control the led (switch it on to off or off to on if the button is pressed). Do not forget to update the setup function if required. Test. 
  3. 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