Week 08: Embedded Programming

keywords: embedded system, microcontroller, programming environment, programming language, arduino, makefile, c language

In the electronic design week, we designed our own PCB boards and uploaded the hello world program (written by Neil) onto the board. The focus of this week is to program the board to do something.

Datasheet

Datasheet is a document that summarizes the performance and other technical characteristics of a product in details that allows engineers to understand the role of the component in the overall system. Typically, datasheet is created by the manufacturer.

To program the board, I read through the datasheet of the AVR 8bits (ATtiny24/44/84) microcontroller we use at Fab Lab O. As a recap, a microcontroller is a micro computer on a single integrated circuit. A microcontroller come with a CPU (central processing unit), memory and programmable I/O (input/output) peripherals. A microcontroller is designed for embedded systems, such as automobiles, phones, appliances, etc. Typical I/O devices include switches, relays, solenoids, LED's, small or custom liquid-crystal displays, radio frequency devices, and sensors for data such as temperature, humidity, light level etc.

Based on the datasheet, here are some of the main features of AVR 8bits (ATtiny24/44/84) microcontroller:

1. High performance, low power

2. AVR enhanced RISC (Reduced Instruction Set Computer) Architecture: better real time performance; generally have lower cycles per instruction (CPI) than a complex instruction set computer

3. Twelve Programmable I/O Lines

4. Memories:

 In-System, Self-programmable Flash Program Memory (2K/4K byte): downloading and uploading program code by the MCU itself

 EEPROM Data Memory (128/256 bytes): store data processed during the run time

 SRAM Data Memory (128/256 bytes): store non-volatile data (saved regardless if the power is on/off); changeable during run-time

5. Clock:

 clock sources: built-in clock or external resonators

 clock subsystem: ADC, I/O, CPU, Flash

6. Timer/Counter:

 allows accurate program execution timing (event management) and wave generation

7. Analog Comparator:

 compares the voltage on the positive pin and the negative pin

8. 10-bit Analog-to-Digital Converter (ADC)

(*note: analog vs. digital)

9. Special Features

 On-chip Debug System

 Low Power Idle, ADC Noise Reduction, Standby and Power-down Modes

 Enhanced Power-on Reset Circuit

 Internal Calibrated Oscillator

 On-chip Temperature Sensor


Reference: J.travis russett (Fab Lab O Shanghai), Nicolo Gnecchi (Barcelona)


Arduino Software (IDE)

What is Arduino?

Arduino is an open-source electronics platform based on easy-to-use hardware and software. It was developed as an easy prototyping software for students without a background in electronics and programmings. The Arduino programming language is a simplified C language. Other than the Arduino AVR, Arduino IDE supports a range of AVR microcontrollers, including ATtiny44. HERE is a list of third-party boards supported by Arduino IDE.

Importing an ATtiny into Board Library

1. Under Preferences/Additional Boards Manager URLs, add the following URL and click OK:

https://raw.githubusercontent.com/damellis/attiny/ide-1.6.x-boards-manager/package_damellis_attiny_index.json

2. Under Tools/Board/Board Manager, download the ATtiny library “tinySPI”:

3. Your should be able to find ATtiny under Tool. Make sure Board, Clock, Processor, Port and Programmer are on the right setting.

Reference: High Low Tech


What are Sketches?

Sketches are programs written using Arduino Software (IDE). Here is an overview of a sketch:

The board I made has a LED light and a button. Arduino IDE comes with an example library with some demands that can be uploaded onto my board. Before I started uploading, I checked the Arduino pin number for LED and button. I referred to the following pin layout schema (courtesy of PighiXXX), which gives me 3 for button (pin 10 on ATtiny) and 7 for LED (pin 6 on ATtiny):

Here are some of the programs I uploaded:

1. On/Off switch (credit to David A. Mellis):

2. Fade (credit to Arduino public domain)

3. Blinking (credit to xiaowuyi)


Arduino Language

To get myself more familiar with Arduino language, I went through a Lynda tutorial that gives a foundation on Arduino boards and programming. Here are some notes I made based on the tutorial:

int name=pin number

Giving specific pin number name

pinMode (pin, mode)

Specific pin in Arduino to behave as input or output

Sets in void setup

Pin: the number of the pin to configure

Mode: Input or Output

 * INPUT: set it as input

 * INPUT_PULLUP: set it as input - using an internal pull-up resistor

 * OUTPUT: set it as output

digitalWrite (pin, value)

Outputs a value on the specific output pin

Sets in void loop

Pin: the number of the pin to specify

Value: high or low

Example:

 * turn on the LED: digitalWrite (2, HIGH)

 * turn off the LED: digitalWrite (2, LOW)

delay()

Tell the board to do nothing for a specific amount of time (milliseconds)

1000 = delay for one second

Serial

Using serial communication in serial monitor

