You are on page 1of 66

1. LEDBoardModule.

h
#ifndef LEDBoardModule_H
#define LEDBoardModule_H
// Event Definitions
#include "ES_Configure.h" /* gets us event definitions */
#include "ES_Types.h"
/* gets bool type for returns */
// typedefs for the states
// State definitions for use with the query function
typedef enum { Shot1, Shot2, WaitTimer, GameFinished } LED_t ;
// Public Function Prototypes
bool InitializeLED ( uint8_t Priority );
bool ES_PostLEDBoardSM( ES_Event ThisEvent );
ES_Event LEDSM ( ES_Event ThisEvent );
#endif /* LEDBoardModule_H */

2. LEDBoardModule.c
//Module for LEDs on Game Board:
#include
#include
#include
#include

"ES_Configure.h"
"ES_Framework.h"
"ES_DeferRecall.h"
"LEDBoardModule.h"

#include
#include
#include
#include
#include
#include
#include

"inc/hw_memmap.h"
"inc/hw_types.h"
"inc/hw_gpio.h"
"inc/hw_sysctl.h"
"driverlib/sysctl.h"
"driverlib/pin_map.h"
"driverlib/gpio.h"

#include <stdint.h>
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#include "inc/hw_memmap.h"
#include "inc/hw_types.h"
#include "inc/hw_gpio.h"
#include "inc/hw_sysctl.h"
#include "ES_Port.h"
#include "termio.h"
#include "driverlib/gpio.h"
#include "FearJoyModule.h"
#define ALL_BITS (0xff <<2)
//Modular Variables:

// Define PART_TM4C123GH6PM in project

static
static
static
static
static
static
static

uint8_t MyPriority;
LED_t CurrentState;
uint8_t FirstShot;
uint8_t SecondShot;
ES_Event FirstLit;
ES_Event SecondLit;
char LitLED;

