Continue to Site

Welcome to EDAboard.com

Welcome to our site! EDAboard.com is an international Electronics Discussion Forum focused on EDA software, circuits, schematics, books, theory, papers, asic, pld, 8051, DSP, Network, RF, Analog Design, PCB, Service Manuals... and a whole lot more! To participate you need to register. Registration is free. Click here to register now.

help for my code.. its just routine

Status
Not open for further replies.

mldt28

Newbie level 6
Newbie level 6
Joined
Feb 20, 2013
Messages
14
Helped
0
Reputation
0
Reaction score
0
Trophy points
1,281
Visit site
Activity points
1,401
hi guys..
i have a functional code but i just i wanted to post it if there is a better way on executing my program...... here is my program and the area where im having a hard time is the void main...
which consist of reading from SUART and at the same time READING from GSM recieved text

Code:
// LCD module connections
sbit LCD_RS at RB0_bit;
sbit LCD_EN at RB1_bit;
sbit LCD_D4 at RB2_bit;
sbit LCD_D5 at RB3_bit;
sbit LCD_D6 at RB4_bit;
sbit LCD_D7 at RB5_bit;

sbit LCD_RS_Direction at TRISB0_bit;
sbit LCD_EN_Direction at TRISB1_bit;
sbit LCD_D4_Direction at TRISB2_bit;
sbit LCD_D5_Direction at TRISB3_bit;
sbit LCD_D6_Direction at TRISB4_bit;
sbit LCD_D7_Direction at TRISB5_bit;

//Used by PDU decoder routines
#define MESSAGE_ENCODED_SIZE  70                          //!< Size of SMS payload
#define MESSAGE_LENGTH        80                          //!< Max allowed text in SMS
#define hex_nmbr "0123456789ABCDEF"                       //!< Flash string container, look up table

//MACROS for LCD
#define debugCRLF() ((Soft_UART_Write(0x0D)),(Soft_UART_Write(0x0A)))           //!< Print newline to lcd
#define clrscr()    ((Soft_UART_Write(0x1B)),(Soft_UART_Write(0x45)))           //!< Clear LCD

//MACROS for controlling the isr
#define setSearch(a) ((searchWat=a),(searchFor=searchStrings[a]))     //!< set the string to be waited by interrupt from GSM
#define rxeset() ((bRx_on=0),(iBuff=0),(irx=0),(Ack=0))               //!< Used to initialize buffer for gsm response reception
#define rx_on()  ((bRx_on=1))                                         //!< turn on  reciever (interrupt)
#define rx_off()  ((bRx_on=0))                                        //!< turn off reciever (interrupt)

const unsigned char    hex_lookup[]         = hex_nmbr;              //!< Lookup table -> int 2 hex
const unsigned char    mask[7]              = {1,3,7,15,31,63,127};  //!< Lookup table -> mask
const unsigned char    power[7]             = {128,64,32,16,8,4,2};  //!< Lookup table -> 2^( 7 - i )

const unsigned int     BUFF_SIZE = 900;
const unsigned int     OK_ = 0;
const unsigned int     RDY_ = 1;
const unsigned int     CMTI_ = 2;
const unsigned int     READY_ = 3;
const unsigned int     CRLF_ = 4;

static unsigned char            Message[64];
static unsigned char            Number[20];
static volatile unsigned char   Buff[BUFF_SIZE], irx, bRx_on=0, searchWat=0;
static volatile unsigned int    iBuff;
static volatile unsigned char   Ack;

//COMMANDS TO GSM
const unsigned char AT_CMGF1[]                   = "AT+CMGF=1\r";
const unsigned char AT_CMGD[]                    = "AT+CMGDA=1\r";
const unsigned char AT_CSQ[]                     = "AT+CSQ\r";
const unsigned char AT_CMGF[]                    = "AT+CMGF=0\r";
const unsigned char AT_CMGL[]                    = "AT+CMGL\r";
const unsigned char AT[]                         = "AT\r";
const unsigned char ATE0[]                       = "ATE0\r";
const unsigned char AT_CNMI[]                    = "AT+CNMI=1,1,,,1\r";
const unsigned char AT_CPMS[]                    = "AT+CPMS=\"ME\",\"ME\",\"ME\"\r";

