ECTE333 Tutorial 01 Solution
ECTE333 Tutorial 01 Solution
Write C program for ATmega16 to read 4×3 keypad and show on 7-segment display
Lam Phung ECTE333 Tutorial 1 4/26
Tutorial 1’s overview
1. C Development Environment
3. C Language Elements
4. Bit-wise Operators
5. Digital IO Ports
a) What is the role of the header file <avr/io.h> in a C program for the
Atmel AVR?
<avr/io.h> contains the C definitions for all registers and flags of the AVR
microcontroller.
Depending on the device selected for the project, <avr/io.h> will redirect
to a specific header file.
b) Write C code that uses inline assembly coding to create a delay of one CPU
clock cycle.
To create a delay of one clock cycle, use the assembly instruction nop:
asm volatile("nop");
return;
break;
c) Name the C keyword for forcing the next iteration of a loop to start
immediately.
continue;
switch (a){
case ‘0’:
PORTA = 0b00111111;
break;
case ‘1’ : Lab 1 example
…
case ‘9’: 7-segment display
PORTA = 0b01101111; (video)
break;
default:
PORTA = 0b00000000;
}
Lam Phung ECTE333 Tutorial 1 10/26
Q3 - C Language Elements
e) Differentiate the two C operators & and &&.
& is the bit-wise AND, used on integer data types: x & 0b00000010.
&& is the logical AND, used with logical variables: if ((x>0) && (x<10)){…}
a) Determine the number of bits and the value ranges for C variables.
char is 8-bit, int is 16-bit, long int is 32-bit (for Atmel AVR 8-bit).
Modifier ‘unsigned’ has a range of 0, 1, …, 2n-1, where n is the number of bits.
The size of char, int, long int may depend on the CPU and compiler.
Notes: To improve code portability, we can also use fixed-width data types.
#include <inttypes.h> // header file for integer data types
int8_t a; // 8-bit signed
int16_t b; // 16-bit signed
int32_t c; // 32-bit signed
uint8_t d; // 8-bit unsigned
uint16_t e; // 16-bit unsigned
C symbol | & ^
x OP 0 = … x 0 x
x OP 1 = … 1 x x
7 6 5 4 3 2 1 0 bit position
a x x x x x x x x
mask 0 1 0 1 0 1 0 1
a = a | 0b01010101;
Both methods of writing are acceptable.
a |= 0b01010101;
7 6 5 4 3 2 1 0 bit position
a x x x x x x x x
mask 0 1 0 1 0 1 0 1
a = a & 0b01010101;
Both methods of writing are acceptable.
a &= 0b01010101;
7 6 5 4 3 2 1 0
Code:
a x x x x x x x x
if ((a & 0b00000100) == 0)
mask 0 0 0 0 0 1 0 0 d = ‘9’;
else
a & mask 0 0 0 0 0 x 0 0
d = 0;
Shorter version:
d = ((a & 0b00000100) ==0)?’9’:0;
Code:
if ((a & 0b00001000) != 0)
e = 0xC3;
else
d = 0b0111 0110;
7 6 5 4 3 2 1 0 bit position
a x x x x x x x x
mask 0 0 0 0 0 0 0 1
a = a ^ 0b00000001;
Both methods of writing are acceptable.
a ^= 0b00000001;
Bit number 7 6 5 4 3 2 1 0
Assigned to na Column 1 Column 2 Column 3 Row 1 Row 2 Row 3 Row 4
int main(void){
unsigned char n, result;
n = 13; // any integer input
result = is_prime(n); // call function
For example, if user presses key ‘2’ then LED2 will be on.
Write C code to invert bits 0, 1, and 2 of a, while keeping all other bits unchanged.