Instead of directly reading a sensor and then activating an activator, it is mor
ID: 3854737 • Letter: I
Question
Instead of directly reading a sensor and then activating an activator, it is more common to read a sensor, store the value read into a variable and then evaluate the variable to activate an actuator. Now that we have some tools, let’s do this in three different ways.
Problem statement: Read the four switch. When button 0 is pressed, light red LED 0. When button 1 is pressed, light red LED 1. When button 2 is pressed, light red LED 2. When button 3 is pressed, light red LED 3. Write three programs, one using each method.
a. Write down the inputs and outputs for your program
b. Generate an algorithm to solve this problem, documented in pseudocode
c. Generate a set of test inputs and test your algorithm
d. Write a C program to solve the problem
Method 1: Use four variables switch0, switch1, switch2, switch3 to store the state of each button. Test the value stored in the four variables to determine if the corresponding LED should be lit or not
Method 2: Use an array switch_state[] to store the state of each button. Test the value stored in corresponding location in the array to determine if the corresponding LED should be lit or not
Method 3: Use a single variable switch_state to store the state of each button. This will entail encoding the four button states in some manner. Hint: bitwise & and | is very useful for this type of encoding.
Explanation / Answer
Inputs :
Button 0
Button 1
BUtton 2
Button 3
Outputs :
LED0
LED1
LED2
LED3
b . Algortihm :
read switch
if ( button [0] )
LED 0 : Red Light is displayed
if(button [1])
LED 1 : Red Light is displayed
if(button [2])
LED 2: Red Light is displayed
if(button [3])
LED3 : Red Light is displayed
c .Test INput and Test Output :
b [4]= {0,1,1,1}; b[4] = {LED1,LED2,LED3 }
b[4] = {1,0,1,1}; b[4] = { LED0,LED2,LED3}
b[4] = {1,1,0,1}; b[4] = {LED0, LED1,LED3}
b[4]= {1,1,1,0}; b[4] = {LED0, LED1,LED2 }
#include <stdio.h>
int main()
{
int switch0 =0;
int switch1 =0;
int switch2 =0;
int switch3 =0;
printf(" Press button for the corresponding LED you want ");
scanf(&switch0,&switch1,&switch2,&switch3);
if(switch0 == 1)
{
printf(" LED0 is lighted ");
}
if(switch1 == 1)
{
printf(" LED1 is lighted ");
}
if(switch2 ==1 )
{
printf(" LED2 is lighted ");
}
if(switch3 ==1 )
{
printf(" LED3 is lighted ");
}
return 0;
}
Program 2 :
#include <stdio.h>
int main()
{
int switch_state[] ;
printf(" Enter position of the array corresponding to the LED you want to lit ");
scanf("%d",&i);
switch_state[i] =1;
switch(i)
{
case '0' :
printf(" LED0 is to be lighted ");
break;
case '1':
printf(" LED1 is to be lighted ");
break;
case '2' :
printf(" LED2 is to ne lighted ");
break;
case '3' :
printf(" LED3 is to be lighted ");
break;
}
return 0;
}