//Modular Functions
bool InitializeLED ( uint8_t Priority );
static void InitFeedback(void);
bool ES_PostLEDBoardSM( ES_Event ThisEvent );
ES_Event LEDSM (ES_Event ThisEvent);
static void LightIt ( ES_Event ThisEvent );
static bool IsLEDLit( ES_Event ThisEvent );
static void LightLEDs (void);
static void EnablePortsLED(void);
static void PulseSRCLK(void);
static void PulseRCLK(void);
static void ButtonVibration(char input);
/****************************************************************************
Function
InitializeLED
Parameters
uint8_t : the priorty of this service
Returns
bool, false if error in initialization, true otherwise
Description
Saves away the priority, and does any
other required initialization for this service
Notes
Author
Greg Campbell 11/8/14
****************************************************************************/
bool InitializeLED ( uint8_t Priority )
{
ES_Event ThisEvent;
MyPriority = Priority;
EnablePortsLED();
//Enable Output LED Ports
InitFeedback();
//Enable Button Vibration Ports
CurrentState = GameFinished; //Start in Between Game State
LitLED = 0x00;
//Turn Off LEDs
LightLEDs();
//Send Signal Through Shift Register
ButtonVibration(0);
//Start Button Vibration Low
// post the initial transition event
ThisEvent.EventType = ES_INIT;
ES_PostLEDBoardSM(ThisEvent);
if (ES_PostToService( MyPriority, ThisEvent) == true)
{
printf("LED Board Initialized \n\r");

return true;
}else
{
return false;
}
}
/****************************************************************************
Function
ES_PostLEDBoardSM
Parameters
ES_Event ThisEvent ,the event to post to the queue
Returns
bool false if the Enqueue operation failed, true otherwise
Description
Posts an event to this state machine's queue
Notes
Author
Greg Campbell 11/8/14
****************************************************************************/
bool ES_PostLEDBoardSM( ES_Event ThisEvent )
{
return ES_PostToService( MyPriority, ThisEvent);
}
ES_Event LEDSM( ES_Event ThisEvent ){

//Bring in button fired event

LED_t NextState = CurrentState;


State
ES_Event ReturnValue;
//Initialize Return Value
ReturnValue.EventType = ES_NO_EVENT;
switch (CurrentState){
//Choose Response Based on Current State

//Initialize Next

//Set Return to No Event

case GameFinished :
//If Between Games
LitLED = 0;
//Turn Off LEDs
LightLEDs();
//Send through shift register
if (ThisEvent.EventType == EV_StartGame){
//If Event is to
Start Game
NextState = Shot1;
//Go to first shot
}
break;
case Shot1 :
shot

//If we are in the state for first

if (ThisEvent.EventType == EV_EndGame){
//If the game
ended by timeout
LitLED = 0x00;
//turn off LEDs
LightLEDs();
//Send through shift register

between games
}
else{

NextState = GameFinished;

//Go to state of in-

break;

bool IfInput1 = IsLEDLit(ThisEvent);


//Set input
to whether or not LED is already lit
if ( IfInput1 == 0 ){
//If LED isn't yet lit
//printf("Shot1 Taken \n\r");
LightIt(ThisEvent);
//Light the LED
FirstLit.EventType = ThisEvent.EventType;
//Store that this was first Lit
FirstShot = ThisEvent.EventParam;
//Store the event param (1,2,3, or 4) to check for pair later
NextState = Shot2;
//Go to state Shot2
ButtonVibration(1);
//Start Button Vibrating to show that on second
shot
break;
}
else{
//printf("Shot1 Bypassed \n\r");
//because already
lit
break;
}
}
case Shot2 :
//On to the second shot state
if (ThisEvent.EventType == EV_EndGame){
//if game timed
out
LitLED = 0x00;
//turn off LEDs
LightLEDs();
//send through shift register
NextState = GameFinished;
//Send to between game state
ButtonVibration(0);
//turn off button
vibration
break;
}
else{
bool IfInput2 = IsLEDLit(ThisEvent);
//check if second shot
already lit
if ( IfInput2 == 0 ){
//if not lit
//printf("Shot2 Taken \n\r");
LightIt(ThisEvent);
ButtonVibration(0);
//turn off button vibration
SecondShot = ThisEvent.EventParam;
//store
event param to check for pair
if(FirstShot == SecondShot){
//if successful pair
if( LitLED == 0xff ){
//if game is won
ES_Event EndGame;
EndGame.EventType=EV_EndGame;

PostFearJoySM(EndGame);
//tell Fear Joy game ended
NextState = GameFinished;
//go to between game state
LitLED = 0x00;
//turn off LEDs so that next player
doesn't know where shapes are
LightLEDs();
//send through shift register
//printf("Game Over");
}
else{
NextState = Shot1;
//if game not over, go back to Shot1 state
}
}
else{
//if pair doesn't match
SecondLit.EventType = ThisEvent.EventType;
//store which light was lit
ES_Timer_InitTimer(1,1000);
//leave lit
for 1 second
NextState = WaitTimer;
//go
to wait timer state
//Light Up Robot Eyes
}
break;
}
else{
//if second shot already lit
//printf("Shot2 Bypassed \n\r");
break;
}
}

out

state

case WaitTimer :
//if in state waiting for timer
if (ThisEvent.EventType == EV_EndGame){
//if game times
LitLED = 0x00;
//turn off LEDs
LightLEDs();
//send through shift register
NextState = GameFinished;
//go to between game

break;
}
if(ThisEvent.EventType == ES_TIMEOUT && ThisEvent.EventParam == 1)
{
//if timer 1 times out
switch (FirstLit.EventType){
//go to state depending
on which LED was lit first
case EV_1L :
switch (SecondLit.EventType){
//go
to state depending on second lit - depending on the pair, both those LEDs will
be turned off.
case EV_2L :
LitLED &= 0x5f;
LightLEDs();
break;
case EV_2R :
LitLED &= 0x6f;

case

case

case

case

to
be

to
be

LightLEDs();
break;
EV_3L :
LitLED &= 0x77;
LightLEDs();
break;
EV_3R :
LitLED &= 0x7b;
LightLEDs();
break;
EV_4L :
LitLED &= 0x7d;
LightLEDs();
break;
EV_4R :
LitLED &= 0x7e;
LightLEDs();
break;

}
break;
case EV_1R :
switch (SecondLit.EventType){
//go
state depending on second lit - depending on the pair, both those LEDs will
turned off.
case EV_2L :
LitLED &= 0x9f;
LightLEDs();
break;
case EV_2R :
LitLED &= 0xaf;
LightLEDs();
break;
case EV_3L :
LitLED &= 0xb7;
LightLEDs();
break;
case EV_3R :
LitLED &= 0xbb;
LightLEDs();
break;
case EV_4L :
LitLED &= 0xbd;
LightLEDs();
break;
case EV_4R :
LitLED &= 0xbe;
LightLEDs();
break;
}
break;
case EV_2L :
switch (SecondLit.EventType){
//go
state depending on second lit - depending on the pair, both those LEDs will
turned off.
case EV_1L :
LitLED &= 0x5f;
LightLEDs();

break;
case EV_1R :
LitLED &= 0x9f;
LightLEDs();
break;
case EV_3L :
LitLED &= 0xd7;
LightLEDs();
break;
case EV_3R :
LitLED &= 0xdb;
LightLEDs();
break;
case EV_4L :
LitLED &= 0xdd;
LightLEDs();
break;
case EV_4R :
LitLED &= 0xde;
LightLEDs();
break;
}

to
be

to
be

break;
case EV_2R :
switch (SecondLit.EventType){
//go
state depending on second lit - depending on the pair, both those LEDs will
turned off.
case EV_1L :
LitLED &= 0x6f;
LightLEDs();
break;
case EV_1R :
LitLED &= 0xaf;
LightLEDs();
break;
case EV_3L :
LitLED &= 0xe7;
LightLEDs();
break;
case EV_3R :
LitLED &= 0xeb;
LightLEDs();
break;
case EV_4L :
LitLED &= 0xed;
LightLEDs();
break;
case EV_4R :
LitLED &= 0xee;
LightLEDs();
break;
}
break;
case EV_3L :
switch (SecondLit.EventType){
//go
state depending on second lit - depending on the pair, both those LEDs will
turned off.

case EV_1L :
LitLED &= 0x77;
LightLEDs();
break;
case EV_1R :
LitLED &= 0xb7;
LightLEDs();
break;
case EV_2L :
LitLED &= 0xd7;
LightLEDs();
break;
case EV_2R :
LitLED &= 0xe7;
LightLEDs();
break;
case EV_4L :
LitLED &= 0xf5;
LightLEDs();
break;
case EV_4R :
LitLED &= 0xf6;
LightLEDs();
break;
}

break;
case EV_3R :
switch (SecondLit.EventType){
//go
to state depending on second lit - depending on the pair, both those LEDs will
be turned off.
case EV_1L :
LitLED &= 0x7b;
LightLEDs();
break;
case EV_1R :
LitLED &= 0xbb;
LightLEDs();
break;
case EV_2L :
LitLED &= 0xdb;
LightLEDs();
break;
case EV_2R :
LitLED &= 0xeb;
LightLEDs();
break;
case EV_4L :
LitLED &= 0xf9;
LightLEDs();
break;
case EV_4R :
LitLED &= 0xfa;
LightLEDs();
break;
}
break;
case EV_4L :

switch (SecondLit.EventType){
//go
to state depending on second lit - depending on the pair, both those LEDs will
be turned off.
case EV_1L :
LitLED &= 0x7d;
LightLEDs();
break;
case EV_1R :
LitLED &= 0xbd;
LightLEDs();
break;
case EV_2L :
LitLED &= 0xdd;
LightLEDs();
break;
case EV_2R :
LitLED &= 0xed;
LightLEDs();
break;
case EV_3L :
LitLED &= 0xf5;
LightLEDs();
break;
case EV_3R :
LitLED &= 0xf9;
LightLEDs();
break;
}
break;
case EV_4R :
switch (SecondLit.EventType){
//go
to state depending on second lit - depending on the pair, both those LEDs will
be turned off.
case EV_1L :
LitLED &= 0x7e;
LightLEDs();
break;
case EV_1R :
LitLED &= 0xbe;
LightLEDs();
break;
case EV_2L :
LitLED &= 0xde;
LightLEDs();
break;
case EV_2R :
LitLED &= 0xee;
LightLEDs();
break;
case EV_3L :
LitLED &= 0xf6;
LightLEDs();
break;
case EV_3R :
LitLED &= 0xfa;
LightLEDs();
break;

break;
}
NextState = Shot1;
}

// Next state will be Shot1

break;
}

CurrentState = NextState;
//No matter which state we were just in,
next timer we will be in "NextState"
return ReturnValue;
//Return NO_Event
}
void LightIt ( ES_Event ThisEvent ){
single shot - the LED that is aimed at is lit
switch (ThisEvent.EventType){
case EV_1L :
LitLED |= 0x80;
LightLEDs();
break;
case EV_1R :
LitLED |= 0x40;
LightLEDs();
break;
case EV_2L :
LitLED |= 0x20;
LightLEDs();
break;
case EV_2R :
LitLED |= 0x10;
LightLEDs();
break;
case EV_3L :
LitLED |= 0x08;
LightLEDs();
break;
case EV_3R :
LitLED |= 0x04;
LightLEDs();
break;
case EV_4L :
LitLED |= 0x02;
LightLEDs();
break;
case EV_4R :
LitLED |= 0x01;
LightLEDs();
break;
}
}

//For Event call to light

bool IsLEDLit( ES_Event ThisEvent ){


//Checks if LED is lit
bool ReturnValue = false;
//Initiate to Return False
//printf("Check if LED %d Lit \n\r",ThisEvent.EventType);
switch (ThisEvent.EventType){
//Depending on which LED is shot,
that LED is checked

case EV_1L :
if ( (LitLED & 0x80) != 0x00){
ReturnValue = true;
//printf("1L already lit \n\r");
break;
}
else{
break;
//Otherwise break and return
false (That LED is not Lit)
}
case EV_1R :
if ( (LitLED & 0x40) != 0x00){
ReturnValue = true;
//printf("1R already lit \n\r");
break;
}
else{
break;
}
case EV_2L :
if ( (LitLED & 0x20) != 0x00){
ReturnValue = true;
//printf("2L already lit \n\r");
break;
}
else{
break;
}
case EV_2R :
if ( (LitLED & 0x10) != 0x00){
ReturnValue = true;
//printf("2R already lit \n\r");
break;
}
else{
break;
}
case EV_3L :
if ( (LitLED & 0x08) != 0x00){
ReturnValue = true;
//printf("3L already lit \n\r");
break;
}
else{
break;
}
case EV_3R :
if ( (LitLED & 0x04) != 0x00){
ReturnValue = true;
//printf("3R already lit \n\r");
break;
}
else{
break;
}
case EV_4L :
if ( (LitLED & 0x02) != 0x00){

ReturnValue = true;
//printf("4L already lit \n\r");
break;
}
else{

break;
}

case EV_4R :
if ( (LitLED & 0x01) != 0x00){
ReturnValue = true;
//printf("4R already lit \n\r");
break;
}
else{
break;
}
default :
if(1){
ReturnValue = true;
//If Event was none of
these, then act light a lit LED was shot
break;
}
}
return ReturnValue;
//Return whether or not LED is
lit
}
void LightLEDs (void){
//Send LitLED through shift register
for(int i=0;i<=7;i++){
//shift throught each bit in LitLED
if (((LitLED << i )&(0x80))==0){
//if the MSB of shifted LitLED
is low
HWREG (GPIO_PORTC_BASE + (GPIO_O_DATA+ ALL_BITS)) &= BIT4LO;
//Set corresponding LED to off
}else{
//if it's high
HWREG (GPIO_PORTC_BASE + (GPIO_O_DATA+ ALL_BITS)) |= BIT4HI;
//set corresponding LED to on
}
PulseSRCLK();
//printf("Pulse S Clock");
}
PulseRCLK();
//printf("Pulse R Clock");
//printf("LEDs %x were lit \n\r",LitLED);
}
void PulseSRCLK(void){
//When you pulse S clock
HWREG (GPIO_PORTC_BASE + (GPIO_O_DATA+ ALL_BITS)) |=(GPIO_PIN_5); //Go high
HWREG (GPIO_PORTC_BASE + (GPIO_O_DATA+ ALL_BITS)) &=~(GPIO_PIN_5); //Go low
}
void PulseRCLK(void){
//When you pulse R clock
HWREG (GPIO_PORTC_BASE + (GPIO_O_DATA+ ALL_BITS)) |=(GPIO_PIN_6);
//Go high
HWREG (GPIO_PORTC_BASE + (GPIO_O_DATA+ ALL_BITS)) &=~(GPIO_PIN_6);
//Go low
}

void EnablePortsLED(void){
//Enable C 4-6 as digital output for
lights
HWREG(SYSCTL_RCGCGPIO) |= SYSCTL_RCGCGPIO_R2;
HWREG(GPIO_PORTC_BASE+GPIO_O_DEN) |= (GPIO_PIN_4 | GPIO_PIN_5 |
GPIO_PIN_6);
HWREG(GPIO_PORTC_BASE+GPIO_O_DIR) |= (GPIO_PIN_4 | GPIO_PIN_5 |
GPIO_PIN_6);
}
/****************************************************************************
Function
InitFeedback
Parameters
None
Returns
Nothing
Description
Sets Port F1 to output
Notes
Author
Hnin Ookhiin 11/15/14
****************************************************************************/
void InitFeedback() {
//Enable E2 as digital output for
vibration motors
HWREG(SYSCTL_RCGCGPIO) |= (SYSCTL_RCGCGPIO_R4);
HWREG(GPIO_PORTE_BASE+GPIO_O_DEN) |= (GPIO_PIN_2);
HWREG(GPIO_PORTE_BASE+GPIO_O_DIR) |= (GPIO_PIN_2);
}
void ButtonVibration(char input) {
//0 inputs to turn off, 1 to turn on
if (input==0) {
//printf("Vibrate Off \v\r");
HWREG (GPIO_PORTE_BASE + (GPIO_O_DATA+ ALL_BITS)) &=
~(GPIO_PIN_2);
} else if (input!=0) {
//printf("Vibrate On \v\r");
HWREG (GPIO_PORTE_BASE + (GPIO_O_DATA+ ALL_BITS)) |= (GPIO_PIN_2);
}
}

3 ButtonModule.h

/****************************************************************************
Header file for template Flat Sate Machine
based on the Gen2 Events and Services Framework
****************************************************************************/
#ifndef ButtonModule_H
#define ButtonModule_H
// Event Definitions
#include "ES_Configure.h" /* gets us event definitions */
#include "ES_Types.h"
/* gets bool type for returns */

// typedefs for the states


// State definitions for use with the query function
typedef enum { DEBOUNCING, READY2SAMPLE } ButtonState_t ;
// Public Function Prototypes
bool InitializeButton ( uint8_t Priority );
bool PostButtonService( ES_Event ThisEvent );
ES_Event RunButtonDebounceSM( ES_Event ThisEvent );
bool CheckButtonEvents(void);
#endif /* ButtonModule_H */

4. ButtonModule.c

/****************************************************************************
Module
ButtonModule.c
Revision
1.0.0
Description
This is the Module for the reset button
Notes
History
When
Who
What/Why
-------------- ---------11/9/2014
gmc
created
****************************************************************************/
/*----------------------------- Include Files -----------------------------*/
/* include header files for this state machine as well as any machines at the
next lower level in the hierarchy that are sub-machines to this machine
*/
#include "ES_Configure.h"
#include "ES_Framework.h"
#include "ButtonModule.h"
#include <stdint.h>
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#include "inc/hw_memmap.h"
#include "inc/hw_types.h"
#include "inc/hw_gpio.h"
#include "inc/hw_sysctl.h"
#include "ES_Port.h"
#include "termio.h"
#include "driverlib/gpio.h"
#include "GunFire.h"
#include "FearJoyModule.h"
#define ALL_BITS (0xff<<2)

#define INPUT_PORT HWREG(GPIO_PORTC_BASE+(GPIO_O_DATA + ALL_BITS))


#define BUTTON_PIN GPIO_PIN_7
/*----------------------------- Module Defines ----------------------------*/
/*---------------------------- Module Functions ---------------------------*/
/* prototypes for private functions for this machine.They should be functions
relevant to the behavior of this state machine
*/
static void EnablePorts1(void);
bool InitializeButton( uint8_t Priority );
bool CheckButtonEvents(void);
ES_Event RunButtonDebounceSM(ES_Event ThisEvent);
static void StartDebounceTimer(void);
/*---------------------------- Module Variables ---------------------------*/
// everybody needs a state variable, you may need others as well.
// type of state variable should match htat of enum in header file
static ButtonState_t CurrentState;
// with the introduction of Gen2, we need a module level Priority var as well
static uint8_t MyPriority;
static uint8_t LastButtonState;
/*------------------------------ Module Code ------------------------------*/
/****************************************************************************
Function
InitializeButton
Parameters
uint8_t : the priorty of this service
Returns
bool, false if error in initialization, true otherwise
Description
Initializes the button to be pressed
Notes
Author
Greg Campbell 10/29/14
****************************************************************************/
bool InitializeButton ( uint8_t Priority )
{
ES_Event ThisEvent;
MyPriority = Priority;
EnablePorts1();

//enable the port

LastButtonState = INPUT_PORT & BUTTON_PIN ; //Checks input pin current


signal and sets to LastButtonState
CurrentState = DEBOUNCING;
//Create Unsigned Character for
Current State and set to DEBOUNCING
StartDebounceTimer();
// post the initial transition event

ThisEvent.EventType = ES_INIT;
if (ES_PostToService( MyPriority, ThisEvent) == true)
{
printf("Button Initialized \n\r");
return true;
}
else
{
printf("We Failed \n\r");
return false;
}

/****************************************************************************
Function
PostButtonService
Parameters
EF_Event ThisEvent , the event to post to the queue
Returns
boolean False if the Enqueue operation failed, True otherwise
Description
Posts an event to this state machine's queue
Notes
Author
Greg Campbell 10/29/14
****************************************************************************/
bool PostButtonService( ES_Event ThisEvent )
{
return ES_PostToService( MyPriority, ThisEvent);
}
/****************************************************************************
Function
RunButtonDebounceSM
Parameters
ES_Event : the event to process
Returns
ES_Event, ES_NO_EVENT if no error ES_ERROR otherwise
Description
Acts if button is pressed, sends data to other modules
Notes
uses nested switch/case to implement the machine.
Author
Greg Campbell 10/29/14
****************************************************************************/
ES_Event RunButtonDebounceSM( ES_Event ThisEvent )
{
ES_Event ReturnEvent;
ReturnEvent.EventType = ES_NO_EVENT; // assume no errors

switch ( CurrentState )
{
case DEBOUNCING :
// If current state is DEBOUNCING
if ( ThisEvent.EventType == ES_TIMEOUT )// only respond to ES_TimeOut
{
// now put the machine into the actual initial state
CurrentState = READY2SAMPLE;
}
break;
case READY2SAMPLE :
// If current state is state one
switch ( ThisEvent.EventType )
{
case EV_ButtonPushed : //If event is event one
StartDebounceTimer();
printf("Button Pushed \n\r");
// Execute action function for state one : event one
CurrentState = DEBOUNCING;
//Decide what the next
state will be
ES_Event ButtonFire;
//This Event Happened
ES_Event GameStart;
//This Event Happened
ButtonFire.EventType = EV_FireGun;
//Event is Button Push
GameStart.EventType = EV_StartGame;
//Event is Game Start
//printf("Post Things \n\r");
PostGunFireSM(ButtonFire);
//Post that event happened to
Gun Fire SM
PostFearJoySM(GameStart);
//Post
that event happened to Fear Joy SM
break;
// repeat cases as required for relevant events
case EV_ButtonUp :
StartDebounceTimer();
printf("Button Up \n\r");
// Execute action function for state one :
event one
CurrentState = DEBOUNCING;//Decide what the next state will be
} // end switch on CurrentEvent
break;
}
return ReturnEvent;

// end switch on Current State

}
/****************************************************************************
Function
Check Button Events
Parameters
none

Returns
bool true if event was posted, false otherwise
Description
Posts an event to this state machine's queue
Notes
Author
Greg Campbell 10/27/14
****************************************************************************/
bool CheckButtonEvents(){
bool ReturnValue = false; //Set default value of return to False
uint8_t CurrentButtonState = (INPUT_PORT & BUTTON_PIN); //Checks input pin
current signal
if ( CurrentButtonState != LastButtonState){
//If Change in button state
ReturnValue = true;
//Event Happened
if (CurrentButtonState != 0){
ES_Event ThisEvent;
//This Event Happened
ThisEvent.EventType =
EV_ButtonPushed;
//It was a Button Pushed Event
PostButtonService(ThisEvent);
//Post that even happened to Button
SM
}
else{
ES_Event ThisEvent;
//This Event Happened
ThisEvent.EventType = EV_ButtonUp;
//It was a Button Up Event
PostButtonService(ThisEvent);
//Post that even happened to Button SM
}
}
LastButtonState = CurrentButtonState;
//Update Last state
return ReturnValue;
//Return bool value
}
/***************************************************************************
private functions
***************************************************************************/
/****************************************************************************
Function
EnablePorts1
Parameters
None
Returns
Nothing
Description
Sets Port A Pin 3 to Input
Notes
Author
Greg Campbell 10/29/14
****************************************************************************/

void EnablePorts1(){
HWREG(SYSCTL_RCGCGPIO) |= (SYSCTL_RCGCGPIO_R2);
//Enable Port C
HWREG(GPIO_PORTC_BASE+GPIO_O_DEN) |= (GPIO_PIN_7); //Enable Pin 7 as
Digital I/O
HWREG(GPIO_PORTC_BASE+GPIO_O_DIR) &= ~(GPIO_PIN_7); //Ensure Pin 7 is an
Input
}
/****************************************************************************
Function
StartDebounceTimer
Parameters
None
Returns
Nothing
Description
Starts the Debounce Timer Using EventChecker
Notes
Author
Greg Campbell 10/29/14
****************************************************************************/
void StartDebounceTimer(){
ES_Timer_InitTimer(11,50);
//Set Debounce timer for 50
milliseconds
}

/*------------------------------- Footnotes -------------------------------*/


/*------------------------------ End of file ------------------------------*/

5. GunX.h
#ifndef GunX_H
#define Gunx_H
// Event Definitions
#include "ES_Configure.h" /* gets us event definitions */
#include "ES_Types.h"
/* gets bool type for returns */
// typedefs for the states
// State definitions for use with the query function
typedef enum { Left, LeftMiddle, Middle,
RightMiddle, Right } GunXState_t ;
// Public Function Prototypes
bool InitGunX ( uint8_t Priority );
bool PostGunX( ES_Event ThisEvent );
ES_Event RunGunXSM( ES_Event ThisEvent );

#endif

6. Gunx.c

/*----------------------------- Include Files -----------------------------*/


/* include header files for this state machine as well as any machines at the
next lower level in the hierarchy that are sub-machines to this machine
*/
#include "ES_Configure.h"
#include "ES_Framework.h"
#include "GunX.h"
#include "ADCSWTrigger.h"
#include "inc/hw_memmap.h"
#include "inc/hw_types.h"
#include "inc/hw_gpio.h"
#include "inc/hw_sysctl.h"
#include "ES_Port.h"
#include "termio.h"
#include "driverlib/gpio.h"
#include "PWMTiva.h"
#include "GunFire.h"
#define ALL_BITS (0xff <<2)
/*----------------------------- Module Defines ----------------------------*/
#define LEFT_HIGH 860
#define LEFT_MIDDLE_HIGH 1390
#define LEFT_MIDDLE_LOW 890
#define MIDDLE_HIGH 1890
#define MIDDLE_LOW 1420
#define RIGHT_MIDDLE_HIGH 2310
#define RIGHT_MIDDLE_LOW 1920
#define RIGHT_LOW 2340
#define ServoLow 2.45
#define ServoHigh 13.15
#define ServoPotRatio 225
/*---------------------------- Module Functions ---------------------------*/
/* prototypes for private functions for this machine.They should be functions
relevant to the behavior of this state machine
*/
/*---------------------------- Module Variables ---------------------------*/
// everybody needs a state variable, you may need others as well.
// type of state variable should match htat of enum in header file
static GunXState_t CurrentState;
// with the introduction of Gen2, we need a module level Priority var as well
static uint8_t MyPriority;
static uint32_t CurrentInputState; // Create local variable CurrentInputState
static double ServoInput = 7.5;
/*------------------------------ Module Code ------------------------------*/
/****************************************************************************
Function
InitGunX
Parameters

uint8_t : the priorty of this service


Returns
bool, false if error in initialization, true otherwise
Description
Saves away the priority, sets up the initial transition and does any
other required initialization for this state machine
Notes
****************************************************************************/
bool InitGunX ( uint8_t Priority )
{
ES_Event ThisEvent;
// Initialize the MyPriority variable with the passed in parameter
MyPriority = Priority;
// Initialize the port line to receive gun x-position events (Port E pin

4)

HWREG(SYSCTL_RCGCGPIO) |= BIT4HI | BIT2HI;


HWREG(GPIO_PORTE_BASE+GPIO_O_DEN) |= BIT4HI;
// Enable pin 4 to be
digital I/O line
HWREG(GPIO_PORTE_BASE+GPIO_O_DIR) &= BIT4LO;
// Enable pin 4 to be an
input
PWM_TIVA_SetFreq(50, 1);
PWM_TIVA_SetDuty(7.5, 2);
ADC0_InitSWTriggerSeq3(9);
CurrentState = Middle;
CurrentInputState = 2042;
ES_Timer_InitTimer(15,20);
ThisEvent.EventType = ES_INIT;
if (ES_PostToService( MyPriority, ThisEvent) == true)
{
printf("GunX Initialized \n\r");
return true;
}else
{
return false;
}
}
/****************************************************************************
Function
PostGunX
Parameters
EF_Event ThisEvent , the event to post to the queue
Returns
boolean False if the Enqueue operation failed, True otherwise
Description
Posts an event to this state machine's queue
Notes
****************************************************************************/
bool PostGunX( ES_Event ThisEvent )
{
return ES_PostToService( MyPriority, ThisEvent);

}
/****************************************************************************
Function
RunGunXSM
Parameters
ES_Event : the event to process
Returns
ES_Event, ES_NO_EVENT if no error ES_ERROR otherwise
Description
add your description here
Notes
uses nested switch/case to implement the machine.
Author
J. Edward Carryer, 01/15/12, 15:23
****************************************************************************/
ES_Event RunGunXSM( ES_Event ThisEvent )
{
ES_Event ReturnEvent;
ReturnEvent.EventType = ES_NO_EVENT; // assume no errors
GunXState_t NextState; // Create local variable NextState
NextState = CurrentState; // Initialize NextState to CurrentState

switch ( CurrentState ) // Based on the current state, choose one of the


following
{
case Left : // If current state is Left
// If the posted event is TIMEOUT from GunX timer
if ( (ThisEvent.EventType == ES_TIMEOUT) &&
(ThisEvent.EventParam == 15) )
{
// Read the current input state from the input
pin
CurrentInputState = ADC0_InSeq3();
// If the current input state is greater than
the voltage limit of Left state
if ( CurrentInputState >= LEFT_HIGH )
{
// Set NextState to LeftMiddle
NextState = LeftMiddle;
// Post LtoLM to GunFiringSM
ES_Event LeftEvent;
LeftEvent.EventType = LtoLM;
PostGunFireSM( LeftEvent );
//printf("LtoLM \n\r");
}
}
break;
case LeftMiddle : // If current state is LeftMiddle
// If the posted event is TIMEOUT from GunX timer

if (
{

(ThisEvent.EventType == ES_TIMEOUT) &&


(ThisEvent.EventParam == 15)

// Read the current input state from the input

pin

CurrentInputState = ADC0_InSeq3();
// If the current input state is greater than
the voltage limit of LeftMiddle state
if ( CurrentInputState >= LEFT_MIDDLE_HIGH )
{
// Set NextState to Middle
NextState = Middle;
// Post LMtoM to GunFiringSM
ES_Event LeftMiddleEvent;
LeftMiddleEvent.EventType = LMtoM;
PostGunFireSM( LeftMiddleEvent );
//printf("LMtoM \n\r");
}
// If the current input state is less than the
voltage limit of LeftMiddle state
if ( CurrentInputState < LEFT_MIDDLE_LOW )
{
// Set NextState to Left
NextState = Left;
// Post LMtoL to GunFiringSM
ES_Event LeftMiddleEvent;
LeftMiddleEvent.EventType = LMtoL;
PostGunFireSM( LeftMiddleEvent );
//printf("LMtoL \n\r");
}
}
break;

pin

case Middle : // If current state is Middle


// If the posted event is TIMEOUT from GunX timer
if ( (ThisEvent.EventType == ES_TIMEOUT) &&
(ThisEvent.EventParam == 15) )
{
// Read the current input state from the input

CurrentInputState = ADC0_InSeq3();
// If the current input state is greater than
the voltage limit of Middle state
if ( CurrentInputState >= MIDDLE_HIGH )
{
// Set NextState to Middle
NextState = RightMiddle;
// Post MtoRM to GunFiringSM
ES_Event MiddleEvent;
MiddleEvent.EventType = MtoRM;
PostGunFireSM( MiddleEvent );
//printf("MtoRM \n\r");
}
// If the current input state is less than the
voltage limit of Middle state
if ( CurrentInputState < MIDDLE_LOW )
{

}
break;

pin

// Set NextState to LeftMiddle


NextState = LeftMiddle;
// Post MtoLM to GunFiringSM
ES_Event MiddleEvent;
MiddleEvent.EventType = MtoLM;
PostGunFireSM( MiddleEvent );
//printf("MtoLM \n\r");

case RightMiddle : // If current state is RightMiddle


// If the posted event is TIMEOUT from GunX timer
if ( (ThisEvent.EventType == ES_TIMEOUT) &&
(ThisEvent.EventParam == 15) )
{
// Read the current input state from the input

CurrentInputState = ADC0_InSeq3();
// If the current input state is greater than
the voltage limit of RightMiddle state
if ( CurrentInputState >= RIGHT_MIDDLE_HIGH )
{
// Set NextState to Right
NextState = Right;
// Post RMtoR to GunFiringSM
ES_Event RightMiddleEvent;
RightMiddleEvent.EventType = RMtoR;
PostGunFireSM( RightMiddleEvent );
//printf("RMtoR \n\r");
}
// If the current input state is less than the
voltage limit of RightMiddle state
if ( CurrentInputState < RIGHT_MIDDLE_LOW )
{
// Set NextState to Middle
NextState = Middle;
// Post RMtoM to GunFiringSM
ES_Event RightMiddleEvent;
RightMiddleEvent.EventType = RMtoM;
PostGunFireSM( RightMiddleEvent );
//printf("RMtoM \n\r");
}
}
break;
case Right : // If current state is Right
// If the posted event is TIMEOUT from GunX timer
if ( (ThisEvent.EventType == ES_TIMEOUT) &&
(ThisEvent.EventParam == 15) )
{
// Read the current input state from the input
pin
voltage limit of Right state

CurrentInputState = ADC0_InSeq3();
// If the current input state is less than the
if ( CurrentInputState < RIGHT_LOW )

// Set NextState to RightMiddle


NextState = RightMiddle;
// Post RtoRM to GunFiringSM
ES_Event RightEvent;
RightEvent.EventType = RtoRM;
PostGunFireSM( RightEvent );
//printf("RtoRM \n\r");

break;
default :
;
}

ServoInput = ServoHigh - (float)CurrentInputState/ServoPotRatio;


if (ServoInput < ServoLow){
//Just in Case Servo Has
Overly Low Input (from bad Pot Reading)
ServoInput = ServoLow;
}
if (ServoInput > ServoHigh){
//Just in Case
Servo Has Overly High Input (from bad Pot Reading)
ServoInput = ServoHigh;
}
PWM_TIVA_SetDuty(ServoInput, 2);
//printf("Current Input is %d \n\r",CurrentInputState);
ES_Timer_InitTimer(15,20);
CurrentState = NextState;
return ReturnEvent;
}

7. GunFire.h

#ifndef GunFire_H
#define GunFire_H
// Event Definitions
#include "ES_Configure.h" /* gets us event definitions */
#include "ES_Types.h"
/* gets bool type for returns */
// typedefs for the states
// State definitions for use with the query function
typedef enum {LeftUp, LeftDown, LeftMiddleUp, LeftMiddleDown,
MiddleUp, MiddleDown, RightMiddleUp,
RightMiddleDown, RightUp, RightDown } GunFireState_t ;
// Public Function Prototypes
bool InitGunFire ( uint8_t Priority );
bool PostGunFireSM( ES_Event ThisEvent );
ES_Event RunGunFireSM( ES_Event ThisEvent );
GunFireState_t QueryGunFireSM ( void );
#endif /* FSMTemplate_H */

8. GunFire.c
/*----------------------------- Include Files -----------------------------*/
/* include header files for this state machine as well as any machines at the
next lower level in the hierarchy that are sub-machines to this machine
*/
#include "ES_Configure.h"
#include "ES_Framework.h"
#include "GunX.h"
#include "ADCSWTrigger.h"
#include "inc/hw_memmap.h"
#include "inc/hw_types.h"
#include "inc/hw_gpio.h"
#include "inc/hw_sysctl.h"
#include "ES_Port.h"
#include "termio.h"
#include "driverlib/gpio.h"
#include "PWMTiva.h"
#include "GunFire.h"
#define ALL_BITS (0xff <<2)
/*----------------------------- Module Defines ----------------------------*/
#define LEFT_HIGH 860
#define LEFT_MIDDLE_HIGH 1390
#define LEFT_MIDDLE_LOW 890
#define MIDDLE_HIGH 1890
#define MIDDLE_LOW 1420
#define RIGHT_MIDDLE_HIGH 2310
#define RIGHT_MIDDLE_LOW 1920
#define RIGHT_LOW 2340
#define ServoLow 2.45
#define ServoHigh 13.15
#define ServoPotRatio 225
/*---------------------------- Module Functions ---------------------------*/
/* prototypes for private functions for this machine.They should be functions
relevant to the behavior of this state machine
*/
/*---------------------------- Module Variables ---------------------------*/
// everybody needs a state variable, you may need others as well.
// type of state variable should match htat of enum in header file
static GunXState_t CurrentState;
// with the introduction of Gen2, we need a module level Priority var as well
static uint8_t MyPriority;
static uint32_t CurrentInputState; // Create local variable CurrentInputState
static double ServoInput = 7.5;
/*------------------------------ Module Code ------------------------------*/
/****************************************************************************
Function
InitGunX
Parameters
uint8_t : the priorty of this service

Returns
bool, false if error in initialization, true otherwise
Description
Saves away the priority, sets up the initial transition and does any
other required initialization for this state machine
Notes
Author
J. Edward Carryer, 10/23/11, 18:55
****************************************************************************/
bool InitGunX ( uint8_t Priority )
{
ES_Event ThisEvent;
// Initialize the MyPriority variable with the passed in parameter
MyPriority = Priority;
// Initialize the port line to receive gun x-position events (Port E pin

4)

HWREG(SYSCTL_RCGCGPIO) |= BIT4HI | BIT2HI;


HWREG(GPIO_PORTE_BASE+GPIO_O_DEN) |= BIT4HI;
// Enable pin 4 to be
digital I/O line
HWREG(GPIO_PORTE_BASE+GPIO_O_DIR) &= BIT4LO;
// Enable pin 4 to be an
input
PWM_TIVA_SetFreq(50, 1);
PWM_TIVA_SetDuty(7.5, 2);
ADC0_InitSWTriggerSeq3(9);
CurrentState = Middle;
CurrentInputState = 2042;
ES_Timer_InitTimer(15,20);
ThisEvent.EventType = ES_INIT;
if (ES_PostToService( MyPriority, ThisEvent) == true)
{
printf("GunX Initialized \n\r");
return true;
}else
{
return false;
}
}
/****************************************************************************
Function
PostGunX
Parameters
EF_Event ThisEvent , the event to post to the queue
Returns
boolean False if the Enqueue operation failed, True otherwise
Description
Posts an event to this state machine's queue
Notes
Author

J. Edward Carryer, 10/23/11, 19:25


****************************************************************************/
bool PostGunX( ES_Event ThisEvent )
{
return ES_PostToService( MyPriority, ThisEvent);
}
/****************************************************************************
Function
RunGunXSM
Parameters
ES_Event : the event to process
Returns
ES_Event, ES_NO_EVENT if no error ES_ERROR otherwise
Description
add your description here
Notes
uses nested switch/case to implement the machine.
Author
J. Edward Carryer, 01/15/12, 15:23
****************************************************************************/
ES_Event RunGunXSM( ES_Event ThisEvent )
{
ES_Event ReturnEvent;
ReturnEvent.EventType = ES_NO_EVENT; // assume no errors
GunXState_t NextState; // Create local variable NextState
NextState = CurrentState; // Initialize NextState to CurrentState

switch ( CurrentState ) // Based on the current state, choose one of the


following
{
case Left : // If current state is Left
// If the posted event is TIMEOUT from GunX timer
if ( (ThisEvent.EventType == ES_TIMEOUT) &&
(ThisEvent.EventParam == 15) )
{
// Read the current input state from the input
pin
CurrentInputState = ADC0_InSeq3();
// If the current input state is greater than
the voltage limit of Left state
if ( CurrentInputState >= LEFT_HIGH )
{
// Set NextState to LeftMiddle
NextState = LeftMiddle;
// Post LtoLM to GunFiringSM
ES_Event LeftEvent;
LeftEvent.EventType = LtoLM;
PostGunFireSM( LeftEvent );
//printf("LtoLM \n\r");
}

break;

pin

case LeftMiddle : // If current state is LeftMiddle


// If the posted event is TIMEOUT from GunX timer
if ( (ThisEvent.EventType == ES_TIMEOUT) &&
(ThisEvent.EventParam == 15) )
{
// Read the current input state from the input

CurrentInputState = ADC0_InSeq3();
// If the current input state is greater than
the voltage limit of LeftMiddle state
if ( CurrentInputState >= LEFT_MIDDLE_HIGH )
{
// Set NextState to Middle
NextState = Middle;
// Post LMtoM to GunFiringSM
ES_Event LeftMiddleEvent;
LeftMiddleEvent.EventType = LMtoM;
PostGunFireSM( LeftMiddleEvent );
//printf("LMtoM \n\r");
}
// If the current input state is less than the
voltage limit of LeftMiddle state
if ( CurrentInputState < LEFT_MIDDLE_LOW )
{
// Set NextState to Left
NextState = Left;
// Post LMtoL to GunFiringSM
ES_Event LeftMiddleEvent;
LeftMiddleEvent.EventType = LMtoL;
PostGunFireSM( LeftMiddleEvent );
//printf("LMtoL \n\r");
}
}
break;
case Middle : // If current state is Middle
// If the posted event is TIMEOUT from GunX timer
if ( (ThisEvent.EventType == ES_TIMEOUT) &&
(ThisEvent.EventParam == 15) )
{
// Read the current input state from the input
pin

CurrentInputState = ADC0_InSeq3();
// If the current input state is greater than
the voltage limit of Middle state
if ( CurrentInputState >= MIDDLE_HIGH )
{
// Set NextState to Middle
NextState = RightMiddle;
// Post MtoRM to GunFiringSM
ES_Event MiddleEvent;
MiddleEvent.EventType = MtoRM;
PostGunFireSM( MiddleEvent );
//printf("MtoRM \n\r");

}
// If the current input state is less than the
voltage limit of Middle state

if ( CurrentInputState < MIDDLE_LOW )


{
// Set NextState to LeftMiddle
NextState = LeftMiddle;
// Post MtoLM to GunFiringSM
ES_Event MiddleEvent;
MiddleEvent.EventType = MtoLM;
PostGunFireSM( MiddleEvent );
//printf("MtoLM \n\r");
}

break;
case RightMiddle : // If current state is RightMiddle
// If the posted event is TIMEOUT from GunX timer
if ( (ThisEvent.EventType == ES_TIMEOUT) &&
(ThisEvent.EventParam == 15) )
{
// Read the current input state from the input
pin

CurrentInputState = ADC0_InSeq3();
// If the current input state is greater than
the voltage limit of RightMiddle state
if ( CurrentInputState >= RIGHT_MIDDLE_HIGH )
{
// Set NextState to Right
NextState = Right;
// Post RMtoR to GunFiringSM
ES_Event RightMiddleEvent;
RightMiddleEvent.EventType = RMtoR;
PostGunFireSM( RightMiddleEvent );
//printf("RMtoR \n\r");
}
// If the current input state is less than the
voltage limit of RightMiddle state
if ( CurrentInputState < RIGHT_MIDDLE_LOW )
{
// Set NextState to Middle
NextState = Middle;
// Post RMtoM to GunFiringSM
ES_Event RightMiddleEvent;
RightMiddleEvent.EventType = RMtoM;
PostGunFireSM( RightMiddleEvent );
//printf("RMtoM \n\r");
}
}
break;
case Right : // If current state is Right
// If the posted event is TIMEOUT from GunX timer
if ( (ThisEvent.EventType == ES_TIMEOUT) &&
(ThisEvent.EventParam == 15) )
{

// Read the current input state from the input

pin

CurrentInputState = ADC0_InSeq3();
// If the current input state is less than the
voltage limit of Right state

if ( CurrentInputState < RIGHT_LOW )


{
// Set NextState to RightMiddle
NextState = RightMiddle;
// Post RtoRM to GunFiringSM
ES_Event RightEvent;
RightEvent.EventType = RtoRM;
PostGunFireSM( RightEvent );
//printf("RtoRM \n\r");
}

break;
default :
;
}

ServoInput = ServoHigh - (float)CurrentInputState/ServoPotRatio;


if (ServoInput < ServoLow){
//Just in Case Servo Has
Overly Low Input (from bad Pot Reading)
ServoInput = ServoLow;
}
if (ServoInput > ServoHigh){
//Just in Case
Servo Has Overly High Input (from bad Pot Reading)
ServoInput = ServoHigh;
}
PWM_TIVA_SetDuty(ServoInput, 2);
//printf("Current Input is %d \n\r",CurrentInputState);
ES_Timer_InitTimer(15,20);
CurrentState = NextState;
return ReturnEvent;
}

9. RobotTimer.h
#ifndef RobotTimer_H
#define RobotTimer_H
#include "ES_Configure.h"
#include "ES_Types.h"
// Public Function Prototypes
bool InitRobotTimer ( uint8_t Priority );
bool PostRobotTimer( ES_Event ThisEvent );
ES_Event RunRobotTimer( ES_Event ThisEvent );
#endif

10. RobotTimer.c
/*----------------------------- Include Files -----------------------------*/
/* include header files for the framework and this service
*/
#include "ES_Configure.h"
#include "ES_Framework.h"
#include "ES_DeferRecall.h"
#include "ES_PostList.h"
#include "inc/hw_memmap.h"
#include "inc/hw_types.h"
#include "inc/hw_gpio.h"
#include "inc/hw_sysctl.h"
#include "driverlib/sysctl.h"
#include "driverlib/pin_map.h"
#include "driverlib/gpio.h"
#include "RobotTimer.h"
#define ALL_BITS (0xff <<2)
/*---------------------------- Module Functions ---------------------------*/
/* prototypes for private functions for this service.They should be functions
relevant to the behavior of this service
*/
static void InitLED(void);
static void PulSRCLK(void);
static void PulRCLK(void);
static void LightupLEDtimer(void);
static void RobotVibration(char);
static void InitRobot(void);
/*---------------------------- Module Variables ---------------------------*/
// with the introduction of Gen2, we need a module level Priority variable
static uint8_t MyPriority;
static uint16_t TimeLED;//=0x0000;
//Start InitRobotTimer function
bool InitRobotTimer ( uint8_t Priority )
{
ES_Event ThisEvent;
//
if( ThisEvent.EventType == EV_StartGame){
//Initialize the MyPriority variable with the passed in parameter.
MyPriority = Priority;
//Set EventType = ES_Init
ThisEvent.EventType = ES_INIT;
//Call InitLED function to Initialize LED pin
InitLED();
//Call InitRobot fucntion to initialize robot pin
InitRobot();
// set input data to shift register to 0
TimeLED =0;
//Call light up function to initialize LED
LightupLEDtimer();
//}
if (ES_PostToService( MyPriority, ThisEvent) == true)
{

printf("Timing Initialized \n\r");


return true;
}else
{
return false;
}
}
//End InitRobotTimer function
//Start PostRobotTimer function
bool PostRobotTimer( ES_Event ThisEvent )
{
return ES_PostToService( MyPriority, ThisEvent);
}
//End PostRobotTimer function
//Start RunRobotTimer function
ES_Event RunRobotTimer( ES_Event ThisEvent )
{
//printf("RunRobot \n\r");
ES_Event ReturnEvent;
ReturnEvent.EventType = ES_NO_EVENT;
// ThisEvent is EV_StartGame
if(ThisEvent.EventType == EV_StartGame){
//printf("EV_StartGame Recieved \n\r");
// set input data to shift register to 0
TimeLED =0;
//call light up function
LightupLEDtimer();
//call to start timers
ES_Timer_InitTimer(LED_Timer, 3749);
ES_Timer_InitTimer(Robot_Timer,15000);
}
//If ThisEvent is ES_Timeout and EventParam is LED_Timer
if( (ThisEvent.EventType == ES_TIMEOUT) && (ThisEvent.EventParam ==LED_Timer))
{
//printf("if");
// re-start timer & announce
//Start LED_Timer
ES_Timer_InitTimer(LED_Timer, 3749 );
// Set Most Significant 0 in TimeLED to 1
TimeLED *=2;
//printf("TimeLED_1 IS %d.\n\r",TimeLED);
TimeLED +=1;
//printf("TimeLED_2 IS %d.\n\r",TimeLED);
//Call light up function
LightupLEDtimer();
printf("Time Tick \n\r");
}
//If

ThisEvent is ES_Timeout and EventParam is Robot_Timer


if( (ThisEvent.EventType == ES_TIMEOUT) && (ThisEvent.EventParam ==
Robot_Timer)){
printf("Robot Vibrated \n\r");
//call robot vibration function
RobotVibration(1);

ES_Timer_InitTimer(Robot_EndTimer,2000);
ES_Timer_InitTimer(Robot_Timer, 15000);
}
ThisEvent is ES_Timeout and EventParam is Robot_EndTimer
if ((ThisEvent.EventType==ES_TIMEOUT) &&
(ThisEvent.EventParam==Robot_EndTimer)) {
//call robot vibration to stop vibrate
RobotVibration(0);
}
// if ThisEvent is EV_EndGame
if (ThisEvent.EventType == EV_EndGame){
//stop timers
ES_Timer_StopTimer(LED_Timer);
ES_Timer_StopTimer(Robot_Timer);
//turn off all the lights
TimeLED =0;
LightupLEDtimer();
}
return ReturnEvent;
}
//End RunRobotTimer function
//If

//Start InitRobot fucntion


void InitRobot(void) {
// Init pinE pin 1 for Robot Vibration
HWREG(SYSCTL_RCGCGPIO) |= SYSCTL_RCGCGPIO_R4;
HWREG(GPIO_PORTE_BASE+GPIO_O_DEN) |= BIT1HI;
HWREG(GPIO_PORTE_BASE+GPIO_O_DIR) |= BIT1HI;
}
//End InitRobot fucntion
//Start RobotVibration function
void RobotVibration(char input) {
//if input is not 0
if (input!=0) {
//output high
HWREG (GPIO_PORTE_BASE + (GPIO_O_DATA+ ALL_BITS)) |= BIT1HI;
}
// if input is 0
else if (input==0) {
//output low
HWREG (GPIO_PORTE_BASE + (GPIO_O_DATA+ ALL_BITS)) &= BIT1LO;
}
}
//End RobotVibration function
//Start LightupLEDtimer fucntion
void LightupLEDtimer( void ){
//For loop i = 0-15, increasing i each time
//putting each bit data into the shift register
for(int i=0;i<=15;i++){
//if TimeLED left by i and it is 0
if (((TimeLED << i )&(0x8000))==0){
//Post 0 to Port E Pin 4
HWREG (GPIO_PORTF_BASE + (GPIO_O_DATA+ ALL_BITS)) &= BIT4LO;
}
//end if

else{
//else post 1 to port E pin 4
HWREG (GPIO_PORTF_BASE + (GPIO_O_DATA+ ALL_BITS)) |= BIT4HI;
}
//Call function to pulse SRCLK
PulSRCLK();
//printf("Pulse SC");
}
//edn for loop
//call function to pulse RCLK
PulRCLK();
//printf("Pulse RC");
}
//End LightupLEDtimer fucntion
//Start InitLED fucntion
void InitLED(void){
//Initialize PortFpin2 to be used SRCLK pulse input
//Initialize PortFpin3 to be use as RCLK pulse input
//Initialize PortFpin4 to be use as dataInput for shift register
volatile uint32_t Dummy;
HWREG(SYSCTL_RCGCGPIO) |= SYSCTL_RCGCGPIO_R5;
Dummy = HWREG(SYSCTL_RCGCGPIO);
HWREG(GPIO_PORTF_BASE+GPIO_O_DEN) |= (GPIO_PIN_4 | GPIO_PIN_2 |
GPIO_PIN_3);
HWREG(GPIO_PORTF_BASE+GPIO_O_DIR) |= (GPIO_PIN_4 | GPIO_PIN_2 |
GPIO_PIN_3);
}
//End LightupLEDtimer fucntion
//Start PulSRCLK function
void PulSRCLK(void){
//set portF pin 2 to 1
HWREG (GPIO_PORTF_BASE + (GPIO_O_DATA+ ALL_BITS)) |=(GPIO_PIN_2);
//time delay
for (int i = 0; i <= 200; i++);
////set portF pin 2 to 0
HWREG (GPIO_PORTF_BASE + (GPIO_O_DATA+ ALL_BITS)) &=~(GPIO_PIN_2);
}
//End PulSRCLK function
//Start PulRCLK function
void PulRCLK(void){
//Set portE pin 3 to 1
HWREG (GPIO_PORTE_BASE + (GPIO_O_DATA+ ALL_BITS)) |=(GPIO_PIN_3);
//time delay
for (int i = 0; i <= 200; i++);
//Set portE pin3 to 0
HWREG (GPIO_PORTF_BASE + (GPIO_O_DATA+ ALL_BITS)) &=~(GPIO_PIN_3);
}

11. FearJoyModule.h
/**********************************************************************

Header file for Fear Joy State Machine


based on the Gen2 Events and Services Framework
****************************************************************************/
#ifndef FearJoyModule_H
#define FearJoyModule_H
// Event Definitions
#include "ES_Configure.h" /* gets us event definitions */
#include "ES_Types.h"
/* gets bool type for returns */
// typedefs for the states
// State definitions for use with the query function
typedef enum {Fear, GamePlay,GameEnd } FearJoyState_t ;
// Public Function Prototypes
bool InitFearJoy(uint8_t);
bool PostFearJoySM(ES_Event);
ES_Event RunFearJoySM(ES_Event);
#endif

12. FearJoyModule.c
/****************************************************************************
Module
FearJoyModule.c
Revision
1.0.1
Description
This implements the Fear and Joy state machine under the
Gen2 Events and Services Framework.
Notes
History
When
Who
What/Why
-------------- ---------11/9/14
Hnin
Created
11/12/14
Hnin
Compiled/ Changed name from FearJoySM.c to
FearJoyModule.c
****************************************************************************/
/*----------------------------- Include Files -----------------------------*/
/* include header files for this state machine as well as any machines at the
next lower level in the hierarchy that are sub-machines to this machine
*/
#include <stdint.h>
#include <stdbool.h>
#include <stdio.h>

#include "inc/hw_types.h"
#include "inc/hw_memmap.h"
#include "driverlib/sysctl.h"
#include "driverlib/gpio.h"
#include "driverlib/interrupt.h"
#include "utils/uartstdio.h"
#include "inc/hw_gpio.h"
#include "ES_Configure.h"
#include "ES_Framework.h"
#include "ES_Port.h"
#include "termio.h"
#include "inc/hw_sysctl.h"
#include "ES_Configure.h"
#include "ES_Framework.h"
#include "FearJoyModule.h"
#include "RobotTimer.h"
#include "LEDBoardModule.h"
/*----------------------------- Module Defines ----------------------------*/
#define ALL_BITS (0xff<<2)
/*---------------------------- Module Functions ---------------------------*/
/* prototypes for private functions for this machine.They should be functions
relevant to the behavior of this state machine
*/
bool InitFearJoy(uint8_t);
bool PostFearJoySM(ES_Event);
ES_Event RunFearJoySM(ES_Event);
static void RedMoodLEDs(char);
static void GreenMoodLEDs(char);
static void RobotVibrate(char input);

/*---------------------------- Module Variables ---------------------------*/


// everybody needs a state variable, you may need others as well.
// type of state variable should match htat of enum in header file
static FearJoyState_t CurrentState;
static uint8_t MyPriority;
/*------------------------------ Module Code ------------------------------*/
/****************************************************************************
Function
InitFearJoy
Parameters
uint8_t : the priorty of this service
Returns
bool, false if error in initialization, true otherwise
Description
Saves away the priority, sets up the initial transition and does any
other required initialization for this state machine
Notes

****************************************************************************/
bool InitFearJoy ( uint8_t Priority )
{
ES_Event ThisEvent;
MyPriority = Priority;
CurrentState = Fear;
//Initialize ports for mood lights and robot vibration
HWREG(SYSCTL_RCGCGPIO)|= BIT0HI | BIT3HI |BIT4HI;
int Dummy;
Dummy=HWREG(SYSCTL_RCGCGPIO);
HWREG(GPIO_PORTA_BASE+GPIO_O_DEN)
HWREG(GPIO_PORTD_BASE+GPIO_O_DEN)
HWREG(GPIO_PORTE_BASE+GPIO_O_DEN)
HWREG(GPIO_PORTA_BASE+GPIO_O_DIR)
HWREG(GPIO_PORTD_BASE+GPIO_O_DIR)
HWREG(GPIO_PORTE_BASE+GPIO_O_DEN)

|=
|=
|=
|=
|=
|=

BIT5HI;
BIT6HI;
BIT1HI;
BIT5HI;
BIT6HI;
BIT1HI;

printf("Fear Joy Initialized \n\r");


ThisEvent.EventType = ES_INIT;
if (ES_PostToService( MyPriority, ThisEvent) == true)
{
return true;
}else
{
return false;
}
}
/****************************************************************************
Function
PostFearJoySM
Parameters
EF_Event ThisEvent , the event to post to the queue
Returns
boolean False if the Enqueue operation failed, True otherwise
Description
Posts an event to this state machine's queue
Notes
****************************************************************************/
bool PostFearJoySM( ES_Event ThisEvent )
{
return ES_PostToService( MyPriority, ThisEvent);
}
/****************************************************************************
Function
RunFearJoySM
Parameters

ES_Event : the event to process


Returns
ES_Event, ES_NO_EVENT if no error ES_ERROR otherwise
Description
The program determines the start of the gameplay and sets the moodlights to
show Fear and Joy settings.
Notes
uses nested switch/case to implement the machine.
****************************************************************************/
ES_Event RunFearJoySM( ES_Event ThisEvent )
{
ES_Event ReturnEvent;
ReturnEvent.EventType = ES_NO_EVENT;
//returns no event
FearJoyState_t NextState;
NextState=CurrentState;
//Initialize that next
state will be current state
switch ( CurrentState )
{
case Fear :
//In Fear State
RobotVibrate(1); //Robot Vibrates
RedMoodLEDs(1);
//Red Lights are on
//printf("Fear State \n\r");
if ( ThisEvent.EventType == EV_StartGame )
//If
told to start game
{
//printf("in Game Started \n\r");
ES_Event StartGame;
StartGame.EventType=EV_StartGame;
PostRobotTimer(StartGame);
//Let Robot Timer Know game started
ES_PostLEDBoardSM(StartGame);
//Let LED board know game started
RobotVibrate(0);
//Robot Stops Vibrating
NextState=GamePlay;
//Will move into gameplay next
RedMoodLEDs(1);
//Keep Red lights on
ES_Timer_InitTimer(GameTimer,60000);
//Start 60 second game clock
}
break;
case GamePlay :
//If currently playing game
if ( ThisEvent.EventType == EV_EndGame )
//If End of
Game comes from outside event (game won)
{
//printf("in Gameplay state \n\r");
NextState=GameEnd;
//Goes into Game End State
ES_Timer_InitTimer(EndTimer,30000);
//Set 30 second timer between games

RedMoodLEDs(0);

//Turn off red LEDs

GreenMoodLEDs(1);

//Turn on green LEDs


ES_Event Ended;
Ended.EventType = EV_EndGame;
PostRobotTimer(Ended);
//Tell timer game is over
ES_PostLEDBoardSM(Ended);
//Tell LED game is over
}
if (ThisEvent.EventType == ES_TIMEOUT &&
ThisEvent.EventParam == GameTimer)
//If game ended from timeout (game
lost)
{
//printf("Game ended \n\r");
NextState=GameEnd;
//Game
is over
RobotVibrate(1);
//Robot vibrates
ES_Timer_InitTimer(EndTimer, 5000);
//Wait 5
Seconds before can be played again
ES_Event Ended;
Ended.EventType = EV_EndGame;
PostRobotTimer(Ended);
//Tell Timer that
game is over
ES_PostLEDBoardSM(Ended);
//Tell LED Board
that game is over
}
break;
case GameEnd :
if (ThisEvent.EventType==ES_TIMEOUT && ThisEvent.EventParam
== EndTimer)
//If Between game timer has timed out
{
//printf("Game Ended \n\r");
NextState=Fear;
//go to fear
state
GreenMoodLEDs(0);
//turn off green
LEDs
RedMoodLEDs(1);
//turn on
red LEDs
RobotVibrate(1);
//vibrate robot
}
break;
default:
;

}
CurrentState=NextState;
return ReturnEvent;

//update current state


//return no_event

}
void RedMoodLEDs(char input) {
if (input ==0)
{

//control red mood LEDs (1 on 0 off)

HWREG(GPIO_PORTA_BASE+ALL_BITS) &= BIT5LO;


//printf("Red mood LEDs off \n\r");
} else if (input==1) {
HWREG(GPIO_PORTA_BASE+ALL_BITS) |= BIT5HI;
//printf("Red mood LEDs on \n\r");
}
}
void GreenMoodLEDs(char input) {
//control green mood LEDs (1 on 0
off)
if (input ==0)
{
HWREG(GPIO_PORTD_BASE+ALL_BITS) &= BIT6LO;
//printf("Green mood LEDs off \n\r");
} else if (input ==1) {
HWREG(GPIO_PORTD_BASE+ALL_BITS) |= BIT6HI;
//printf("Green mood LEDs on \n\r");
}
}
void RobotVibrate(char input) {
//control robot vibrations (1 on 0
off)
if (input!=0) {
//printf("Robot On \n\r");
HWREG (GPIO_PORTE_BASE + (GPIO_O_DATA+ ALL_BITS)) |= BIT1HI;
} else if (input==0) {
//printf("Robot Off \n\r");
HWREG (GPIO_PORTE_BASE + (GPIO_O_DATA+ ALL_BITS)) &= BIT1LO;
}
}

13. GunY.h

/****************************************************************************
Header file for Gun Y Position State Machine
based on the Gen2 Events and Services Framework
****************************************************************************/
#ifndef GunY_H
#define GunY_H
// Event Definitions
#include "ES_Configure.h" /* gets us event definitions */
#include "ES_Types.h"
/* gets bool type for returns */
// typedefs for the states
// State definitions for use with the query function
typedef enum { GunUp, GunDown } GunYState_t ;
// Public Function Prototypes

bool InitGunY(uint8_t);
bool PostGunYSM(ES_Event);
ES_Event RunGunYSM(ES_Event);
bool CheckRightHall(void);
bool CheckLeftHall(void);

#endif

14. GunY.c

/****************************************************************************
Module
GunY.c
Revision
1.0.1
Description
This implements the Gun Y Position state machine under the
Gen2 Events and Services Framework.
Notes
History
When
Who
What/Why
-------------- ---------11/8/14
Hnin
11/12/14
Hnin
GunYPosition.c to GunY.c

Created
Compiled/changed name from

Changed hall states to detect falling edge instead of rising edge


****************************************************************************/
/*----------------------------- Include Files -----------------------------*/
/* include header files for this state machine as well as any machines at the
next lower level in the hierarchy that are sub-machines to this machine
*/
#include <stdint.h>
#include <stdbool.h>
#include <stdio.h>
#include "inc/hw_types.h"
#include "inc/hw_memmap.h"
#include "driverlib/sysctl.h"
#include "driverlib/gpio.h"
#include "driverlib/interrupt.h"
#include "utils/uartstdio.h"
#include "inc/hw_gpio.h"
#include "ES_Configure.h"
#include "ES_Framework.h"
#include "ES_Port.h"
#include "termio.h"
#include "inc/hw_sysctl.h"
#include "ES_Configure.h"
#include "ES_Framework.h"
#include "GunY.h"
#include "GunFire.h"

#include "PWMTiva.h"
/*----------------------------- Module Defines ----------------------------*/
#define ALL_BITS (0xff<<2)
/*---------------------------- Module Functions ---------------------------*/
/* prototypes for private functions for this machine.They should be functions
relevant to the behavior of this state machine
*/
bool InitGunY(uint8_t);
bool PostGunYSM(ES_Event);
ES_Event RunGunYSM(ES_Event);
bool CheckRightHall(void);
bool CheckLeftHall(void);
/*---------------------------- Module Variables ---------------------------*/
// everybody needs a state variable, you may need others as well.
// type of state variable should match htat of enum in header file
static GunYState_t CurrentState;
static uint8_t MyPriority;
/*------------------------------ Module Code ------------------------------*/
/****************************************************************************
Function
InitGunY
Parameters
uint8_t : the priorty of this service
Returns
bool, false if error in initialization, true otherwise
Description
Saves away the priority, sets up the initial transition and does any
other required initialization for this state machine
Notes
Author
J. Edward Carryer, 10/23/11, 18:55
****************************************************************************/
bool InitGunY ( uint8_t Priority )
{
ES_Event ThisEvent;
MyPriority = Priority;
CurrentState = GunDown;
//Initialize Port B
HWREG(SYSCTL_RCGCGPIO)|= BIT1HI;
int Dummy;
Dummy=HWREG(SYSCTL_RCGCGPIO);
//Initalize Pin 0 and Pin 1 to be digital inputs (B0 - Right Hall, B1Left Hall)

HWREG(GPIO_PORTB_BASE+GPIO_O_DEN) |= (BIT0HI | BIT1HI);


HWREG(GPIO_PORTB_BASE+GPIO_O_DIR) &= (BIT0LO & BIT1LO);
PWM_TIVA_SetDuty(5, 3);
using PWM slot 3

//Initialize Tiva in GunDown Position (5)

ThisEvent.EventType = ES_INIT;
if (ES_PostToService( MyPriority, ThisEvent) == true)
{
printf("Gun Y Initialized \n\r");
return true;
}else
{
return false;
}

/****************************************************************************
Function
PostTemplateFSM
Parameters
EF_Event ThisEvent , the event to post to the queue
Returns
boolean False if the Enqueue operation failed, True otherwise
Description
Posts an event to this state machine's queue
Notes
Author
J. Edward Carryer, 10/23/11, 19:25
****************************************************************************/
bool PostGunYSM( ES_Event ThisEvent )
{
return ES_PostToService( MyPriority, ThisEvent);
}
/****************************************************************************
Function
RunGunYSM
Parameters
ES_Event : the event to process
Returns
ES_Event, ES_NO_EVENT if no error ES_ERROR otherwise
Description
add your description here
Notes
uses nested switch/case to implement the machine.
****************************************************************************/
ES_Event RunGunYSM( ES_Event ThisEvent )
{

ES_Event ReturnEvent;
ReturnEvent.EventType = ES_NO_EVENT;
GunYState_t NextState;
NextState=CurrentState;
//Initialize NextState as Current State

//Always returns no event

switch ( CurrentState )
//Difference actions based on state of SM
{
case GunDown :
if ( ThisEvent.EventType == EV_LeftHallRisingEdge )
//If Gun is
down and Left hall posts rising edge
{
NextState=GunUp;
//Set next state to gun up
PWM_TIVA_SetDuty(6.3, 3);
//Move gun to gun up position with servo
ES_Event ThisEvent;
ThisEvent.EventType=EV_GunUp;
PostGunFireSM(ThisEvent);
//Post gun up to gunfire
//printf("Posted GunDown to GunFiring and
GunYServo \n\r");
}
break;
case GunUp:
if (ThisEvent.EventType == EV_RightHallRisingEdge)
{
NextState=GunDown;
//set next state machine state to gun down
PWM_TIVA_SetDuty(5, 3);
//Move gun to gun down position with servo
ES_Event ThisEvent;
ThisEvent.EventType=EV_GunDown;
PostGunFireSM(ThisEvent);
//Post gun down event to gunfire sm
//printf("Posted GunUp to GunFiring and
GunYServo \n\r");
}
default :
;
}
}

CurrentState=NextState;
return ReturnEvent;

//implement next state


//return NO_EVENT

bool CheckRightHall(void)
//Event checker to see if right hall has changed
position, returns true if event detected
{
static char LastInputState=0; //Assume first input state was 0
bool ReturnVal;
ReturnVal=false;
//Initialize
ReturnVal as false
char CurrentInputState;

CurrentInputState= HWREG(GPIO_PORTB_BASE+ALL_BITS)& BIT0HI;


the Current InputState from the Hall

//Read

if (CurrentInputState!= LastInputState)
//If state has changed
{
//printf("RightHall Event \n\r");
ReturnVal=true;
//return true
if (CurrentInputState != BIT0HI)
//If current input state is
low (representing actuation of hall)
{
ES_Event ThisEvent;
ThisEvent.EventType=EV_RightHallRisingEdge;
PostGunYSM(ThisEvent);
//Post Hall
rising edge to Gun Y SM
}
}
LastInputState = CurrentInputState; //Update Current State
return ReturnVal;
}
bool CheckLeftHall(void) //Event checker to see if right hall has changed
position, returns true if event detected
{
static char LastInputState=0;//Assume first input state was 0
bool ReturnVal;
ReturnVal=false;
//Initialize
ReturnVal as false
char CurrentInputState;
CurrentInputState= HWREG(GPIO_PORTB_BASE+ALL_BITS)& BIT1HI;
the Current InputState from the Hall

//Read

if (CurrentInputState!= LastInputState)
//If state has changed
{
//printf("RightHall Event \n\r");
ReturnVal=true;
if (CurrentInputState != BIT1HI) //If current input state is low
(representing actuation of hall)
{
ES_Event ThisEvent;
ThisEvent.EventType=EV_LeftHallRisingEdge;
PostGunYSM(ThisEvent);
//Post Hall
rising edge to Gun Y SM
}
}
LastInputState = CurrentInputState; //Update Current State
return ReturnVal;
}

15. ADCSWTrigger.h
//
//
//
//
//
//

ADCSWTrigger.h
Runs on LM4F120/TM4C123
Provide functions that initialize ADC0 SS3 to be triggered by
software and trigger a conversion, wait for it to finish,
and return the result.
Daniel Valvano

// September 11, 2013


/* This example accompanies the book
"Embedded Systems: Real Time Interfacing to Arm Cortex M Microcontrollers",
ISBN: 978-1463590154, Jonathan Valvano, copyright (c) 2013
Copyright 2013 by Jonathan W. Valvano, valvano@mail.utexas.edu
You may use, edit, run or distribute this file
as long as the above copyright notice remains
THIS SOFTWARE IS PROVIDED "AS IS". NO WARRANTIES, WHETHER EXPRESS, IMPLIED
OR STATUTORY, INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE APPLY TO THIS SOFTWARE.
VALVANO SHALL NOT, IN ANY CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL,
OR CONSEQUENTIAL DAMAGES, FOR ANY REASON WHATSOEVER.
For more information about my classes, my research, and my books, see
http://users.ece.utexas.edu/~valvano/
*/
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//

There are many choices to make when using the ADC, and many
different combinations of settings will all do basically the
same thing. For simplicity, this function makes some choices
for you. When calling this function, be sure that it does
not conflict with any other software that may be running on
the microcontroller. Particularly, ADC0 sample sequencer 3
is used here because it only takes one sample, and only one
sample is absolutely needed. Sample sequencer 3 generates a
raw interrupt when the conversion is complete, but it is not
promoted to a controller interrupt. Software triggers the
ADC0 conversion and waits for the conversion to finish. If
somewhat precise periodic measurements are required, the
software trigger can occur in a periodic interrupt. This
approach has the advantage of being simple. However, it does
not guarantee real-time.
A better approach would be to use a hardware timer to trigger
the ADC0 conversion independently from software and generate
an interrupt when the conversion is finished. Then, the
software can transfer the conversion result to memory and
process it after all measurements are complete.

// This initialization function sets up the ADC according to the


// following parameters. Any parameters not explicitly listed
// below are not modified:
// Max sample rate: <=125,000 samples/second
// Sequencer 0 priority: 1st (highest)
// Sequencer 1 priority: 2nd
// Sequencer 2 priority: 3rd
// Sequencer 3 priority: 4th (lowest)
// SS3 triggering event: software trigger
// SS3 1st sample source: Ain9 (PE4)
// SS3 interrupts: enabled but not promoted to controller
void ADC0_InitSWTriggerSeq3_Ch9(void);
//
//
//
//

This initialization function sets up the ADC according to the


following parameters. Any parameters not explicitly listed
below are not modified:
Max sample rate: <=125,000 samples/second

// Sequencer 0 priority: 1st (highest)


// Sequencer 1 priority: 2nd
// Sequencer 2 priority: 3rd
// Sequencer 3 priority: 4th (lowest)
// SS3 triggering event: software trigger
// SS3 1st sample source: programmable using variable 'channelNum' [0:7]
// SS3 interrupts: enabled but not promoted to controller
void ADC0_InitSWTriggerSeq3(uint32_t channelNum);
// This initialization function sets up the ADC according to the
// following parameters. Any parameters not explicitly listed
// below are not modified:
// Max sample rate: <=125,000 samples/second
// Sequencer 0 priority: 1st (highest)
// Sequencer 1 priority: 2nd
// Sequencer 2 priority: 3rd
// Sequencer 3 priority: 4th (lowest)
// SS3 triggering event: always trigger
// SS3 1st sample source: programmable using variable 'channelNum' [0:11]
// SS3 interrupts: enabled but not promoted to controller
void ADC0_InitAllTriggerSeq3(uint32_t channelNum);
//------------ADC0_InSeq3-----------// Busy-wait Analog to digital conversion
// Input: none
// Output: 12-bit result of ADC conversion
uint32_t ADC0_InSeq3(void);

16. ADCSWTrigger.c
//
//
//
//
//
//
//

ADCSWTrigger.c
Runs on LM4F120/TM4C123
Provide functions that initialize ADC0 SS3 to be triggered by
software and trigger a conversion, wait for it to finish,
and return the result.
Daniel Valvano
September 11, 2013

/* This example accompanies the book


"Embedded Systems: Real Time Interfacing to Arm Cortex M Microcontrollers",
ISBN: 978-1463590154, Jonathan Valvano, copyright (c) 2013
Copyright 2013 by Jonathan W. Valvano, valvano@mail.utexas.edu
You may use, edit, run or distribute this file
as long as the above copyright notice remains
THIS SOFTWARE IS PROVIDED "AS IS". NO WARRANTIES, WHETHER EXPRESS, IMPLIED
OR STATUTORY, INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE APPLY TO THIS SOFTWARE.
VALVANO SHALL NOT, IN ANY CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL,
OR CONSEQUENTIAL DAMAGES, FOR ANY REASON WHATSOEVER.
For more information about my classes, my research, and my books, see
http://users.ece.utexas.edu/~valvano/
*/
#include <stdint.h>
#include "inc/tm4c123gh6pm.h"
#include "termio.h"

//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//

There are many choices to make when using the ADC, and many
different combinations of settings will all do basically the
same thing. For simplicity, this function makes some choices
for you. When calling this function, be sure that it does
not conflict with any other software that may be running on
the microcontroller. Particularly, ADC0 sample sequencer 3
is used here because it only takes one sample, and only one
sample is absolutely needed. Sample sequencer 3 generates a
raw interrupt when the conversion is complete, but it is not
promoted to a controller interrupt. Software triggers the
ADC0 conversion and waits for the conversion to finish. If
somewhat precise periodic measurements are required, the
software trigger can occur in a periodic interrupt. This
approach has the advantage of being simple. However, it does
not guarantee real-time.
A better approach would be to use a hardware timer to trigger
the ADC0 conversion independently from software and generate
an interrupt when the conversion is finished. Then, the
software can transfer the conversion result to memory and
process it after all measurements are complete.

// This initialization function sets up the ADC according to the


// following parameters. Any parameters not explicitly listed
// below are not modified:
// Max sample rate: <=125,000 samples/second
// Sequencer 0 priority: 1st (highest)
// Sequencer 1 priority: 2nd
// Sequencer 2 priority: 3rd
// Sequencer 3 priority: 4th (lowest)
// SS3 triggering event: software trigger
// SS3 1st sample source: Ain9 (PE4)
// SS3 interrupts: enabled but not promoted to controller
void ADC0_InitSWTriggerSeq3_Ch9(void){ volatile uint32_t delay;
// 1) activate clock for Port E
SYSCTL_RCGCGPIO_R |= 0x10;
while((SYSCTL_PRGPIO_R&0x10) != 0x10){};
delay = SYSCTL_RCGCGPIO_R;
//
allow time for clock to stabilize
delay = SYSCTL_RCGCGPIO_R;
GPIO_PORTE_DIR_R &= ~0x10;
// 2) make PE4 input
/////////////////////////////////////////////////////
GPIO_PORTE_AFSEL_R |= 0x10;
// 3) enable alternate function on PE4
GPIO_PORTE_DEN_R &= ~0x10;
// 4) disable digital I/O on PE4
GPIO_PORTE_AMSEL_R |= 0x10;
// 5) enable analog functionality on PE4
SYSCTL_RCGCADC_R |= 0x0001;
// 7) activate ADC0
// while((SYSCTL_PRADC_R&0x0001) != 0x0001){};
// good code, but not yet
implemented in simulator
delay = SYSCTL_RCGCADC_R;
// extra time for clock to stabilize
delay = SYSCTL_RCGCADC_R;
// extra time for clock to stabilize
delay = SYSCTL_RCGCADC_R;
// extra time for clock to stabilize
delay = SYSCTL_RCGCADC_R;
ADC0_PC_R &= ~0xF;
// 7) clear max sample rate field
///////////////////////////////////////////////////////
ADC0_PC_R |= 0x1;
//
configure for 125K samples/sec
ADC0_SSPRI_R = 0x0123;
// 8) Sequencer 3 is highest priority
ADC0_ACTSS_R &= ~0x0008;
// 9) disable sample sequencer 3

ADC0_EMUX_R &= ~0xF000;


ADC0_SSMUX3_R &= ~0x000F;
ADC0_SSMUX3_R += 9;
ADC0_SSCTL3_R = 0x0006;
ADC0_IM_R &= ~0x0008;
ADC0_ACTSS_R |= 0x0008;

//
//
//
//
//
//

10) seq3 is software trigger


11) clear SS3 field
set channel
12) no TS0 D0, yes IE0 END0
13) disable SS3 interrupts
14) enable sample sequencer 3

}
// This initialization function sets up the ADC according to the
// following parameters. Any parameters not explicitly listed
// below are not modified:
// Max sample rate: <=125,000 samples/second
// Sequencer 0 priority: 1st (highest)
// Sequencer 1 priority: 2nd
// Sequencer 2 priority: 3rd
// Sequencer 3 priority: 4th (lowest)
// SS3 triggering event: software trigger
// SS3 1st sample source: programmable using variable 'channelNum' [0:11]
// SS3 interrupts: enabled but not promoted to controller
void ADC0_InitSWTriggerSeq3(uint32_t channelNum){ volatile uint32_t delay;
switch(channelNum){
// 1) activate clock
case 0:
case 1:
case 2:
case 3:
case 8:
case 9:
//
these are on GPIO_PORTE
SYSCTL_RCGCGPIO_R |= 0x10;
while((SYSCTL_PRGPIO_R&0x10) != 0x10){};
break;
case 4:
case 5:
case 6:
case 7:
//
these are on GPIO_PORTD
SYSCTL_RCGCGPIO_R |= 0x08;
while((SYSCTL_PRGPIO_R&0x08) != 0x08){};
break;
case 10:
case 11:
//
these are on GPIO_PORTB
SYSCTL_RCGCGPIO_R |= 0x02;
while((SYSCTL_PRGPIO_R&0x02) != 0x02){};
break;
default: return;
//
0 to 11 are valid channels on the
LM4F120/TM4C123
}
delay = SYSCTL_RCGCGPIO_R;
// extra time for clock to stabilize
delay = SYSCTL_RCGCGPIO_R;
switch(channelNum){
case 0:
//
Ain0 is on PE3
GPIO_PORTE_DIR_R &= ~0x08; // 3.0) make PE3 input
GPIO_PORTE_AFSEL_R |= 0x08; // 4.0) enable alternate function on PE3
GPIO_PORTE_DEN_R &= ~0x08; // 5.0) disable digital I/O on PE3
GPIO_PORTE_AMSEL_R |= 0x08; // 6.0) enable analog functionality on PE3
break;
case 1:
//
Ain1 is on PE2
GPIO_PORTE_DIR_R &= ~0x04; // 3.1) make PE2 input
GPIO_PORTE_AFSEL_R |= 0x04; // 4.1) enable alternate function on PE2

GPIO_PORTE_DEN_R &= ~0x04; // 5.1) disable digital I/O on PE2


GPIO_PORTE_AMSEL_R |= 0x04; // 6.1) enable analog functionality on PE2
break;
case 2:
//
Ain2 is on PE1
GPIO_PORTE_DIR_R &= ~0x02; // 3.2) make PE1 input
GPIO_PORTE_AFSEL_R |= 0x02; // 4.2) enable alternate function on PE1
GPIO_PORTE_DEN_R &= ~0x02; // 5.2) disable digital I/O on PE1
GPIO_PORTE_AMSEL_R |= 0x02; // 6.2) enable analog functionality on PE1
break;
case 3:
//
Ain3 is on PE0
GPIO_PORTE_DIR_R &= ~0x01; // 3.3) make PE0 input
GPIO_PORTE_AFSEL_R |= 0x01; // 4.3) enable alternate function on PE0
GPIO_PORTE_DEN_R &= ~0x01; // 5.3) disable digital I/O on PE0
GPIO_PORTE_AMSEL_R |= 0x01; // 6.3) enable analog functionality on PE0
break;
case 4:
//
Ain4 is on PD3
GPIO_PORTD_DIR_R &= ~0x08; // 3.4) make PD3 input
GPIO_PORTD_AFSEL_R |= 0x08; // 4.4) enable alternate function on PD3
GPIO_PORTD_DEN_R &= ~0x08; // 5.4) disable digital I/O on PD3
GPIO_PORTD_AMSEL_R |= 0x08; // 6.4) enable analog functionality on PD3
break;
case 5:
//
Ain5 is on PD2
GPIO_PORTD_DIR_R &= ~0x04; // 3.5) make PD2 input
GPIO_PORTD_AFSEL_R |= 0x04; // 4.5) enable alternate function on PD2
GPIO_PORTD_DEN_R &= ~0x04; // 5.5) disable digital I/O on PD2
GPIO_PORTD_AMSEL_R |= 0x04; // 6.5) enable analog functionality on PD2
break;
case 6:
//
Ain6 is on PD1
GPIO_PORTD_DIR_R &= ~0x02; // 3.6) make PD1 input
GPIO_PORTD_AFSEL_R |= 0x02; // 4.6) enable alternate function on PD1
GPIO_PORTD_DEN_R &= ~0x02; // 5.6) disable digital I/O on PD1
GPIO_PORTD_AMSEL_R |= 0x02; // 6.6) enable analog functionality on PD1
break;
case 7:
//
Ain7 is on PD0
GPIO_PORTD_DIR_R &= ~0x01; // 3.7) make PD0 input
GPIO_PORTD_AFSEL_R |= 0x01; // 4.7) enable alternate function on PD0
GPIO_PORTD_DEN_R &= ~0x01; // 5.7) disable digital I/O on PD0
GPIO_PORTD_AMSEL_R |= 0x01; // 6.7) enable analog functionality on PD0
break;
case 8:
//
Ain8 is on PE5
GPIO_PORTE_DIR_R &= ~0x20; // 3.8) make PE5 input
GPIO_PORTE_AFSEL_R |= 0x20; // 4.8) enable alternate function on PE5
GPIO_PORTE_DEN_R &= ~0x20; // 5.8) disable digital I/O on PE5
GPIO_PORTE_AMSEL_R |= 0x20; // 6.8) enable analog functionality on PE5
break;
case 9:
//
Ain9 is on PE4
GPIO_PORTE_DIR_R &= ~0x10; // 3.9) make PE4 input
GPIO_PORTE_AFSEL_R |= 0x10; // 4.9) enable alternate function on PE4
GPIO_PORTE_DEN_R &= ~0x10; // 5.9) disable digital I/O on PE4
GPIO_PORTE_AMSEL_R |= 0x10; // 6.9) enable analog functionality on PE4
////////////////////////////////////////////////////
//printf("Analog Input Case 9 \n\r");
break;
case 10:
//
Ain10 is on PB4
GPIO_PORTB_DIR_R &= ~0x10; // 3.10) make PB4 input
GPIO_PORTB_AFSEL_R |= 0x10; // 4.10) enable alternate function on PB4
GPIO_PORTB_DEN_R &= ~0x10; // 5.10) disable digital I/O on PB4

GPIO_PORTB_AMSEL_R |= 0x10;
break;
case 11:
GPIO_PORTB_DIR_R &= ~0x20;
GPIO_PORTB_AFSEL_R |= 0x20;
GPIO_PORTB_DEN_R &= ~0x20;
GPIO_PORTB_AMSEL_R |= 0x20;
break;

// 6.10) enable analog functionality on PB4


//
//
//
//
//

3.11)
4.11)
5.11)
6.11)

