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"
}