// Search strings and variables
const unsigned char OK[]    = "OK\r\n";
const unsigned char RDY[]   = "RDY";
const unsigned char CMTI[]  = "CMTI:";
const unsigned char READY[] = ">";
const unsigned char CRLF[]  = "\r\n";
const unsigned char *searchFor;
const unsigned char *searchStrings[] = {OK, RDY, CMTI, READY, CRLF};

int            ZIP_decompress( unsigned char *compressed, unsigned char *decompressed );  //decode PDU encoded text
int            ZIP_atoi( unsigned char *a );                                              // some utilities
int            ZIP_htoi( unsigned char hex );                                             // some utilities
void           ZIP_itoh( int n, unsigned char *ret );                                     // some utilities
unsigned char* TOOLS__decodeCMGL( unsigned char * in_handle );                            // return true start of sms in pdu text
void           COM_puts(const unsigned char *cmd);                                        //send commands to gsm
void           Init();                                                                    // initialization routines
void           ReadAll();                                                                 // read all new unread text messages
int            Check_Acknowledged(unsigned long int timeout);                             // check if acknowledged flag is set
void           deleteSMS();
float          powerAnalyzer_Read(void);

void interrupt()
{
    unsigned char current;
    INTCON.GIE = 0;                                                             //disable all interrupts
    if(PIR1.RCIF)                                                               // check if interrupt source is RCIF
    {
         current = RCREG;                                                       // save the character receive to a variable
         if(bRx_on==1)                                                          // check if receiver PIC should save received values
         {
             Buff[iBuff] = current;                                             // save value to buffer
             Buff[iBuff+1] = '\0';                                              // put null character next to ibuffer
             if((iBuff++) == BUFF_SIZE)                                         // if overflow.. just turn off receiver
             {
                  rx_off();
                  iBuff = 0;
             }
             if(searchFor[irx]==current)
             {
                  irx++;
                  if(searchFor[irx]=='\0')
                  {
                       irx = 0;
                       if(searchWat==CMTI_)                       // if new Message received
                       {
                            setSearch(CRLF_);
                       }
                       else
                       {
                            Ack = 1;                              // pattern found, raise flag
                            rx_off();
                       }
                  }
             }
             else
                  irx = 0;                                        // pattern not found , reset counter
         }
         PIR1.RCIF = 0;
    }
    INTCON.GIE = 1;
}

