Traffic Light , Finite State Machine with Arduino

September 18, 2015 1 comment


This exercise with the Arduino is inspired by the course:

Embedded Systems – Shape The World

Chapter : Finite State Machines

By Dr. Jon Valvano , professor in the Department of Electrical and Computer Engineering at The University of Texas.

-The C code was adjusted to the Arduino and checked with a simulator.

-Some changes were made in labels for better understanding.

-Most of the time was dedicated to make clear ilustrations and diagrams.

As the chapter explain, the Ojetive is:

Design a traffic light controller for the intersection of two equally busy one-way streets.

The goal is to maximize traffic flow, minimize waiting time at a red light, and avoid accidents.

Traffic light Controller using two sensors and 6 lights.

Two sensors detects the presence of cars in each direction.

Two traffic lights (Red,Yellow,Green) to control the traffic flow.

List heuristics describing how the traffic light is to operate:

-If no cars are coming, stay in a GREEN state. (which one doesn’t matter).

-To change from GREEN to RED, implement a YELLOW light of 0.5 seconds.

-GREEN lights will last at least 3 seconds.

-If cars are only coming in one direction, move to and stay GREEN in that direction.

-If cars are coming in both directions, cycle through all four states.

General System Diagram:


Definition of Inputs and Output:

Two Inputs from Switches detecting presence of cars in each direction.

Six Outputs to control the Lights ( RED, YELLOW, GREEN) in each direction.


Finite State Machine Transition Table

Four states are defined:

State O: goS    Cars going in South Direction GREEN signal, West Direction with RED signal.

State 1: waitS  Cars waiting in South Direction YELLOW signal, West Direction with RED signal.

State 2: goW    Cars going in West Direction GREEN signal, South Direction with RED signal.

State 3: waitW  Cars waiting in South Direction YELLOW signal, South Direction with RED signal.


Every state is described graphically in the following form:


The complete Finite State Machine Diagram:


The wiring diagram with the Arduino UNO:


An this is the Sketch running in the simulator:

