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.

Problem with" if Condition" in C language

Status
Not open for further replies.

fizo741

Member level 1
Member level 1
Joined
Aug 10, 2012
Messages
34
Helped
0
Reputation
0
Reaction score
0
Trophy points
1,286
Location
Tehran/Iran
Visit site
Activity points
1,539
Hi,
I use this program in order to sense temperature with MLX90614
and show object temp and ambient temp on a lcd.(These codes are for Application note of MLX90614)But unfortunately if conditions in MemRead1 function dosen't work it means nothing returns from TX_byte() function so program passes all of ifs
(if dosent work).I compiled it with codevision and it dosent have any error.
Any one who is good at C language would you please help me to understand why and what should i do to correct it?
functions are at the end.
Thanks in advance.
Code:
/*****************************************************
This program was produced by the
CodeWizardAVR V1.25.7 beta 5 Standard
Automatic Program Generator
© Copyright 1998-2007 Pavel Haiduc, HP InfoTech s.r.l.
http://www.hpinfotech.com

Project : 
Version : 
Date    : 11/11/2009
Author  : F4CG                            
Company : F4CG                            
Comments: 


Chip type           : ATmega16L
Program type        : Application
Clock frequency     : 3.000000 MHz
Memory model        : Small
External SRAM size  : 0
Data Stack size     : 256
*****************************************************/

#include <mega16.h>
#include <delay.h>
#include <stdio.h>
// Alphanumeric LCD Module functions
#asm
   .equ __lcd_port=0x1B ;PORTA
#endasm
#include <lcd.h> 
char str[16];
char x,y;
int DELAY_1=250;

  
#define  _SCL      PORTC.0
#define  _SDA      PORTC.1
#define mSDA_HIGH()   _SDA=1;DDRC.1=0;  //Set SDA line
#define mSDA_LOW()   _SDA=0;DDRC.1=1; 
#define mSCL_LOW()    _SCL=0
#define mSCL_HIGH()   _SCL=1
#define RAM_Access 0x00//RAM access command
#define RAM_Tobj1  0x07//Tobj1 address in the RAM
#define RAM_Ta     0x06//Ta address  in the RAM
#define EEPROM_Access 0x20//EEPROM access command 
#define HIGHLEV  3
#define LOWLEV   1
#define TBUF    10
#define SA       0x5A


void  START_bit() ;
 void  STOP_bit();
 void  DummyCommand(unsigned char byte);   
 unsigned char TX_byte(unsigned char Tx_buffer);  
 void  MCUinit(void); 
 void  send_bit(unsigned char bit_out);
 unsigned char Receive_bit(void);
 float CalcTemp1(unsigned int data1);
 float CalcTemp2(unsigned int data2);
 unsigned char RX_byte(unsigned char ack_nack);   
 unsigned int  MemRead1( unsigned char SlaveAddress, unsigned char command1);
 unsigned int  MemRead2(unsigned char SlaveAddress, unsigned char command2);
 unsigned char PEC_calculation(unsigned char pec[]);
 unsigned char i;



// Declare your global variables here

void main(void)
{
unsigned char      SlaveAddress;//Contains device address
 unsigned char    command1;  //Contains the access command 
 unsigned char    command2;  //Contains the access command 
 unsigned int     data1,data2;//Contains data value 
 float            temp1,temp2;//Contains the calculated temperature


                  
 SlaveAddress=SA<<1; //Set device address 
 command1=RAM_Access|RAM_Tobj1; 
 command2=RAM_Access|RAM_Ta;

// DummyCommand(SlaveAddress);//This is need if Request Command is sent even
                            //when the module is in SMBUS mode
delay_ms(200);             //Wait after POR,Tvalid=0.15 s



PORTA=0x00;
DDRA=0xFF;


PORTB=0x00;
DDRB=0x00;

PORTC=0x02;
DDRC=0x01;

PORTD=0x00;
DDRD=0xFF;





// LCD module initialization
lcd_init(16);

while (1)
      { 
       
      data1=MemRead1(SlaveAddress,command1); //Read memory 
           
      temp1=CalcTemp1(data1);//Calculate temperature
      
      
       for(i=0;i<=3;i++)
      delay_ms(DELAY_1);//wait 1 second          
      data2=MemRead2(SlaveAddress,command2);//Read memory
      temp2 =CalcTemp2(data2) ;//Calculate temperature 
      for(i=0;i<=3;i++)
      delay_ms(DELAY_1);//wait 1 second
      x=PINA,y=PINA;
      lcd_clear();
      lcd_gotoxy(0,0);
      sprintf(str,"temp1=%00f   temp2=%00f",x,y);
      lcd_puts(str);
      delay_ms(100);
      
      }
      }
