CCS C Software and Maintenance Offers
FAQFAQ   FAQForum Help   FAQOfficial CCS Support   SearchSearch  RegisterRegister 

ProfileProfile   Log in to check your private messagesLog in to check your private messages   Log inLog in 

CCS does not monitor this forum on a regular basis.

Please do not post bug reports on this forum. Send them to support@ccsinfo.com

16F877A hardware stack overflow problem

 
Post new topic   Reply to topic    CCS Forum Index -> General CCS C Discussion
View previous topic :: View next topic  
Author Message
mlkushan



Joined: 16 Nov 2008
Posts: 22
Location: Sri Lanka

View user's profile Send private message Send e-mail Visit poster's website Yahoo Messenger

16F877A hardware stack overflow problem
PostPosted: Wed Jan 14, 2009 11:21 am     Reply with quote

Hi all,

I'm doing a project on wireless sensor networks. So i have designed sensor nodes using 16f877a micro controller (without using existing sensor nodes). I have written a program node to an end station node. The code has been posted below. So i compiled that code using the CCS PCM C Compiler, Version 4.057. When i simulated that code using 16F PIC simulator IDE, it gave the error "Hardware Stack Overflow". Still i couldn't figure out a solution to my problem.

Here as a test data string, i sent a router reply packet by the bellow code segment on the main program. Then the simulator gave the above mentioned problem.

Code:

//send a test packet
createPacket(0x02, 0x00);     // Send a test packet here


So please be kind enough to show me the reasons to my above mentioned problem. It would be very helpful, if any one can guide me on correct path to solve my problem. This code didn't gave any errors while it was being compiled. ROM memory usage was 41% and RAM memory usage was 20% - 33%.

Any help regarding my matters are highly appreciated.
Thank you all.

Kushan


Code:

#include <16F877A.h>
#device adc=8

#FUSES NOWDT                    //No Watch Dog Timer
#FUSES XT                       //Crystal osc <= 4mhz
#FUSES NOPUT                    //No Power Up Timer
#FUSES NOPROTECT                //Code not protected from reading
#FUSES NODEBUG                  //No Debug mode for ICD
#FUSES NOBROWNOUT               //No brownout reset
#FUSES NOLVP                    //No low voltage prgming, B3(PIC16) or B5(PIC18) used for I/O
#FUSES NOCPD                    //No EE protection
#FUSES WRT_50%                  //Lower half of Program Memory is Write Protected

#use delay(clock=4000000)
#use rs232(baud=9600,parity=N,xmit=PIN_C6,rcv=PIN_C7,bits=8)

#include <math.h>
#include <stdlibm.h>
#include <string.h>

//function prototypes
void sendData(int8 envTemp, int8 packetType);
void payloadDecipher(unsigned int num_rounds, unsigned int8* packetPayload);
void payloadEncipher(unsigned int num_rounds, unsigned int8* packetPayload);
void createPacket(int8 packetType, int8 payloadLength);

//For encryption and decryption
unsigned int8 key[] = {0x80, 0x00, 0x80, 0x80};    //32bit int8 key of for XTEA

//define the packet payload array pointer
int8 *packetPayload;
int8 *packet;

//Array for keeping routing entries
//route_table[0] for keeping the nexthop address
//route_table[1] for keeping the hopcount
int8 route_table[2];

//mainteains the Air Conditioner state
int1 AC_State = FALSE;   

//for RXTX data communication
#define RX_BUFFER_SIZE 12
#define TX_BUFFER_SIZE 12
#define DELIM 0xFE      //since we are using bytes
#byte TXREG=0x19
#byte PIR1 = 0x0c
#bit TXIF=PIR1.4

unsigned int8 rx_buffer[RX_BUFFER_SIZE + 1];
unsigned int8 tx_buffer[TX_BUFFER_SIZE + 1];
int8 rx_wr_index = 0;
int8 tx_rd_index = 0;
int8 tx_wr_index = 0;
int8 tx_counter = 0;
int8 rxd;
int1 data_avail = FALSE;

