Thursday, 22 March 2012

Week 9: PIC Program

Week No: 9
Date: 22/3/2012


Title of Activity: PIC program


Objective:


1) To program the PIC according to our design
2) To make the project work as we intend it to be


Content / Procedure:


1) Use C Language 
2) Use PCW compiler 
3) Refer to AT command guide and GSM module guide
4) Burn program into integrated circuit PIC18F452


Conclusion: 


1) It take quite a long time for me to finish this program because I do not use to it.

Figure 1: Schematic Diagram


Program:

GSM_MAIN
#include "SOC.h"
#include "global.h"
#include "macro.h"
#include <string.h>
#include "peripheral.c"
#include "GSM.c"
#include "intr_handler.c"
#include "eeprom_data.c"

//------------------------------------------------------------------------------
// convert ADC digital value to analog
//------------------------------------------------------------------------------
float calc_current(float adc_value)
{
   float current_value;
  
   current_value = ((5*adc_value)/1024);
  
   return(current_value);
}


//------------------------------------------------------------------------------
// MAIN FUNCTION
//------------------------------------------------------------------------------
void main()
{
   char phone_number2[14];
   int test_loop;
   unsigned long current_sense_timer = 0;
   unsigned long send_alert_sms_timer = 0;
   unsigned long start_timeout = 0;
   boolean result;
   float ADC1_val,ADC2_val,ADC3_val,ADC4_val;
   float cur1,cur2,cur3,cur4;
     
   #if DEBUG_ON
      WTF = 0;
   #endif
  
   // Set non 0D 0A to TRUE when startup
   exit_non_OD_OA();
   g_msg_read_in=0;
   //output_high(MOVE_LED);
  
   // I/O and other peripheral setup
   peripheral_setup();
   // UART setup
   serial_init();

 #if (!DISABLE_POWER_ON)
   // Program start - check for GSM first
   fprintf(PC,"\r\nGSM - let GSM modem do internal initialize!");
   // check for call ready and set timeout for 120s
     do
     {
        check_call_ready();
        delay_ms(1000);
        start_timeout++;
     }
    while((!g_ok_to_go) && (start_timeout < 120));
  
   // if time out, something wrong
   if(start_timeout >= 120)
   {
      // for now just stuck here
      fprintf(PC,"\r\nERROR! GSM not ready to communicate!");
      for(;;);
   }
   else
   {
      fprintf(PC," GSM Call Ready!");
   }
  
#endif

   // Initizlize GSM - echo off, clear GSM receive buffer, set to text mode
   fprintf(PC,"\r\nInitialize GSM modem");
   GSM_init();

   // Just test incase EEPROM is used to store phone number - not used
   ep_write_phone_number(phone_number);    // eeprom write oK!
   ep_read_phone_number(phone_number2);    // eeprom read ok!
 
  // MAIN LOOP
   for(;;)
   {
  
      // Check for incoming SMS notification from GSM modem
      check_incoming_data();
      result = FAIL;
     
      // there is incoming data --> decode and extract out SMS msg
      if(g_msg_read_in)
      {
         fprintf(PC,"\r\n\r\nIncoming data!!!");
         g_msg_read_in = 0;
        
         // send read SMS msg to GSM and store data in message array
         result = check_on_read();

         // send SMS msg to PC
         fprintf(PC,"\r\nMSG : ");
         fprintf(PC,message,"\f");
         fprintf(PC,"\r\n\r\nDone!");
      }
     
      // the SMS coming in is valid
      if (result == SUCCESS)
      {
         // Check is it user command is valid and if valid set the output
         for(test_loop = 0; test_loop < 12; test_loop++)
         {
            result = FAIL;
        
            switch(test_loop)
            {
               case 0:
                  if(comp_str(P1_on,MESSAGE_STRING))
                     lamp_output(LAMP_1,TURN_ON);
               break;
              
               case 1:
                  if(comp_str(P2_on,MESSAGE_STRING))
                     lamp_output(LAMP_2,TURN_ON);
                  break;
               
               case 2:
                  if(comp_str(P3_on,MESSAGE_STRING))
                     lamp_output(LAMP_3,TURN_ON);    
                  break;
              
               case 3:
                  if(comp_str(P4_on,MESSAGE_STRING))
                     lamp_output(LAMP_4,TURN_ON);
                  break;

               case 4:
                  if(comp_str(PAll_on,MESSAGE_STRING))
                     lamp_output(LAMP_ALL,TURN_ON);
                  break;

               case 5:
                  if(comp_str(P1_off,MESSAGE_STRING))
                     lamp_output(LAMP_1,TURN_OFF);
                  break;
              
               case 6:
                  if(comp_str(P2_off,MESSAGE_STRING))
                     lamp_output(LAMP_2,TURN_OFF);
                  break;
              
               case 7:
                  if(comp_str(P3_off,MESSAGE_STRING))
                     lamp_output(LAMP_3,TURN_OFF);
                  break;
              
               case 8:
                  if(comp_str(P4_off,MESSAGE_STRING))
                     lamp_output(LAMP_4,TURN_OFF);
                  break;

               case 9:
                  if(comp_str(PAll_off,MESSAGE_STRING))
                     lamp_output(LAMP_ALL,TURN_OFF);
                  break;

               case 10:                                      // special case
                  if(comp_str(status_in,MESSAGE_STRING))
                     g_got_msg_to_send = SUCCESS;
                  break;

               default:
                  break;
            }
         }
        
         current_sense_timer = 0;
      }

      // send sms if STAT command was received
      if(g_got_msg_to_send)
      {
         GSM_send(0,1);
         g_got_msg_to_send = FAIL;
      }
     
      // read all the ADC
      SET_ADC_CHANNEL(0);
      ADC1_val = READ_ADC(ADC_START_AND_READ);
      delay_us(200);
      cur1 = calc_current(ADC1_val);
      SET_ADC_CHANNEL(1);
      ADC2_val = READ_ADC(ADC_START_AND_READ);
      delay_us(200);
      cur2 = calc_current(ADC2_val);
      SET_ADC_CHANNEL(2);
      ADC3_val = READ_ADC(ADC_START_AND_READ);
      delay_us(200);
      cur3 = calc_current(ADC3_val);
      SET_ADC_CHANNEL(3);
      ADC4_val = READ_ADC(ADC_START_AND_READ);
      delay_us(200);
      cur4 = calc_current(ADC4_val);

      // update value of to PC
      if(current_sense_timer == 10)
      {
         fprintf(PC,"\r\n%2.3f A",cur1);
         fprintf(PC,"   %2.3f A",cur2);
         fprintf(PC,"   %2.3f A",cur3);
         fprintf(PC,"   %2.3f A",cur4);
         current_sense_timer = 0;
      }
     
      // Check movement on sensor
      if(input(MOVE_SENSE))
      {
         // might be sending SMS... but not so frequent
         // but LED make sense
         output_low(MOVE_LED);
         if(g_intruder_detected == 0)
         {
            g_intruder_detected = SUCCESS;
            send_alert_sms_timer = 0;
         }
      }
      else
      {
         output_high(MOVE_LED);
      }
     
      // in 1 minutes send 1 sms alert house owner
      if(!input(MOVE_SENSE_EN) && (send_alert_sms_timer == 60) && g_intruder_detected)
      {
         fprintf(PC,"\r\n\r\nIntruder Msg Send!\r\n");
         GSM_send(intruder_msg,0);
         g_intruder_detected = FAIL;
         send_alert_sms_timer = 0;
      }
  
      current_sense_timer++;
      send_alert_sms_timer++;
      delay_ms(1000);
   }
}