void  START_bit() {
 
 mSDA_HIGH(); //set SDA line       
 delay_us(TBUF); //Wait a few microseconds  
 mSCL_HIGH();    //Set SCL line
 delay_us(TBUF); //Stop condition setup time 
 
 mSDA_LOW() ;//Set SDA line 
          
 delay_us(TBUF);
 mSCL_LOW();   
 delay_us(TBUF);
 
 
}

 void STOP_bit(void){
    
  mSCL_LOW();           //Clear SCL line
  delay_us(TBUF);//Wait a few microseconds 
   
  mSDA_LOW() ; //clear SDA line
       
  delay_us(TBUF); //Wait a few microseconds
  mSCL_HIGH();   //Set SCL line
  delay_us(TBUF); //Stop condition setup time
  
  mSDA_HIGH(); //Set SDA line 
          
    
  }
  
void send_bit(unsigned char bit_out ) {  

  if(bit_out==0){mSDA_LOW() ;}        
  else          {mSDA_HIGH();} 
 
  delay_us(5);   
  mSCL_HIGH();//Set SDA line
  for(i=0;i<=11;i++)     
  delay_ms(DELAY_1); //High Level of Clock Pulse  
  mSCL_LOW(); //Clear SCL line   
  for(i=0;i<=3;i++)   
  delay_ms(DELAY_1);//Low Level of Clock Pulse
     
 // mSCA_HIGH(); // Master release SDA line, 
 return;
  }//End of send_bit() 
  
unsigned char Receive_bit(void){ 

 unsigned char  Ack_bit;
 
  DDRC.1=0; 
  mSCL_HIGH();//Set SCL line
  for(i=0;i<=11;i++)     
 delay_ms(DELAY_1); //High Level of Clock Pulse
  if(_SDA)  Ack_bit=1;    //\Read acknowledgment bit,save it in Ack_bit
  else      Ack_bit=0; // /
  
  
  mSCL_LOW();//Clear SCL line
 for(i=0;i<=3;i++)      
 delay_ms(DELAY_1);  //Low level of Clock Pulse     
   
  return Ack_bit; 
 } //End of Receive_bit 
     


unsigned char  TX_byte(unsigned char Tx_buffer){


    

 unsigned char  Bit_counter;
  unsigned char  Ack_bit;
  unsigned char  bit_out;
  
  
  for(Bit_counter=8;Bit_counter>=1;Bit_counter--){
           PORTD.0=~PORTD.0;
           if(Tx_buffer&0x80==1) //If the current bit of Tx_buffer is 1 set bit_out
           bit_out=1;           //else clear bit_out
            else
            bit_out=0;
           send_bit( bit_out ); //Send the current bit on SDA
            Tx_buffer<<=1;      //Get next bit for checking
            } 
          Ack_bit=Receive_bit();
             //Get acknowledgment bit 

          return Ack_bit;
     }//End of TX_byte()       
              
void DummyCommand(unsigned char byte){


  START_bit();   //Start condition
  TX_byte( byte ); //Send Slave Address or whatever,no need ACK checking
  STOP_bit();     //Stop condition
  }   
float CalcTemp1(unsigned int data1){
 
  float temp1;
  temp1=(data1*0.02)-273.15;
   return temp1;
   }
 
float CalcTemp2(unsigned int data2) {

   float temp2;
   temp2=(data2*0.02)-273.15;
   return temp2;
  }                                                                                            