Ain11 is on PB5
make PB5 input
enable alternate function on PB5
disable digital I/O on PB5
enable analog functionality on PB5

}
SYSCTL_RCGCADC_R |= 0x0001;
// 7) activate ADC0
// while((SYSCTL_PRADC_R&0x0001) != 0x0001){};
// good code, but not yet
implemented in simulator
delay = SYSCTL_RCGCADC_R;
// extra time for clock to stabilize
delay = SYSCTL_RCGCADC_R;
// extra time for clock to stabilize
delay = SYSCTL_RCGCADC_R;
// extra time for clock to stabilize
delay = SYSCTL_RCGCADC_R;
printf("Analog Input Delay \n\r"); //Adriano's Black Magic
ADC0_PC_R &= ~0xF;
// 9) clear max sample rate field
//////////////////////////////////////////////////////////////
//printf("Analog Input 3rd Stop \n\r");
ADC0_PC_R |= 0x1;
//
configure for 125K samples/sec
ADC0_SSPRI_R = 0x3210;
// 10) Sequencer 3 is lowest priority
ADC0_ACTSS_R &= ~0x0008;
// 11) disable sample sequencer 3
ADC0_EMUX_R &= ~0xF000;
// 12) seq3 is software trigger
ADC0_SSMUX3_R &= ~0x000F;
// 13) clear SS3 field
ADC0_SSMUX3_R += channelNum;
//
set channel
ADC0_SSCTL3_R = 0x0006;
// 14) no TS0 D0, yes IE0 END0
ADC0_IM_R &= ~0x0008;
// 15) disable SS3 interrupts
ADC0_ACTSS_R |= 0x0008;
// 16) enable sample sequencer 3
}
// This initialization function sets up the ADC according to the
// following parameters. Any parameters not explicitly listed
// below are not modified:
// Max sample rate: <=125,000 samples/second
// Sequencer 0 priority: 1st (highest)
// Sequencer 1 priority: 2nd
// Sequencer 2 priority: 3rd
// Sequencer 3 priority: 4th (lowest)
// SS3 triggering event: always trigger
// SS3 1st sample source: programmable using variable 'channelNum' [0:7]
// SS3 interrupts: enabled but not promoted to controller
void ADC0_InitAllTriggerSeq3(uint32_t channelNum){ volatile uint32_t delay;
switch(channelNum){
// 1) activate clock
case 0:
case 1:
case 2:
case 3:
case 8:
case 9:
//
these are on GPIO_PORTE
SYSCTL_RCGCGPIO_R |= 0x10;
while((SYSCTL_PRGPIO_R&0x10) != 0x10){};
break;
case 4:
case 5:
case 6:
case 7:
//
these are on GPIO_PORTD

SYSCTL_RCGCGPIO_R |= 0x08;
while((SYSCTL_PRGPIO_R&0x08) != 0x08){};
break;
case 10:
case 11:
//
these are on GPIO_PORTB
SYSCTL_RCGCGPIO_R |= 0x02;
while((SYSCTL_PRGPIO_R&0x02) != 0x02){};
break;
default: return;
//
0 to 11 are valid channels on the
LM4F120/TM4C123
}
delay = SYSCTL_RCGCGPIO_R;
// 2) extra time for clock to stabilize
delay = SYSCTL_RCGCGPIO_R;
switch(channelNum){
case 0:
//
Ain0 is on PE3
GPIO_PORTE_DIR_R &= ~0x08; // 3.0) make PE3 input
GPIO_PORTE_AFSEL_R |= 0x08; // 4.0) enable alternate function on PE3
GPIO_PORTE_DEN_R &= ~0x08; // 5.0) disable digital I/O on PE3
GPIO_PORTE_AMSEL_R |= 0x08; // 6.0) enable analog functionality on PE3
break;
case 1:
//
Ain1 is on PE2
GPIO_PORTE_DIR_R &= ~0x04; // 3.1) make PE2 input
GPIO_PORTE_AFSEL_R |= 0x04; // 4.1) enable alternate function on PE2
GPIO_PORTE_DEN_R &= ~0x04; // 5.1) disable digital I/O on PE2
GPIO_PORTE_AMSEL_R |= 0x04; // 6.1) enable analog functionality on PE2
break;
case 2:
//
Ain2 is on PE1
GPIO_PORTE_DIR_R &= ~0x02; // 3.2) make PE1 input
GPIO_PORTE_AFSEL_R |= 0x02; // 4.2) enable alternate function on PE1
GPIO_PORTE_DEN_R &= ~0x02; // 5.2) disable digital I/O on PE1
GPIO_PORTE_AMSEL_R |= 0x02; // 6.2) enable analog functionality on PE1
break;
case 3:
//
Ain3 is on PE0
GPIO_PORTE_DIR_R &= ~0x01; // 3.3) make PE0 input
GPIO_PORTE_AFSEL_R |= 0x01; // 4.3) enable alternate function on PE0
GPIO_PORTE_DEN_R &= ~0x01; // 5.3) disable digital I/O on PE0
GPIO_PORTE_AMSEL_R |= 0x01; // 6.3) enable analog functionality on PE0
break;
case 4:
//
Ain4 is on PD3
GPIO_PORTD_DIR_R &= ~0x08; // 3.4) make PD3 input
GPIO_PORTD_AFSEL_R |= 0x08; // 4.4) enable alternate function on PD3
GPIO_PORTD_DEN_R &= ~0x08; // 5.4) disable digital I/O on PD3
GPIO_PORTD_AMSEL_R |= 0x08; // 6.4) enable analog functionality on PD3
break;
case 5:
//
Ain5 is on PD2
GPIO_PORTD_DIR_R &= ~0x04; // 3.5) make PD2 input
GPIO_PORTD_AFSEL_R |= 0x04; // 4.5) enable alternate function on PD2
GPIO_PORTD_DEN_R &= ~0x04; // 5.5) disable digital I/O on PD2
GPIO_PORTD_AMSEL_R |= 0x04; // 6.5) enable analog functionality on PD2
break;
case 6:
//
Ain6 is on PD1
GPIO_PORTD_DIR_R &= ~0x02; // 3.6) make PD1 input
GPIO_PORTD_AFSEL_R |= 0x02; // 4.6) enable alternate function on PD1
GPIO_PORTD_DEN_R &= ~0x02; // 5.6) disable digital I/O on PD1
GPIO_PORTD_AMSEL_R |= 0x02; // 6.6) enable analog functionality on PD1
break;
case 7:
//
Ain7 is on PD0

GPIO_PORTD_DIR_R &= ~0x01;


GPIO_PORTD_AFSEL_R |= 0x01;
GPIO_PORTD_DEN_R &= ~0x01;
GPIO_PORTD_AMSEL_R |= 0x01;
break;
case 8:
GPIO_PORTE_DIR_R &= ~0x20;
GPIO_PORTE_AFSEL_R |= 0x20;
GPIO_PORTE_DEN_R &= ~0x20;
GPIO_PORTE_AMSEL_R |= 0x20;
break;
case 9:
GPIO_PORTE_DIR_R &= ~0x10;
GPIO_PORTE_AFSEL_R |= 0x10;
GPIO_PORTE_DEN_R &= ~0x10;
GPIO_PORTE_AMSEL_R |= 0x10;
break;
case 10:
GPIO_PORTB_DIR_R &= ~0x10;
GPIO_PORTB_AFSEL_R |= 0x10;
GPIO_PORTB_DEN_R &= ~0x10;
GPIO_PORTB_AMSEL_R |= 0x10;
break;
case 11:
GPIO_PORTB_DIR_R &= ~0x20;
GPIO_PORTB_AFSEL_R |= 0x20;
GPIO_PORTB_DEN_R &= ~0x20;
GPIO_PORTB_AMSEL_R |= 0x20;
break;

//
//
//
//

3.7)
4.7)
5.7)
6.7)

