Switches and interrupts on a PSoC 1 Microcontroller

I. Introduction / Summary

The most practical way for a microcontroller to retrieve input is via interrupt.  The vast majority of modern processors have interrupt functionality.  This functionality allows a processor to work on background tasks while no input has happened. Once input is detected, the processor diverts its attention to react, then returns to where it left off after the interrupt has been serviced.

II. Description and Circuit Diagrams

An optical encoder is connected to VCC and ground to provide power to its internal emitters, detectors, and squaring circuitry.  The encoders outputs are connected to P1[4] and P1[5] on the PSoc board. P2[0-6] are connected to a LCD on the evaluation board.

Using this setup, we will display to the LCD a number between 0 and 100 that reflects the direction of the encoder rotation.

III. Description of Software

The software routine enables interrupts, starts the LCD, and takes a measurement of the B output of the rotary encoder upon startup.  It then simply executes an infinite loop with no consequences.  The only way to leave this loop is via an interrupt triggered by a change in either the A or B inputs from the rotary encoder.  Once a change in input is detected, the execution jumps to the interrupt service routine named PSoC_GPIO_ISR_C(void). This ISR takes a measurement of the A input, clears the LCD, then performs an XOR operation on the current A and the previously stored B to determine whether the rotary encoder was turned clockwise or counter clockwise.  A count variable (initially = 50) is incremented or decremented accordingly within the explicitly defined limits of 0~100. The LCD is updated to display the count variable. Finally the current value of B is stored to be used during the next execution of the ISR.

IV. Validation and Testing

The setup was tested by turning the rotary encoder clockwise and counter-clockwise while observing the LCD to see the count being updated.  The encoder was moved to both the upper and lower limits to ensure that the LCD display correctly prevented any value < 0 or > 100 from being displayed.

V. Program listing

/*
 * Filename: RotaryInterrupt.c
 *
 * Title: updating a LCD with interrupts using a rotary encoder
 *
 * Description: This source code file is used with a Psoc 3 microcontroller to read a rotary
 * encoder. Every time the encoder is moved, the LCD is updated to reflect the movement.
 *
 * Copyright 2011 BK Turley & Robert Sanson. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification, are
 * permitted provided that the following conditions are met:
 *
 *   1. Redistributions of source code must retain the above copyright notice, this list of
 *      conditions and the following disclaimer.
 *
 *   2. Redistributions in binary form must reproduce the above copyright notice, this list
 *      of conditions and the following disclaimer in the documentation and/or other materials
 *      provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY BK Turley & Robert Sanson ''AS IS'' AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
 * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BK Turley, Robert Sanson OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * The views and conclusions contained in the software and documentation are those of the
 * authors and should not be interpreted as representing official policies, either expressed
 * or implied, of BK Turley & Robert Sanson.
 *
 */

#include <m8c.h>        // part specific constants and macros
#include "PSoCAPI.h"    // PSoC API definitions for all User Modules
#include <stdlib.h>
#include <string.h>

#pragma interrupt_handler PSoC_GPIO_ISR_C

// Global Variables
int count = 50;
BOOL CW;
BYTE A, B;
unsigned char cnt_as_str[8];

void main(void)
{
	// Enable global interrupts (see m8c.h)
	M8C_EnableGInt;
	// Enable GPIO Interrupts (see m8c.h)
	M8C_EnableIntMask(INT_MSK0,INT_MSK0_GPIO);

	LCD_Start();

	// Set A and B to current values
	B = OpEncB_Data_ADDR & OpEncB_MASK;

	// Spin here forever
	while(1);
}

void PSoC_GPIO_ISR_C(void)
{
	A = OpEncA_Data_ADDR & OpEncA_MASK;  // get current A value

	LCD_Control(LCD_DISP_CLEAR_HOME); //clear lcd

	CW = (B >> 5) ^ (A >> 4); //determine CW or CCW

	if (CW)
	{
		if (count <= 99)
			count++;
	} else {
		if (count >= 1)
			count--;
	}

	//display count on line 1
	itoa(cnt_as_str,count,10);
	LCD_Position(0,0);
	LCD_PrString(cnt_as_str);

	B = OpEncB_Data_ADDR & OpEncB_MASK; //get fresh value for B
}

Polling a switch Using a PSoC 1 Microcontroller

     One way for a microcontroller to retrieve input is known as polling.  Polling means repeatedly measuring  a sensors value.  I will describe how to poll a pushbutton switch  and react to its measurement when using a Psoc3 microcontroller.

 