GSM.c
#include "serial.c"

//------------------------------------------------------------------------------
// Enter No OD OA check
//------------------------------------------------------------------------------
void enter_non_OD_OA(void)
{
   g_read_int = 1;
}

//------------------------------------------------------------------------------
// Exit No OD OA check
//------------------------------------------------------------------------------
void exit_non_OD_OA(void)
{
   g_read_int = 0;
}

//------------------------------------------------------------------------------
// find size of character
//------------------------------------------------------------------------------
int size_of_char(int8 input_v)
{
   int temp;
  
   if (r_ok == input_v)
   {
      temp = sizeof(r_ok);
   }
   else if(msg_in == input_v)
   {
      temp = sizeof(msg_in);
   }
   else if(ate_cmd == input_v)
   {
      temp = sizeof(ate_cmd);
   }
   else if(text_cmd == input_v)
   {
      temp = sizeof(text_cmd);
   }
   else if(del_msg_cmd == input_v)
   {
      temp = sizeof(del_msg_cmd);
   }
   else if(send_msg_cmd == input_v)
   {
      temp = sizeof(send_msg_cmd);
   }
   else if(read_msg_cmd == input_v)
   {
      temp = sizeof(read_msg_cmd);
   }  
   else if(message == input_v)
   {
      temp = sizeof(message);
   }
   else if(P1_on == input_v)
   {
      temp = sizeof(P1_on);
   }
   else if(P2_on == input_v)
   {
      temp = sizeof(P2_on);
   }
   else if(P3_on == input_v)
   {
      temp = sizeof(P3_on);
   }
   else if(P4_on == input_v)
   {
      temp = sizeof(P4_on);
   }
   else if(P1_off == input_v)
   {
      temp = sizeof(P1_off);
   }
   else if(P2_off == input_v)
   {
      temp = sizeof(P2_off);
   }
   else if(P3_off == input_v)
   {
      temp = sizeof(P3_off);
   }
   else if(P4_off == input_v)
   {
      temp = sizeof(P4_off);
   }
   else if(intruder_msg == input_v)
   {
      temp = sizeof(intruder_msg);
   }
   else if(phone_number == input_v)
   {
      temp = sizeof(phone_number);
   }
   else if(status_in == input_v)
   {
      temp = sizeof(status_in);
   }
   else if(call_ready == input_v)
   {
      temp = sizeof(call_ready);
   }
   else if(PAll_on == input_v)
   {
      temp = sizeof(PAll_on);
   }
   else if(PAll_off == input_v)
   {
      temp = sizeof(PAll_off);
   }
   else if(status_out1 == input_v)
   {
      temp = sizeof(status_out1);
   }
   else if(at_basic == input_v)
   {
      temp = sizeof(at_basic);
   }
   else if(r_error == input_v)
   {
      temp = sizeof(r_error);
   }
   else if(r_ok_echo == input_v)
   {
      temp = sizeof(r_ok_echo);
   } 
   else
   {
      temp = 1;
   }
  
   return(temp);
}


