Professional Documents
Culture Documents
Topic/Week 9
C has standard libraries for complex tasks: data type conversions, standard
input/output, long-integer arithmetic.
The Atmel AVR instruction set is designed to support C compilers: C code can be
converted efficiently to assembly code.
C tools
• We need two tools for C development: Atmel AVR Studio and WinAVR.
Atmel AVR Studio
An integrated development environment for Atmel AVR microcontroller.
It includes editor, assembler, emulator, HEX file downloader.
Available at: www.atmel.com/tools/studioarchive.aspx
WinAVR
A C compiler for AVR microcontrollers.
Can be used alone, or as a plug-in for Atmel AVR Studio.
Available at: winavr.sourceforge.net
In this example, header file <avr/io.h> contains all register definitions for the
selected AVR microcontroller.
#include <avr/io.h> // avr header file for all registers/pins
int main(void){
unsigned char i; // temporary variable
DDRA = 0x00; // set PORTA for input
DDRB = 0xFF; // set PORTB for output
PORTB = 0x00; // turn ON all LEDs initially
while(1){
// Read input from PORTA, which is connected to the 8 switches
i = PINA;
// Send output to PORTB, which is connected to the 8 LEDs
PORTB = i;
}
return 1;
}
C comments
• Comments are text that the compiler ignores.
C blocks
A C block is a group of statements enclosed by braces {}.
It is typically associated with if, switch, for, do, while, or functions.
while (1){
// Read input from PORTA - connected to the 8 switches
i = PINA;
// Send output to PORTB - connected to the 8 LEDs
PORTB = i;
}
#define Preprocessor Directive
• Preprocessor directives are not actually part
of the C language syntax, but they are
accepted as such because of their use and
familiarity.
• The preprocessor is a step separate from the
actual compilation of a program, which
happens before the actual compilation begins.
• The first C standard was released 1989 nationally in USA, by their national
standard institute ANSI. This release is called C89 or ANSI-C. From 1989-
1990 this was "the C language".
• In 1999, the C standard was revised, lots of things changed (ISO
9899:1999). This version of the standard is called C99. From 1999-2011,
this was "the C language". Most C compilers still follow this version.
ISMAIL FKE UTM 2017 27
VARIABLE SCOPE
• Constants and variables must be declared prior to their use.
• The scope of a variable is its accessibility within the program.
• A variable can be declared to have either local or global scope.
• Local variables are memory spaces allocated by the function when the
function is entered, typically on the program stack or a compiler-created
heap space and are not accessible from other functions, which means
their scope is limited to the functions in which they are declared.
– The local variable declaration (using the same identifier) can be used in
multiple functions without conflict, since the compiler sees each of these
variables as being part of that function only.
• A global or external variable is a memory space that is allocated by the
compiler and can be accessed by all the functions in a program (unlimited
scope).
– A global variable can be modified by any function and will retain its value to
be used by other functions.
<< Shift left x << 3 Shift bits in x three positions to the left
>> Shift right x >> 1 Shift bits in x one position to the right
Bitwise Operators
• Bitwise operators perform functions that will affect the operand at the bit
level.
• These operators work on integer constant (in an expression) or variables
(in an operation)
Greater than or
>= x >=5 1 is x is greater than or equal to 5, 0 otherwise
equal to
Less than or
<= x <= y 1 is x is smaller than or equal to y, 0 otherwise
equal to
/ Division x / y Divide x by y
- Negation -x Negate x
Decrement Operators Compound
Assignment Operators
• Decrement operators function in a similar manner, causing a subtraction-
of-one operation to be performed in a pre-decrement or post-decrement
fashion:
j--; // j = j-1
--j; // j = j-1
• Compound assignment operators are another method of reducing the
amount of syntax required during the construction of a program.
– Examples:
a += 3; // a = a + 3
b -= 2; // b = b – 2
c *= 5; // c = c * 5
d /= a; // d = d / a
• the operator precedence establishes the order in which expressions are evaluated
by the compiler.
• When in doubt, either nest the expressions with parentheses—to guarantee the
order of process—or look up the precedence for the operator in question.
• The primary operators like dot (.), bracket ([]), and indirection (->) are used in
ISMAIL FKE UTM 2017 58
Pointers and Arrays
Flow control in C
• By default, C statements are executed sequentially.
To change the program flow, there are six types of statements
if-else statement
Conditional
switch statement
while statement
for statement Iterative
do statement
int sum, i;
i = 1; sum = 0;
while (i <= 10){
sum = sum + i;
i = i + 1;
}
CONTROL STATEMENTS
• DO/WHILE LOOP
– The instructions in a do/while loop are always executed once before
the test on the expression determine whether or not to remain in the
loop.
do
{
statement1;
statement2;
...
} while (expression);
or
do
statement;
while (expression);
ISMAIL FKE UTM 2017 62
‘do’ statement
• General syntax
do {
statements;
} while (expression);
int sum, i;
i = 1; sum = 0; // Initialization
do{
sum = sum + i;
i = i + 1;
} while (i <= 10);
CONTROL STATEMENTS
• FOR LOOP
– A for loop construct (structure) executes a statement or a statement
block a specific number of times determined from a initialization, a
test, and an action declaration.
for (expr1; expr2; expr3)
{
statement1;
statement2;
...
}
or
for(expr1; expr2; expr3)
statement;
ISMAIL FKE UTM 2017 64
‘for’ statement
• General syntax
for (expression1; expression2; expression3){
statements;
}
– expression1 is run before the loop starts.
– expression2 is evaluated before each iteration.
– expression3 is run after each iteration.
if(expression) or
{ if(expression)
statement1; statement1;
statement2; else
} statement2;
else ...
{
statement3;
statement4;
...
}
Example
char a, b, sum;
a = 4; b = -5;
sum = a + b;
if (sum < 0)
printf(“sum is negative”);
else if (sum > 0)
printf(“sum is positive”);
else
printf(“sum is zero”);
CONTROL STATEMENTS
• SWITCH/CASE
– The switch/case statement is used to execute a statement, or a group
of statements, selected by the value of an expression.
– SWITCH identify the Variable and CASE test the variable.
– If test is TRUE the statement under the particular CASE is executed
(block “{}” structure is not recognised) and proceed to execute next
statement.
– A BREAK statement is needed to exit the SWITCH block (structure)
int sum, i;
i = 1; sum = 0;
while (i <= 10){
sum = sum + i;
i = i + 1;
if (i > 5)
break;
}
‘continue’ statement in loop
• The ‘continue’ statement skips the subsequent statements in
the code block, and forces the execution of the next iteration.
int sum, i;
i = 1; sum = 0; // Initialization
while (i <= 10){
i = i + 1;
if (i < 5)
continue;
sum = sum + i;
}
‘switch’ statement
• General syntax
switch (expression)
case constant_1:
statement_1; Use ‘break’ to separate
break; different cases.
case constant_2:
statement_2;
break;
…
case constant_n:
statement_n;
break;
default:
statement_other;
}
‘switch’ statement ─ Example
Example: Find the bit pattern to display a digit on the 7-segment LED.
To display ‘1’ 0 0 0 0 0 1 1 0
To display ‘2’ 0 1 0 1 1 0 1 1
‘switch’ statement ─ Example
#include <avr/io.h>
int main() {
unsigned char digit; // input
unsigned char led_pattern; // output
while (1) {
switch (digit) {
case ‘0’:
led_pattern = 0b00111111;
break;
case ‘1’:
led_pattern = 0b00000110;
break;
case ‘2’:
led_pattern = 0b01011011;
break;
//you can complete more cases here...
default:
}
PORTB = led_pattern; // send to PORTB and 7-segment LED (CC)
}
return 1;
}
C arrays
• An array is a list of values that have the same data type.
In C, array index starts from 0.
int main ()
{
/* local variable definition */
int a = 100;
int b = 200;
int ret;
/* calling a function to get max value */
ret = max(a, b);
printf( "Max value is : %d\n", ret );
return 0;
} ISMAIL FKE UTM 2017 83
Call by Value
• The call by value method of passing arguments to a function copies the
actual value of an argument into the formal parameter of the function.
• In this case, changes made to the parameter inside the function have no
effect on the argument.
84
Call by Reference
• The call by reference method of passing arguments to a function copies
the address of an argument into the formal parameter. Inside the function,
the address is used to access the actual argument used in the call.
• It means the changes made to the parameter affect the passed argument.
• To pass a value by reference, argument pointers are passed to the
functions just like any other value.
• So accordingly, you need to declare the function parameters as pointer
types as in the following function swap(), which exchanges the values of
the two integer variables pointed to, by their arguments.
85
#include <stdio.h>
Call by Reference
/* function prototype*/
void swap(int *x, int *y);
/* function definition to swap the values */
void swap(int *x, int *y)
{
int temp;
temp = *x; /* save the value at address x */
*x = *y; /* put y into x */
*y = temp; /* put temp into y */
return;
}
int main ()
{
/* local variable definition */
int a = 100;
int b = 200;
/* calling a function to swap the values.
* &a indicates pointer to a i.e. address of variable a and
* &b indicates pointer to b i.e. address of variable b.
*/
swap(&a, &b);
return 0;
}
86
Generic C Program
//Headers of Library used
//Declare #define for F_CPU for operating speed of ATmega32
#define F_CPU 1000000 //Define CPU speed as 1MHz
//Declare #include of all Library headers used
#include <avr/io.h>
#include <avr/pgmspace.h>
#include <util/delay.h>
#include <avr/interrupt.h>
//Declare #define of identifier that represent constant value
#define AsInput 0x00
#define AsOutput 0xff
#define EnablePullUpResistor 0xff
#define EnableINT0 1<<INT0
#define SetISC01 (1<<ISC01)
#define ClearISC00 ~(1<<ISC00)
#define NoSwitchPressed 0xffISMAIL FKE UTM 2017 87
Generic C Program
//Declare functions prototypes
void OutLED(uint8_t);
//Declare Interrupt Service Routine
INT0_vect()
{
GlobalCount++;
}
//Declare Function
void OutLED(uint8_t OutData)
{
DDRB=AsOutput;
PORTB=OutData;
_delay_ms(500);
}
{
SwData=PINA;
if(SwData==NoSwitchPressed)
OutLED(GlobalCount);
}
} ISMAIL FKE UTM 2017 89
Significant Elements to Take Note
Elements Description
; A semicolon is used to indicate the end of an expression.An
expression
in its simplest form is a semicolon alone.
{} Braces “{}” are used to delineate the beginning and the end
of the
function’s contents. Braces are also used to indicate when a
series of
statements is to be treated as a single block.
“text” Double quotes are used to mark the beginning and the end
of a text
string.
// or /* . . . */ Slash-slash or slash-star/star-slash are used as comment
delimiters. Comments are just that, a programmer’s notes.
Comments are critical to the readability of a
program.
ISMAIL FKE UTM 2017 90
Exercise
• Write a C program which is to be loaded to an
ATmega32 or ATmega32A chip. The program will
display the count of 0 to 9 at a seven segment
display and roll over to zero at a 1 second pace.
The common anode active low single digit seven
segment display is connected to port B with the
“d.p segment” pin at the MSB of port B and the
“a segment” pin at the LSB of port B. Data for the
seven segment numeric character of display will
be stored in flash memory.
S7
S6
S5
S4
S3 PButton1
S2
S1
S0
Figure Ex1
92
The Question
Referring to Figure Ex1 and “Appendix A for Laboratory sheet” program
Lab2Exp1.c,
1. Create a C GCC executable project
2. In the global scope, declare a variable that will store the look-up table
for seven segment character of 0 to 9 at the Flash Memory. Before the
“Shell loop” initialise all ports connected to switch and LEDs and Seven
Segment appropriately using a function calls. Enable internal pull-up
resistor on all input ports.
3. In the “Shell loop” read switch status.
4. By using “switch-case” control statement execute the following:
a) If SW0 is pressed, call a function that will count at the seven
segment from 0 to 9 and exit at a 500ms delay. The function will
retrieve the character from look-up table. Call a function in this
function to retrieve the character. Uses the delay function available
in util\delay.h library.
b) If SW1 is pressed, program will call another function which will
display a “Running Light” sequence pattern at the LED.
c) If other switch are pressed, its up to you what to do……
93
SUMMARY
• Header files, variables, variable storage class,
pointers, constants, bitwise/logical operators,
control statements , functions.
94