0% found this document useful (0 votes)
18 views

RTES Embedded Systems Week 3 Part2

Uploaded by

vruchat05
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

RTES Embedded Systems Week 3 Part2

Uploaded by

vruchat05
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 50

RTES: Embedded Systems

Week 3 Part2

sheridancollege.ca
All.

Learning outcomes
 Microcontroller System Description (Clock & System Port
configuration & Programming)
 Implement a simple PIC24 system that has an in-circuit
programming interface.
 Write C code for the PIC24 μC that implements I/O via
pushbutton switches and LEDs using a finite state machine
approach.
 Discuss the different features of the PIC24 parallel ports
such as bidirectional capability, weak pull-ups, and open-
drain outputs.

2
All.

The “for” Loop Forms

Any or all components of the for loop may be empty (missing)


• No loop counter is defined: another variable defined outside of the
loop may be used
for ( ; factor < 100; factor *= 2 ) {
… }
• No condition is defined: the break keyword is used to break the
loop
for ( int total = 0; ; ) {

if ( <test> ) {
break;
}

}
• No iteration statement is defined: one or more statements inside
the loop block move the loop to the next iteration
3
All.

while{ } Loops
while(expression)
{
statement1;
statement2;
}
Example:
k = -10;
while(k < 41)
{
Temp = k * 9/5 + 32;
k++;
The while Loop flow chart
printf(“Temp: %f \n”, Temp);
}

4
All.

The do-while Loop

Conditional loop that repeats the loop


block while the Boolean expression it
defines is true. The condition is
evaluated AFTER the loop block is
executed once
 The statements inside the loop block
will always execute at least once
 The loop stops when the Boolean
expression becomes false
 The sequence of statements that are
executed in the loop must change one
or more of the operands of the
Boolean expression
5
All.

Difference between the while and do-while loops


while loop do while loop

#include <stdio.h> #include <stdio.h>