/*
 * Filename: switchpolling.c
 *
 * Title: Polling a switch with a Psoc microcontroller
 *
 * Description: This source code file is used with a Psoc 3 microcontroller to poll a switch.
 *  Upon detecting a change in the switches state, An LCD is updated to display the number of
 *  times the switch has been closed in Hex and decimal format.
 *
 * Copyright 2011 BK Turley & Robert Sanson. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification, are
 * permitted provided that the following conditions are met:
 *
 *   1. Redistributions of source code must retain the above copyright notice, this list of
 *      conditions and the following disclaimer.
 *
 *   2. Redistributions in binary form must reproduce the above copyright notice, this list
 *      of conditions and the following disclaimer in the documentation and/or other materials
 *      provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY BK Turley & Robert Sanson ''AS IS'' AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
 * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BK Turley & Robert Sanson OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * The views and conclusions contained in the software and documentation are those of the
 * authors and should not be interpreted as representing official policies, either expressed
 * or implied, of BK Turley & Robert Sanson.
 *
 */

#include         // part specific constants and macros
#include "PSoCAPI.h"    // PSoC API definitions for all User Modules
#include 	// needed to use itoa()

void main(void)
{
	WORD count = 0; // holds the number of switch presses
	unsigned char c2[4]; // holds count's value after conversion to a C string.
	unsigned char cnt[12] = "Counting   "; //a label for LCD
	unsigned char lbl[12] = "Hex:   Dec:"; //another label for LCD

	LCD_Start();

	while (1)//poll, but only increment count once per switch press.
	{
		BOOL pressed = SWITCH_Data_ADDR & SWITCH_MASK; //take a measurement of the switch state
		if (pressed)
		{
			count++;
			while (pressed)
			{
				LCD_Position(0,0);
				LCD_PrString(cnt);
				pressed = SWITCH_Data_ADDR & SWITCH_MASK;
			}
		}

		// Display count to LCD in Hex and Decimal format.
		LCD_Position(0,0);
		LCD_PrString(lbl);
		LCD_Position(1,0);
		LCD_PrHexByte(count);
		LCD_Position(1,7);
		itoa(c2,count,10);// store count's value as a decimal string for display purposes.
		LCD_PrString(c2);
	}

}

Simple Multi-threaded web server written in C using pthreads

This Multi-threaded web server takes advantage of the posix thread library to enable it it serve multiple files at the same time.  Compile using gcc and run on a linux server.


// Multi-Threaded web server using posix pthreads
// BK Turley 2011

//this simple web server is capible of serving simple html, jpg, gif & text files

//----- Include files ---------------------------------------------------------
#include <stdio.h>          // for printf()
#include <stdlib.h>         // for exit()
#include <string.h>         // for strcpy(),strerror() and strlen()
#include <fcntl.h>          // for file i/o constants
#include <sys/stat.h>       // for file i/o constants
#include <errno.h>

/* FOR BSD UNIX/LINUX  ---------------------------------------------------- */
#include <sys/types.h>      //
#include <netinet/in.h>     //
#include <sys/socket.h>     // for socket system calls
#include <arpa/inet.h>      // for socket system calls (bind)
#include <sched.h>
#include <pthread.h>        /* P-thread implementation        */
#include <signal.h>         /* for signal                     */
#include <semaphore.h>      /* for p-thread semaphores        */
/* ------------------------------------------------------------------------ */  

//----- HTTP response messages ----------------------------------------------
#define OK_IMAGE    "HTTP/1.0 200 OK\nContent-Type:image/gif\n\n"
#define OK_TEXT     "HTTP/1.0 200 OK\nContent-Type:text/html\n\n"
#define NOTOK_404   "HTTP/1.0 404 Not Found\nContent-Type:text/html\n\n"
#define MESS_404    "<html><body><h1>FILE NOT FOUND</h1></body></html>"

//----- Defines -------------------------------------------------------------
#define BUF_SIZE            1024     // buffer size in bytes
#define PORT_NUM            6110     // Port number for a Web server (TCP 5080)
#define PEND_CONNECTIONS     100     // pending connections to hold
#define TRUE                   1
#define FALSE                  0
#define NTHREADS 5                     /* Number of child threads        */
#define NUM_LOOPS  10                  /* Number of local loops          */
#define SCHED_INTVL 5                  /* thread scheduling interval     */
#define HIGHPRIORITY 10

/* global variables ---------------------------------------------------- */
sem_t thread_sem[NTHREADS];
int   next_thread;
int   can_run;
int   i_stopped[NTHREADS]; 

unsigned int	client_s;				// Client socket descriptor