/*Traffic_Light.ino        17 SEP 2015
Implementing the traffic light controller using Finite State Machines modeling.
Using Direct Port Manipulation in the Arduino UNO.
Creating a Data Structure in C.
Port B pins 0 and 1 as inputs (Arduino pins 8 and 9):
Pin 8 = North Switch
Pin 9 = East Switch
Port D pins 2 to 7 as outputs (Arduino pins 2 to 7):
Pin 2 = North Red light
Pin 3 = North Yellow light
Pin 4 = North Green light
Pin 5 = East Red light
Pin 6 = East Yellow light
Pin 7 = East Green light
Based in: Finite State MachinesFrom:
#define SENSORS  PINB      // define the ATmega328 Port to read the switches
#define LIGHTS   PORTD     // define the ATmega328 Port to drive the lights
// Linked data structure
struct State {
  int Out; 
  int Time;  
  int Next[4];}; 
typedef const struct State STyp;
#define goS   0
#define waitS 1
#define goW   2
#define waitW 3
STyp FSM[4]={
 {0x21,3000,{goS,waitS,goS,waitS}},       //State 0 (goS)   go South.
 {0x22, 500,{goW,goW,goW,goW}},       //State 1 (waitS) wait South.
 {0x0C,3000,{goW,goW,waitW,waitW}},    //State 2 (goW)   go West.
 {0x14, 500,{goS,goS,goS,goS}}};        //State 3 (waitW) wait West.
int State;  // index to the current state 
int Input; 

void setup(){
  DDRB &= B11111100;  // Port B pins 0 and 1 as inputs (Arduino pins 8 and 9)
  DDRD |= B11111100;  // Port D pins 2 to 7 as outputs (Arduino pins 2 to 7)

void loop(){
    LIGHTS = (FSM[State].Out)<<2;    // set lights
    Input = SENSORS & B00000011;     // read sensors
    State = FSM[State].Next[Input];  


Any comment to improve this presentation will be appreciated, thanks for visiting

Arduino For Free, Almost.

September 9, 2015 Leave a comment


It is amazing how the movement initiated by the Arduino Team has led to a widespread growth of both hardware and software to develop applications using microcontrolers.

This growth has allowed to offer an Arduino UNO Compatible for only $2.84 (Including shipping to many countries).

One of Massimo Banzi’s aspirations was to have an inexpensive and easy way to create devices that interact with their environment using sensors and actuators. Mission accomplished !.



I got this Arduino UNO compatible from China (Delivered in 10 days). After installing te CH340G driver, I was able to download sketches without problems.



While taking some pictures with the Magnifier Plus-HD of my Galaxy NOTE, started to realize how well designed and assembled is this development board.



Upon inspection of this Arduino compatible we can observe :

-AMS 1117-3.3, 3.3 Volts regulator, capable of providing 1 Ampere. The regulator is capable of feeding radios and telephone modems directly, specially the ESP8266 for Internet connections.

– 25V capacitors, instead of the usual 16V used in some clones.

-16Mhz Crystal, instead of a Ceramic Resonator, which allows us to measure time more precisely.

-MICRO-USB connector. Much more common and easy to find.

-Additional holes to solder headers for:

*Double connector for the whole Arduino I/O.

* Analog pins A6 and A7.

*Serial connection (GND 5V TX RX)

*I2C onnection (GND 3.3V SCL SDA)

Originally was considered the use of the DIP-28 package rather than the SMD counterpart of the ATMEGA328 in the Arduinos, now it turns out that is less expensive to replace the whole product instead of substitute the ATMEGA328. You can buy from MOUSER or DIGIKEY the microcontroller in 10 counts for a price bigger than the complete board! . This without taking into consideration that one still has to burn the bootloader in the new device.


We are very fortunate to live in this age with plenty of sensors and controllers to experiment with.

All of this is empowering people to create new solutions to old problems, many of them will become products and prosperous business.

In honor of the enormous contribution the Arduino Team has made and continue making, I absolutely support the purchase of their products to give continuity to the great project of democratizing knowledge.

The open hardware and open software movements has allowed everyone to have access to these advances without regards of their socio-economic status.

You did it Massimo!

Categories: Uncategorized

NodeMCU Breathing LED with Arduino IDE

August 20, 2015 Leave a comment


The first sketch used to test an Arduino compatible board is Blink.
After run Blink in my new NodeMCU Development Kit,
Started experiments with the WiFi connection:
-Mini servers to control leds, servos, etc..
-Send light intensity and temperature to ThingSpeak, Xively, Plotly etc..
-Serial data bridges

The blue led in the board was used to signal the execution of a particular procedure.
Because the GPIO16 (DO) limitation to use the analogWrite() and looking to see my LED doing something else…

Inspired by the Apple’s “breathing” pattern used for the sleep indicator.
Here is the code to generate a “breathing LED”.

The Arduino code runs inside a multitasking application, the ESP8266 is running at the same time TCP and WiFi stacks.
The sketch can breake the multitasking execution if your code runs in a blocking section.
The delayMicroseconds() is one of those blocking functions, delay(0)  was used to prevent watchdog reset inside the PWM loops.

/*LED_Breathing.ino  20 AUG 2015
Using NodeMCU Development Kit V1.0
Going beyond Blink sketch to see the blue LED breathing.
A PWM modulation is made in software because GPIO16 can't
be used with analogWrite().

#define LED     D0        // Led in NodeMCU at pin GPIO16 (D0).
#define BRIGHT    350     //max led intensity (1-500)
#define INHALE    1250    //Inhalation time in milliseconds.
#define PULSE     INHALE*1000/BRIGHT
#define REST      1000    //Rest Between Inhalations.

//----- Setup function. ------------------------
void setup() {                
  pinMode(LED, OUTPUT);   // LED pin as output.    

//----- Loop routine. --------------------------
void loop() {
  //ramp increasing intensity, Inhalation: 
  for (int i=1;i<BRIGHT;i++){
    digitalWrite(LED, LOW);          // turn the LED on.
    delayMicroseconds(i*10);         // wait
    digitalWrite(LED, HIGH);         // turn the LED off.
    delayMicroseconds(PULSE-i*10);   // wait
    delay(0);                        //to prevent watchdog firing.
  //ramp decreasing intensity, Exhalation (half time):
  for (int i=BRIGHT-1;i>0;i--){
    digitalWrite(LED, LOW);          // turn the LED on.
    delayMicroseconds(i*10);          // wait
    digitalWrite(LED, HIGH);         // turn the LED off.
    delayMicroseconds(PULSE-i*10);  // wait
    delay(0);                        //to prevent watchdog firing.
  delay(REST);                       //take a rest...

NodeMCU ESP-12 Development Kit V1.0

August 15, 2015 Leave a comment

Here is my Pinout Diagram of this wonderful board for IoT development:


With added circuitry to manage the RESET and FLASH from the USB Serial Port, this board is  great for development.

After some LUA scripts and trying the Arduino IDE with it…  This Board is awesome!


I’ll continue experimenting with this one for a while…

Interrupts with the TRINKET analog comparator

July 12, 2015 Leave a comment

Here I’m sharing a working example using the analog comparator of the Adafruit’s  TRINKET (ATtiny85).



/*Trinket_comp_ISR.ino 12 JUL 2015
  Sketch to test interrupts fron the analog comparator.
  2.5 Volt in ANI0 (voltage divider).
  Potentiometer input in ANI1  An interrupt is generated in every change of the comparator output (toggle).
  The interrupt set the flag  "triggered".
  The main loop program checks for the flag, if the flag is set, test the output value  of the comparator
  and modify the state of the LED according.*/

