Example of implementing a "traffic light" with 3 leds. There are four states: red, red + yellow, green and yellow.
It uses CallSubPlus to switch to the next state after the current state duration.
	
	
	
		
		
		
			
		
		
	
	
		 
	
	
	
	
	
	
	
	
		
			
			
			
			
			
		
	
	
	
		
	
	
		
	
			
			It uses CallSubPlus to switch to the next state after the current state duration.
 
	
			
				B4X:
			
		
		
		Sub Process_Globals
   Public Serial1 As Serial
   Type State (Red As Boolean, Yellow As Boolean, Green As Boolean, Duration As UInt)
   Private Green, Yellow, Red As Pin
   Private States(4) As State
   Private CurrentStateIndex As Int = 0
End Sub
Private Sub AppStart
   Serial1.Initialize(115200)
   Log("AppStart")
   Red.Initialize(Red.A0, Red.MODE_OUTPUT)   
   Yellow.Initialize(Yellow.A1, Yellow.MODE_OUTPUT)   
   Green.Initialize(Green.A2, Green.MODE_OUTPUT)   
   'Reset the pins
   For Each p As Pin In Array As Pin(Red, Yellow, Green)
     p.DigitalWrite(False)
   Next
   SetState(States(0), True, False, False, 1000) 'red
   SetState(States(1), True, True, False, 500) 'yellow  + red
   SetState(States(2), False, False, True, 1000) 'green
   SetState(States(3), False, True, False, 500) 'yellow
   RunState(0)
End Sub
Private Sub SetState(s As State, RedValue As Boolean, YellowValue As Boolean, GreenValue As Boolean, duration As UInt)
   s.Red = RedValue
   s.Yellow = YellowValue
   s.Green = GreenValue
   s.Duration = duration
End Sub
Private Sub RunState(unused As Byte)
   Log("CurrentStateIndex: ", CurrentStateIndex)
   Dim s As State = States(CurrentStateIndex)
   Red.DigitalWrite(s.Red)
   Yellow.DigitalWrite(s.Yellow)
   Green.DigitalWrite(s.Green)
   CurrentStateIndex = (CurrentStateIndex + 1) mod States.Length
   'switch to the next state after the current state duration.
   CallSubPlus("RunState", s.Duration, 0)
End Sub 
				 
 
		 
 
		 
 
		 
 
		 
 
		 
 
		 
 
		 
 
		 
 
		 
 
		