/* Child thread implementation ----------------------------------------- */
void *my_thread(void * arg)
{
	unsigned int	myClient_s;			//copy socket

	/* other local variables ------------------------------------------------ */
  char           in_buf[BUF_SIZE];           // Input buffer for GET resquest
  char           out_buf[BUF_SIZE];          // Output buffer for HTML response
  char           *file_name;                 // File name
  unsigned int   fh;                         // File handle (file descriptor)
  unsigned int   buf_len;                    // Buffer length for file reads
  unsigned int   retcode;                    // Return code

  myClient_s = *(unsigned int *)arg;		// copy the socket

  /* receive the first HTTP request (HTTP GET) ------- */
      retcode = recv(client_s, in_buf, BUF_SIZE, 0);

      /* if receive error --- */
      if (retcode < 0)
      {   printf("recv error detected ...\n"); }

      /* if HTTP command successfully received --- */
      else
      {
        /* Parse out the filename from the GET request --- */
        strtok(in_buf, " ");
        file_name = strtok(NULL, " ");

		//test for high priority file
		if(0 == strcmp(&file_name[1],"test_00.jpg")){
			int diditwork = pthread_setschedprio(pthread_self(), HIGHPRIORITY);
			if(!diditwork)
				printf("priority wasn't increased correctly ...\n");
			else{
				printf("High priority thread created ...\n");
			}
		}

        /* Open the requested file (start at 2nd char to get rid of leading "\") */
        fh = open(&file_name[1], O_RDONLY, S_IREAD | S_IWRITE);

        /* Generate and send the response (404 if could not open the file) */
        if (fh == -1)
        {
          printf("File %s not found - sending an HTTP 404 \n", &file_name[1]);
          strcpy(out_buf, NOTOK_404);
          send(client_s, out_buf, strlen(out_buf), 0);
          strcpy(out_buf, MESS_404);
          send(client_s, out_buf, strlen(out_buf), 0);
        }
        else
        {
          printf("File %s is being sent \n", &file_name[1]);
          if ((strstr(file_name, ".jpg") != NULL)||(strstr(file_name, ".gif") != NULL))
          { strcpy(out_buf, OK_IMAGE); }

          else
          { strcpy(out_buf, OK_TEXT); }
          send(client_s, out_buf, strlen(out_buf), 0);

          buf_len = 1;
          while (buf_len > 0)
          {
            buf_len = read(fh, out_buf, BUF_SIZE);
            if (buf_len > 0)
            {
              send(client_s, out_buf, buf_len, 0);
               //printf("%d bytes transferred ..\n", buf_len);
            }
          }

          close(fh);       // close the file
          close(client_s); // close the client connection
		  pthread_exit(NULL);
        }
      }

}

//===== Main program ========================================================
int main(void)
{
  /* local variables for socket connection -------------------------------- */
  unsigned int			server_s;				// Server socket descriptor
  struct sockaddr_in	server_addr;			// Server Internet address
  //unsigned int			client_s;			// Client socket descriptor
  struct sockaddr_in	client_addr;			// Client Internet address
  struct in_addr		client_ip_addr;			// Client IP address
  int					addr_len;				// Internet address length

  unsigned int			ids;					// holds thread args
  pthread_attr_t		attr;					//	pthread attributes
  pthread_t				threads;				// Thread ID (used by OS)

  /* create a new socket -------------------------------------------------- */
  server_s = socket(AF_INET, SOCK_STREAM, 0);

  /* fill-in address information, and then bind it ------------------------ */
  server_addr.sin_family = AF_INET;
  server_addr.sin_port = htons(PORT_NUM);
  server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
  bind(server_s, (struct sockaddr *)&server_addr, sizeof(server_addr));

  /* Listen for connections and then accept ------------------------------- */
  listen(server_s, PEND_CONNECTIONS);

  /* the web server main loop ============================================= */
  pthread_attr_init(&attr);
  while(TRUE)
  {
    printf("my server is ready ...\n");  

    /* wait for the next client to arrive -------------- */
    addr_len = sizeof(client_addr);
    client_s = accept(server_s, (struct sockaddr *)&client_addr, &addr_len);

    printf("a new client arrives ...\n");  

    if (client_s == FALSE)
    {
      printf("ERROR - Unable to create socket \n");
      exit(FALSE);
    }

    else
    {
		/* Create a child thread --------------------------------------- */
		ids = client_s;
        pthread_create (					/* Create a child thread        */
                   &threads,				/* Thread ID (system assigned)  */
                   &attr,					/* Default thread attributes    */
                   my_thread,				/* Thread routine               */
                   &ids);					/* Arguments to be passed       */

    }
  }

  /* To make sure this "main" returns an integer --- */
  close (server_s);  // close the primary socket
  return (TRUE);        // return code from "main"
}

Simple Example of Multithreading in C Linux

This simple example demonstrates the use of multithreading in the linux environment. This little piece of C code has two threads, a producer thread and a consumer thread. The producer thread generates 600 random numbers, which are passed one at a time to a consumer thread via shared memory. Both threads sum all of the random numbers. The fact that both the producer and consumer have the same sum is proof that the thread are communicating together correctly.


/*
 * File:   CS314_P01_BKT.c
 * Author: BK Turley
 *
 */

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/sem.h>

#define FIFO_Size 10 //not used anywhere
#define NUM_REPEAT 600  // 6000000 takes wayyyyy too long.

#define SHMKEY     ((key_t) 8080)   /* The shared memory ID                 */
#define SEMKEY_1   ((key_t) 8081L)  /* The semaphore ID for MUTEX           */
#define PERMS      0666             /* Access permission codes             */

/* Prototypes ------------------------------------------------------------- */
void insert_delay();
void insert_delay_long();
int sem_create(key_t sem_key, int init_val); /* Creating a semaphore    */
void sem_rm(int id);                         /* Remove a semaphore      */
int randomint(void);                        // return a random number from 1-200
//note that 0 values indicate empty locations.