unsigned char RX_byte(unsigned char ack_nack){
   
 
  unsigned char   RX_buffer;         
 unsigned char  Bit_Counter;

  
for(Bit_Counter=8;Bit_Counter>=1;Bit_Counter--){
  
   if(Receive_bit()){   //Get abit from SDA line
    
     RX_buffer<<=1;      //If the bit is HIGH save 1 in RX_buffer
      RX_buffer|=0b00000001;
     } 
     
   else{
     
      RX_buffer<<=1;    //If the bit is LOW save o in RX-buffer
      RX_buffer&=0b11111110;
      }
       }
   send_bit(ack_nack);   //Sends acknowledgment bit  
   return RX_buffer;
   }
   
 unsigned int MemRead1(unsigned char SlaveAddress,unsigned char command1) {
     unsigned int  data1;//Data storage (DataH:DataL)
     unsigned char Pec;//PEC byte storage
     unsigned char  DataL;//Low data byte storage
     unsigned char  DataH;//High data byte storage
     unsigned char arr[6]; //Buffer for the sent bytes 
     unsigned char PecReg; //Calculated PEC byte storage
      unsigned char ErrorCounter;     //Defines the number of the attempts for communaication with MLX90614   
         
     unsigned char  Ack_bit;
    unsigned char Nack_bit; 
    
     ErrorCounter=0x00;           //Initialising of ErrorCounter 
     do{
         
          
          repeat:
                                           
      STOP_bit();     //If slave send NACK stop comunication
      
        --ErrorCounter; //Pre-decrement ErrorCounter
         if(!ErrorCounter){ //ErrorCounter=0?
           break;       //Yes,go out from do-while{}
            }
          START_bit();    //Start condition
          
       if(TX_byte(SlaveAddress)){ //Send SlaveAddress
        
         
          goto repeat;          //Repeat comunication again                             
           }

       if(TX_byte(command1))  {  //Send command1  
            
           goto repeat;          //Repeat comunication again
           }
         START_bit();           //Repeat Start condition
         if(TX_byte(SlaveAddress)){//Send SlaveAddress
         
            goto repeat; //Repeat comunication again 
            }

          DataL=RX_byte(Ack_bit);  //Read low data,master must send ACK
         
           
           DataH=RX_byte(Ack_bit);  //Read low data,master must send ACK 
           Pec=RX_byte(Nack_bit);   //Read PEC byte,master should send NACK
         STOP_bit();        //STOP condition
           
           arr[5]=SlaveAddress;    //
          arr[4]=command1;         //
           arr[3]=SlaveAddress;    // Load array arr
          arr[2]=DataL;          //
           arr[1]=DataH;          //
           arr[0]=0;              //
           PecReg=PEC_calculation(arr);//Calcula
           
           
                      }while(1);//If received and calculated CRC are
                             
                             //equal go out from do-while{}
           *((unsigned char*)(&data1))=DataL;                     
          *((unsigned char*)(&data1)+1)=DataH;//data1=DataH:DataL 
        
           return data1;
          } 
          
    
   unsigned int MemRead2(unsigned char SlaveAddress,unsigned char command2) {
     unsigned int  data2;//Data storage (DataH:DataL)
     unsigned char Pec;//PEC byte storage
     unsigned char  DataL;//Low data byte storage
    unsigned char  DataH;//High data byte storage
    unsigned char arr[6]; //Buffer for the sent bytes 
     unsigned char PecReg; //Calculated PEC byte storage
      unsigned char ErrorCounter;     //Defines the number of the attempts for communaication with MLX90614   
         
     unsigned char  Ack_bit;
     unsigned char Nack_bit; 
    
     ErrorCounter=0x00;              //Initialising of ErrorCounter
    do{
   repeat:
                                      
         STOP_bit();     //If slave send NACK stop comunication
      
        --ErrorCounter; //Pre-decrement ErrorCounter
         if(!ErrorCounter){ //ErrorCounter=0?
            break;       //Yes,go out from do-while{}
            }
           START_bit();    //Start condition
        while(1){    
         if(TX_byte(SlaveAddress)){ //Send SlaveAddress
           
            goto repeat;          //Repeat comunication again
            } 
            };
         if(TX_byte(command2))  {  //Send command1  
            
            goto repeat;          //Repeat comunication again
            }
           START_bit();           //Repeat Start condition
          if(TX_byte(SlaveAddress)){//Send SlaveAddress
         
            goto repeat; //Repeat comunication again 
            }

           DataL=RX_byte(Ack_bit);  //Read low data,master must send ACK
         
           
           DataH=RX_byte(Ack_bit);  //Read low data,master must send ACK 
           Pec=RX_byte(Nack_bit);   //Read PEC byte,master should send NACK
           STOP_bit();        //STOP condition
           
           arr[5]=SlaveAddress;    //
           arr[4]=command2;         //
           arr[3]=SlaveAddress;    // Load array arr
          arr[2]=DataL;          //
           arr[1]=DataH;          //
           arr[0]=0;              //
           PecReg=PEC_calculation(arr);//Calculate CRC
           }while(PecReg!=Pec);//If received and calculated CRC are
                               //equal go out from do-while{}
          *((unsigned char*)(&data2))=DataL;                     
           *((unsigned char*)(&data2)+1)=DataH;//data2=DataH:DataL
            return data2;
          }  
 
         
          
      
     unsigned char PEC_calculation(unsigned char pec[]){
     
          unsigned char    crc[6];
          unsigned char    BitPosition=47;
          unsigned char    shift;
          unsigned char    i;
          unsigned char    j;
          unsigned char    temp;
         do{  
             crc[5]=0;      /*Load CRC value 0x000000000107*/
              crc[4]=0;
              crc[3]=0;
             crc[1]=0x01;
              crc[0]=0x07;
              BitPosition=47;
             shift=0;
              //Find first 1 in transmited message
              i=5;          /*Set highest index*/
              j=0;
              while((pec[i]&(0x80>>j))==0&& i>0){
                    BitPosition--;
                    if(j<7){
                    j++;
                    }
                   else{ 
                         j=0x00;
                        i--;
                       }
                   }
                   shift=BitPosition-8; /*Get shift value for crc value*/
                   
                   //Shift crc value
                   while(shift){
                            for(i=5;i<0xFF;i--){
                                   if((crc[i-1]&0x80)&&(i>0)){
                                           temp=1;
                                           } 
                                           else{ 
                                                  temp=0;
                                                }
                                                  crc[i]<<=1;
                                                  crc[i]+=temp;
                                             } 
                                          //   shift--;
                                           }
                                           //Exclusive OR between pec and crc
                                           for(i=0;i<=5;i++){
                                                   pec[i]^=crc[i];
                                             }      
                                           }while(BitPosition>8);
                                           return pec[0];
                                         }/*END of PEC _calculation*/
              
                                 
             void  MCUinit(void)
             {
             
             //SMBus setting-up
                     mSDA_HIGH();   //The bus is in idle state
                     mSCL_HIGH();   //SDA and SCL are in high level from pull up resistors
                }/*End of init()*/
 