//Define AC state
#define ACStateON 0xAA
#define ACStateOFF 0xBB

//for routting algorithm
#define CoordntrAdd 0x00 //Defining the Address of the Coordinator
#define RouterAdd01 0x81 //Address of this Router device
#define EndDevAdd01 0x01 //Addresses of End Devices
#define BrdcastAdd 0xFF

//SPI communication parameters
#define SPI_MODE_0  (SPI_L_TO_H | SPI_XMIT_L_TO_H)   //    low       leading edge
#define SPI_MODE_1  (SPI_L_TO_H)                     //    low       trailing edge
#define SPI_MODE_2  (SPI_H_TO_L)                     //    high      leading edge
#define SPI_MODE_3  (SPI_H_TO_L | SPI_XMIT_L_TO_H)   //    high      trailing edge

#int_RDA
void RDA_isr(void) {
   rx_buffer[rx_wr_index] = getc();
   rxd = rx_buffer[rx_wr_index];
   rx_wr_index++;
   
   if(rxd==DELIM){
      data_avail = TRUE;
      rx_wr_index = 0;
   }
   
   if (rx_wr_index > RX_BUFFER_SIZE) {          //prevent buffer overflows
      rx_wr_index = 0;
   }
}

#int_TBE
void TBE_isr(void) {
   if (tx_counter != 0) {
      putc(tx_buffer[tx_rd_index]);
     
      if (++tx_rd_index > TX_BUFFER_SIZE) {
         tx_rd_index = 0;
      }
     
      tx_counter--;
     
      if (tx_counter == 0) {
         disable_interrupts(INT_TBE);
      }
   }
}

void bputc(int c) {
   int restart = 0;
   if (tx_counter == 0){
      restart = 1;
   }
   tx_buffer[tx_wr_index++] = c;
   if (tx_wr_index > TX_BUFFER_SIZE) {
      tx_wr_index = 0;
   }
   tx_counter++;
   if (restart == 1){
      enable_interrupts(INT_TBE);
   }
}

void setIrCommand(int8 ACState, int8 tempValue){
   if(ACState == ACStateON){
      spi_write(0x32);         //set AC ON
   }   
   else if(ACState == ACStateOFF){
      spi_write(0x64);         //set AC OFF
   }
   else if((tempValue > 0x16) && (tempValue < 0x31)){
      spi_write(tempValue);      //set temperature value here.
   }
}