#define LED 4 

volatile boolean triggered=false;

//------------ Analog Comparator Interrupt Routine ----------------------------
  triggered = true;
void setup(){
  ADCSRB &= ~(1<<ACME);             //Set AIN1 as the negative input (Potentiometer).
  DIDR0 |= (1<<AIN1D)|(1<<AIN0D);   // disable digital inputs.
//ACSR – Analog Comparator Control and Status Register   
  ACSR = B00001000; // comparator interrupt enabled and tripped on toggle. (compare with AN1)
      //  ||||||||_ ACIS0 ACIS1, ACIS0: Analog Comparator Interrupt Mode Select
      //  |||||||__ ACIS1 10= falling edge; 11= raising edge; 00= toggle.
      //  ||||||___ ACIC  Reserved Bit
      //  |||||____ ACIE  Interrupt Enable
      //  ||||_____ ACI   Analog Comparator Interrupt Flag (R/W), write 1 to clear it.
      //  |||______ ACO   Analog Comparator Output (read only)
      //  ||_______ ACBG  1= Bandgap Select (1.1V); 0= compare with AIN0 (pin 6)
      //  |________ ACD   Analog Comparator Disable

  digitalWrite(LED, HIGH);//LED on for 100 milliseconds.
  //Put the LED status as the analog comparator output (inverted)
  if(ACSR & (1<<ACO))digitalWrite(LED, LOW);
  else digitalWrite(LED, HIGH);

void loop(){
    if(ACSR & (1<<ACO))digitalWrite(LED, LOW);
    else digitalWrite(LED, HIGH);
    triggered= false;

Arduino and Two Stepper Motors

May 30, 2015 4 comments



This project consist in moving two stepper motors “simultaneously”.
Really there is a loop where both motors are moved “one step at a time” to reach their final position.
5 Volts steppers with external power source are used.


Here is the video in YouTube:

Here is the Sketch:


Two_Steppers.ino  30 MAY 2015

Driving two steppers concurrently with the Arduino Nano.
stepperX follows potentiometer on analog input 0.
stepperY follows potentiometer on analog input 1.
A timeout is used to turn off coils and save energy in battery
operated applications.

Arduino NANO.
Drivers: ULN2003A
Stepper Motors: 28BYJ48, 5VDC, step angle 5.625 °
                Gear reduction 64:1
                No-load starting frequency:> = 500PPS (4 rpm)
                Coil resistance 60 Ohms.               

#include <Stepper.h>

#define  STEPSREV    4096    // 64(fullsteps) * 64 (reduction ratio)
#define  SPEED       4       // motor speed (RPM)

#define  COIL_1X     11
#define  COIL_2X     9
#define  COIL_3X     10
#define  COIL_4X     8

#define  COIL_1Y     7
#define  COIL_2Y     5
#define  COIL_3Y     6
#define  COIL_4Y     4

#define  POT_X       0
#define  POT_Y       1                
#define  TIMEOUT     1000    //Turns off after 1 sec of inactivity.
#define  NOISE       8       //inmunity in steps because analog noisy readings.

// create the instances of the stepper class.
Stepper stepperX(STEPSREV, COIL_1X, COIL_2X, COIL_3X, COIL_4X);
Stepper stepperY(STEPSREV, COIL_1Y, COIL_2Y, COIL_3Y, COIL_4Y);

int potValX,potValY;           // potentiometers analog readings
int Xpos,Ypos;                 // Actual steppers positions(0-4096)->(0-360°)
int newXpos, newYpos;          // New steppers positions
unsigned long stampX, stampY;  // last move time stamped.

//============== functions ====================================================

//Read the potentiometers and map the reading to mach 360 degrees.
void readPots(){
  potValX = analogRead(POT_X);          // read POT_X value (0-1023).
  potValY = analogRead(POT_Y);          // read POT_Y value (0-1023).
  newXpos= map(potValX,0,1023,0,2047);  // Map pot X range to one stepper turn.
  newYpos= map(potValY,0,1023,0,2047);  // Map pot Y range to the stepper turn.
// Aproach stepperX to the newX position.
void aproachX(int newX){
  int Xdir = Xpos<newX ? 1 : -1;
  stepperX.step(Xdir);        // move one step in the Xdir direction.
  Xpos += Xdir;               // update Xpos.
  stampX = millis();          // stamp actual time.

// Aproach stepperY to the newY position.
void aproachY(int newY){
  int Ydir = Ypos<newY ? 1 : -1;
  stepperY.step(Ydir);        // move one step in the Ydir direction.
  Ypos += Ydir;               // update Ypos.
  stampY = millis();          // stamp actual time.

//Check for inactivity and turn off the steppers coils to save battery.
void CheckTimeout(){
  if((millis() - stampX) > TIMEOUT){   //Turn Off StepperX coils.
    digitalWrite(COIL_1X, LOW);
    digitalWrite(COIL_2X, LOW);
    digitalWrite(COIL_3X, LOW);
    digitalWrite(COIL_4X, LOW);
  if((millis() - stampY) > TIMEOUT){   //Turn Off StepperY coils.
    digitalWrite(COIL_1Y, LOW);
    digitalWrite(COIL_2Y, LOW);
    digitalWrite(COIL_3Y, LOW);
    digitalWrite(COIL_4Y, LOW);

//=================== setup ===================================================
void setup(){
  stepperX.setSpeed(SPEED);  // set the X motor speed.
  stepperY.setSpeed(SPEED);  // set the Y motor speed.
  Xpos = newXpos;
  Ypos = newYpos;

//================= main loop =================================================
void loop(){
//if diference is greater than NOISE move steppers.
  if(abs(newXpos - Xpos)> NOISE) aproachX(newXpos);
  if(abs(newYpos - Ypos)> NOISE) aproachY(newYpos);

  CheckTimeout();   //check for inactivity.









Serial Commands to Arduino ( LED control )

May 4, 2015 2 comments

Serial_LED_control A small sketch to show how to implement a command menu using the Serial Monitor of the Arduino IDE. In this example the switch statement is used to identify the received command and execute the corresponding action.

— Command list: —

? -> Print this HELP

a -> LED On  “activate”

d -> LED Off “deactivate”

s -> LED     “status”


/*Serial_LED_02.ino  Arduining 4 May 2015
Controlling the LED in pin 13 with the Serial Monitor.
--- Command list: ---
? -> Print this HELP 
a -> LED On  "activate"
d -> LED Off "deactivate"
s -> LED     "status" 

Example using the switch statement.
#define LED 13          // Pin 13 is connected to the LED
char rxChar= 0;         // RXcHAR holds the received command.

//=== function to print the command list:  ===========================
void printHelp(void){
  Serial.println("--- Command list: ---");
  Serial.println("? -> Print this HELP");  
  Serial.println("a -> LED On  \"activate\"");
  Serial.println("d -> LED Off \"deactivate\"");
  Serial.println("s -> LED     \"status\"");  
//---------------- setup ---------------------------------------------
void setup(){
  Serial.begin(9600);   // Open serial port (9600 bauds).
  pinMode(LED, OUTPUT); // Sets pin 13 as OUTPUT.
  Serial.flush();       // Clear receive buffer.
  printHelp();          // Print the command list.

//--------------- loop ----------------------------------------------- 
void loop(){
  if (Serial.available() >0){          // Check receive buffer.
    rxChar =;            // Save character received. 
    Serial.flush();                    // Clear receive buffer.
  switch (rxChar) {
    case 'a':
    case 'A':                          // If received 'a' or 'A':
	if (digitalRead(LED) == LOW){        // If LED is Off:
          digitalWrite(LED,HIGH);      // Turn On the LED.
          Serial.println("LED turned On");
        else Serial.println("LED already On!");

    case 'd':
    case 'D':                          // If received 'd' or 'D':
	if (digitalRead(LED) == HIGH){       // If LED is On:
          digitalWrite(LED,LOW);       // Turn Off the LED.
          Serial.println("LED turned Off");
        else Serial.println("LED already Off!");
    case 's':
    case 'S':                          // If received  's' or 'S':
	if (digitalRead(LED) == HIGH)        // Read LED status.
          Serial.println("LED status: On");
        else Serial.println("LED status: Off");
    case '?':                          // If received a ?:
        printHelp();                   // print the command list.
      Serial.println("' is not a command!");
// End of the Sketch.


Get every new post delivered to your Inbox.

Join 35 other followers