//------------------------------------------------------------------------------
// compare string (based on buffer TYPE)
//------------------------------------------------------------------------------
boolean comp_str(int *input, int buffer_type)
{
   int i;
   int ok_count = 0;
   boolean error = FAIL;
   int max_size;
  
   max_size = size_of_char(input);
   
   for(i=0;i<max_size;i++)
   {
      switch (buffer_type)
      {
         case DATA_INPUT_STRING:
            if(data_input[i] == *input)
            {
               ok_count++;
            }
            break;
       
         case INCOMING_MSG_STRING:
            if(incoming_msg[i] == *input)
            {
               ok_count++;
            }
            break;           

         case MESSAGE_STRING:
            if(message[i] == *input)
            {
               ok_count++;
            }
            break;           
      }
     
      input++;
   }

   // FOR DEBUGGING PURPOSES
   //fprintf(PC,"\r\nok_count = %d ",ok_count);      
   //fprintf(PC,"\r\nmax_size = %d ",max_size);
   //fprintf(PC,data_input,"\r\n\f ");
  
   if(ok_count == max_size)
   {
      error = SUCCESS;
   }
  
   return(error);
}


//------------------------------------------------------------------------------
// send character to GSM modem
//------------------------------------------------------------------------------
void send_char(int *input)
{
   int i;
   int max_size;

   max_size = size_of_char(input);

   for(i=0;i<max_size;i++)
   {
      delay_ms(100);
      // FOR DEBUGGING PURPOSES
      #if DEBUG_ON
      if(WTF == 1)
         fprintf(PC,"%c",*input);
      #endif
      fprintf(GSM_MODEM,"%c",*input++);
   }
}

//------------------------------------------------------------------------------
// send special character to GSM modem
//------------------------------------------------------------------------------
void send_special_char(int i)
{
   delay_ms(100);
   // FOR DEBUGGING PURPOSES
   #if DEBUG_ON
   if(WTF == 1)
      fprintf(PC,"%c",special_char[i]);
   #endif
   fprintf(GSM_MODEM,"%c",special_char[i]);
}

//------------------------------------------------------------------------------
// send number to GSM modem
//------------------------------------------------------------------------------
void send_num(unsigned long num)
{
   delay_ms(100);
   // FOR DEBUGGING PURPOSES
   #if DEBUG_ON
   if(WTF == 1)
      fprintf(PC,"%lu",num);
   #endif
   fprintf(GSM_MODEM,"%lu",num);    
}

//------------------------------------------------------------------------------
// Reset GSM by sending dummy command
//------------------------------------------------------------------------------
void send_dummy_command(void)
{
   enter_non_OD_OA();
   incoming_msg_cleanup();
   pInData_init();
   fprintf(GSM_MODEM,"x");
   send_special_char(return_c);
   exit_non_OD_OA();
   buffer_cleanup();
   pdata_init();
}

//------------------------------------------------------------------------------
// check for OK reply from GSM modem
//------------------------------------------------------------------------------
boolean check_r_ok(void)
{
   boolean error = FAIL;

   delay_ms(250);
  
   if(g_HBI_SPP)
   {
      error = comp_str(r_ok, DATA_INPUT_STRING);
      buffer_cleanup();
      g_HBI_SPP = FAIL;
   }

   return(error);
}

//------------------------------------------------------------------------------
// Send AT basic command
//------------------------------------------------------------------------------
void check_at_cmd(void)
{
   boolean error;
  
   do
   {              
      send_char(at_basic);                                //ECHO off   
      error = check_r_ok();
   }
   while(error != SUCCESS);
}