make PD0 input


enable alternate function on PD0
disable digital I/O on PD0
enable analog functionality on PD0

//
//
//
//
//

3.8)
4.8)
5.8)
6.8)

Ain8 is on PE5
make PE5 input
enable alternate function on PE5
disable digital I/O on PE5
enable analog functionality on PE5

//
//
//
//
//

3.9)
4.9)
5.9)
6.9)

Ain9 is on PE4
make PE4 input
enable alternate function on PE4
disable digital I/O on PE4
enable analog functionality on PE4

//
//
//
//
//

3.10)
4.10)
5.10)
6.10)

Ain10 is on PB4
make PB4 input
enable alternate function on PB4
disable digital I/O on PB4
enable analog functionality on PB4

//
//
//
//
//

3.11)
4.11)
5.11)
6.11)

Ain11 is on PB5
make PB5 input
enable alternate function on PB5
disable digital I/O on PB5
enable analog functionality on PB5

}
SYSCTL_RCGCADC_R |= 0x0001;
// 7) activate ADC0
// while((SYSCTL_PRADC_R&0x0001) != 0x0001){};
// good code, but not yet
implemented in simulator
delay = SYSCTL_RCGCADC_R;
// extra time for clock to stabilize
delay = SYSCTL_RCGCADC_R;
// extra time for clock to stabilize
delay = SYSCTL_RCGCADC_R;
// extra time for clock to stabilize
delay = SYSCTL_RCGCADC_R;
ADC0_PC_R &= ~0xF;
// 9) clear max sample rate field
ADC0_PC_R |= 0x1;
//
configure for 125K samples/sec
ADC0_SSPRI_R = 0x3210;
// 10) Sequencer 3 is lowest priority
ADC0_ACTSS_R &= ~0x0008;
// 11) disable sample sequencer 3
ADC0_EMUX_R |= 0xF000;
// 12) seq3 is continuous trigger
ADC0_SSMUX3_R &= ~0x000F;
// 13) clear SS3 field
ADC0_SSMUX3_R += channelNum;
//
set channel
ADC0_SSCTL3_R = 0x0006;
// 14) no TS0 D0, yes IE0 END0
ADC0_IM_R &= ~0x0008;
// 15) disable SS3 interrupts
ADC0_ACTSS_R |= 0x0008;
// 16) enable sample sequencer 3
}
//------------ADC0_InSeq3-----------// Busy-wait Analog to digital conversion
// Input: none
// Output: 12-bit result of ADC conversion
uint32_t ADC0_InSeq3(void){ uint32_t result;
ADC0_PSSI_R = 0x0008;
// 1) initiate SS3
while((ADC0_RIS_R&0x08)==0){};
// 2) wait for conversion done

// if you have an A0-A3 revision number, you need to add an 8 usec wait
here
result = ADC0_SSFIFO3_R&0xFFF;
// 3) read result
ADC0_ISC_R = 0x0008;
// 4) acknowledge completion
return result;
}

