serial.cpp

An application used to vote, for example in the school, where a teacher have a lot of student and want to know their respons to a question. The teacher using a PC can see the answer of all student on his PC. every student have one of this box and they are connected through RS422 and the PC using a rs232/rs422 converter make a polling for each one of this box and can see the key pressed. (by Gianni Franchi).




#include "p16f84.h"

#include "serial.h"



// My board clock

#pragma CLOCK_FREQ 12000000   





// This is used to detect the Start bit on serial Frame

char OldBit;





/*

   Interrupt handler 

   Used just to have a timing into the application

   Just increment the MS_TIMER every 10.6 ms

*/

void interrupt( void )

{

   MS_TIMER=MS_TIMER+10;

    clear_bit( INTCON, T0IF );  //clear TMR0 overflow flag

}





/*

   Setup porta and bit for serial communication

   PA.0 = Serial RX

   PA.1 = Serial TX

   

   Serial port used in this application is 9600 8 N 1

*/

void Init_Serial ()

{

   OldBit=porta & 1; // Get the actual state of serial pin input

   porta=porta | 2;  // Set the serial in the Mark state (+VCC)

}





/*

   Send char at 9600 8 N 1

*/

void TxChar (char ch)

{

   char Bits[10];

   char i=0;

   char bit=1;



   // Preparing a buffer of 10 bits (START+8(DATA)+STOP)

   Bits[0]=porta & 253;

   Bits[9]=porta | 2;



   for (i=1;i<9;i++)

   {

      Bits[i]=porta & 253;

      if (ch & bit) Bits[i]=porta | 2;

      bit=bit<<1;

   }



   // sending bit using a fixed delay

   // I used a buffer so i'm sure that i'll have the same timing for each one bits

   for (i=0;i<10;i++)

   {

      porta=Bits[i];

      delay_us (BIT_DELAY);   // Fixed delay

   }

}









/*

   Receive char in PA0 at 9600 8 N 1

*/

int RxChar ()

{

   int Bit;

   int i;

   int Byte=0;

   int Ret;



   Ret=NO_CHAR;



   Bit=porta & 1; // Get the actual state of RX



   // Detect if start bit is received

   // falling edge of RX

   if (OldBit!=Bit && Bit==0) // Start Bit received ??

   {

      // I received the start bit, now i'm going to get the DATA Bits

      for (i=0;i<8;i++)

      {

         // delay for each char, here is different from TX,because the instruction above

         // make some delay itself

         delay_us (BIT_DELAY-5);

         Byte=Byte>>1;           // the first bit received is the last B0,B1,...B7

         if (porta & 1) Byte|=128;

      }

      delay_us (BIT_DELAY-30); // Delay for the Stop Bit

      Ret=Byte;

   }

   OldBit=1;   // This is the old state of RX



   return Ret;

}






http://www.sourceboost.com/home.html

Copyright © 2002-2006 SourceBoost Technologies