Tricolor LED

 

Code: (Example)

DEFINE OSC 4 'set clock
inv9600 con 16468'set a constant with the baudmode 9600-8-n-1-inverted:
btnClicked var byte 'value set by buttons to check against color choice
randVar VAR WORD 'random number to choose color values from arrays
choiceVar var word 'formatted version of randVar
counter var byte 'counter sets which LED user is answering

start:

'r array represents values for R in RGB. Values are 0-255
r var byte(5)
r(0)=244 'red
r(1)=0 'green
r(2)=0 'blue
r(3)=254 'orange
r(4)=254 ' yellow

'g array represents values for G in RGB. Values are 0-255
g var byte(5)
g(0)=0 'red
g(1)=254 'green
g(2)=0 'blue
g(3)=150 'orange
g(4)=0 ' yellow

'b array represents values for B in RGB. Values are 0-255
b var byte(5)
b(0)=0 'red
b(1)=0 'green
b(2)=254 'blue
b(3)=0 'orange
b(4)=254 ' yellow

'Define Buttons
input PORTB.7'red button
input PORTB.6'green button
INPUT PORTB.5'blue button
INPUT PORTB.4'orange button
INPUT PORTB.3'yellow button

'LED #1
OUTPUT PORTC.3'red
OUTPUT PORTD.0'green
OUTPUT PORTD.1'blue

'LED #2
OUTPUT PORTC.4'red
OUTPUT PORTD.3'green
OUTPUT PORTD.2'blue

'LED #3
OUTPUT PORTD.7'red
OUTPUT PORTD.6'green
OUTPUT PORTD.5'blue

'ALARM
output PORTA.1

'initialize variables
counter=0
btnClicked=5'set higher than array length
choiceVar=5'set higher than array length

main:
HIGH PORTA.1
gosub setRandom

'**********test first light**********'
while counter<1
gosub checkBtns
'PWM Pin,Duty,Cycle for LED #1
PWM PORTC.3,r(choiceVar), 1
PWM PORTD.0,g(choiceVar), 1
PWM PORTD.1,b(choiceVar), 1
wend
pause 500
btnClicked=5'reset btnClicked in case same value comes up
'Turn off LED #1
PWM PORTC.3,0, 1
PWM PORTD.0,0, 1
PWM PORTD.1,0, 1

'**********test second light**********'
gosub setRandom
while counter<2
gosub checkBtns
'PWM Pin,Duty,Cycle for LED #2
PWM PORTC.4,r(choiceVar), 1
PWM PORTD.3,g(choiceVar), 1
PWM PORTD.2,b(choiceVar), 1
wend
pause 500
btnClicked=5'reset btnClicked in case same value comes up
'Turn off LED #2
PWM PORTC.4,0, 1
PWM PORTD.3,0, 1
PWM PORTD.2,0, 1

'**********test third light**********'
gosub setRandom
while counter<3
gosub checkBtns
'PWM Pin,Duty,Cycle for LED #3
PWM PORTD.7,r(choiceVar), 1
PWM PORTD.6,g(choiceVar), 1
PWM PORTD.5,b(choiceVar), 1
wend
'Turn off LED #3
PWM PORTD.7,0, 1
PWM PORTD.6,0, 1
PWM PORTD.5,0, 1
LOW PORTA.1'turn off alarm
goto main

setRandom:
adcin 0, randVar'generate random number
choiceVar = randvar//4'limit choiceVar to 4 values
return

checkBtns:
'Check Value sent by button
if PORTB.7 then btnClicked=0'if red button clicked
if PORTB.6 then btnClicked=1'if green button clicked
if PORTB.5 then btnClicked=2'if blue button clicked
if PORTB.4 then btnClicked=3'if orange button clicked
if PORTB.3 then btnClicked=4'if yellow button clicked
if btnClicked=choiceVar then counter=counter+1
return