RX and TX pins are used as serial ports; these pins cannot be used as digital I/O if you are using serial communication

Serial.begin()

Sets the data rate in bits per second

Serial.print()

Show number or text


In general variables, set int counter=(a starting number) as the initial named variable

For example, if it is int counter=0, the counter would start from 0

Then in void loop, if you set counter=counter+1, the variable would add 1 each time


ON/OFF Switch with LED Blinking

As a practice, I want to write a Arduino program that makes the led blinks when the switch is pressed (ON). When I press the switch again (OFF), the led stops blinking and turns off. Here is the first program I wrote, which did not work. The led would blink once, and then goes off. The blink is not infinite. Here is the code:

int button = 3;
int led = 7;

int state = 0;
int reading;
int previous = LOW;

long time = 0;
long debounce = 20;

void setup() {
pinMode(button, INPUT);
pinMode(led, OUTPUT);
}

void loop() {

reading = digitalRead(button);

if (reading == LOW&&state==0){
  digitalWrite(led,HIGH);
  delay(200);
  digitalWrite(led,LOW);
  delay(200);
 }

if (reading ==LOW&&state==1){
  digitalWrite(led,LOW);
state=0;  
}
 
}

The code had two issues, one is that the delay part misses a looping command that performs the infinite blink. The other problem is that it has a button command instead of a switch command. On a button command, the blinking would only be infinite if I keep my thumb on the button. If I want a switch, the command should read the ON LED as the ON switch, and the OFF LED as the OFF switch. I went back to David A. Mellis’s code in the example library. With Saverio’s suggestion, I put the blinking command into a new if line, which makes it a condition only when the button is HIGH (ON). Here is the code:

int inPin = 3;
int outPin = 7;

int state = HIGH;
int reading;
int previous = LOW;

long time = 0;
long debounce = 200;

void setup()
{
  pinMode(inPin, INPUT);
  pinMode(outPin, OUTPUT);
}

void loop()
{
  reading = digitalRead(inPin);

  // if the input just went from LOW and HIGH and we've waited long enough
  // to ignore any noise on the circuit, toggle the output pin and remember
  // the time
  if (reading == HIGH && previous == LOW && millis() - time > debounce) {
    if (state == HIGH)
      state = LOW;
    else
      state = HIGH;

    time = millis();    
  }

if(state==HIGH){
  digitalWrite(outPin,HIGH);
  delay(200);
  digitalWrite(outPin,LOW);
  delay(200);
}
  previous = reading;
}

The code worked. However, it has several limitations. One is that it would only work when the board is connected with the FabISP. In the image below you can see the led keeps blinking even when trying to turn the switch off.

Another problem is when I press the button to turn the led off, it is usually delayed. This is because it takes time for the last line in void loop to go back to the first line.


Troubleshooting

Delay is a blocking function that completely stops the microcontroller for a given time, before resuming the loop execution. A colleague at Fab Lab O suggested me to look into Timer command on Arduino, which allows the board to go back to its first line in void loop without using the delay command.When I imported the Arduino Timer library and tried to upload a Blink sketch from its library, however, it does not compile with attiny 44.

I tried to combine the button code into the current code, which does not have delay () command, but still encountered similar issues.

void loop()
{
  reading = digitalRead(inPin);

  if (reading == HIGH && previous == LOW && millis() - time > debounce) {
    if (state == HIGH)
      state = LOW;
    else
      state = HIGH;

    time = millis();    
  }

if(state==HIGH){
  digitalWrite(outPin,HIGH);
}else{
  digitalWrite(outPin,LOW);
}
  previous = reading;
}

I thought this might be an issue not related to the sketch, but the microcontroller. I studied the clock speed of the microcontroller, which affects the time it takes to run the loop() command.

According to the datasheet of ATTINY44, it is rated for maximum 4MHz operation. With its default 8.0MHz clock source setting, its initial system clock is 1MHz. According to the data sheet, there are ways to adjust the default clock speed. Under Tools/Clock, the clock speed can be selected. I chose 1MHz when I uploaded the code. Then, when I changed to 8Mhz and uploaded the sketch, the led responsed to the button faster.

It is important to point out that an Arduino Uno with ATMEGA328 is rated for 16Mhz clock (16 million instructions per second) operation, which runs the loop () command much faster than ATTINY44. The led may response faster if the clock speed is higher.

Understanding Makefile

Makefile is ran when uploading a .c format code onto the microcontroller. Instead of selecting board, programmer, clock, port under Tools as in Arduino, these are all written into the Makefile. The structure of a Makefile is quite simple. Here is the hello world Makefile Neil has written:

Every time when uploading a new code, depending on the microcontroller and the code, only a few commands need to be changed.


File from This Week

switchledblinking.zip (Arduino file for the Blinking LED with Switch)



back to Assignments