ELE2303 WORKSHOP 6 – State Based code design
Demo section
How to use a switch statement to build state based code.
Problem section (corrections in red since workshop was recorded)
1. Start with the sample solution project code from Workshop 5 (see next page)
OR Create a new project for a PIC18F4620 processor (assume Fosc = 10Mhz)
Include the “atraso.h” and “lcd.h”, atraso.c and lcd.c in your project as well as
your main program. Look for these in folder on study desk in workshops area.
[ Make sure you use #pragma config WDT = OFF in your main program ]
Build it to ensure it has no syntax errors.
2. Comment out the code within the while(1) loop using /* */
(commenting out code allows you to reuse the code as you need)
Place a 1000mS delay just inside the top of the while(1) loop
Declare a variable called ‘state’ as a global variable, initialise it to zero
Add a switch(state) statement within the loop
Add 3 cases within the switch statement, ending each with a ‘break;’
Compile this to ensure the syntax is correct
3. Add lines of code to read inputs, test for conditions and control outputs to achieve
the operation depicted in the state diagram below. SW0= RB0, SW1 = RB1,
MOTOR = LC2, T is a counter variable decremented once per second(loop).
4. Add appropriate LCD display messages to your program
Homework section
Measure speed on POT2 (analog input AN1) each loop, add a state such that you
can control the speed of the motor between two limits (simple On/OFF control)
idle wait
operate
SW0 = 1 / MOTOR = 0
SW0 = 0 / MOTOR = 1, T=10
T > 0 / MOTOR = 1, T- -
T = 0 / MOTOR = 1, T=30
SW1 = 0 / MOTOR = 0
SW1 = 0 / MOTOR = 0
T > 0 / MOTOR = 1, T- -
T = 0 / MOTOR = 0/*
* File: main.c
* Author: phythian
*
* Created on 10 April 2017, 3:52 PM
*/
#pragma config WDT = OFF
#define SW0 PORTBbits.RB0
#define SW1 PORTBbits.RB1
#include
#include "lcd.h"
#include "atraso.h"
#include
#include
unsigned char str[20];
unsigned char str2[6];
char c = 5;
int i = -123;
float f = 1.234;
int status;
char *buf;
void main(void)
{
TRISB = 0x03;
TRISD = 0x00;
TRISE = 0b00000000;
lcd_init();
lcd_cmd(L_L2);
itoa(str,i,10);
//buf = ftoa(f,&status);
//strcpy(str,buf);
lcd_str(str);
while(1)
{
lcd_cmd(L_L1);
strcpy(str,"pressed ");
lcd_str("press a button");
while((SW0 == 1) && (SW1 == 1));
if(SW0 == 0)
{
strcpy(str2,"RB0");
}
if(SW1 == 0)
{
strcpy(str2,"RB1");
}
lcd_cmd(L_L2);
strcat(str,str2);
lcd_str(str);
atraso_ms(1000);
lcd_cmd(L_CLR);
}
}
/*
* File: state_main.c
* Author: phythian
*
* Created on 12 May 2014, 2:45 PM
*
* a general form of a state based
program
*/
int input;
int output;
int state;
void main()
{
TRISB.b0 = 1;
output = 0;
state = 0;
while(1)
{
//delay
delay_ms(10);
// read inputs
input = PORTB.b0;
switch (state)
{
case 0 :
if (input == 1)
{
output = 1;
state = 1;
}
else
{
output = 0;
state = 0;
}
break;
case 1 :
if (input == 1)
{
output = 0;
state = 0;
}
else
{
output = 1;
state = 1;
}
break;
default: // error code here
for bad state
break;
}
}
}