int main() int main()
{ {
int i=0; int i=0;
while(i==1) do
{ {
printf("while vs do- printf("while vs do-while\n");
while"); }while(i==1);
} printf("Out of loop");
printf("Out of loop"); }
}
Output: Output:
Out of loop while vs do-while
Out of loop

The do-while runs at least once even if the condition is false


because the condition is evaluated, after the execution of the
body of loop.
6
All.

What is function in C program?


It is a block of statements that performs a specific task. For example, if
you are writing a C program and need to perform a same task in that
program more than once, what you are going to choose:
 Use the same set of statements every time you want to perform the
task?
 Create a function to perform that task, and just call it every time you
need to perform that task?

The answer is the second option, a good practice and a good programmer
always uses functions while writing code in C.

7
All.

What is a function?-contd.
A function is a named block of statements:
 The statements have a common purpose, solving a unique problem
 The statements may work with global variables declared at the top of the file

The statements inside the function are executed when the function is called or
invoked
 The program “remembers” where the call came from and returns to the statement
right after the call when the function completes

A function has two parts:


 Declaration: Introduces the function and provides the function’s name, return data
type, and each parameter’s name along with its data type
 Definition: Defines the function statement block, the collection of statements that
execute when the function is called

8
All.

How many types of functions?


1. Predefined function for example, printf(), scanf() , pow(), sqrt(), rand()….
2. User defined function here complete logic of the program should be
written (created) by the user.

Why we use function in C?


There are two important reasons to use function in c programming:
3. Reusability: once the function is defined, it can be reused in many parts
in your application.
4. Reduce the complexity of the program by dividing the large problem
into different small sub problems.
5. Abstraction, if you are using the function in your application, then you
do not have to worry about how its work inside ( the internal
prototype), for example, scanf function we can use it multiple times in
your code without worry how it is work.

9
All.

Why we need functions in C


 To improve the code readability.
 Debugging of the code would be easier if you use functions,
as errors are easy to be traced.
 It reduces the size of the code, duplicate set of statements
are replaced by function calls.

2024-11-26 10
All.

Function Properties
 A function has a name, return type, list of parameters, and scope
 Name identifies the function (same naming rules as variables)
 Return type
 The data type of the information returned by the function (e.g. int, double, char,
etc.)
 Used when the function calculates or generates a value
 If the function does not return a value, its return type is defined as void

 List of parameters declares the input variables needed by the function


 In C you can also do output parameters using pointers or references
 Recall scanf had variables with ‘&’ in front to get data from the function

 Scope is global by default. If you add the static keyword before the return type
then the scope of the function is that .c file (module) only.

11
All.

Function Parameters
 They are usually input variables whose values are provided by
the caller
 The list of function parameters is enclosed in( parentheses)
 A parameter is declared like a local variable
 When multiple parameters are needed they are separated
using a comma
 It is common for functions to not need any parameters
 The function declaration should use (void)
 Empty parentheses are needed when calling, e.g. printArea()

12
All.

Function Names

By convention function names start with a lower-case letter with the
following words capitalized (e.g. calculateArea)
Can contain numbers(not at the beginning)

 Same convention as a variables but should not start with _



Function names should represent an action not a thing
 They are the elements of a program that DO things
 Functions are called, they execute, they may calculate a value

 Names are usually made of two words: a verb (predicate) and noun

(object). If only one verb is used it MUST be the verb.



Have to be descriptive to express what the method does
 do(…) // what does this method do?
 calculateArea() // what does this method do?

13
All.

Function parameters

A function parameter is an input variable whose value is provided by the
caller code
 Also called arguments
 The caller supplies a value
 The runtime places the value inside the parameter variable
 The function “sees” the value through the parameter variable

The list of function parameters is enclosed in (parenthesis)

A parameter is specified like any other variable <type> <name> but
without a semicolon

When multiple parameters are needed they are separated using a comma

It is possible for functions to NOT need any parameters
 Parenthesis are still needed; nothing is placed between parenthesis

14
All.

The anatomy of a function

The sign of a
method

Function <return type> <function name> (T1 p1, T2 p2, T3 p3)


declaratio
n {
List of parameters
statement 1;
statement 2; What the method does: the set of statements that
Function
execute when the method is called (invoked)
Definition

statement n;
}

NO semicolon

NO semicolon

15
All.

What is Structure?
Structure is another user defined data type available in C that
allows to combine data items of different kinds.
 It is a collection of related variables under one name.
 The variables of may be of different data types
 Structures are used to represent a record. For example the
student record
 Keyword struct introduces the structure definition will be
outside the main program.
 Members of the same structure type must have unique
names, but two different structure types may contain
members of the same name without conflict.

16
All.

Structure Examples
Bank account Student information:
information:  student id,
 account number,  last name,
 account type  first name
 account holder  gender,
 first name
 last name
 balance

17
All.

Why structs in C?
 Assume, you want to store information about a person:
User name, citizenship number, and salary; you can create different
variables name, citNo and salary to store this information.

What if you need to store information of more than one person?


 Now, you need to create different variables for each information per
person: name1, citNo1, salary1, name2, citNo2, salary2,etc.

A better approach would be to have a collection of all related information


under a single name Person structure and use it for every person.

18
All.

Create Struct Variables


When a struct type is declared, no storage or memory is
allocated. To allocate memory of a given structure type and
work with it, we need to create variables.
struct Person
{ char name[50];
int citNo;
float salary;
};
int main()
{
struct Person person1, person2, p[20];
return 0;
}

19
All.

How to Declare a Structure Variable (Method 1)


// Structure to handle complex numbers
struct complex
{
float re;
float im;
} x, y; // Declare x and y of type complex

20
All.

How to Use a Structure Variable


// Structure to handle complex numbers
struct complex
{
float re;
float im;
} x, y; // Declare x and y of type complex

int main(void)
{
x.re = 1.25; // Initialize real part of x
x.im = 2.50; // Initialize imaginary part of x
y = x; // Set struct y equal to struct x
...

21
All.

How to Create a Structure Type with typedef


// Structure type to handle
complex numbers
typedef struct
{
float re; // Real part
float im; // Imaginary part
} complex

22
All.

How to Pass Structures to Functions


typedef struct
{
float re;
float im;
} complex;
void display(complex x)
{
printf(“(%f + j%f)\n”, x.re, x.im);
}
int main(void)
{
complex a = {1.2, 2.5};
complex b = {3.7, 4.0};
display(a);
display(b);
}

23
All.

In C, you can declare a structure by using the struct keyword together


with typedef. This allows you to more easily specify variables because
typedef creates an alias for the structure. Here's an example:
// Declaration of a structure named PORTBBITS
typedef struct {
unsigned RB0 : 1; // Bit-field for RB0
unsigned RB1 : 1; // Bit-field for RB1
unsigned RB2 : 1; // Bit-field for RB2
unsigned RB3 : 1; // Bit-field for RB3
unsigned RB4 : 1; // Bit-field for RB4
unsigned RB5 : 1; // Bit-field for RB5
unsigned RB6 : 1; // Bit-field for RB6
unsigned RB7 : 1; // Bit-field for RB7
} PORTBBITS;

int main() {
// Declaration of a variable using the PORTBBITS structure
PORTBBITS portB;

// Accessing individual bits


portB.RB0 = 1;
portB.RB1 = 0;

return 0;
}
24
All.

PIC24 Microcontroller
Basic GPI/O

25
All.

Oscillator Configurations in PIC24


Microcontrollers

Clock Sources: PIC24 microcontrollers offer various clock


sources, including:
- internal oscillator (FRC),
- external crystals, and
- PLL (Phase-Locked Loop)

26
All.

PIC24 Clock Sources

27
All.

 Internal Oscillator (FRC): Fast RC Oscillator is an internal


oscillator with good accuracy and a quick startup time. It is
suitable for applications with moderate clock precision
requirements.
 External Crystals: External crystals provide higher precision
clocking. They are commonly used when accurate timing is
crucial, such as in communication protocols.
 PLL (Phase-Locked Loop): PLL is a frequency multiplier that
allows the microcontroller to achieve the desired output
frequency (higher clock speeds). It is beneficial when the
system requires increased processing power.

28
All.

PIC24 Digital I/O


 Digital I/O (Input/Output) operations on a PIC24 microcontroller
involve interacting with the digital pins to either read the state
(voltage level) of an input pin or set the state of an output pin.

1. Digital Pins: the PIC24 microcontroller has a set of pins that can be
configured as digital inputs or outputs. Each pin can be thought of as a
binary switch that can be in one of two states: high (1) or low (0).
2. Configuration: before using a pin, you need to configure it as either an
input or an output. This is done through configuration registers. For
example, setting a pin as an output might involve configuring the
corresponding TRIS (Tri-State) register.
3. Reading from Digital Input Pins: to read the state of a digital input pin,
you would typically use a function or directly check the state of a specific
bit in a register. For example, reading the state of pin RB0

29
All.

PIC24FJ128GA Family-Pin Diagrams (100-pin TQFP) 30


All.

GPIO (General-Purpose Input/Output)

31
All.

 Each digital I/O port on a PIC24 microcontroller usually has four


registers, each of which has a specific function in setting and controlling the
behaviour of the pins:
1. TRISx (Data Direction Register): Tri-State Data Direction Control Register
for Port x
example:
TRISAbits.TRISA0 = 1; // Configures RA0 as an input
TRISBbits.TRISB1 = 0; // Configures RB1 as an output
TRISA=0x00FF; // Configures PORTA (0-7)as input and the 8-15 as output
2. PORTx (Port Register): Reads the logic state (voltage level) of each pin on
the port when configured as an input. It also provides the initial value
when configured as an output.
example:
if (PORTAbits.RA1 == 1) {
// The logic state of RA1 is high
}
3. LATx (Latch Register):Port x Latch Register, Controls the logic state (voltage
level) of each pin when configured as an output. Writing to LATx sets or
clears the corresponding output latch, which, in turn, affects the output
state.(it holds the last value written to PORTx)
example:
LATAbits.LATA3 = 1; // Sets the logic state of RA3 to high 32
All.

4. ODCx (Open-Drain Control Register):Open-Drain Control Register for


Port x. it configures specific pins on the port as open-drain outputs.
Open-drain pins can pull the voltage level low but require an external
pull-up resistor to set the voltage level high
ODCBbits.ODCB2 = 1; // Configures RB2 as an open-drain output

33
All.

 Tri-State Buffer (TSB) Review


A tri-state buffer (TSB) has input, output, and output- enable (OE) pins.
Output can either be '1', '0' or 'Z' (high impedance).

 Schmitt Trigger Input Buffer Review


Each IO input has a Schmitt trigger input buffer; this transforms slowly
rising/falling input transitions into sharp rising/falling transitions
internally.

34
All.

35
All.

 Port A and TRISA Register


Port A is an 8-bit wide, bidirectional port. Bits of the TRISA
control the PORTA pins. All Port A pins act as digital
inputs/outputs. Five of them can also be analog inputs (denoted
as AN):

36
All.

 Port D and TRISD Register


Port D is an 8-bit wide, bidirectional port. Bits of the TRISD register determine
the function of its pins. A logic one (1) in the TRISD register configures the
appropriate port pin as input.

37
All.

More on PIC24 Pin Configuration


 How to configure pins as inputs or outputs?

1. Selecting the Pin Direction:


- To configure a pin as an input, you typically set the corresponding bit in
the TRIS (TRI-State) register to 1.
- To configure a pin as an output, you set the corresponding bit in the
TRIS register to 0.

TRISAbits.TRISA0 = 1; // Configure RA0 as an input


TRISBbits.TRISB1 = 0; // Configure RB1 as an output

38
All.

2. Pin Multiplexing:
Many PIC24 microcontrollers support multiple functions on a single pin
through pin multiplexing. This allows you to assign different peripheral
functions (e.g., UART, SPI, I2C) to the same physical pin. We configure the
multiplexing by setting bits in the appropriate registers (e.g., RPINR, RPOR).

// Assigning UART2 receive to RP8 (RB8)


RPINR19bits.U2RXR = 8;

// Assigning UART2 transmit to RP9 (RB9)


RPOR4bits.RP9R = 5;

39
All.

40
All.

41
All.

void delay(unsigned int milliseconds) {


unsigned int i, j;
for (i = 0; i < 1000; i++)
for (j = 0; j < 800; j++); // Adjust this value based on your
oscillator frequency
}
• Clock Frequency (f): 32 MHz
• Inner Loop Iterations (Ninner): 800 If we want a 1-second delay with
the given delay function, how you
• Outer Loop Iterations (Nouter): 1000
can adjust the inner and outer
1. Clock Period (Tclock): iteration values accordingly?
Tclock=clock=1/32 MHz=31.25 ns
2. Inner Loop Time (Tinner):
Tinner​=Tclock​×Ninner
​=31.25ns×800
=25μs
3. Outer Loop Time (Touter):
Touter= Tinner​× Nouter
=25μs×1000=25ms
4. Total Delay Time (Ttotal​):
total =Touter=25 ms
42
All.

How to work with switches?

43
All.

Mechanical Switch Bounce

Mechanical switches can


'bounce' (cause multiple
transitions) when pressed.

Scope shot of switch bounce; in this case, only bounced once, and settled in about
~500 microseconds. After detecting a switch state change, do not want to sample
again until switch bounce has settled. Our default value of 15 milliseconds is plenty
of time. Do not want to wait too long; a human switch press is always > 50 ms in
duration

44
All.

45
All.

46
All.

47
All.

48
All.

Q: Write a C program to turn ON the lower four LEDs connected to


Port A (RA3-RA0) with the higher four LEDs connected to Port A(RA7-
RA4) alternately with a delay of 0.5 seconds.
// Function to create a delay in milliseconds
void delay(unsigned int milliseconds)
{
unsigned int i_counter, j _counter;
for (i_counter = 0; i_counter < milliseconds; i_counter ++)
for (j _counter = 0; j _counter < 16000; j _counter ++);
}

#include “config”

49
All.

// Configuration settings for the oscillator


#pragma config POSCMOD = XT
#pragma config OSCIOFNC = OFF
#pragma config FCKSM = CSDCMD
#pragma config FNOSC = PRIPLL
#pragma config IESO = OFF
#pragma config WDTPS = PS32768
#pragma config FWPSA = PR128
#pragma config WINDIS = ON
#pragma config FWDTEN = OFF
#pragma config ICS = PGx2
#pragma config GWRP = OFF
#pragma config GCP = OFF
#pragma config JTAGEN = OFF

50

You might also like