void main(){
   int8 pwmDuty = 50;
   long counter = 0;
   int8 envTemp;
   int8 *packet;
   int8 *rxPcketPayload;
   int8 a;
   //delay_ms(2000);   //initializing delay

   setup_adc_ports(AN0);
   setup_adc(ADC_CLOCK_INTERNAL);
   //set_tris_a(0b00000001);
   setup_psp(PSP_DISABLED);
   
   delay_us(100); //This ensures the slave has time to wake before master
   setup_spi(SPI_MASTER|SPI_MODE_0|SPI_CLK_DIV_4);
   delay_us(100);
   
   setup_timer_0(RTCC_INTERNAL|RTCC_DIV_1);
   setup_timer_1(T1_DISABLED);
   setup_timer_2(T2_DIV_BY_1,24,1);
   setup_ccp1(CCP_PWM);
   set_pwm1_duty(pwmDuty);
   setup_comparator(NC_NC_NC_NC);
   setup_vref(FALSE);
   enable_interrupts(INT_RDA);
   enable_interrupts(GLOBAL);

   // TODO: USER CODE!!
   // TODO: USER CODE!!
   route_table[1] = 0xFF; // First initialise the hop count to the largest value.
   
   while(true){
      packet = (int8 *)calloc(12,sizeof(int8));  //create a data packet here
      //packet listener code
      if(data_avail)
      {
         data_avail = FALSE; 
         if((rx_buffer[0] != EndDevAdd01) || (rx_buffer[0] != BrdcastAdd)){
            memset(rx_buffer,0,sizeof(rx_buffer));           //drop the rx packet
         }
         else{
            switch(rx_buffer[4]){ // switch the packet type
               case 0x01:  // Route request packet
                  if(route_table[1] > rx_buffer[5]){    //check the hop count value of the incoming packet
                     route_table[0] = rx_buffer[1];     // Nearest source's address
                     route_table[1] = rx_buffer[5];     // update the hop count
                  }
                  createPacket(0x02, 0x00);     // Send a route reply packet       
               break;
           
               case 0x02: // Route reply packet, from others, shold be droped
                  // Drop the packet
               break;
           
               case 0x03: // Data packet from the cordinator
                  rxPcketPayload = (int8 *)calloc(rx_buffer[6], sizeof(int8));  //allocate memory of the size of incoming packet payload length to store the incoming data
                  for(a = 0; a < rx_buffer[6]; a++){
                     *(rxPcketPayload + a) = rx_buffer[(7 + a)];      //store the payload into rxPcketPayload
                  }
                  for(a = 0; a < rx_buffer[6]; (a += 2)){
                     payloadDecipher(32,(rxPcketPayload + a));        //decrypt the packet here
                  }
                  //first byte of the payload is the ACState and the second byte of the payload is the tempValue
                  setIrCommand(*rxPcketPayload, *(rxPcketPayload + 1));
                  free(rxPcketPayload); //free the alocated memory
               break;
           
               case 0x04: // Emergency
                  set_adc_channel(0);        //the next read_adc call will read channel0. This is needed when there are more analog inputs
                  envTemp = read_adc() * 500/1024;
                  envTemp = floor(envTemp);
                  sendData(envTemp, 0x03); 
                  sendData(envTemp, 0x04);                 //send emergency data packet
               break;         
            }
            memset(rx_buffer,0,sizeof(rx_buffer));     
         } 
      }
      //End of packet listener code
     
      //send a test packet
      createPacket(0x02, 0x00);     // Send a test packet here
     
      counter++;      //set the counter here as a timer
      if(counter == 2000){       //if the counter equals to 2000 it reads the temperature value from the sensor
         counter = 0;            //Again set the counter to zero
         set_adc_channel(0);        //the next read_adc call will read channel0. This is needed when there are more analog inputs
         envTemp = read_adc() * 500/1024;
         envTemp = floor(envTemp);
         sendData(envTemp, 0x03);             //send data packet to the cordianter which contains environment temperature
      }
     
   free(packet); //free the memory, allocated for the entire packet
   }
}

void payloadEncipher(unsigned int num_rounds, unsigned int8* packetPayload){
   
   unsigned int8 fblock, sblock, i, sum=0;
   unsigned int8 delta=0x9E3779B9;
   
   fblock = *packetPayload;
   sblock = *(packetPayload + 1);
   
   for(i=0; i<num_rounds; i++) {
      fblock += (((sblock << 4) ^ (sblock >> 5)) + sblock) ^ (sum + key[sum & 3]);
      sum += delta;
      sblock += (((fblock << 4) ^ (fblock >> 5)) + fblock) ^ (sum + key[(sum>>11) & 3]);
   }
   
   *packetPayload = fblock;
   *(packetPayload + 1) = sblock;
}
 
void payloadDecipher(unsigned int num_rounds, unsigned int8* packetPayload) {
   unsigned int8 fblock, sblock, i, sum;
   unsigned int8 delta=0x9E3779B9;
   
   
   fblock = *packetPayload;
   sblock = *(packetPayload + 1);
   sum=delta*num_rounds;
   
   for(i=0; i<num_rounds; i++) {
      sblock -= (((fblock << 4) ^ (fblock >> 5)) + fblock) ^ (sum + key[(sum>>11) & 3]);
      sum -= delta;
      fblock -= (((sblock << 4) ^ (sblock >> 5)) + sblock) ^ (sum + key[sum & 3]);
   }
   
   *packetPayload = fblock;
   *(packetPayload + 1) = sblock;
}