//------------------------------------------------------------------------------
// Send echo off command
//------------------------------------------------------------------------------
void echo_off(void)
{
   boolean error;
  
   send_char(ate_cmd);
   send_char(ate_cmd);
   send_char(ate_cmd);
  
   do
   {             
      send_char(ate_cmd);                                //ECHO off   
      error = check_r_ok();
   }
   while(error != SUCCESS);
}

//------------------------------------------------------------------------------
// Send clear all read message command
//------------------------------------------------------------------------------
void clear_read_msg(void)
{
   unsigned long i;
   boolean error;
  
   for(i=1;i<31;i++)
   {
      do                                              //Clear all MSG
      {       
         send_char(del_msg_cmd);
         send_num(i);
         send_special_char(return_c);
         error = check_r_ok();
      }
      while(error != SUCCESS);
      fprintf(PC,".");
   }  
}

//------------------------------------------------------------------------------
// Send clear current read message command
//------------------------------------------------------------------------------
void clear_current_read_msg(void)
{
   unsigned long i;
   boolean error;

   i = 1;
  
   do                                              //Clear current MSG
   {       
      send_char(del_msg_cmd);
      send_num(i);
      send_special_char(return_c);
      error = check_r_ok();
   }
   while(error != SUCCESS);
 
}

//------------------------------------------------------------------------------
// Send text mode command
//------------------------------------------------------------------------------
void set_text_mode(void)
{
   boolean error;
  
   do
   {      
      send_char(text_cmd);                                   //Text mode
      error = check_r_ok();
   }
   while(error != SUCCESS);    
}

//------------------------------------------------------------------------------
// GSM Initialization
//------------------------------------------------------------------------------
void GSM_init(void)
   echo_off();
   fprintf(PC,"\r\nEcho was set to off!");
   delay_ms(1000);
  
   fprintf(PC,"\r\nClearing inbox");
   clear_read_msg();
   fprintf(PC,"<-- Inbox was emptied!");
   delay_ms(1000);

   set_text_mode();
   fprintf(PC,"\r\nText mode set!");
   delay_ms(1000);
  
   fprintf(PC,"\r\n\r\nGSM SYSTEM READY!");
}

//------------------------------------------------------------------------------
// Send message to GSM modem
//------------------------------------------------------------------------------
boolean GSM_send(int8 input, boolean lamp_status)
{
   boolean error;
   int i,port_data,temp;

   do
   {
      delay_ms(250);

      //Send dummy byte
      send_dummy_command();
      buffer_cleanup();
      pdata_init();
      incoming_msg_cleanup();
      pInData_init();
     
      check_at_cmd();
      set_text_mode();
     
      // To avoid stuck in OD OA check in interrupt handler we just take data
      enter_non_OD_OA();                       
      fprintf(GSM_MODEM,"AT+CMGS=");
      fputc(0x22,GSM_MODEM);
      fprintf(GSM_MODEM,"+60122717486");
      fputc(0x22,GSM_MODEM);
      fputc(0x0D,GSM_MODEM);
      delay_ms(50);
      error = comp_str(r_error,INCOMING_MSG_STRING);
   }
   while(error == SUCCESS);         // if Error msg receive try again
  
   buffer_cleanup();
   pdata_init();
   incoming_msg_cleanup();
   pInData_init();
     
   if(lamp_status)
   {
      port_data = LAT_PORTB >> 2;
      send_char(status_out1);
        
      for(i = 0; i < 4; i++)
      {
         temp = port_data & 1;
         switch (i)
         {
            case 0:
               if(temp)
                  send_char(P1_off);
               else
                  send_char(P1_on);
               break;

            case 1:
               if(temp)
                  send_char(P2_off);
               else
                  send_char(P2_on);
               break;

            case 2:
               if(temp)
                  send_char(P3_off);
               else
                  send_char(P3_on);
               break;

            case 3:
               if(temp)
                  send_char(P4_off);
               else
                  send_char(P4_on);
               break;
         }
         port_data >>= 1;
      }
   }
   else
   {
      send_char(input);
   }
   fputc(0x1A,GSM_MODEM);
  
   delay_ms(1000);
   buffer_cleanup();
   incoming_msg_cleanup();
   pdata_init();
   pInData_init();
  
   // Exit the non OD OA to enable OD OA check
   exit_non_OD_OA();
  
   clear_current_read_msg();
  
   return(error);
}

//------------------------------------------------------------------------------
// check message from a AT read sms command
//------------------------------------------------------------------------------
boolean search_for_message(void)
{
   int counter;
   int i;
   int OD_OA_counter;
  
   counter = 0;
   OD_OA_counter=0;
     
   for(counter=0;counter<max_buffer_size;counter++)
   {
      if(incoming_msg[counter] == 0x0D)
      {
         OD_OA_counter++;
         if(OD_OA_counter == 2)
         {
            break;
         }
      }
   }
     
   i=0;
   do
   {
      *pmessage++=incoming_msg[counter+i];
      i++;
   }
   while(incoming_msg[counter+i] != 0x0D);

   *pmessage = 0;
  
   return(SUCCESS);
}