void main(void)
{

      char extra[10], kwdata[10], kwhdata[10], kwhratesum[10];
      float total = 0;
      float total2 = 0;
      float ave = 0;
      float ave2 = 0;
      float kw =0;
      float kw2 =0;
      float kwh =0;
      float kwh2 =0;
      float kwhsum = 0;
      float kwhrate = 0;
      float rate = 0;
      float ratesum = 0;

      float wattsec_ = 0;
      int count = 0;
      int count2 = 0;

      TRISD.F3 = 0;     // output1 to relay
      TRISB.F6 = 0;     // output2 to led

      PORTB = 0;
      PORTD.F2 = 1;
      Delay_ms(500);

      Init();
      setSearch(CMTI_);
      rxeset();
      rx_on();

      for(;;)
      {
           while(!Ack)
           {  /*
               wattsec_ = powerAnalyzer_Read();
               count++;
               count2++;
               total += wattsec_;
               total2 += wattsec_;
               kw = wattsec_/1000;
               kwh = kw / 3600;
               kwhsum +=  kwh;


               sprintf(kwdata, "%.2f", kw);        //FloatToStr(kw,kwdata);
               sprintf(kwhdata, "%.2f", kwhsum);     //FloatToStr(kwhsum,kwhdata);

               Lcd_Cmd(_LCD_CLEAR);
               Lcd_Out(1,1, "KW: ");
               Lcd_Out(1,5, kwdata);
               Lcd_Out(2,1, "KW/hour: ");
               Lcd_Out(2,10, kwhdata);
               Lcd_Out(3,1, "KWH/30SEC: ");
               Lcd_Out(3,12, extra);
               Lcd_Out(4,1, "BILL: ");
               Lcd_Out(4,7, kwhratesum);


               if((count % 30) == 0){

               ave = total / 1000;               //to kph /30 secs
               ave2 = ave  / 3600;               // recode pagconvert**********************************************
               sprintf(extra, "%.5f", ave2);     // to GSM modem
                                                    //FloatToStr(ave2, extra);

                    // --------------- Code here to Send MSG ---------------- //
                    COM_puts("AT+CMGF=1\r\n");
                    Delay_ms(1000);
                    COM_puts("AT+CMGS=\"09184637272\"\r\n");
                    Delay_ms(1500);

                    UART1_WRITE_TEXT(extra);

                    Delay_ms(500);
                    Uart1_Write(0x1A);
                    COM_puts(AT_CMGF);
                    Delay_ms(1500);
                    // ------------- End Code here to Send MSG -------------- //

                    total = 0;
                    count = 0;
                    delay_ms(2000);
               }

               if((count2 % 60) == 0){
               kw2 = total2 / 1000;
               kwh2 = kw2 / 3600;
               kwhrate = kwh2 * 4.0740;


               sprintf(kwhratesum, "%.2f", kwhrate);

                    // --------------- Code here to Send MSG ---------------- //
                    COM_puts("AT+CMGF=1\r\n");
                    Delay_ms(1000);
                    COM_puts("AT+CMGS=\"09184637272\"\r\n");
                    Delay_ms(1500);

                    UART1_WRITE_TEXT(kwhratesum);

                    Delay_ms(500);
                    Uart1_Write(0x1A);
                    COM_puts(AT_CMGF);
                    Delay_ms(1500);
                    // ------------- End Code here to Send MSG -------------- //


                    total2 = 0;
                    count2 = 0;
                    delay_ms(2000);
               }     */
           }
           ReadAll();
           setSearch(CMTI_);
           rxeset();
           rx_on();
      }
}

void Init()
{
        Soft_UART_Init(&PORTD, 1, 0, 9600, 0);
        UART1_Init(9600);
        INTCON = 0xC0;
        PIR1.RCIF = 0;
        PIE1.RCIE = 1;
        ADCON1 = 0x0F;

        PORTD.F2 = 0;
        Delay_ms(600);
        PORTD.F2 = 1;

        TRISB = 0;
        Lcd_Init();
        Lcd_Cmd(_LCD_CURSOR_OFF);
        /*
        // wait for gsm to turned on
        setSearch(RDY_);
        rxeset();
        rx_on();

         while(!Ack){
            Lcd_Out(1,2, "Waiting for GSM");
            // waiting
        }  /
        Lcd_Cmd(_LCD_CLEAR);
               */
        // Test for rx tx
        setSearch(OK_);
        rxeset();
        rx_on();

        while(!Ack){
            // wait for OK reply from gsm
            COM_puts(AT);
            Delay_ms(500);
            Lcd_Out(1,3, "Testing GSM");
        }
        Lcd_Cmd(_LCD_CLEAR);

        Delay_ms(1000);   COM_puts(ATE0);      PORTB.F6 = 0;
        Delay_ms(400);    COM_puts(AT_CMGF);   PORTB.F6 = 1;
        Delay_ms(400);    COM_puts(AT_CPMS);   PORTB.F6 = 0;
        Delay_ms(400);    COM_puts(AT_CNMI);   PORTB.F6 = 1;
        Delay_ms(1000);   COM_puts(AT_CMGD);   PORTB.F6 = 0;

        Lcd_Out(1,6, "GSM BASED");
        Lcd_Out(2,2, "Energy Monitoring");
        Lcd_Out(3,8, "System");
        Lcd_Out(4,1, "AROMAMI");
        Delay_ms(2000);
}