// Function to create the data packet
void createPacket(int8 packetType, int8 payloadLength){
   int8 a = 0;
   
   if(packetType == 0x03){         //for normal data packet
      *packet = route_table[0];      //add the nearest destination address to send the packet
   }
   
   else if(packetType == 0x04){  //for emergencey packet
      *packet = BrdcastAdd;      //add the broadcast address to send the packet
   }
   
   *(packet + 1) = EndDevAdd01;       //add the source address to the packet
   *(packet + 2) = CoordntrAdd;     //add the final destination address(cordinator)
   *(packet + 3) = EndDevAdd01;     //add the originator node address  to the packet
   *(packet + 4) = packetType;    //set the packet type here
   *(packet + 5) = 0x00;        //set the hop count here
   *(packet + 6) = payloadLength; //add the payload length to the packet
   
   if(payloadLength != 0x00){
      for(a = 0; a < payloadLength; a++){
         *(packet + (a + 7)) = *(packetPayload + a);   //add the payload to the packet here
      }
   }
   
   *(packet + (6 + payloadLength + 1)) = DELIM;        //add the delimeter to the end of the packet
   
   for (a=0;a < (7 + payloadLength) ;a++){             //send the packet data
      bputc(*(packet + a));                                               
   } 
   
   for (a=0;a < (7 + payloadLength) ;a++){             //send the packet data
      printf("%d",(*(packet + a)));                                               
   }
}

// Sending data
void sendData(int8 envTemp, int8 packetType){
   int8 payloadLength = 0x00;   //set the payload length
   int8 a;
   
   packetPayload = (int8 *)calloc(4, sizeof(int8)); //allocate memory for the packet payload
   
   if(AC_State){
      *(packetPayload + 0) = ACStateON;     //AC is in on state
      payloadLength++;
   } else { 
      *(packetPayload + 0) = ACStateOFF;     //AC is in off state
      payloadLength++;
   }
   
   *(packetPayload + 1) = envTemp;       //here temperature values sholud be assigned
   payloadLength++;

   //payload length should be an even number
   for(a = 0; a < payloadLength; (a += 2)){
      payloadEncipher(32, (packetPayload + a));    //encrypt the packet payload here
   }
   
   if(packetType == 0x03){
      createPacket(0x03, payLoadLength);    //send data packet
   }
   else if(packetType == 0x04){
      createPacket(0x04, payLoadLength);    //send emergency data packet
   }
   free(packetPayload); //free the memory, allocated for the packet payload
}

_________________
Kushan Sharma
mlkushan@gmail.com
PCM programmer



Joined: 06 Sep 2003
Posts: 21708

View user's profile Send private message

PostPosted: Wed Jan 14, 2009 3:51 pm     Reply with quote

Quote:
When i simulated that code using 16F PIC simulator IDE

Does you mean the MPLAB simulator ? If so, what version of MPLAB ?
mlkushan



Joined: 16 Nov 2008
Posts: 22
Location: Sri Lanka

View user's profile Send private message Send e-mail Visit poster's website Yahoo Messenger

PostPosted: Wed Jan 14, 2009 7:15 pm     Reply with quote

hi,

Thanks for accepting my request on.

Quote:

Does you mean the MPLAB simulator ? If so, what version of MPLAB ?