//------------------------------------------------------------------------------
// Send get msg command from GSM
//------------------------------------------------------------------------------
boolean GSM_read_sms(void)
{
   boolean error;
   unsigned long number;
   number = 1;
  
   enter_non_OD_OA();
   incoming_msg_cleanup();
   message_cleanup();
   pmessage_init();
   pInData_init();
  
   send_char(read_msg_cmd);
   send_num(number);
   send_special_char(return_c);
     
   delay_ms(500);
   exit_non_OD_OA();
  
   error = search_for_message();
   clear_current_read_msg();

   return(error);
}

//------------------------------------------------------------------------------
// read incoming msg
//------------------------------------------------------------------------------
BOOLEAN check_on_read(void)
{
   boolean error = FAIL;
  
   error = GSM_read_sms();
   g_HBI_SPP = FAIL;
  
   return(error);
}

//------------------------------------------------------------------------------
// check for incoming msg from GSM modem
//------------------------------------------------------------------------------
void check_incoming_data(void)
{
   boolean error = FAIL;

   if(g_HBI_SPP)
   {
      error = comp_str(msg_in,DATA_INPUT_STRING);
      g_HBI_SPP = FAIL;
   }
  
   if(error)
   {
      g_msg_read_in = SUCCESS;
   }
}

//------------------------------------------------------------------------------
// check Call Ready
//------------------------------------------------------------------------------
void check_call_ready(void)
{
   boolean error = FAIL;

   if(g_HBI_SPP)
   {
      error = comp_str(call_ready,DATA_INPUT_STRING);
      g_HBI_SPP = FAIL;
   }
  
   if(error)
   {
      g_ok_to_go = SUCCESS;
   }
}


Global.h


#define  DEBUG_ON             FALSE
#define  DISABLE_POWER_ON     TRUE

#byte    LAT_PORTB      = 0xF8A

//------------------------------------------------------------------------------
// enum for the special character
//------------------------------------------------------------------------------
enum
{
   ctrl_z         = 0,
   return_c       = 1
};

//------------------------------------------------------------------------------
// enum for the character as above
//------------------------------------------------------------------------------
enum
{
   FAIL           = 0,
   SUCCESS        = 1,
};

enum
{
   DATA_INPUT_STRING    = 0,
   INCOMING_MSG_STRING  = 1,
   MESSAGE_STRING       = 2
};

//------------------------------------------------------------------------------
// char array for special character
//------------------------------------------------------------------------------
const char special_char[10]={0x1A,0x0D};              // Used in send msg

//------------------------------------------------------------------------------
// GSM Reply table and protocol
//------------------------------------------------------------------------------
char r_ok[2]            ={'O','K'};
char r_error[7]         ={0x0D,0x0A,'E','R','R','O','R'};
char r_ok_echo[7]       ={'A','T',0x0D,0x0D,0x0A,'O','K'};

char at_basic[3]        ={'A','T',0x0D};
char ate_cmd[5]         ={'A','T','E','0',0x0D};
char text_cmd[10]       ={'A','T','+','C','M','G','F','=','1',0x0D};
char del_msg_cmd[8]     ={'A','T','+','C','M','G','D','='};
char send_msg_cmd[8]    ={'A','T','+','C','M','G','S','='};
char read_msg_cmd[8]    ={'A','T','+','C','M','G','R','='};
char msg_in[5]          ={'+','C','M','T','I'};
char P1_on[7]           ={0x0D,0x0A,'P','1',' ','O','N'};
char P2_on[7]           ={0x0D,0x0A,'P','2',' ','O','N'};
char P3_on[7]           ={0x0D,0x0A,'P','3',' ','O','N'};
char P4_on[7]           ={0x0D,0x0A,'P','4',' ','O','N'};
char PAll_on[8]         ={0x0D,0x0A,'A','L','L',' ','O','N'};
char P1_off[8]          ={0x0D,0x0A,'P','1',' ','O','F','F'};
char P2_off[8]          ={0x0D,0x0A,'P','2',' ','O','F','F'};
char P3_off[8]          ={0x0D,0x0A,'P','3',' ','O','F','F'};
char P4_off[8]          ={0x0D,0x0A,'P','4',' ','O','F','F'};
char PAll_off[9]        ={0x0D,0x0A,'A','L','L',' ','O','F','F'};
char status_in[6]       ={0x0D,0x0A,'S','T','A','T'};
char status_out1[6]     ={'S','T','A','T','U','S'};
char call_ready[10]      ={'C','a','l','l',' ','R','e','a','d','y'};