Last edited:

Re: Problem with nothing return to if condition in C language

It is not working because there is a do...while(1) loop inside MemRead1() function. The program connat come outside the do...while(1) koop. You have to use some condition other than 1 for do... while(1) loop like do... while(so condition).
 
Re: Problem with nothing return to if condition in C language

Im sorry i forgot to correct codition of do...while() ,I did it to check my program.

condition of do...while(PecReg!=Pec) ,When i used it again if didnt work properly.
 

I will check you code tomorrow. What is the exact problem and how do you say that MemRead1() function has problems.
 
As i said TX_byte() function dosen't return any thing to if conditon so if doesnt work.I wrote a line in diffrent parts of progrom to toggle a pin like
Code:
 PORTD.0=~PORTD.0
and i wrote 1 i in condition of do-while in order to stay in loop and repeat loop ,then i put exe codes to micro in proteus then i simulate it i used oscope to see signals but PIN in if didnt turn off and turn on !Every time program executes takes 3 to 5 minutes!
Please note that if Ack_bit =0 it means acknowledge program should go out of if
and if Ack_bit=1 means not acknowledge program should go to repeat lable.
I've attached proteus and image of circuit.
1-14-2002 9-10-23 PM.png11-30-2009 8-34-13 PM.png
 
Last edited:

I was busy. I will check today. Please zip and post your project files and proteus file. Which Compiler are you using and what is the Clock frequency.

OK. i got it. You are using CodeVision AVR and Fosc = 3 MHz.

Send the files and also send the .cof file. I wil debug and see.
 
Last edited:

After examining the posted code, my first response would be to fire the programmer whom developed the example code.

In over thirty-five years of coding, much of it in the C programming language, I've yet to have found it necessary to use a single GOTO, the Melexis Semiconductors provided example code is littered with GOTOs.

Melexis Semiconductors should be ashamed of themselves for releasing such a perfect example of how NOT to code in C.


Rather than waste my time rewriting much of the above code example, I would suggest utilizing the attached firmware source code for an AVR/MLX90614 development board sold by Sparkfun.

The code was written for the AVR-GCC Compiler, WinAVR, Atmel Toolset, etc, however you should be able to port it to CodevisionAVR and modified to your requirements without too much difficulty.

The schematics and additional information for the development board for which the code was originally developed can be found at the following link:

Evaluation Board for MLX90614 IR Thermometer


BigDog
 

Attachments

  • SparkFun-IR-Evaluation-Board-master.zip
    17.8 KB · Views: 141
bigdogguru said:
After examining the posted code, my first response would be to fire the programmer whom developed the example code.

In over thirty-five years of coding, much of it in the C programming language, I've yet to have found it necessary to use a single GOTO, the Melexis Semiconductors provided example code is littered with GOTOs.

Melexis Semiconductors should be ashamed of themselves for releasing such a perfect example of how NOT to code in C.

+1.

I do not have 35 years of experience BigDog, but it is the first time I see a reference example by a semiconductor manufacturer that uses GOTO. The programmer should be fired by Melexis Semiconductors themselves, since this example causes a very bad impression on their company.
 

Re: Problem with&amp;amp;quot; if Condition&amp;amp;quot; in C language

Ok.It is proteus file





Alexxx,do you mean these codes are wrong? I am not an experiecend person ,I should get result because it's my final project at university.My professor told me it's better to use catalog's code to get result,and i don't have alot of time to finish.
 

Attachments

  • change-p.rar
    12.7 KB · Views: 94
Last edited:

Bigdogguru and alexxx ,Please more explain why programmer should be fired ?
I should persuade my professor because he made me to use these codes.
Know it's more than 3 month's i'm working on this project because i don't have enough experience.
.I did'nt see any thing in scl ,sda pins practical:-(
I would appreciate
 

Typically there is no error when using goto. The problem is that by using goto, a code often very hard to understand is created. Such a code is bug prone and often difficult to fix. It is like writing in assembly. C offers all the tools (if-else, for, while etc) to avoid the use of goto, in all cases when this command "seems" to be necessary. Goto should be avoided by new programmers, although it is often used by them because it offers an easy way to drive code flow somewhere else inside code memory. Usually it is avoided by experienced programmers.

Code:
a=1;

label:
if (a == 10)
{
  a++;
}

In the above code do you know the value of 'a' below label? The answer is no. Because you don't know if the code passed from "a=1" statement, or came from somewhere else with the use of goto. Many other examples could be given on this, search the web and you will find plenty of them.
 
I was busy. I will check today. Please zip and post your project files and proteus file. Which Compiler are you using and what is the Clock frequency.

OK. i got it. You are using CodeVision AVR and Fosc = 3 MHz.

Send the files and also send the .cof file. I wil debug and see.
Finally,you did'nt check program?what is your opinion?
 

The .cof file you sent is not showing code in Proteus. Maybe you have to change some option while compiling. Without proper .cof file I cannot debug in Proteus. I have CodeVision Evaluation. can you post your CodeVision Project files? Also mention the name of the main project file.
 

I attched for you all of my project files in a zip file,Name of main project file is END.
Do you want i send again?
 
Last edited:

Status
Not open for further replies.

Similar threads

Part and Inventory Search

Welcome to EDABoard.com

Sponsor

Back
Top