No, that is a software simulator.
(Details about the simulator http://www.oshonsoft.com/pic.html)

Thanks in advance.
kushan
_________________
Kushan Sharma
mlkushan@gmail.com
PCM programmer



Joined: 06 Sep 2003
Posts: 21708

View user's profile Send private message

PostPosted: Wed Jan 14, 2009 7:58 pm     Reply with quote

It could be a simulator bug. On the Oshonsoft webpage, they do not
list any bug fixes. They always say "Several small and/or invisible
improvements".

Look at the Stack Usage for your program, which is given at the top
of the .LST file. The .LST file is in your project directory. It should be
a maximum of 8 levels for the 16F877A. It will probably be OK.


I looked at your code a little. I notice that you use calloc() but you don't
check to see if the returned pointer is NULL. This would indicate that
calloc() failed to get the requested memory block. For example, in this
code, you don't check if packetPayload is NULL before you start using it:
Quote:
packetPayload = (int8 *)calloc(4, sizeof(int8));

if(AC_State){
*(packetPayload + 0) = ACStateON; //AC is in on state
payloadLength++;
}


Also, I notice that in the routine below, you are allocating a block of RAM
and then you free it at the end of the function:
Quote:
void sendData(int8 envTemp, int8 packetType){
int8 payloadLength = 0x00; //set the payload length
int8 a;

packetPayload = (int8 *)calloc(4, sizeof(int8)); //allocate memory for the packet payload
.
.
.
free(packetPayload); //free the memory, allocated for the packet payload
}

Did you know that you can do the same thing with a simple array
declaration ? The CCS compiler will (internally) allocate memory for
the local array, and then free it when the routine exits. That's one of
the great features of CCS. Just add the line shown in bold below and
get rid of calloc() and free():
Quote:
void sendData(int8 envTemp, int8 packetType){
int8 payloadLength = 0x00; //set the payload length
int8 a;
int8 packetPayload[4];


My advice is, get rid of calloc() and free(), and use standard array
declarations in your program. It's possible that some bug in these
functions or your usage of them is causing the stack overflow problem.
mlkushan



Joined: 16 Nov 2008
Posts: 22
Location: Sri Lanka

View user's profile Send private message Send e-mail Visit poster's website Yahoo Messenger

PostPosted: Thu Jan 15, 2009 1:42 am     Reply with quote

Thanks for your help.

I made some modifications on my code.
Initially

Code:
int8 *packet;
had been defined in two places. I removed it and defined it inside the main function. Then the above mentioned error was not given.

Finally i changed code by modifying
Code:
packet = (int8 *)calloc(12,sizeof(int8));  //create a data packet here


as

Code:
int8 packet[12]

then it again didn't gave the above mentioned error.

But the delimiter which is needed to assigned at the end of the byte stream, is not assigned.

Code:
 packet[payloadLength + 7] = DELIM';        //add the delimeter to the end of the packet


when i simulate the code it doesn't show the DELIM at the end of the byte stream.

The bellow code segment should print the entire byte stream on the hardware UART output of the simulator. but it prints only up to the delimiter.

Code:
for (a=0;a < (7 + payloadLength) ;a++){             //send the packet data
      printf("%d",packet[a]);                                               
   }


Thank you very much and your help is highly appreciated.
Kushan

Code:

#include <16F877A.h>
#device adc=8

#FUSES NOWDT                    //No Watch Dog Timer
#FUSES XT                       //Crystal osc <= 4mhz
#FUSES NOPUT                    //No Power Up Timer
#FUSES NOPROTECT                //Code not protected from reading
#FUSES NODEBUG                  //No Debug mode for ICD
#FUSES NOBROWNOUT               //No brownout reset
#FUSES NOLVP                    //No low voltage prgming, B3(PIC16) or B5(PIC18) used for I/O
#FUSES NOCPD                    //No EE protection
#FUSES WRT_50%                  //Lower half of Program Memory is Write Protected

#use delay(clock=4000000)
#use rs232(baud=9600,parity=N,xmit=PIN_C6,rcv=PIN_C7,bits=8)

#include <math.h>
#include <stdlibm.h>
#include <string.h>

//function prototypes
void sendData(int8 envTemp, int8 packetType, int8 *packet);
void payloadDecipher(unsigned int num_rounds, unsigned int8* packetPayload);
void payloadEncipher(unsigned int num_rounds, unsigned int8* packetPayload);
void createPacket(int8 packetType, int8 payloadLength, int8 *packet);

//For encryption and decryption
unsigned int8 key[] = {0x80, 0x00, 0x80, 0x80};    //32bit int8 key of for XTEA

//define the packet payload array pointer
int8 *packetPayload;

//Array for keeping routing entries
//route_table[0] for keeping the nexthop address
//route_table[1] for keeping the hopcount
int8 route_table[2];

//mainteains the Air Conditioner state
int1 AC_State = FALSE;   

//for RXTX data communication
#define RX_BUFFER_SIZE 12
#define TX_BUFFER_SIZE 12
#define DELIM 0xFF      //since we are using bytes
#byte TXREG=0x19
#byte PIR1 = 0x0c
#bit TXIF=PIR1.4

unsigned int8 rx_buffer[RX_BUFFER_SIZE + 1];
unsigned int8 tx_buffer[TX_BUFFER_SIZE + 1];
int8 rx_wr_index = 0;
int8 tx_rd_index = 0;
int8 tx_wr_index = 0;
int8 tx_counter = 0;
int8 rxd;
int1 data_avail = FALSE;

//Define AC state
#define ACStateON 0xAA
#define ACStateOFF 0xBB

//for routting algorithm
#define CoordntrAdd 0x00 //Defining the Address of the Coordinator
#define RouterAdd01 0x81 //Address of this Router device
#define EndDevAdd01 0x01 //Addresses of End Devices
#define BrdcastAdd 0xFF

//SPI communication parameters
#define SPI_MODE_0  (SPI_L_TO_H | SPI_XMIT_L_TO_H)   //    low       leading edge
#define SPI_MODE_1  (SPI_L_TO_H)                     //    low       trailing edge
#define SPI_MODE_2  (SPI_H_TO_L)                     //    high      leading edge
#define SPI_MODE_3  (SPI_H_TO_L | SPI_XMIT_L_TO_H)   //    high      trailing edge

#int_RDA
void RDA_isr(void) {
   rx_buffer[rx_wr_index] = getc();
   rxd = rx_buffer[rx_wr_index];
   rx_wr_index++;
   
   if(rxd==DELIM){
      data_avail = TRUE;
      rx_wr_index = 0;
   }
   
   if (rx_wr_index > RX_BUFFER_SIZE) {          //prevent buffer overflows
      rx_wr_index = 0;
   }
}

#int_TBE
void TBE_isr(void) {
   if (tx_counter != 0) {
      putc(tx_buffer[tx_rd_index]);
     
      if (++tx_rd_index > TX_BUFFER_SIZE) {
         tx_rd_index = 0;
      }
     
      tx_counter--;
     
      if (tx_counter == 0) {
         disable_interrupts(INT_TBE);
      }
   }
}

void bputc(int c) {
   int restart = 0;
   if (tx_counter == 0){
      restart = 1;
   }
   tx_buffer[tx_wr_index++] = c;
   if (tx_wr_index > TX_BUFFER_SIZE) {
      tx_wr_index = 0;
   }
   tx_counter++;
   if (restart == 1){
      enable_interrupts(INT_TBE);
   }
}

void setIrCommand(int8 ACState, int8 tempValue){
   if(ACState == ACStateON){
      spi_write(0x32);         //set AC ON
   }   
   else if(ACState == ACStateOFF){
      spi_write(0x64);         //set AC OFF
   }
   else if((tempValue > 0x16) && (tempValue < 0x31)){
      spi_write(tempValue);      //set temperature value here.
   }
}

void main(){
   int8 pwmDuty = 50;
   long counter = 0;
   int8 envTemp;
   int8 *rxPcketPayload;
   int8 a;
   int8 packet[12];
   //delay_ms(2000);   //initializing delay

   setup_adc_ports(AN0);
   setup_adc(ADC_CLOCK_INTERNAL);
   //set_tris_a(0b00000001);
   setup_psp(PSP_DISABLED);
   
   delay_us(100); //This ensures the slave has time to wake before master
   setup_spi(SPI_MASTER|SPI_MODE_0|SPI_CLK_DIV_4);
   delay_us(100);
   
   setup_timer_0(RTCC_INTERNAL|RTCC_DIV_1);
   setup_timer_1(T1_DISABLED);
   setup_timer_2(T2_DIV_BY_1,24,1);
   setup_ccp1(CCP_PWM);
   set_pwm1_duty(pwmDuty);
   setup_comparator(NC_NC_NC_NC);
   setup_vref(FALSE);
   enable_interrupts(INT_RDA);
   enable_interrupts(GLOBAL);

   // TODO: USER CODE!!
   // TODO: USER CODE!!
   route_table[1] = 0xFF; // First initialise the hop count to the largest value.
   
   while(true){
      //packet listener code
      if(data_avail)
      {
         data_avail = FALSE; 
         if((rx_buffer[0] != EndDevAdd01) || (rx_buffer[0] != BrdcastAdd)){
            memset(rx_buffer,0,sizeof(rx_buffer));           //drop the rx packet
         }
         else{
            switch(rx_buffer[4]){ // switch the packet type
               case 0x01:  // Route request packet
                  if(route_table[1] > rx_buffer[5]){    //check the hop count value of the incoming packet
                     route_table[0] = rx_buffer[1];     // Nearest source's address
                     route_table[1] = rx_buffer[5];     // update the hop count
                  }
                  createPacket(0x02, 0x00, packet);     // Send a route reply packet       
               break;
           
               case 0x02: // Route reply packet, from others, shold be droped
                  // Drop the packet
               break;
           
               case 0x03: // Data packet from the cordinator
                  rxPcketPayload = (int8 *)calloc(rx_buffer[6], sizeof(int8));  //allocate memory of the size of incoming packet payload length to store the incoming data
                  for(a = 0; a < rx_buffer[6]; a++){
                     *(rxPcketPayload + a) = rx_buffer[(7 + a)];      //store the payload into rxPcketPayload
                  }
                  for(a = 0; a < rx_buffer[6]; (a += 2)){
                     payloadDecipher(32,(rxPcketPayload + a));        //decrypt the packet here
                  }
                  //first byte of the payload is the ACState and the second byte of the payload is the tempValue
                  setIrCommand(*rxPcketPayload, *(rxPcketPayload + 1));
                  free(rxPcketPayload); //free the alocated memory
               break;
           
               case 0x04: // Emergency
                  set_adc_channel(0);        //the next read_adc call will read channel0. This is needed when there are more analog inputs
                  envTemp = read_adc() * 500/1024;
                  envTemp = floor(envTemp);
                  sendData(envTemp, 0x03, packet); 
                  sendData(envTemp, 0x04, packet);                 //send emergency data packet
               break;         
            }
            memset(rx_buffer,0,sizeof(rx_buffer));     
         } 
      }
      //End of packet listener code

      //send a test packet
      createPacket(0x02, 0x00, packet);     // Send a test packet here
     
      if(counter == 1000){       //if the counter equals to 2000 it reads the temperature value from the sensor
         counter = 0;            //Again set the counter to zero
         set_adc_channel(0);        //the next read_adc call will read channel0. This is needed when there are more analog inputs
         envTemp = read_adc() * 500/1024;
         envTemp = floor(envTemp);
         sendData(envTemp, 0x03, packet);             //send data packet to the cordianter which contains environment temperature
      }
      counter++;      //set the counter here as a timer
   }
}

void payloadEncipher(unsigned int num_rounds, unsigned int8* packetPayload){
   
   unsigned int8 fblock, sblock, i, sum=0;
   unsigned int8 delta=0x9E3779B9;
   
   fblock = *packetPayload;
   sblock = *(packetPayload + 1);
   
   for(i=0; i<num_rounds; i++) {
      fblock += (((sblock << 4) ^ (sblock >> 5)) + sblock) ^ (sum + key[sum & 3]);
      sum += delta;
      sblock += (((fblock << 4) ^ (fblock >> 5)) + fblock) ^ (sum + key[(sum>>11) & 3]);
   }
   
   *packetPayload = fblock;
   *(packetPayload + 1) = sblock;
}
 
void payloadDecipher(unsigned int num_rounds, unsigned int8* packetPayload) {
   unsigned int8 fblock, sblock, i, sum;
   unsigned int8 delta=0x9E3779B9;
   
   
   fblock = *packetPayload;
   sblock = *(packetPayload + 1);
   sum=delta*num_rounds;
   
   for(i=0; i<num_rounds; i++) {
      sblock -= (((fblock << 4) ^ (fblock >> 5)) + fblock) ^ (sum + key[(sum>>11) & 3]);
      sum -= delta;
      fblock -= (((sblock << 4) ^ (sblock >> 5)) + sblock) ^ (sum + key[sum & 3]);
   }
   
   *packetPayload = fblock;
   *(packetPayload + 1) = sblock;
}

// Function to create the data packet
void createPacket(int8 packetType, int8 payloadLength, int8 *packet){
   int8 a = 0;
   
   if(packetType == 0x04){  //for emergencey packet
      packet[0] = BrdcastAdd;      //add the broadcast address to send the packet
   }
   
   else{         //for normal data packet or router reply packet (sends to the cordinator)
      packet[0] = route_table[0];      //add the nearest destination address to send the packet
   }
   
   packet[1] = EndDevAdd01;       //add the source address to the packet
   packet[2] = CoordntrAdd;     //add the final destination address(cordinator)
   packet[3] = EndDevAdd01;     //add the originator node address  to the packet
   packet[4] = packetType;    //set the packet type here
   packet[5] = 0x00;        //set the hop count here
   packet[6] = payloadLength; //add the payload length to the packet
   
   if(payloadLength != 0x00){
      for(a = 0; a < payloadLength; a++){
         packet[a + 7] = *(packetPayload + a);   //add the payload to the packet here
      }
   }
   
   packet[payloadLength + 7] = DELIM';        //add the delimeter to the end of the packet
   
   for (a=0;a < (7 + payloadLength) ;a++){             //send the packet data
      bputc(packet[a]);                                               
   } 
   for (a=0;a < (7 + payloadLength) ;a++){             //send the packet data
      printf("%d",packet[a]);                                               
   }
}

// Sending data
void sendData(int8 envTemp, int8 packetType, int8 *packet){
   int8 payloadLength = 0x00;   //set the payload length
   int8 a;

   packetPayload = (int8 *)calloc(4, sizeof(int8)); //allocate memory for the packet payload
   
   if(AC_State){
      *(packetPayload + 0) = ACStateON;     //AC is in on state
      payloadLength++;
   } else { 
      *(packetPayload + 0) = ACStateOFF;     //AC is in off state
      payloadLength++;
   }
   
   *(packetPayload + 1) = envTemp;       //here temperature values sholud be assigned
   payloadLength++;

   //payload length should be an even number
   for(a = 0; a < payloadLength; (a += 2)){
      payloadEncipher(32, (packetPayload + a));    //encrypt the packet payload here
   }
   
   if(packetType == 0x03){
      createPacket(0x03, payLoadLength, packet);    //send data packet
   }
   else if(packetType == 0x04){
      createPacket(0x04, payLoadLength, packet);    //send emergency data packet
   }
   
   free(packetPayload); //free the memory, allocated for the packet payload
}

_________________
Kushan Sharma
mlkushan@gmail.com
Display posts from previous:   
Post new topic   Reply to topic    CCS Forum Index -> General CCS C Discussion All times are GMT - 6 Hours
Page 1 of 1

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum


Powered by phpBB © 2001, 2005 phpBB Group