17. PWMTiva.h
#ifndef _PWM_TIVA_
#define _PWM_TIVA_
#include <stdint.h>
void
void
void
void
void

PWM_TIVA_Init(void);
PWM_TIVA_SetDuty( double dutyCycle, uint8_t channel);
PWM_TIVA_SetPeriod( uint16_t reqPeriod, uint8_t group);
PWM_TIVA_SetFreq( uint16_t reqFreq, uint8_t group);
PWM_TIVA_SetPulseWidth( uint16_t NewPW, uint8_t channel);

#endif

18. PWMTiva.c
#include
#include
#include
#include
#include
#include
#include
#include
#include

<stdint.h>
<stdbool.h>
"inc/hw_gpio.h"
"inc/hw_types.h"
"inc/hw_memmap.h"
"driverlib/sysctl.h"
"driverlib/pin_map.h"
"driverlib/gpio.h"
"driverlib/pwm.h"

#include "PWMTiva.h"
static
static
static
static
static
static

uint32_t ulPeriod0;
uint32_t ulPeriod1;
double duty0;
double duty1;
double duty2;
double duty3;

void PWM_TIVA_Init(void)
{
//Configure PWM Clock to system / 32
SysCtlPWMClockSet(SYSCTL_PWMDIV_32);
// Enable the peripherals used by this program.
SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOB);
SysCtlPeripheralEnable(SYSCTL_PERIPH_PWM0); //The Tiva Launchpad has two
modules (0 and 1). Module 1 covers the LED pins
// Calculate the period for 500 Hz including divide by 32 in PWM clock
ulPeriod0 = SysCtlClockGet()/32 / 500; //PWM frequency 500HZ
ulPeriod1 = ulPeriod0;
//Configure PB6,PB7,PB4, PB5 Pins as PWM