char intruder_msg[17]   ={'I','n','t','r','u','d','e','r',' '
                         ,'i','n',' ','h','o','u','s','e'};
                         
char message[60];
char *pmessage;
char phone_number[14]={0x22,'+','6','0','1','9','6','1','2','1','2','5','7',0x22};

//------------------------------------------------------------------------------
// Definition
//------------------------------------------------------------------------------
#define max_buffer_size       100


//------------------------------------------------------------------------------
// Global Variable
//------------------------------------------------------------------------------
char data_input[max_buffer_size];                   // data array
char *pdata;                           // pointer to data buffer
char incoming_msg[max_buffer_size];
char *pInData;
boolean g_msg_read_in = FAIL;
boolean g_ok_to_go = FAIL;
boolean g_HBI_SPP = FAIL;
boolean g_read_int = FAIL;
boolean g_got_msg_to_send = FAIL;
boolean g_intruder_detected = FAIL;
#if DEBUG_ON
boolean WTF;
#endif


 SOC.h

//------------------------------------------------------------------------------
// SOC
//------------------------------------------------------------------------------
#include <18F452.h>

//------------------------------------------------------------------------------
// Special funtion
//------------------------------------------------------------------------------
#device ICD=TRUE
#device adc=10

#FUSES NOWDT                    //No Watch Dog Timer
#FUSES WDT128                   //Watch Dog Timer uses 1:128 Postscale
#FUSES H4                       //High speed osc with HW enabled 4X PLL
#FUSES NOPROTECT                //Code not protected from reading
#FUSES NOOSCSEN                 //Oscillator switching is disabled, main oscillator is source
#FUSES NOBROWNOUT               //No brownout reset
#FUSES BORV20                   //Brownout reset at 2.0V
#FUSES NOPUT                    //No Power Up Timer
#FUSES STVREN                   //Stack full/underflow will cause reset
#FUSES NODEBUG                  //No Debug mode for ICD
#FUSES NOLVP                    //No low voltage prgming, B3(PIC16) or B5(PIC18) used for I/O
#FUSES NOWRT                    //Program memory not write protected
#FUSES NOWRTD                   //Data EEPROM not write protected
#FUSES NOWRTB                   //Boot block not write protected
#FUSES NOWRTC                   //configuration not registers write protected
#FUSES NOCPD                    //No EE protection
#FUSES NOCPB                    //No Boot Block code protection
#FUSES NOEBTR                   //Memory not protected from table reads
#FUSES NOEBTRB                  //Boot block not protected from table reads

//------------------------------------------------------------------------------
// clock and RS232 Definition
//------------------------------------------------------------------------------
#use delay(clock=40000000)
#use rs232(baud=115200,xmit=PIN_C6,rcv=PIN_C7,PARITY=N,bits=8,BRGH1OK,STREAM=GSM_MODEM)
#use rs232(baud=9600,parity=N,xmit=PIN_D0,rcv=PIN_D1,bits=8,FORCE_SW,STREAM=PC)


 serial.c

//------------------------------------------------------------------------------
// Serial related deifinition
//------------------------------------------------------------------------------
#define  CTS      pin_c5
#define  RTS      pin_c4   

//------------------------------------------------------------------------------
// clear receive buffer
//------------------------------------------------------------------------------
void buffer_cleanup(void)
{
   int i;
  
   for(i=0;i<max_buffer_size;i++)
   {
      data_input[i]=0;
   }
}

//------------------------------------------------------------------------------
// clear incoming message buffer (with AT command) when read command send
//------------------------------------------------------------------------------
void incoming_msg_cleanup(void)
{
   int i;
  
   for(i=0;i<max_buffer_size;i++)
   {
      incoming_msg[i]=0;
   }
}

//------------------------------------------------------------------------------
// clear message buffer
//------------------------------------------------------------------------------
void message_cleanup(void)
{
   int i;
  
   for(i=0;i<max_buffer_size;i++)
   {
      message[i]=0;
   }
}

//------------------------------------------------------------------------------
// RTS activate - low
//------------------------------------------------------------------------------
void activate_rts(void)
{
   output_low(RTS);
}

//------------------------------------------------------------------------------
// RTS deactivate - high
//------------------------------------------------------------------------------
void deactivate_rts(void)
{
   output_high(RTS);
}

//------------------------------------------------------------------------------
// Serial Initialization
//------------------------------------------------------------------------------
void serial_init(void)
{
   boolean dummy;
  
   pdata_init();
   buffer_cleanup();
   incoming_msg_cleanup();
   deactivate_rts();
   delay_ms(10);
   activate_rts();
   dummy = input(CTS);
}


Peripheral.c

#define  P4_OUT         pin_b5
#define  P3_OUT         pin_b4
#define  P2_OUT         pin_b3
#define  P1_OUT         pin_b2

