Lab4 Reading Switches P1
Lab4 Reading Switches P1
2
Lab 5: Reading Switches
3
Exercise 1: Control LED by polling SW1
• Write an program to control LEDs by buttons
– Read the status of SW1, if SW1 is pressed -> turn on
GREEN LED, if SW1 is released -> turn off GREEN
LED
• Reading Material
– Chapter 11, 12 & 42 of /Docs/KL46P121M48SF4RM.pdf
4
Exercise 1: Control LED by polling SW1
• SW1 and SW2 are connected as follows.[1]
SW1
Green LED
5
Exercise 1: Control LED by polling SW1
Issue: When one pin is configured as an input and nothing is
connected to the pin ->program cannot read the pin state (floating or
unknown state)
7
Exercise 1: Control LED by polling SW1
9
Exercise 1: Control LED by polling SW1
10
Exercise 1: Control LED by polling SW1
PTC->PDDR &= ;
//This sets PTC3 as an input. There are no masks defined for
each pin so we have to do it by hand
11
Exercise 1: Control LED by polling SW1
Project Flowchart with polling
12
Exercise 1: Control LED by polling SW1
• Reading a pin:
– Port Data Input Register (GPIO_PDIR) - it will return the value of an
input port in a 32 bit format. The value of a single pin can be obtained
by taking that bit from this register.
}
else /* unPressed SW1 */
{
/* do something */
}
13
Exercise 1: Control LED by polling SW1
#include "MKL46Z4.h"
void InitLED();
void InitSW();
int main()
{
InitLED(); //Initialization process for green LED
InitSW(); //Initialization process for SW1
while (1)
{
if ((PTC -> PDIR & (1<<3))==0) //If SW1 is pressed
{
//Do something
}
else
{
//Do something
}
return 0;
}
14
Exercise 1: Control LED by polling SW1
void InitLED()
{
//This enables clock to port
// This sets the Mux control of PTD5 to 001, or GPIO
//This sets PTD5 as an output.
}
void InitSW()
{
//This enables clock to port C
// This sets the Mux control of PTC3 to GPIO & enable pull up resistor & pull select
//This sets PTC3 as an input.
15
Exercise 1:
2: Control LED by polling SW1
SW
• Write an program to control LEDs by buttons
– Read the status of SW1, if SW1 is pressed -> turn on
GREEN LED, if SW1 is released -> turn off GREEN
LED
– Read the status of SW2, if SW2 is pressed -> turn off
RED LED, if SW1 is released -> turn on RED LED
• Reading Material
– Chapter 11, 12 & 42 of /Docs/KL46P121M48SF4RM.pdf
16