/* Global Variables ------------------------------------------------------- */
static struct sembuf op_down[1] = {
    0, -1, 0
};
static struct sembuf op_up[1] = {
    0, 1, 0
};
union {
    int val;
    struct semid_ds *buf;
    ushort *array;
} semctl_arg;

/* The Main --------------------------------------------------------------- */
int main(void) {
    int pid; /* Process ID                          */
    int cpid; /* Child process ID                    */
    long int i; /* Loop counter                        */
    int status; /* The exit code from a child process  */

    int shmid; /* Shared memory ID                    */
    int mutex; /* Semaphore ID for "MUTEX" semaphore  */
    int shared_int[1];
    shared_int[1] = 0;
    int * shm_pointer = &shared_int[0]; /* Pointer to the shared memory        */

    /* Create a shared memory ---------------------------------------------- */
    shmid = shmget(SHMKEY, sizeof (shared_int), PERMS | IPC_CREAT);

    /* Attach the shared memory -------------------------------------------- */
    shm_pointer = (int *) shmat(shmid, (int *) 0, 0);

    /* Create a semaphore -------------------------------------------------- */
    mutex = sem_create(SEMKEY_1, 1);

    /* Create the writer process ------------------------------------------- */
    pid = fork();

    /* If pid is not zero, this must be the parent process --- */
    if (pid != 0) {
        /* The parent process creates the reader process --- */
        pid = fork();

        /* If pid is not zero, this must be the parent process --- */
        if (pid != 0) {
            //printf("\nThe parent process is now waiting for the two processes to be completed ... \n");

            cpid = wait(&status);
            //printf("\nA child process %d with process ID = %d has terminated ... \n", (status / 256), cpid);

            cpid = wait(&status);
            //printf("A child process %d with process ID = %d has terminated ... \n", (status / 256), cpid);

            //printf("\nBoth processes have completed and the parent process is terminating ...\n");

            /* Detaching the shared memory --------------------------------- */
            shmdt(shm_pointer);

            /* Deleting the shared memory ---------------------------------- */
            shmctl(shmid, IPC_RMID, (struct shmid_ds *) 0);

            /* Deleting the MUTEX semaphore -------------------------------- */
            sem_rm(mutex);

            //printf("\nThe parent process is now terminating ... \n\n");
            exit(0);
            // END OF PARENT PROCESS

        }/* If pid is zero, this is the writer process --- */
        else {

            long int prodsum = 0;
            int rand = 0;
            i = 0;

            /* Producer algorithm --- */
            while (i < NUM_REPEAT) {

                /* ENTER THE CRITICAL SECTION --- */
                status = semop(mutex, &op_down[0], 1); /* DOWN Operation --- */
                if (status < 0) {
                    printf("DOWN Operation ERROR (WRITER) .... \n");
                }

                /* CRITICAL SECTION --- */

                if(shm_pointer[1] == 0){
                   shm_pointer[0] = randomint();
                    prodsum = prodsum + shm_pointer[0];
                    shm_pointer[1] = 1;
                    i++;
                }

                /* LEAVE THE CRITICAL SECTION --- */
                status = semop(mutex, &op_up[0], 1); /* UP Operation --- */
                if (status < 0) {
                    printf("UP Operation ERROR (WRITER) .... \n");
                }
            }

            printf("PRODUCER SUM: %d.\n", prodsum);

            /* Terminate the producer process and send a signal to the parent process --- */
            exit(1);
        }
    }/* If pid is zero, this is the consumer process --- */
    else {
        int temp;
        long int conssum = 0;
        i = 0;

        /* consumer algorithm --- */
        while (i < NUM_REPEAT) {

            /* ENTER THE CRITICAL SECTION --- */
            status = semop(mutex, &op_down[0], 1); /* DOWN Operation --- */
            if (status < 0) {
                printf("DOWN Operation ERROR (READER) ... \n");
            }

            /* CRITICAL SECTION --- */

                if(shm_pointer[1] == 1){
                    conssum = conssum + shm_pointer[0];
                    shm_pointer[1] = 0;
                    i++;
                }

            /* LEAVING THE CRITICAL SECTION --- */
            status = semop(mutex, &op_up[0], 1); /* UP Operation --- */
            if (status < 0) {
                printf("UP Operation ERROR (READER) ... \n");
            }
        }
        printf("CONSUMER SUM: %d.\n", conssum);
        exit(2);
    }
}