GPIOPinConfigure(GPIO_PB6_M0PWM0);
GPIOPinConfigure(GPIO_PB7_M0PWM1);
GPIOPinConfigure(GPIO_PB4_M0PWM2);
GPIOPinConfigure(GPIO_PB5_M0PWM3);
GPIOPinTypePWM(GPIO_PORTB_BASE, GPIO_PIN_4 | GPIO_PIN_5 | GPIO_PIN_6 |
GPIO_PIN_7);
//Configure PWM Options
//PWM_GEN_0 Covers M0PWM0 and M0PWM1
//PWM_GEN_1 Covers M0PWM2 and M0PWM3 See page 207 4/11/13 DriverLib doc
PWMGenConfigure(PWM0_BASE, PWM_GEN_0, PWM_GEN_MODE_UP_DOWN |
PWM_GEN_MODE_NO_SYNC);
PWMGenConfigure(PWM0_BASE, PWM_GEN_1, PWM_GEN_MODE_UP_DOWN |
PWM_GEN_MODE_NO_SYNC);
//Set the Period (expressed in clock ticks)
PWMGenPeriodSet(PWM0_BASE, PWM_GEN_0, ulPeriod0);
PWMGenPeriodSet(PWM0_BASE, PWM_GEN_1, ulPeriod1);
//Set PWM duty to
PWM_TIVA_SetDuty(
PWM_TIVA_SetDuty(
PWM_TIVA_SetDuty(
PWM_TIVA_SetDuty(

0 initially
0, 0);
0, 1);
0, 2);
0, 3);