void ReadAll()
{
    unsigned char *myptr, *prev, *tmptr;
    unsigned int len;
    int retval;

    setSearch(OK_);
    rxeset();
    rx_on();
    COM_puts(AT_CMGL);
    retval = Check_Acknowledged(0x100FFFF);

    if(retval>0)
    {
         prev = Buff;
         myptr = strpbrk(prev,"\xA");
         while(myptr)
         {
              *myptr = '\0';
              len = strlen(prev);
              if((len>50) && (prev[len-1]==0x0D))
              {
                  prev[len -1] = '\0';
                  retval = ZIP_decompress(TOOLS__decodeCMGL(prev),Message);
                  if(strstr(Message,"OFF") > 0)
                  {
                     PORTD.F3 = 1;
                  }
                  else if(strstr(Message,"ON") > 0)
                  {
                     PORTD.F3 = 0;
                  }
                  else{}
              }
              prev = myptr + 1;
              myptr = strpbrk(prev,"\xA");
         }
         COM_puts(AT_CMGD);
         Delay_ms(200);
    }
    else if(retval == -1)
    {
         rxeset();
                 // something went wrong when msg is received
         Lcd_Cmd(_LCD_CLEAR);
         Lcd_Out(1,1, "ERROR receiving SMS");
         Delay_ms(2000);

    }
}

int Check_Acknowledged(unsigned long int timeout)
{
    unsigned long int cnt=0;
    cnt = 0;
    while(Ack==0)
    {
        if(cnt>timeout)
        {
            return (-1);
        }
        cnt++;
    }
    return Ack;
}

void COM_puts(const unsigned char *cmd)
{
     while(*cmd)
         UART1_Write(*cmd++);
}

unsigned char* TOOLS__decodeCMGL( unsigned char * in_handle)
{
                                                                                //! Local variables
                                                                                //unsigned char *in_handle;
      unsigned int field_length;
      field_length = 16 * ZIP_htoi( *in_handle++ );
      field_length += ZIP_htoi( *in_handle++ );
      in_handle += 2*field_length + 2;                                          //Skip Service center nmbr
                                                                                //Find length of sender address
      field_length = 16 * ZIP_htoi( *in_handle++ );
      field_length += ZIP_htoi( *in_handle++ );
      if( field_length%2 )
      {
          memcpy(Number,in_handle + 2,field_length+1);
          field_length++;                                                       //Check for trailing F
      }
      else
      {
          memcpy(Number,in_handle + 2,field_length);
      }
      in_handle += 2 + field_length;                                            //Skip fields in header
      in_handle += 14 + 4;                                                      //Skip more fields...TP-PID, TP-DCS and TP-SCTS
      return ( in_handle + 2 );                                                 //Return correct pointer
}

int ZIP_decompress( unsigned char *compressed, unsigned char decompressed[] )
{
                                                                                //! Local variables
    int i,ii,iii;                                                               //String index
                                                                                //unsigned char rest_c, ans_c  , this_c, next_c;
                                                                                //Read and temorary variables
    unsigned int dec_c, rest_c, this_c, next_c, ans_c;
    for( i = ii = iii = rest_c = 0; (this_c = compressed[i++]) != '\0'; )       //Run through complete string
    {
                                                                                //Read:
        next_c = compressed[i++];                                               //Read from in buffer in AVR_SMS_com.c
                                                                                //Convert:
        dec_c = 16 * ZIP_htoi( this_c ) + ZIP_htoi( next_c );                   //Decimal value of the two chars
        ans_c = dec_c & mask[6 - ii];                                           //Mask out the correct bits
        ans_c <<= ii;                                                           //Left shift proper correct of times
        decompressed[iii++] = ans_c + rest_c;                                   //Store
        rest_c = (dec_c & ~mask[6 - ii]) >> ( 7 - ii );                         //Saving up for next time
        if( ii == 6)                                                            //Do carry
        {
            ii = 0;
            decompressed[ iii++ ] = rest_c;
            rest_c = 0;
        }
        else
        {
            ii++;
        }
    }
    decompressed[ iii ] = '\0';                                                 //Terminate string in a proper manner
    return iii;                                                                 //Return length
}

int ZIP_atoi( unsigned char *a )
{
    int i, n;                                                                   //Help variables
    n = 0;                                                                      //Init
    for( i=0; ( a[ i ] >= '0' ) && ( a[ i ] <= '9' ); ++i )                     //Running through string converting from ascii to integer
    {
        n = 10*n + ( a[ i ] - '0' );                                            //Adding value to return Integer
    }
    return n;
}