/* create a semaphore ------------------------------------------------------- */
int sem_create(key_t key, int init_val) {
    register int id, semval;
    int status;

    if (key == IPC_PRIVATE) {
        printf("key == IP_PRIVATE ERROR ... \n");
        return (-1);
    } else if (key == (key_t) - 1) {
        printf("key == -1 ERROR ... \n");
        return (-1);
    }

    id = semget(key, 1, IPC_CREAT | PERMS);
    if (id < 0) {
        printf("sem_get ERROR ... \n");
        return (-1);
    }

    semctl_arg.val = 0;
    semval = semctl(id, 0, GETVAL, semctl_arg);
    if (semval < 0) {
        printf("semctl ERROR ... \n");
    }

    if (semval == 0) {
        semctl_arg.val = init_val;
        status = semctl(id, 0, SETVAL, semctl_arg);
        if (status < 0) {
            printf("Can't SETVAL ... ERROR ... \n");
        }
    }

    return (id);
}

/* insert_delay ------------------------------------------------------------- */
void insert_delay() {
    long int i, j, k;

    for (i = 0; i < 1000000; i++) {
        for (j = 0; j < 5; j++) {
            k = k + 1;
        }
    }
}

/* insert_delay_long -------------------------------------------------------- */
void insert_delay_long() {
    long int i, j, k;

    for (i = 0; i < 1000000; i++) {
        for (j = 0; j < 50; j++) {
            k = k + 1;
        }
    }
}

/* sem_rm ------------------------------------------------------------------- */
void sem_rm(int id) {
    int status;

    semctl_arg.val = 0;
    status = semctl(id, 0, IPC_RMID, semctl_arg);
    if (status < 0) {
        printf("ERROR in sen_rm ... \n");
    }
}

int randomint(void) {
    int lowerlimit = 1;
    int upperlimit = 200;
    srand(time(NULL));
    int random_number = lowerlimit + (rand() % (upperlimit - lowerlimit));
    if (random_number == 0)//make absolutely sure 0 is NEVER returned
        return 1;
    return lowerlimit + (rand() % (upperlimit - lowerlimit));
}

Binary Search Tree implemented. C++

This is my personal implementation of a binary search tree. My tree uses iteration instead of recursion for its insertion, deletion and searches for faster execution because function stack overhead is avoided. Recursion is still used for tree deletion because I didn’t want to implement a stack for the traversal of the tree which is required for deletion.

// SearchableADT test driver
// Copyright (C) 2011 Kyle Turley
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.

// Purpose:
// this test driver is used to emperically test the performance of various
// searchable abstract data structures that adhere to the SearchableADT
// interface.

#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#include <vector>
#include <algorithm>
#include <ctime>
#include <cstdlib>
#include "BST.h"

using namespace std;

void menu_Loop(), menu_Choices(char ans);
void load_dict(), clr_dict(), find_a_word(), find_from_file(), tree_stats(), end_program();
bool isfound(string findme);

//declare a new SearchableADT to test
SearchableADT<string> *dictionary = new BST<string>;

int main() {

    menu_Loop();

    return 0;
}//end main

void menu_Loop() {
    char ans; //declare ans variable, this will be used OVER AND OVER
    do {
        cout << "--- ADT Tinkering Menu ---" << endl;
        cout << "1: Load a Dictionary File" << endl;
        cout << "2: Clear Dictionary" << endl;
        cout << "3: Check for an Entry" << endl;
        cout << "4: Check for Entries from File" << endl;
        cout << "5: Report Tree Statistics" << endl;
        cout << "6: Option 6 - Exit" << endl; //print us some options

        cin >> ans; //take in an answer
        cin.ignore(80, '\n'); 

        menu_Choices(ans);
    } while (ans != '6'); //keep on running on till they pick exit!
}// end menu_Loop()

void menu_Choices(char ans) {
    switch (ans)//roll thru options
    {
        case '1':
            load_dict();
            break;
        case '2':
            clr_dict();
            break;
        case '3':
            find_a_word();
            break;
        case '4':
            find_from_file();
            break;
        case '5':
            tree_stats();
            break;
        case '6':
            end_program();
            break;
        default://THEY DIDNT READ THE MENU, WHO WOULD HAVE THOUGHT?!?!
            cout << "Please read and follow all directions\n";
            break;
    }
}// end menu_Choices(char ans)

//functions, FILL WITH VALUABLE PROGRAMMING SKILLS

// Asks the user for a filename, then loads each whitespace delineated string into the SearchableADT
void load_dict() {

    string filename = "";
    fstream in;
    clock_t start, finish;
    while (!in.is_open()) {
        cout << "Enter a valid C++ file to Load" << endl;
        cin >> filename;
        in.open(filename.c_str());
    }
    start = clock();
    dictionary->loadFromFile(filename);
    finish = clock();
    in.close();
    cout << "## file added to ADT ##" << endl;
    cout << "Load time: " << ((double) (finish - start) / CLOCKS_PER_SEC) << "sec" << endl;
}

// releases all memory occupied by the SearchableADT
void clr_dict() {
    clock_t start, finish;
    start = clock();
    dictionary->clear();
    finish = clock();
    cout << "## ADT CLEARED ##" << endl;
    cout << "time: " << ((double) (finish - start) / CLOCKS_PER_SEC) << "sec" << endl;
}