// Enable the PWM generator


PWMGenEnable(PWM0_BASE, PWM_GEN_0);
PWMGenEnable(PWM0_BASE, PWM_GEN_1);
// Turn on the Output pins
PWMOutputState(PWM0_BASE, PWM_OUT_0_BIT | PWM_OUT_1_BIT | PWM_OUT_2_BIT |
PWM_OUT_3_BIT, true);
}
void PWM_TIVA_SetDuty( double dutyCycle, uint8_t channel)
{
double updateVal;
if ((0 == dutyCycle) || ( dutyCycle >= 100)){ // don't try to calculate with
0 DC
updateVal = 0;
}else{ // reasonable duty cycle number
if (channel < 2){ // group 0
updateVal = (ulPeriod0*dutyCycle)/100;
}else{
updateVal = (ulPeriod1*dutyCycle)/100;
}
}
switch (channel){
case 0:
duty0 = dutyCycle;
PWMPulseWidthSet(PWM0_BASE, PWM_OUT_0,updateVal);
break;
case 1:
duty1 = dutyCycle;

PWMPulseWidthSet(PWM0_BASE, PWM_OUT_1,updateVal);
break;
case 2:
duty2 = dutyCycle;
PWMPulseWidthSet(PWM0_BASE, PWM_OUT_2,updateVal);
break;
case 3:
duty3 = dutyCycle;
PWMPulseWidthSet(PWM0_BASE, PWM_OUT_3,updateVal);
}

break;

}
void PWM_TIVA_SetPulseWidth( uint16_t NewPW, uint8_t channel)
{
switch (channel){
case 0:
if ( NewPW < ulPeriod0)
PWMPulseWidthSet(PWM0_BASE, PWM_OUT_0,NewPW);
break;
case 1:
if ( NewPW < ulPeriod0)
PWMPulseWidthSet(PWM0_BASE, PWM_OUT_1,NewPW);
break;
case 2:
if ( NewPW < ulPeriod1)
PWMPulseWidthSet(PWM0_BASE, PWM_OUT_2,NewPW);
break;

case 3:
if ( NewPW < ulPeriod1)
PWMPulseWidthSet(PWM0_BASE, PWM_OUT_3,NewPW);
break;

}
/*****************************************************************************
PWM_TIVA_SetPeriod( uint16_t reqPeriod, uint8_t group)
sets the requested PWM group's period to the Requested Period
group 0 = channels 0 & 1
group 2 = channels 2 & 3
*****************************************************************************/
void PWM_TIVA_SetPeriod( uint16_t reqPeriod, uint8_t group)
{
//Set the Period (expressed in clock ticks)
if( 0 == group){
ulPeriod0 = reqPeriod;
PWMGenPeriodSet(PWM0_BASE, PWM_GEN_0, ulPeriod0);

PWM_TIVA_SetDuty( duty0, 0);


PWM_TIVA_SetDuty( duty1, 1);
}else{
if( 1 == group){
ulPeriod1 = reqPeriod;
PWMGenPeriodSet(PWM0_BASE, PWM_GEN_1, ulPeriod1);
PWM_TIVA_SetDuty( duty2, 2);
PWM_TIVA_SetDuty( duty3, 3);
}
}

/*****************************************************************************
PWM_TIVA_SetFreq( uint16_t reqPeriod, uint8_t group)
sets the requested PWM group's frequency to the Requested Frequency, in Hz
group 0 = channels 0 & 1
group 2 = channels 2 & 3
*****************************************************************************/
void PWM_TIVA_SetFreq( uint16_t reqFreq, uint8_t group)
{
//Set the Frequency (expressed in Hz)
if( 0 == group){
ulPeriod0 = SysCtlClockGet()/32 /reqFreq;
PWMGenPeriodSet(PWM0_BASE, PWM_GEN_0, ulPeriod0);
PWM_TIVA_SetDuty( duty0, 0);
PWM_TIVA_SetDuty( duty1, 1);
}else{
if( 1 == group){
ulPeriod1 = SysCtlClockGet()/32 /reqFreq;
PWMGenPeriodSet(PWM0_BASE, PWM_GEN_1, ulPeriod1);
PWM_TIVA_SetDuty( duty2, 2);
PWM_TIVA_SetDuty( duty3, 3);
}
}

19. ES_Configure.h

/****************************************************************************
Module
ES_Configure.h
Description
This file contains macro definitions that are edited by the user to
adapt the Events and Services framework to a particular application.
Notes
History
When
Who
-------------- --10/21/13 20:54 jec
08/06/13 14:10 jec

What/Why
-------lots of added entries to bring the number of timers
and services up to 16 each
removed PostKeyFunc stuff since we are moving that
functionality out of the framework and putting it

explicitly into the event checking functions


01/15/12 10:03 jec
started coding
*****************************************************************************/
#ifndef CONFIGURE_H
#define CONFIGURE_H
/****************************************************************************/
// The maximum number of services sets an upper bound on the number of
// services that the framework will handle. Reasonable values are 8 and 16
// corresponding to an 8-bit(uint8_t) and 16-bit(uint16_t) Ready variable size
#define MAX_NUM_SERVICES 16
/****************************************************************************/
// This macro determines that nuber of services that are *actually* used in
// a particular application. It will vary in value from 1 to MAX_NUM_SERVICES
#define NUM_SERVICES 7
/****************************************************************************/
// These are the definitions for Service 0, the lowest priority service.
// Every Events and Services application must have a Service 0. Further
// services are added in numeric sequence (1,2,3,...) with increasing
// priorities
// the header file with the public function prototypes
#define SERV_0_HEADER "GunFire.h"
// the name of the Init function
#define SERV_0_INIT InitGunFire
// the name of the run function
#define SERV_0_RUN RunGunFireSM
// How big should this services Queue be?
#define SERV_0_QUEUE_SIZE 3
/****************************************************************************/
// The following sections are used to define the parameters for each of the
// services. You only need to fill out as many as the number of services
// defined by NUM_SERVICES
/****************************************************************************/
// These are the definitions for Service 1
#if NUM_SERVICES > 1
// the header file with the public function prototypes
#define SERV_1_HEADER "ButtonModule.h"
// the name of the Init function
#define SERV_1_INIT InitializeButton
// the name of the run function
#define SERV_1_RUN RunButtonDebounceSM
// How big should this services Queue be?
#define SERV_1_QUEUE_SIZE 3
#endif
/****************************************************************************/
// These are the definitions for Service 2
#if NUM_SERVICES > 2
// the header file with the public function prototypes
#define SERV_2_HEADER "GunX.h"
// the name of the Init function
#define SERV_2_INIT InitGunX
// the name of the run function

#define SERV_2_RUN RunGunXSM


// How big should this services Queue be?
#define SERV_2_QUEUE_SIZE 3
#endif
/****************************************************************************/
// These are the definitions for Service 3
#if NUM_SERVICES > 3
// the header file with the public function prototypes
#define SERV_3_HEADER "RobotTimer.h"
// the name of the Init function
#define SERV_3_INIT InitRobotTimer
// the name of the run function
#define SERV_3_RUN RunRobotTimer
// How big should this services Queue be?
#define SERV_3_QUEUE_SIZE 3
#endif
/****************************************************************************/
// These are the definitions for Service 4
#if NUM_SERVICES > 4
// the header file with the public function prototypes
#define SERV_4_HEADER "LEDBoardModule.h"
// the name of the Init function
#define SERV_4_INIT InitializeLED
// the name of the run function
#define SERV_4_RUN LEDSM
// How big should this services Queue be?
#define SERV_4_QUEUE_SIZE 3
#endif
/****************************************************************************/
// These are the definitions for Service 5
#if NUM_SERVICES > 5
// the header file with the public function prototypes
#define SERV_5_HEADER "FearJoyModule.h"
// the name of the Init function
#define SERV_5_INIT InitFearJoy
// the name of the run function
#define SERV_5_RUN RunFearJoySM
// How big should this services Queue be?
#define SERV_5_QUEUE_SIZE 3
#endif
/****************************************************************************/
// These are the definitions for Service 6
#if NUM_SERVICES > 6
// the header file with the public function prototypes
#define SERV_6_HEADER "GunY.h"
// the name of the Init function
#define SERV_6_INIT InitGunY
// the name of the run function
#define SERV_6_RUN RunGunYSM
// How big should this services Queue be?
#define SERV_6_QUEUE_SIZE 3
#endif

/****************************************************************************/
// These are the definitions for Service 7
#if NUM_SERVICES > 7
// the header file with the public function prototypes
#define SERV_7_HEADER "TestHarnessService7.h"
// the name of the Init function
#define SERV_7_INIT InitTestHarnessService7
// the name of the run function
#define SERV_7_RUN RunTestHarnessService7
// How big should this services Queue be?
#define SERV_7_QUEUE_SIZE 3
#endif
/****************************************************************************/
// These are the definitions for Service 8
#if NUM_SERVICES > 8
// the header file with the public function prototypes
#define SERV_8_HEADER "TestHarnessService8.h"
// the name of the Init function
#define SERV_8_INIT InitTestHarnessService8
// the name of the run function
#define SERV_8_RUN RunTestHarnessService8
// How big should this services Queue be?
#define SERV_8_QUEUE_SIZE 3
#endif
/****************************************************************************/
// These are the definitions for Service 9
#if NUM_SERVICES > 9
// the header file with the public function prototypes
#define SERV_9_HEADER "TestHarnessService9.h"
// the name of the Init function
#define SERV_9_INIT InitTestHarnessService9
// the name of the run function
#define SERV_9_RUN RunTestHarnessService9
// How big should this services Queue be?
#define SERV_9_QUEUE_SIZE 3
#endif
/****************************************************************************/
// These are the definitions for Service 10
#if NUM_SERVICES > 10
// the header file with the public function prototypes
#define SERV_10_HEADER "TestHarnessService10.h"
// the name of the Init function
#define SERV_10_INIT InitTestHarnessService10
// the name of the run function
#define SERV_10_RUN RunTestHarnessService10
// How big should this services Queue be?
#define SERV_10_QUEUE_SIZE 3
#endif
/****************************************************************************/
// These are the definitions for Service 11
#if NUM_SERVICES > 11
// the header file with the public function prototypes
#define SERV_11_HEADER "TestHarnessService11.h"

// the name of the Init function


#define SERV_11_INIT InitTestHarnessService11
// the name of the run function
#define SERV_11_RUN RunTestHarnessService11
// How big should this services Queue be?
#define SERV_11_QUEUE_SIZE 3
#endif
/****************************************************************************/
// These are the definitions for Service 12
#if NUM_SERVICES > 12
// the header file with the public function prototypes
#define SERV_12_HEADER "TestHarnessService12.h"
// the name of the Init function
#define SERV_12_INIT InitTestHarnessService12
// the name of the run function
#define SERV_12_RUN RunTestHarnessService12
// How big should this services Queue be?
#define SERV_12_QUEUE_SIZE 3
#endif
/****************************************************************************/
// These are the definitions for Service 13
#if NUM_SERVICES > 13
// the header file with the public function prototypes
#define SERV_13_HEADER "TestHarnessService13.h"
// the name of the Init function
#define SERV_13_INIT InitTestHarnessService13
// the name of the run function
#define SERV_13_RUN RunTestHarnessService13
// How big should this services Queue be?
#define SERV_13_QUEUE_SIZE 3
#endif
/****************************************************************************/
// These are the definitions for Service 14
#if NUM_SERVICES > 14
// the header file with the public function prototypes
#define SERV_14_HEADER "TestHarnessService14.h"
// the name of the Init function
#define SERV_14_INIT InitTestHarnessService14
// the name of the run function
#define SERV_14_RUN RunTestHarnessService14
// How big should this services Queue be?
#define SERV_14_QUEUE_SIZE 3
#endif
/****************************************************************************/
// These are the definitions for Service 15
#if NUM_SERVICES > 15
// the header file with the public function prototypes
#define SERV_15_HEADER "TestHarnessService15.h"
// the name of the Init function
#define SERV_15_INIT InitTestHarnessService15
// the name of the run function
#define SERV_15_RUN RunTestHarnessService15
// How big should this services Queue be?

#define SERV_15_QUEUE_SIZE 3
#endif
/****************************************************************************/
// Name/define the events of interest
// Universal events occupy the lowest entries, followed by user-defined events
typedef enum { ES_NO_EVENT = 0,
ES_ERROR, /* used to indicate an error from the service */
ES_INIT,
/* used to transition from initial pseudo-state */
ES_TIMEOUT, /* signals that the timer has expired */
/* User-defined events start here */
ES_NEW_KEY, /* signals a new key received from terminal */
ES_LOCK,
EV_1L,
EV_1R,
EV_2L,
EV_2R,
EV_3L,
EV_3R,
EV_4L,
EV_4R,
EV_ButtonPushed,
EV_ButtonUp,
EV_ButtonFire,
EV_StartGame,
EV_FireGun,
EV_GunUp,
EV_GunDown,
EV_EndGame,
EV_LeftHallRisingEdge,
EV_RightHallRisingEdge,
EV_Dummy,
LtoLM,
LMtoL,
LMtoM,
MtoLM,
MtoRM,
RMtoM,
RMtoR,
RtoRM,
ES_UNLOCK} ES_EventTyp_t ;
/****************************************************************************/
// These are the definitions for the Distribution lists. Each definition
// should be a comma separated list of post functions to indicate which
// services are on that distribution list.
#define NUM_DIST_LISTS 0
#if NUM_DIST_LISTS > 0
#define DIST_LIST0 PostTestHarnessService0, PostTestHarnessService0
#endif
#if NUM_DIST_LISTS > 1
#define DIST_LIST1 PostTestHarnessService1, PostTestHarnessService1
#endif
#if NUM_DIST_LISTS > 2
#define DIST_LIST2 PostTemplateFSM
#endif

#if NUM_DIST_LISTS
#define DIST_LIST3
#endif
#if NUM_DIST_LISTS
#define DIST_LIST4
#endif
#if NUM_DIST_LISTS
#define DIST_LIST5
#endif
#if NUM_DIST_LISTS
#define DIST_LIST6
#endif
#if NUM_DIST_LISTS
#define DIST_LIST7
#endif

> 3
PostTemplateFSM
> 4
PostTemplateFSM
> 5
PostTemplateFSM
> 6
PostTemplateFSM
> 7
PostTemplateFSM

/****************************************************************************/
// This are the name of the Event checking funcion header file.
#define EVENT_CHECK_HEADER "AllEventCheckers.h"
/****************************************************************************/
// This is the list of event checking functions
#define EVENT_CHECK_LIST Check4Keystroke, CheckButtonEvents, CheckRightHall,
CheckLeftHall
/****************************************************************************/
// These are the definitions for the post functions to be executed when the
// corresponding timer expires. All 16 must be defined. If you are not using
// a timer, then you should use TIMER_UNUSED
// Unlike services, any combination of timers may be used and there is no
// priority in servicing them
#define TIMER_UNUSED ((pPostFunc)0)
#define TIMER0_RESP_FUNC TIMER_UNUSED
#define TIMER1_RESP_FUNC ES_PostLEDBoardSM
#define TIMER2_RESP_FUNC PostRobotTimer
#define TIMER3_RESP_FUNC TIMER_UNUSED
#define TIMER4_RESP_FUNC TIMER_UNUSED
#define TIMER5_RESP_FUNC TIMER_UNUSED
#define TIMER6_RESP_FUNC TIMER_UNUSED
#define TIMER7_RESP_FUNC TIMER_UNUSED
#define TIMER8_RESP_FUNC TIMER_UNUSED
#define TIMER9_RESP_FUNC PostFearJoySM
#define TIMER10_RESP_FUNC PostFearJoySM
#define TIMER11_RESP_FUNC PostButtonService
#define TIMER12_RESP_FUNC TIMER_UNUSED
#define TIMER13_RESP_FUNC PostRobotTimer
#define TIMER14_RESP_FUNC PostRobotTimer
#define TIMER15_RESP_FUNC PostGunX
/****************************************************************************/
// Give the timer numbers symbolc names to make it easier to move them
// to different timers if the need arises. Keep these definitions close to the
// definitions for the response functions to make it easier to check that
// the timer number matches where the timer event will be routed
// These symbolic names should be changed to be relevant to your application
#define LEDBoard_1s_Timer 1

#define
#define
#define
#define
#define
#define
#define

Robot_EndTimer 2
GameTimer 10
EndTimer 9
Button_Debounce_Timer 11
GunX_Event_Check_Timer 15
LED_Timer 13
Robot_Timer 14

#endif /* CONFIGURE_H */

20. main.c
#include
#include
#include
#include
#include
#include
#include
#include
#include

<stdint.h>
<stdbool.h>
<stdio.h>
"inc/hw_types.h"
"inc/hw_memmap.h"
"driverlib/sysctl.h"
"driverlib/gpio.h"
"driverlib/interrupt.h"
"utils/uartstdio.h"

#include
#include
#include
#include
#include
#include

"ES_Configure.h"
"ES_Framework.h"
"ES_Port.h"
"termio.h"
"ADCSWTrigger.h"
"PWMTiva.h"

#define clrScrn()
printf("\x1b[2J")
#define goHome() printf("\x1b[1,1H")
#define clrLine() printf("\x1b[K")
int main(void)
{
// Set the clock to run at 40MhZ using the PLL and 16MHz external
crystal
SysCtlClockSet(SYSCTL_SYSDIV_5 | SYSCTL_USE_PLL | SYSCTL_OSC_MAIN
| SYSCTL_XTAL_16MHZ);
TERMIO_Init();
clrScrn();
ES_Return_t ErrorType;
// When doing testing, it is useful to announce just which program
// is running.
puts("\rStarting Test Harness for \r");
printf("the 2nd Generation Events & Services Framework V2.2\r\n");
printf("%s %s\n",__TIME__, __DATE__);
printf("\n\r\n");
printf("Press any key to post key-stroke events to Service 0\n\r");
printf("Press 'd' to test event deferral \n\r");
printf("Press 'r' to test event recall \n\r");

// Your hardware initialization function calls go here\


//Hardware initialization directly from PWM
PWM_TIVA_Init();
PWM_TIVA_SetFreq(50, 0);
PWM_TIVA_SetFreq(400, 1);
PWM_TIVA_SetPulseWidth(1250,0);
PWM_TIVA_SetDuty( 50, 1);
PWM_TIVA_SetDuty( 25, 2);
PWM_TIVA_SetDuty( 50, 3);
// now initialize the Events and Services Framework and start it running
ErrorType = ES_Initialize(ES_Timer_RATE_1mS);
if ( ErrorType == Success ) {
ErrorType = ES_Run();
}
//if we got to here, there was an error
switch (ErrorType){
case FailedPost:
printf("Failed on attempt to Post\n");
break;
case FailedPointer:
printf("Failed on NULL pointer\n");
break;
case FailedInit:
printf("Failed Initialization\n");
break;
default:
printf("Other Failure\n");
break;
}
for(;;)
;
}

You might also like