int ZIP_htoi( unsigned char hex )
{
    if( ( hex >= 'A' ) && ( hex <= 'F' ) )                                      //Test if hex is A-->F?
    {
        return hex - 'A' + 10;
    }
    else                                                                        //Must have something else then:0-->9
    {
        return hex - '0';
    }
}

void ZIP_itoh( int n, unsigned char *ret )
{
    ret[ 0 ] = hex_lookup[ ( n >> 4 ) & 0x0F ];
    ret[ 1 ] = hex_lookup[ ( n & 0x0F ) ];
    ret[ 2 ] = '\0';
}

float powerAnalyzer_Read(void){
     float readData = 0;
     char dat, err, *ptr;
     unsigned char mybuff[54], mypbuff = 0;

     while(1){
         do{ dat = Soft_Uart_Read(&err); }while(err);
         if(dat == 'O'){ break; }
         if((mypbuff == 0) && (dat != 'I')){ continue; }

         mybuff[mypbuff++] = dat;

         if(mypbuff == 53){
             ptr = strtok(mybuff, ",");      // mybuff here contains the string from power analyzer module
             ptr = strtok(0, ",");           // ptr now contains string of watts
             mypbuff = 0;
             break;
         }
     }
     readData = atof(ptr);
     return readData;
}

void deleteSMS()
{
     COM_puts("AT+CMGD=0\r\n");
     COM_puts("AT+CMGD=1\r\n");
     COM_puts("AT+CMGD=2\r\n");
     COM_puts("AT+CMGD=3\r\n");
     COM_puts("AT+CMGD=4\r\n");
     COM_puts("AT+CMGD=5\r\n");
     COM_puts("AT+CMGD=6\r\n");
     COM_puts("AT+CMGD=7\r\n");
     COM_puts("AT+CMGD=8\r\n");
     COM_puts("AT+CMGD=9\r\n");
     COM_puts("AT+CMGD=10\r\n");
     COM_puts("AT+CMGD=11\r\n");
     COM_puts("AT+CMGD=12\r\n");
     COM_puts("AT+CMGD=13\r\n");
     COM_puts("AT+CMGD=14\r\n");
     COM_puts("AT+CMGD=15\r\n");
     COM_puts("AT+CMGD=16\r\n");
     COM_puts("AT+CMGD=17\r\n");
     COM_puts("AT+CMGD=18\r\n");
     COM_puts("AT+CMGD=19\r\n");
     COM_puts("AT+CMGD=20\r\n");
}


// ENZONE
 

How is your GSM connected to MCU Rx pin? What else is connected to Rx pin of MCU? I mean are you using multiple devices to connect to Rx pin of MCU? If yes you have to select device before reading through USART. What if more that one device sends data to Rx pin? Does you GSM module have a CS (chip select) pin?
 

ahmm...
i did use UART1 for the for the GSM and SUART for the AC POWER ANALYZER...
thats how I configured this things....
 

ahm...
im using a PIC18f4550.... i just used an interrupt for the UART part...
for the SUART i didn't...
also im a newbie for this i ain't familiar with the routines all in all...
the code is funtioning...
every second the AC power analyzer fetch data..
at dsame time the INTERRUPT is waiting for new sms msg...
but when i text an sms message...
it works properly but when i text second time...
its stuck...
can u help me here bro??

for a simple scenario

i text my system a msg of OFF to send a signal to portd.f3 and produce 1.
but when i text it back with an ON msg the system didn't respond..
 

How do you know whether MCU is hanging or GSM module is hanging? I think the problem is with serial interrupt. Maybe interrupt is getting disabled after first transmission.

I see serial interrupt code for Rx but not for Tx and I see that you are using mikroC PRO as Compiler. You should not use serial interrupt if you are using UARTx() library. The library will handle the initialization, Rx, and Tx.

Is it

Code C - [expand]
1
2
3
4
5
void COM_puts(const unsigned char *cmd)
{
     while(*cmd)
         UART1_Write(*cmd++);
}


or

Code C - [expand]
1
2
3
4
5
6
void COM_puts(const unsigned char *cmd)
{
    do{
         UART1_Write(*cmd);
    while(*cmd++);
}

 
Last edited:

Status
Not open for further replies.

Part and Inventory Search

Welcome to EDABoard.com

Sponsor

Back
Top