// Asks the user for a word
void find_a_word() {
    string findme;
    cout << "Enter a string to search for" << endl;
    cin >> findme;

    clock_t start, finish;
    start = clock();
    // insert timing code here
    if(isfound(findme)){
        cout << "found it" << endl;
    }else
        cout << "not found" << endl;
    finish = clock();
    cout << "time: " << ((double) (finish - start) / CLOCKS_PER_SEC) << "sec" << endl;
}

void find_from_file() {

    string filename = "";
    fstream in;
    clock_t start, finish;
    stringstream buffer;
    string temp;
    int misspelled_count = 0;

    while (!in.is_open()) {
        cout << "Enter a valid Text file to Read" << endl;
        cin >> filename;
        in.open(filename.c_str());
    }

    buffer << in.rdbuf();
    in.close();
    start = clock();
    // attempt to find each word
    while (buffer.good()) {
        buffer >> temp;
        if(!isfound(temp)){
            cout << temp << " isn't in the dictionary" << endl;
            misspelled_count++;
        }
    }
    finish = clock();
    cout << misspelled_count << " misspelled words were found" << endl;
    cout << "Search time: " << ((double) (finish - start) / CLOCKS_PER_SEC) << "sec" << endl;
}

void tree_stats() {
    clock_t start, finish;
    start = clock();
    cout << "Number of Entries: " << dictionary->numEntries() << endl;
    finish = clock();
    cout << "Report time: " << ((double) (finish - start) / CLOCKS_PER_SEC) << "sec" << endl;
}

bool isfound(string findme){
    bool isfound = false;
    string alphabet = "abcdefghijklmnopqrstuvwxyz";

    // make findme lowercase
    for (int i = 0; i < strlen(findme.c_str()); i++) {
        if (findme[i] >= 0x41 && findme[i] <= 0x5A)
            findme[i] = findme[i] + 0x20;
    }

    //if findme contains a ? character, generate a list of 26 possibilities to search for
    if (findme.find_first_of('?') != string::npos) {
        string possibilities[25];
        int qmarkindex = findme.find_first_of('?');

        for (int i = 0; i < 25; i++) {
            possibilities[i] = findme.replace(qmarkindex, 1, 1, alphabet[i]);
            if (dictionary->isThere(possibilities[i])){
                cout << possibilities[i] << endl;
                isfound = true;
            }
        }
    } else // no '?' character was found,
        isfound = dictionary->isThere(findme);
    return isfound;
}

void end_program(){
	dictionary->clear(); // release memory stored by the dictionary
	exit(0);
}
// Abstract Searchable ADT interface
// Copyright (C) 2011 Kyle Turley
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.

#ifndef SEARCHABLEADT_H
#define SEARCHABLEADT_H

#include <string>

using namespace std;

template <typename T>
class SearchableADT{
public:
	// these are all purely virtual functions that must be implemented by all classes that inherit from SearchableADT().
	virtual int loadFromFile(string filename) = 0;
	virtual void clear(void) = 0;
	virtual void insertEntry(T value) = 0;
	virtual void deleteEntry(T value) = 0;
	virtual bool isThere(T value) = 0 ;
	virtual int numEntries(void) = 0;

private :
	//no private methods or data members.

};

#endif
// BST class
// Copyright (C) 2011 Kyle Turley
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.

#ifndef BST_H
#define BST_H
#pragma once

#include "SearchableADT.h"
#include <cstring>

using namespace std;

template <typename T>
class binarynode {
public:
    T data;
    binarynode<T> *left;
    binarynode<T> *right;
};

template <typename T>
class BST : public SearchableADT<T> {
public:
    BST(void);
    ~BST(void);
    int loadFromFile(string filename);
    void clear(void);
    void insertEntry(T value);
    void deleteEntry(T value);
    bool isThere(T value);
    int numEntries(void);

    // additional methods, not part of abstract interface
    void postorder_delete(binarynode<T>* itr);
    int BST<T>::height(binarynode<T>* itr);

private:
    binarynode<T> * root_ptr;
    double numnodes;

};

template <typename T>
BST<T>::BST(void) {
    root_ptr = NULL;
    numnodes = 0;
}

template <typename T>
BST<T>::~BST(void) {
    this->clear();
}

template <typename T>
int BST<T>::loadFromFile(string filename) {

    fstream in;
    vector<T> vect;
    vector<T>::const_iterator iter;
    std::stringstream buffer;
    string temp;

    in.open(filename.c_str());
    buffer << in.rdbuf();

    // read each word into a vector
    while (buffer.good()) {
        buffer >> temp;
        vect.push_back(temp);
    }
    // randomize the vector for more efficient inserts
    // just in case the user tries to input a sorted file.
    // "A good programmer looks both ways before crossing a one way street"
    srand(time(0));
    random_shuffle(vect.begin(), vect.end());

    //now insert each randomized entry into the BST
    for (iter = vect.begin(); iter != vect.end(); ++iter) {
        //cout << *iter << endl;
        this->insertEntry(*iter);
    }

    return 0;
}