#define  MOVE_SENSE     pin_d4

#define  MOVE_SENSE_EN  pin_e0
#define  MOVE_LED       pin_e2

typedef enum
{
   LAMP_1         = 1,
   LAMP_2         = 2,
   LAMP_3         = 3,
   LAMP_4         = 4,
   LAMP_ALL       = 5,
  
   TURN_ON        = 0xFE,
   TURN_OFF       = 0xFF
}LAMP_SECTION_T;

//------------------------------------------------------------------------------
// Set LAMP on or off
//------------------------------------------------------------------------------
void lamp_output(LAMP_SECTION_T lamp_position, LAMP_SECTION_T turn_on_off)
{
   switch(lamp_position)
   {
      case LAMP_1:
         if(turn_on_off == TURN_ON)
            output_low(P1_OUT);
         else
            output_high(P1_OUT);
         break;

      case LAMP_2:
         if(turn_on_off == TURN_ON)
            output_low(P2_OUT);
         else
            output_high(P2_OUT);
         break;

      case LAMP_3:
         if(turn_on_off == TURN_ON)
            output_low(P3_OUT);
         else
            output_high(P3_OUT);
         break;
        
      case LAMP_4:
         if(turn_on_off == TURN_ON)
            output_low(P4_OUT);
         else
            output_high(P4_OUT);
         break;

      case LAMP_ALL:
         if(turn_on_off == TURN_ON)
         {
            output_low(P1_OUT);
            output_low(P2_OUT);
            output_low(P3_OUT);
            output_low(P4_OUT);
         }
         else
         {
            output_high(P1_OUT);
            output_high(P2_OUT);
            output_high(P3_OUT);
            output_high(P4_OUT);        
         }
         break;

      default:
         break;
   };
}

//------------------------------------------------------------------------------
// peripheral initialization
//------------------------------------------------------------------------------
void peripheral_setup(void)
{
   setup_adc_ports(AN0_AN1_AN2_AN3_AN4);
   setup_adc(ADC_CLOCK_DIV_64);
   setup_psp(PSP_DISABLED);
   setup_spi(SPI_SS_DISABLED);
   setup_wdt(WDT_OFF);
   setup_timer_0(RTCC_INTERNAL);
   setup_timer_1(T1_DISABLED);
   setup_timer_2(T2_DISABLED,0,1);
  
   delay_ms(500);
   lamp_output(LAMP_ALL,TURN_OFF);
  
   enable_interrupts(INT_RDA);
   enable_interrupts(GLOBAL);
}


Eeprom_data.c

//------------------------------------------------------------------------------
// definition to start addres of EEPROM Memory
//------------------------------------------------------------------------------
#define eep_phone_number               0x00
#define eep_phone_number_size          15
#define eep_phone_number_end           eep_phone_number + eep_phone_number_size



//------------------------------------------------------------------------------
// Write Phone number to EEPROM
//------------------------------------------------------------------------------
void ep_write_phone_number(int8 *phone_number)
{
   int8 counter;
  
   for(counter=eep_phone_number;counter<eep_phone_number_end;counter++)
      write_eeprom(counter,*phone_number++);
}

//------------------------------------------------------------------------------
// Read Phone Number from EEPROM
//------------------------------------------------------------------------------
void ep_read_phone_number(int8 *phone_number)
{
   int8 counter;
  
   for(counter=eep_phone_number;counter<eep_phone_number_end;counter++)
      *phone_number++=read_eeprom(counter);
}


intr_handler.c

//------------------------------------------------------------------------------
// Serial Comm Data Receive Interrupt Handler
//------------------------------------------------------------------------------

#INT_RDA
void int_RDA_isr(void)
{
   char temp;

   if(!g_read_int)
   {
      temp=fgetc(GSM_MODEM);        
      if(temp == 0x0D)
      {
         temp=getch(GSM_MODEM);    
         if(temp == 0x0A)
         {
            do
            {
               temp=getch(GSM_MODEM);          
               *pdata++=temp;
            }
            while(temp != 0x0D);
           
            temp=getch(GSM_MODEM);             
            if(temp == 0x0A)
            {
               g_HBI_SPP = SUCCESS;
            }
         }
      }
   }
   else
   {
      *pInData++=fgetc(GSM_MODEM);
   }

   pdata_init();
}



Wednesday, 14 March 2012

Week 8: Build Load Appliances

Week No: 8
Date: 14/3/2012


Title of Activity: Build Load Appliances


Objective:


1) To realizing what have been plan before.
2) To integrate with other circuit to make this project work.
3) To make people see how this project can control motor or electrical machine
4) To make the star-delta and forward reverse motor starter circuit before connected to motor.
5) To protect motor from large starting current.
6) To control motor speed, power and direction.


Content / Procedure:


