Finite State Machine

A Finite State Machine is anything that has a set of defined states such that it cannot be in more than one state at a time. The most obvious example of this is a stoplight, which can only be red, yellow, or green, but never red and yellow, etc. It also does not have to be electronic, though the word “machine” conjures such an image.

For my Finite State Machine project, I built a box with a button. When the button is pressed, it changes the color of the light in the box. Inside the box is a single RGB LED attached to an Arduino, which is programmed to shift through a color array when the switch changes states (from on to off or off to on). The project, though simply constructed, has a lovely multi-color glow effect from the combination of materials that I put together. I spent at least an hour layering different types of plexiglass until I found the effect that I liked the best. I ultimately assembled three layers: the first of iridescent plexi, a second of fogged, translucent plexi, and a hemisphere of plastic. This was the result:

Here is the Arduino code. The resulting light colors were not red, green, and blue as I initially thought. I think this is because I forgot to start all of the colors at LOW or 0. I did not alter the code, however, because I liked the colors that came out of it.

[code lang="c"]//Kim Ash
//Generative Systems - controller for 3 RGB LED device

//char* color[] = {"red", "green", "blue"};
//char c;
int color[] = {0, 1, 2};
String s = "";
int c;
int trueCnt = 0;
const int switchPin = 2;

int prevState = 0;
int lastCtime = 0;
int btnTime = 5000;

int red[3]    = { 100, 0, 0 };
int green[3]  = { 0, 100, 0 };
int blue[3]   = { 0, 0, 100 };

void setup()
{
  Serial.begin(9600);
  pinMode(switchPin, INPUT);
  
  for(int i=3; i<6; i++)  //setup RGB pins
  {
     pinMode(i, OUTPUT); 
  }
}

void loop()
{ 
  int currState = digitalRead(switchPin);

  if(currState == 1 && prevState == 0)
  { 
    
//    if(millis() - lastCtime < btnTime)
//    {
        trueCnt++;
        
        if(trueCnt > 2)
        {
          trueCnt = 0;
        }
//    }
    c = color[trueCnt];
    //Serial.println(s);
    
    switch(c)
    {
      case 0:
        digitalWrite(5, HIGH);
        digitalWrite(4, LOW);
        digitalWrite(3, LOW);
        break;
      
      case 1:
        digitalWrite(5, LOW);
        digitalWrite(4, HIGH);
        digitalWrite(3, LOW);
        break; 
       
       case 2:
         digitalWrite(5, LOW);
         digitalWrite(4, LOW);
         digitalWrite(3, HIGH);
         break;
    }

    prevState = currState;
    lastCtime = millis();
  }

  delay(10);

  if(prevState == 1 && currState == 0)
  {
    prevState = 0;
  }

//  delay(10);
  
//  if(millis()-lastCtime > btnTime){
//   trueCnt = 0; 
//  }
}[/code]