template <typename T>
void BST<T>::clear(void) {
    this->postorder_delete(root_ptr);
    root_ptr = NULL;
    //numnodes = 0;
    return;
}

template <typename T>
void BST<T>::insertEntry(T value) {

    // create the new node to be inserted and populate it with data
    binarynode<T> *temp, *prev, *curr;
    temp = new binarynode<T>;
    temp->data = value;
    temp->left = NULL;
    temp->right = NULL;

    // insert the node into its proper place in the tree
    if (root_ptr == NULL) {
        // the tree is empty so make the new node the root
        root_ptr = temp;
    } else {
        // discover the new nodes proper place in a binary search fashion
        curr = root_ptr;
        while (curr != NULL) {
            prev = curr;
            if (temp->data < curr->data)
                curr = curr->left;
            else
                curr = curr->right;
        }
        // the proper place has been found at this point.  insert the new node
        if (temp->data < prev->data)
            prev->left = temp;
        else
            prev->right = temp;
    }
    numnodes++;
    return;
}

template <typename T>
void BST<T>::deleteEntry(T value) {

    binarynode<T> *prev, *curr, *grandparent;
    prev = curr = grandparent = NULL;

    binarynode<T> *deleteme = new binarynode<T>;
    deleteme->data = value;

    // discover where the node should be in a binary search fashion
    curr = root_ptr;
    while (curr != NULL) {
        grandparent = prev;
        prev = curr;
        if (deleteme->data < curr->data)
            curr = curr->left;
        else if (deleteme->data > curr->data)
            curr = curr->right;
        else
            break;
    }
    if (deleteme->data == prev->data) {// found it, now delete it. There are special cases for different children
        if (prev->left == NULL && prev->right == NULL) { //no children
            if (grandparent->left->data == prev->data)
                grandparent->left = NULL;
            else
                grandparent->right = NULL;
            delete prev;
        } else if (prev->left == NULL && prev->right != NULL) { //right child exists
            if (grandparent->left->data == prev->data)
                grandparent->left = prev->right;
            else
                grandparent->right = prev->right;
            delete prev;
        } else if (prev->left != NULL && prev->right == NULL) { //left child exists
            if (grandparent->right->data == prev->data)
                grandparent->right = prev->left;
            else
                grandparent->left = prev->left;
            delete prev;
        }
    }
    numnodes--;
}

template <typename T>
bool BST<T>::isThere(T value) {
    binarynode<T> *prev, *curr;

    curr = root_ptr;

    // find the right spot in an iterative fashion
    // recursion should be avoided whenever possible for safety and performance
    while (curr != NULL) {
        prev = curr;
        if (value < curr->data)
            curr = curr->left;
        else if (value > curr->data)
            curr = curr->right;
        else if (prev->data == value)
            return true; // value was found
    }
    return false; //value wasn't found
}

template <typename T>
int BST<T>::numEntries(void) {
    // do a post-order traversal counting along the way
    // this is kinda hacked, but I want to preserve the given SearchableADT interface

    cout << "Tree Height: " << height(root_ptr) << endl;

    return numnodes;
}

template <typename T>
void BST<T>::postorder_delete(binarynode<T>* itr) {
    if (itr != NULL) {
        postorder_delete(itr->left);
        postorder_delete(itr->right);
        delete itr;
        numnodes--;
    }
    return;
}

template <typename T>
int BST<T>::height(binarynode<T>* itr) {
    if (itr == NULL)
        return -1;
    else
        return 1 + max(height(itr->left), height(itr->right));
}

#endif

convert integer to any base C++

this function is capable of converting integers to any base format 2-16. this includes binary, octal, and hexadecimal. adding larger bases is as simple as lengthening the alpha string.

//this recursive base converter is valid for base 2~16
void Converter::toBase(int n, int base)
{
    	string alpha="0123456789ABCDEF";
    	if (n > 0)
        	{
        		toBase(n/base,base);
        		cout << alpha[n%base];
        	}
}

Some Great Examples of recursion C++

This little program demonstrates the recursion technique in three different settings.  It includes recursive algorithms to search an array, reverse a number, and find the greatest common divisor of two numbers.

// Boyd Turley
#include <iostream>
#include <string>
#include <fstream>
#include <iomanip> //required to use setw()
#include <cstdio>

using namespace System;
using namespace std;
///////////////////////////////////// Globals
const int TABLE_ROWS = 30;
const int TABLE_COLS = 20;
int table[TABLE_COLS][TABLE_ROWS];
int grid[599];

//////////////////////////////////// FXN Defs.
bool posWhole(int checkme);

void NumReverse(int reverseme);

void setOrder(int num1, int num2);

int GCD(int num1, int num2);

void gridSearch();