1) List down all the component that will be used in the circuit.
2) Draw the circuit of star-delta and forward reverse on the paper for reference.
3) Do the wiring according to the circuit.
4) Test the circuit.


Result and analysis:


1) The circuit consist of:
 - Ac contector 
 - Cable 2.5 mm
 - Overload relay (2x)
 - Timer
 - Miniature circuit breaker (2x)
All these component will be used in the circuit


2) Ac contector function is to control the circuit, this as contactor have a normally open and normally close like relay and can be use with timer to make the circuit to operate according to what we plan.


3) Cable 2.5mm is the usual size of cable that being used, but if the horse power of the motor is bigger or the current that will be passing through is large, we have to used a bigger size cable. The size of the cable can be refer to the table in IEE rules and regulation book.


4) Overload relay function is to control the current in the circuit, if the overload current happens in the circuit or current flow is bigger than the value that we set, it will trip and stop the motor.
5) Timer function is to delay some action in the circuit, and usually it will be use with the ac contector.


6) Miniature circuit breaker function is to trip when this is a over current in the circuit, over current happen when short circuit happens and this device is to protect the user from shock.


Conclusion:


1) The motor that i will be use in this project is squirrel cage induction motor and the motor starter circuit that i will use is suitable with the motor based on cable size and miniature circuit breaker size.


2) For now i will make the motor starter circuit only and connect with the motor when all thing is done.


3) This motor starter circuit will be connected with load driving circuit to make it work.


Picture of Stat-Delta and Forward Reverse starter circuit:


Figure 1: Main star-delta circuitry 

Figure 2: Control star-delta circuitry



Figure 3: Main and control Forward Reverse circuitry



Thursday, 8 March 2012

Week 7: Motion Sensing Development Circuit

Week No: 7
Date: 8/3/2012


Title of Activity: Motion sensing development circuit


Objective:


1) To realizing what have been plan before.
2) To integrate with other circuit to make this project work.
3) To sensing movement at certain places
4) To detect intruder


Content / Procedure:


1) Buy the motion PIR sensor from store.
2) Read the user manual and understand it.
3) Try to incorporate it with the main circuit.


Result and analysis: 


1) PIR sensor means Passive Infra-red sensor.


2) This motion PIR sensor is a pyroelectric device that  can detect infrared rays released by human body motion within the detection area of 5 meters.


3) The PIR sensor can sense even in night mode.


4) If there is an intruder who wish to enter the factory, the microcontroller will be activated high ‘1’ and send notification to the worker stating that intruder in factory.


5) The advantage of PIR sensor is single bit output, small size makes it easy to conceal, compatible with all types of microcontrollers, 5 v till 20 v operation.


6) Calibration - The PIR Sensor requires a ‘warm-up’ time in order to function properly. This is due to the


settling time involved in ‘learning’ its environment. This could be anywhere from 10-60
seconds.


7) Sensitivity - The PIR Sensor has a range of approximately 5 meters. The PIR sensor can sense object up to 120° within 1 meter range.


Conclusion: 


1) This PIR sensor is suitable to be used in my project because it is simple to use, easy to found and cheap.




Picture of PIR motion sensor: 


Figure 1: Product Dimension 

Figure 2: Product Layout

Figure 3: Product Actual Look



Thursday, 1 March 2012

Week 6: Current Sensing Development Circuit

Week No: 6
Date: 1/3/2012


Title of Activity: Current Sensing Development Circuit


Objective: 


1) To realizing what have been plan before.
2) To integrate with other circuit to make this project work.
3) To sensing the current in the main circuit and send the data to micro-controller.
4) To protect the main circuit from over-voltage.
5) To boost current.
6) To convert voltage from AC to DC.
7) To eliminate noise.


Content / Procedure:


1) List down all the component used in the circuit.
2) Draw the circuit in PCB lab and print out the circuit.
3) Hatching the circuit according to the setting in the PCB layout.
4) Solder the component on the circuit board.

5) Test the circuit.


Result and Analysis:


1) The circuit consist of:
 - Power resistor
 - Isolation transformer
 - Capacitor and resistor for filter
 - Operational amplifier IC
 - Diode 
All these component will be attached to the board.


2) Power resistor function is to make the value of voltage equal to current because the value of the resistor is 1 ohm.


3) Isolation transformer function is to avoid the 240 volt direct to the circuit that can cause circuit to burn.


4) Capacitor and resistor for filter function is to reduce noise in the circuit.


5) Operational amplifier IC function is to make the amplifier circuit to boost current.


6) Diode function is to convert voltage from AC to DC.


Conclusion:


1) The filter need to be design more specific and functional to reduce noise more efficiently.
2) Power resistor need to be cover up because it can shock people if accidentally touch.


Picture of Current Sensing Circuit:


Figure 1: Top view

Figure 2: Bottom view