In: Electrical Engineering
With a PSoC4 in PSoC creator:
Using 2 external buttons b0 and b1 to represent ‘0’ and ‘1’, design a sequence detector using C code in PSoC Creator to detect a pattern “1101”. The board LED lights up once, when the sequence “1101” occurs. Use a serial terminal (UART component and serial terminal emulator application) to display the sequence entered. Use the board button for the sequence detector reset.
// A flag variable is used to verify the sequence is correct. flag
is incremented at each correct input.
int flag = 0;
int check(int x,int y)
{
switch(flag)
{
case 0 : {
if(y==1 && x==1) //evaluates true when b1 is pressed
{
flag =1; // 1
detected
}
else flag = 0;
break;
}
case 1 : {
if(y==1 && x==1) //evaluates true when b1 is pressed
{
flag = 2; // 1 detected
}
else flag = 0; // 0 detected
break;
}
case 2 : {
if(y==0 && x==0) //evaluates true when b0 is pressed
{
flag = 3; // 0 detected
}
else if(y==1 && x==1) //evaluates true when b1 is
pressed
{
flag = 2; // 1 detected, Now
sequence is '111....' Hence flag =2;
}
else ;
break;
}
case 3 : {
if(y==1 && x==1) //evaluates true when b1 is pressed
{
flag = 4; // 1 detected
}
if(y==0 && x==0) //evaluates true when b0 is pressed
{
flag = 0; // 0 detected
}
break;
}
}
if(flag==4)
{
digitalWrite(3,HIGH);
// LED set to high
delay(2000);
digitalWrite(3,LOW);
// LED set to low
flag=2;
//'1101' detected. If las one has to be taken as 1st input of
following sequnece keep it. Else if you want to start fresh, change
value of flag to 0.
}
return 0;
}
void setup() {
//let the inputs be connected at pin 0,1
//note that PIN0 represents b0 which signifies '0' and hence should
be pulled up using a resistor to +5V. This is necessary to identify
a change from high level(5V) to low level(0).
//note that PIN1 represents b1 which signifies '1' and hence should
be pulled down using a resistor to ground. This is necessary to
identify a change from low level(0V) to high level(5V).
pinMode(0,INPUT);
pinMode(1,INPUT);
//let the LED be connected to pin 3
pinMode(3,OUTPUT);
}
void loop() {
//receive inputs and check whether the sequence is 1101
int x = digitalRead(0); //evaluates 0 when b0 is pressed and 1
when not pressed
delay(500);
// avoid debouncing
int y = digitalRead(1); //evaluates 1 when b1 is pressed and 0 when
not pressed
delay(500);
// avoid debouncing
check(x,y);
}