///////////////////////////////////////////////////////////////////////////////////////// MAIN
int main(array<System::String ^> ^args)
{
	char thechoice = 0;

		while(thechoice != '!')
		{
			system("cls");
			cout << "Recursion Menu:"<<endl
			 << "S.  Search an array for a number." << endl
			 << "M. Mirror a number." << endl
			 << "G. Greatest Common Devisor." << endl
			 << "Q. Quit Program." << endl;
			cin >> thechoice;

		switch(thechoice)
		{
			int num;
			case 'S':
			case 's':
				{
					system("cls");
					gridSearch();
					cout << endl;
					system("pause");
					break;
				}
			case 'M':
			case 'm':
				{
				system("cls");
				cout << "Enter the number to be mirrored" << endl << "\n\t";
// validate positive and whole
				if(!(cin >> num))
				{
					cout << "thats not a int, try again.";
					thechoice = '#';

								// {// flush cin buffer somehow...}

					system("pause");
					break;
				}
				NumReverse(num);
				break;
				}
			case 'G':
			case 'g':
				{
					system("cls");
					unsigned int num1,num2;
					cout << "Enter two intigers to find their GCD"<<endl;
					cin >> num1 >>num2;
					cout << GCD(num1,num2) << endl;
					system("pause");
					break;
				}
			case 'Q':
			case 'q':
				{
					thechoice  = '!';
					break;
				}
			default:
				{
					cout << "Enter S, M, G, or Q followed by the enter key.\n\n";
					cin.clear();

					system("pause");
					break;
				}
		}}

		cout << "\n\tend Of prog\n";
		system("pause");
	return 0;
}

///////////////////////////////////////////////////////////////////////////////////////// FXN METHODS
bool posWhole(int checkme)
{
	return true;
}

void NumReverse(int reverseme)
{
	if(reverseme<=0)
	{	cout << "Bad Input";
		system("pause");
		return;
	}
	else{
		//base case: 1 digit.
		if((reverseme/10) < 1)
		{
			cout << reverseme << "...is the mirrored number." << endl;
			system("pause");
			system("cls");
			return ;
		}
		//recursive step:
		cout << (reverseme%10);
		NumReverse(reverseme/10);
	}
}

void setOrder(int num1, int num2)
{
	if(num1>num2)
	{
		int tempswap = num1;
		num1 = num2;
		num2 = tempswap;
	}
}

int GCD(int num1, int num2)
{
	setOrder(num1,num2);
	while(num1<=0 || num2<=0)
	{
		cout << "No negative numbers"<<endl;
		cin >> num1 >> num2;
	}
	if(num1%num2 ==0)
	{
		return num2;
	}
	return (GCD(num2,(num1%num2)));
}

void gridSearch()
{
	int findme=0;
		ifstream in;
	in.open("values.txt");
	if(!in)	//crap on invalid input
	{
		cout << "Wrong file, Ya Hippy\n";
		system("pause");
		return;
	}

	int i,tmp,gridctr = 0;
	cout<<"\n   ";
			for(i=0;i<TABLE_COLS;i++)//print top row

			{
				cout <<setw(4)<< i;
			}
			cout << endl;
	while(!in.eof()) // File reading begins here
	{
		for(i=0;i<TABLE_ROWS;i++)// FOR EACH ROW
		{
			for(int j=0;j<TABLE_COLS;j++) //FILL ITS COL VALUES
			{
				//char tmp;
				if(j==0) //insert a left margin
					cout<<endl<<setw(3)<<i;
				in >> tmp;
				cout << setw(4)<< tmp; 

				//grid[TABLE_ROWS][TABLE_COLS] = tmp;    //write tmp to array   

				//the above doest nothing at all????!!! Driving me friggin crazy!!!!
				//I cant even attempt to search the grid without properly loading it.
				// im punking out and using a regular array
				grid[gridctr] = tmp;
				gridctr++;
			}
		}
	}
	// failed recursion attempt

	//int low = 0;
	//int high = 599;
	//cout << "\nEnter a number to Locate";
	//cin >> findme;
	//if(findme == grid[(high-low)/2])
	//{
	//	cout << "\nnumber found at row:" << (i%20) << "  col:" << (grid[(high-low)/2]%20);
	//}
	//else{
	//	if(findme < grid[(high-low)/2])
	//	{
	//		return;                            //cant figure out how to modularize and still be able to lookup the grid
	//	}
	//}

	//iterative punkout... gotta turn in something that runs..

	while(findme>=0)
	{
		cout << "\nEnter a number to Locate. Any negative entry will exit";
		cin >> findme;
		i=0;
		while(grid[i] <= findme)
		{
			if(grid[i]==findme)
				cout << "\nnumber found at row:" << (i/20) << "  col:" << (i%20);
			i++;
		}
	}findme=0;
}

Dynamic Array Example C++

//this is an example of an array of dynamic memory

#include <iostream>
using namespace std;
void main()
{
   typedef int* IntPtr;
   IntPtr intList;
   int listSize;
   cout << "How big is the list? ";
   cin >> listSize;
   intList = new int[listSize];
   for (int i = 0; i < listSize; i++)
   {
      intList[i] = i;
      cout << intList[i] << ' ' << &intList[i] << endl;
   }
   cout << endl;
   delete [] intList; //ALLWAYS remember to match new statements with delete statements
   system("pause");
}