Search code examples
c++ccompiler-errorsavratmega16

Implicit declaration of function and conflicting type - AVR


This is my first program for AVR. While building, the code is showing error: conflicting types for 'Encode' implicit declaration of 'Encode'

I have written the following code:

#include <avr/io.h>
#include <util/delay.h>
#include <stdlib.h>

#define SegDataPort PORTC
#define SegDataPin PINC
#define SegDataDDR DDRC

#define SegCntrlPort PORTD
#define SegCntrlPin PIND
#define SegCntrlDDR DDRD

int main(void)
{
   SegDataDDR = 0xFF;
   SegCntrlDDR = 0xF3;
   SegCntrlPort = 0xF3;
   SegDataPort = 0x00;
   unsigned char adc_value;
   float volt = adc_value/1023;
   int temp = floor(volt*10 + 0.5);

   SegDataPort = Encode(temp1%10);

   //^^^^ implicit declaration of 'Encode' 

   SegCntrlPort = ~0x01;
   SegDataPort = Encode((temp1/10)%10);
   SegCntrlPort = ~0x02;
   SegDataPort = Encode(temp1/100);
   SegCntrlPort = ~0x04;
}

unsigned char Encode(int digit)
{
   unsigned char val;
   switch(digit)
   {
      case 0 : Val = 0b00111111;
      case 1 : val = 0b00000110;

      /// so on till case 9
   }
   return val;
}

I am using ATmega16 as microcontroller. I have also added much more libraries such as math for floor function and others. I have tried changing int to unsigned int, unsigned char and others but it is still not working and showing same error. Please help me.


Solution

  • implicit declaration of 'Encode'

    In C a function needs to be either declared or defined before it has been used (called).

    Either

    • Move the definition of Encode() function before main()
    • Add a forward declaration to Encode() before main().

    That said, floor() is a function, defined in math.h and defined in the math library. To use that, you need to #include <math.h> and link with -lm at compilation time.


    About the programmic logic used here,

    unsigned char adc_value;
    float volt = adc_value/1023;
    int temp = floor(volt*10 + 0.5);
    

    are pretty problematic, because

    1. adc_value is used uninitialized, which leads to undefined behaviour.
    2. adc_value is of type char. Dividing it by a value of 1023 will always give a result of 0 as the division will take place as an integer division and won't produce a float result itself, as you migh have expected.

    My suggestions, change that code block to

    int adc_value = <some value to initialize>;  //or some input function
    float volt = (float)adc_value/1023;          //enforce floating point division
    int temp = floor(volt*10 + 0.5);