Error 1098 conflicting declarations for variable

Hi everyone.I am practicing I2C communication on my PIC16F1513. This is my first time, so for this I have generated the code of the necessary drivers using the MPLAB X MCC.My first intention is to be able to write 1 byte (0x10) in the 0x10 register of the slave with the address 0x00 using the "I2C_W...

John Brown

New Member

  • Total Posts : 18
  • Reward points : 0
  • Joined: 2011/01/03 04:02:00
  • Location: 0
  • Status: offline

Hi everyone.
I am practicing I2C communication on my PIC16F1513. This is my first time, so for this I have generated the code of the necessary drivers using the MPLAB X MCC.
My first intention is to be able to write 1 byte (0x10) in the 0x10 register of the slave with the address 0x00 using the «I2C_Write1ByteRegister» function, but the compiler gives me the following error:

«main.c: 73: 9: warning: implicit declaration of function ‘I2C_Write1ByteRegister’ is invalid in C99 [-Wimplicit-function-declaration]
I2C_Write1ByteRegister (0x00, 0x10, 0x10); «
main.c:73:: error: (1098) conflicting declarations for variable «_I2C_Write1ByteRegister» (mcc_generated_files/examples/i2c_master_example.c:91)

The three parameters of said function are uint8_t, so I don’t understand why this error is caused.
Someone could help me?
MPLAB X IDE version: v5.50
Compiler version: XC8 v2.32
If you need more code I will provide it.
Thank you so much.

void main(void)
{
    // initialize the device
    SYSTEM_Initialize();

    // When using interrupts, you need to set the Global and Peripheral Interrupt Enable bits
    // Use the following macros to:

    // Enable the Global Interrupts
    //INTERRUPT_GlobalInterruptEnable();

    // Enable the Peripheral Interrupts
    //INTERRUPT_PeripheralInterruptEnable();

    // Disable the Global Interrupts
    //INTERRUPT_GlobalInterruptDisable();

    // Disable the Peripheral Interrupts
    //INTERRUPT_PeripheralInterruptDisable();

    while (1)
    {
        // Add your application code
        I2C_Write1ByteRegister(0x00, 0x10, 0x10);
    }
}

void I2C_Write1ByteRegister(i2c_address_t address, uint8_t reg, uint8_t data)
{
    while(!I2C_Open(address)); // sit here until we get the bus..
    I2C_SetDataCompleteCallback(wr1RegCompleteHandler,&data);
    I2C_SetBuffer(&reg,1);
    I2C_SetAddressNackCallback(NULL,NULL); //NACK polling?
    I2C_MasterWrite();
    while(I2C_BUSY == I2C_Close()); // sit here until finished.
}
typedef uint8_t i2c_address_t;

Nigel

Super Member

  • Total Posts : 455
  • Reward points : 0
  • Joined: 2021/03/12 07:18:23
  • Location: 0
  • Status: offline

Re: error: (1098) conflicting declarations for variable


2021/09/20 06:19:22

(permalink)

2 declarations of I2C_Write1ByteRegister ?
Or header is different from file in c file ?

Mysil

Super Member

  • Total Posts : 4604
  • Reward points : 0
  • Joined: 2012/07/01 04:19:50
  • Location: Norway
  • Status: offline

Re: error: (1098) conflicting declarations for variable


2021/09/20 06:49:00

(permalink)

Hi,
Warning from the compiler, indicate that the called function is not correctly declared (or by a header file) in the main program file.
Main program code shown in message #1 is incomplete,
there is nothing showing what function declarations, and/or header files are included.

 I2C_Write1ByteRegister function is provided in a examples subdirectory generated by MCC,
but it may not be included in the default main program file.
You may need something like this:

#include "mcc_generated_files/mcc.h"
#include "mcc_generated_files/examples/i2c_master_example.h"  

 Edit:
When you provide functions to be called in the same file as program doing the calling,
then functions to be called, must be known by the compiler  BEFORE the function is called.
That means you may provide a prototype declaration Before the main(…)  code, 

 
void I2C_Write1ByteRegister(i2c_address_t address, uint8_t reg, uint8_t data);  /* Prototype declaration, note the semicolon! */

 void main(void)
{   ... /* The whole main program code */
     ...
}

 void I2C_Write1ByteRegister(i2c_address_t address, uint8_t reg, uint8_t data)   /* note, no semicolon. */
{   ...  /* Body of the function to be called from somewhere else. */
}

or you may place the entire code of the function to be called Before main(…){ … }

     Mysil

post edited by Mysil — 2021/09/20 07:22:08

John Brown

New Member

  • Total Posts : 18
  • Reward points : 0
  • Joined: 2011/01/03 04:02:00
  • Location: 0
  • Status: offline

Re: error: (1098) conflicting declarations for variable


2021/09/20 07:05:35

(permalink)

Hi Mysil.
You are the Master Supreme :))).
The following statement was missing:
#include «mcc_generated_files/examples/i2c_master_example.h»

 Thank you «[link=mailto:nigel@murtonpikesystems.co.uk»]nigel@murtonpikesystems.co.uk»[/link] too for your contribution :)

See more:

I am using GSM modem to send the text msg to the number who has sent the previous msg to the GSM modem (i.e, REPLY to sms) I am able to retrieve the phone no. and have stored the phone no. is a array. I have also created another array for storing the msg. However wen i read the phone no. array which i have set the limit to size 12 only also includes part of the elements of msg array also…. Later on i found out dat since both the arrays have taken sequential memory locations (i.e, phone array ends at memory location 05B and msg array starts from memory location 05C.
Hence to retify this prob I created a function as below…

lcd_putnstr(13,phone_num_buf); 
void lcd_putnstr(unsigned char len, char *str)
{
  unsigned char i = 0;
  while(*str != NULL && i < len)
  {
    lcd_write(*str);
    str++;
    i++;
  }
}


void putnstr(unsigned char len, char *str)
{
  unsigned char i = 0;
  while(*str != NULL && i < len)
  {
    putch(*str);
    str++;
    i++;
  }
}

putnstr(SIZE_OF_PH_NUM, (char* )phone_num);

#define SIZE_OF_PH_NUM 13

have declared the function where ever required but wen i compile it throws an error as…

Error [1098] conflicting declarations for variable and it points to putnstr function..

how this bug can be resolved???

Updated 30-Jun-10 21:54pm


There is probably a library routine with the same name in a header file you use. Try renaming putnstr to something that is unlikely to conflict, like put_n_str_

«There is probably a library routine with the same name in a header file you use. Try renaming putnstr to something that is unlikely to conflict, like put_n_str_»

This also does not solve the issue… i have tried changing the function name but the same error occur..

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject,
20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8
+1 (416) 849-8900

Чт июн 05, 2014 22:10:06

Чет нифига не пойму! В PIC16F887 вообще возможно сохранение таблицы в памяти программ аналогично PIC18м?

Чт июн 05, 2014 22:17:15

Да, возможно.
Только не очень удобно. Через байт получается 6 бит.

Чт июн 05, 2014 22:17:35

Возможно. Но обращение будет не как в PIC18 (табличное чтение), а через retlw. Собственно, при проганье на Си это по барабану :)

Чт июн 05, 2014 22:38:48

Аlex писал(а):Возможно. Но обращение будет не как в PIC18 (табличное чтение), а через retlw.

Именно как в 18-х. Табличное.
887-ой один из первых 16-х ПИКов с самопрограммированием. А значит можно читать флеш как данные через косвенную адресацию

Чт июн 05, 2014 22:50:06

КРАМ писал(а):Именно как в 18-х. Табличное.

Хм… , точно. Поспешил я с ответом, извиняюсь :roll:
Параграф 10.0 даташита, DATA EEPROM AND FLASH PROGRAM MEMORY CONTROL.

Сб июн 07, 2014 20:45:06

Мои нейроны забодала ошибка:

Error [1098] …. conflicting declarations for variable «_Lcd_puts» (D:My designsDozerDozer.c:28)
(908) exit status = 1

Вызов этой функции изнутри Lcd_test(); проблем не вызывает, а вручную из void main() валит ошибками.
Заранее спасибо за желание помочь. :beer:

Отбой — я не там вписал используемые функции, всего то. :)))

Вс июн 08, 2014 13:06:21

Кто нибудь работал с таким синизубым модулем или чем нибудь оналогичным? xs3868 интересует общение по UART, как переименовать , вводить команды… я попробовал, забивать команды из даташита но на команды не реагирует, а отвечает какойто кашей. :kill: :kill хелп Изображение

Вс июн 08, 2014 13:32:53

Скорость передачи нужно правильную установить.

Вс июн 08, 2014 14:04:56

Alexeyslav писал(а): правильную установить.

скорость ставил рекомендуемую, я ее выделил, 8 дата бит, 1 стоп бип программа терминал 1.9

Вложения
58.jpg
(24.74 KiB) Скачиваний: 197

Вс июн 08, 2014 14:57:34

На заборе тоже написано… а там дрова лежат. Твой терминал не ругается на Framing error или другие ошибки? Посмотри осциллографом реально какая скорость в порту на выходе модуля, он ведь может быть настроен на ЛЮБУЮ скорость а не дефолтную. Кто его знает у кого и где он побывал прежде чем попасть к тебе. Обычно они приходят настроенные на 38400.

Пн июн 09, 2014 13:20:14

Мучает вопрос — для чего ставятся 2 конденсатора от кварца на общий? Собственно не знаю в какую тему вопрос — поскольку он и генераторов на логике с кварцем тоже касается.

Пн июн 09, 2014 15:09:20

Это своеобразный кикстартер.

Пн июн 09, 2014 15:23:18

Конденсаторы являются частью генератора, они создают необходимый сдвиг фазы для того чтобы генератор смог работать устойчиво на основной частоте кварца. Без них он будет долго раскачиваться и может не завестись вовсе, или завестись на фундаментальной частоте кварца или на одной из его гармоник. Если посмотреть даташит на конкретный кварцевый резонатор там указываются оптимальные значения этих емкостей, с которыми кварц будет работать наиболее устойчиво.

Пн июн 09, 2014 15:29:55

Alexeyslav писал(а):Если посмотреть даташит на конкретный кварцевый резонатор

Поправлю — на конкретный микроконтроллер, ибо генератор в микрконтроллере.

Пн июн 09, 2014 17:39:05

Нет, именно на кварцевый резонатор. эти конденсаторы являются одновременно элементами генератора и элементами эквивалентной схемы резонатора. Из-за их несоответствия резонатору последний может возбуждаться на неродной частоте или вовсе частота уйдет от номинала. В даташите на МК имеются номиналы РЕКОМЕНДУЕМЫЕ, а на кварцевый резонатор — оптимальные.

Вт июн 10, 2014 15:52:00

почему при передаче по UART получается так: при первой передаче от одного контроллера другому второй на дисплей выводит только 4 символа из N переданных? при последующих передачах все нормально.
передатчик

приемник

скрины протеуса в прикрепленке

этот усарт меня убивает :(

Вложения
hello-mir.png
2
(51.22 KiB) Скачиваний: 282
hell.png
1
(53.32 KiB) Скачиваний: 243

Вт июн 10, 2014 16:32:39

можно попробовать восстановить как нагенерил Codevision
т.е. убрать lcd_out=1;
и так сделать:

Код:
if (rx_buffer_overflow)
{
lcd_clear();
for (i=0; i<10; i++)
{
lcd_puts(&rx_buffer[i]);
}
//delay_ms(200); это зачем - пока пауза могут прийти данные с компорта многократно
rx_buffer_overflow = 0;
rx_wr_index= 0;
rx_counter = 0;
}

а вот когда посылаем надо выдержать паузу между посылками — пока микроконтроллер выводит на индикатор:

Код:
while (1)
if (PINC.2==1)
{
for (i=0; i<10; i++)
{
unsigned char symbol = d[i];
USART_transmitter(symbol);
}
delay_ms(200);
}

Вт июн 10, 2014 17:07:34

oleg110592 писал(а)://delay_ms(200); это зачем — пока пауза могут прийти данные с компорта многократно

я отправляю по нажатию кнопки пока что. паузы были потому что отслеживал выполнение программы светодиодами :)

премного благодарен. все заработало, но с небольшими комментариями:
конструкция

Код:
for (i=0; i<10; i++)
{
lcd_puts(&rx_buffer[i]);
}

не нужна. в rx_buffer хранится вся принятая строка и выходит так, что она целиком выводится на дисплей командой lcd_puts(&rx_buffer[0]). в случае for’a она просто 10 раз подряд пишется и с какими-то искажениями уже (индекс в скобках обозначает символ, с которого начинается передача строки. поставил экран побольше и проверил)
ну и задержка в передатчике понадобилась при исправленном приемнике (а то лишнее докидывал передатчик), хотя до этого и без нее обходилось, начиная со второй передачи :)

Вт июн 10, 2014 23:24:28

тогда наверное можно просто так выводить строку из массива:
lcd_puts(rx_buffer);

Ср июн 11, 2014 09:20:36

oleg110592 писал(а):lcd_puts(rx_buffer);

да, действительно работает

Powered by phpBB © phpBB Group.

phpBB Mobile / SEO by Artodia.

Ok, thanks for the replies guys.
It looks like I’ve been breaking a few rules with my ‘include code.c’
Ian, I’ll have a read of your multi-file link later tonight. Thanks.

Now that I’ve tried to implement the code correctly I’m getting some errors. I hope the following makes sense.

I’ve done the following:

  • I’ve removed the «include TSYS01.c» from my main code.
  • For my 2nd code file TSYS01.c, I’ve separated out the header file stuff (variable definitions and function declarations) into TSYS01.h.
  • I’ve added the TSYS01.h file to the project and have added the TSYS01.c file as a source file.

So I now have 4 files:
main.c
main.h
TSYS01.c      //functions for TSYS01 sensor.
TSYS01.h

Prior to these changes the code compiled and ran fine on the hardware.

Now when I compile a get some errors:

TSYS01.c:26: warning: (361) function declared implicit int
(908) exit status = 1
TSYS01.c:27: warning: (361) function declared implicit int
TSYS01.c:28: warning: (361) function declared implicit int
TSYS01.c:29: warning: (361) function declared implicit int
TSYS01.c:30: warning: (361) function declared implicit int
TSYS01.c:39: error: (984) type redeclared
TSYS01.c:39: error: (1098) conflicting declarations for variable «TSYS01_reset» (TSYS01.c:38)
make[2]: *** [build/default/debug/TSYS01.p1] Error 1
make[2]: *** Waiting for unfinished jobs….
nbproject/Makefile-default.mk:99: recipe for target ‘build/default/debug/TSYS01.p1’ failed
main_temp.c:686: warning: (343) implicit return at end of non-void function
make[1]: *** [.build-conf] Error 2
make[2]: Leaving directory ‘C:/Users/home/MPLABXProjects/SDI12_TEMP.X’
make: *** [.build-impl] Error 2
nbproject/Makefile-default.mk:84: recipe for target ‘.build-conf’ failed
make[1]: Leaving directory ‘C:/Users/home/MPLABXProjects/SDI12_TEMP.X’
nbproject/Makefile-impl.mk:39: recipe for target ‘.build-impl’ failed

BUILD FAILED (exit value 2, total time: 429ms)

Googling tells me the «function declared implicit int» warnings (functions are in TSYS01.c) mean that the functions prototypes are missing so it assumes it takes no arguments and returns an int.
Yet I have declared the functions in the header file TSYS01.h which is included by the line ‘include TSYS01.h’ the main.c program.

The type «TSYS01.c:39: error: (984) type redeclared» error is pointing at the function below in the TSYS01.c file
void TSYS01_reset(void) //reset the TSYS01 IC
{}

The second error «TSYS01.c:39: error: (1098) conflicting declarations for variable «TSYS01_reset» (TSYS01.c:38)» is pointing at the {} brackets of the same function.

main.c — includes

// all pragma statements snipped for brevity

//###################################################################
//   I N C L U D E   F I L E S
//   "local project file"
//###################################################################
#include "temp.h"  // header file for main
#include "TSYS01.h"      //header file for TSYS01 sensor code

#include "usart.h" // adds h/w serial support
#include <string.h> // adds string tools
#include <delays.h> // adds the delays lib
#include <timers.h> // adds the timer lib
#include <stdlib.h> // adds data conversion lib
#include <stdio.h>
#include <i2c.h> // for I2C sensor

//#include "TSYS01.c"   

// rest of code snipped for brevity

TSYS01.h

//******************************************************************************
// TSYS01.h
//******************************************************************************

//TSYS01 variable declarations
unsigned short long ADC16; // was double
unsigned long ADC24 = 9378708; // TSYS01 temperature result, was double
unsigned short long ADC_MSB = 0; // 3 x 8 bit bytes read from TSYS01 combined = ADC24
unsigned int ADC_MID = 0;
unsigned int ADC_LSB = 0;

float Temp_C;                   //calculated temperature Celcius
//unsigned char TempStr[8]="."; //temp ascii string

//calibration coefficients, 16 bit integers
double k4 = 28446;//unsigned int
unsigned int k3 = 0;//24926;
unsigned int k2 = 0;//36016;
unsigned int k1 = 0;//32791;
unsigned int k0 = 0;//40781;

//calibration coefficient nibbles
unsigned char k4MSB = 0;
unsigned char k4LSB = 0;
unsigned char k3MSB = 0;
unsigned char k3LSB = 0;
unsigned char k2MSB = 0;
unsigned char k2LSB = 0;
unsigned char k1MSB = 0;
unsigned char k1LSB = 0;
unsigned char k0MSB = 0;
unsigned char k0LSB = 0;

//TSYS01 function declarations
 void TSYS01_read(void);           //Reads sensor using functions below
 void TSYS01_reset(void);          //Reset the TSYS01 sensor IC
 void TSYS01_read_coeffs(void);    //Reads 5 x 16 bit coefficients from the TSYS01
 void TSYS01_convert(void);        //Instructs TSYS01 sensor to do a measurement
 void TSYS01_read_ADC(void);       //Reads TSYS01 ADC result, ADC result left in ADC24
 void TSYS01_calc(void);           //Calc temp using ADC val & coeffs from TSYS01

TSYS01.c

//*****************************************************************************
//TSYS01.c  F U N C T I O N S  F O R  T S Y S 0 1   T E M P  S E N S O R
//*****************************************************************************
//
// void TSYS01_read(void)           Reads sensor using functions below
//
// void TSYS01_reset(void)          Reset the TSYS01 sensor IC
// void TSYS01_read_coeffs(void)    Reads 5 x 16 bit coefficients from the TSYS01
// void TSYS01_convert(void)        Instructs TSYS01 sensor to do a measurement
// void TSYS01_read_ADC(void)       Reads TSYS01 ADC result, ADC result left in ADC24
// void TSYS01_calc(void)           Calc temp using ADC val & coeffs from TSYS01
//
// Use TSYS01_read() function to read the sensor. It uses all the other functions.
// It: resets IC, reads coeffs, starts conversion, reads ADC & then calls  calc.
// After calc the temp is stored as a string TempStr[] and as a float Temp_C
//
//*****************************************************************************

//*********************************************************************
// void TSYS01_read(void)
// Read the sensor using functions below
//*********************************************************************
void TSYS01_read(void)
{
TSYS01_reset();         // reset the TSYS01 IC
TSYS01_read_coeffs();   // read the calc coefficients from the TSYS01 sensor
TSYS01_convert();       // instruct TSYS01 sensor to perform a conversion [takes 15mS]
TSYS01_read_ADC();      // read the ADC temp value from the TSYS01 sensor
TSYS01_calc();          // calc temp from TSYS01 ADC value, result in T &     
}

//*********************************************************************
// void TSYS01_reset(void)
// Reset the TSYS01 sensor IC
//*********************************************************************
void TSYS01_reset(void) //reset the TSYS01 IC
{
unsigned char data = 0;   
data = SSPBUF; //read anything in buffer to clr buffer full status

         IdleI2C();   //wait until I2C bus is idle
     StartI2C();  //send start
     WriteI2C(0xEE);   //write address of TSYS01 = 0xEE
     IdleI2C();   

     WriteI2C(0x1E); //write reset command 0x1E to I2C slave
     IdleI2C();   
     StopI2C();   
} //close of TSYS01_reset()

//rest of functions snipped for brevity

Skip to main content

Forum for Electronics

Forum for Electronics

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.

  • Digital Design and Embedded Programming

  • Microcontrollers

You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an alternative browser.

[SOLVED] help on some compiler error problems. [hi-tech C]


  • Thread starter

    romel_emperado


  • Start date

    Aug 22, 2011

Status
Not open for further replies.

  • #1

Advanced Member level 2

Joined
Jul 23, 2009
Messages
606
Helped
45
Reputation

132

Reaction score
65
Trophy points
1,318
Location

philippines

Activity points

6,061


hello, i’ve worked this project yesterday using PIC18f2550 with Hi-tech C v9.64 and it builds pretty well with no error and it’s working.. this in not my work I just want to edit this project to port it to other device.

today Im using PIC18f4550 with Hi-tech C v9.66 compiler and I got many errors.. I need your help because Im lack of programming knowledge and I don’t want to get it into worse outcome.. I dont believe it’s a systax error because it buils well in lower version and working in simulation.

I already commented out the config fuses of the device and this error is not register related errors..

these are the errors:

Error   [983] C:Documents and SettingsmelDesktopPIC184550materialsPIC18 Petit FAT File Systemsrc_picc18pff.h; 103.6 storage class redeclared
Error   [984] C:Documents and SettingsmelDesktopPIC184550materialsPIC18 Petit FAT File Systemsrc_picc18pff.h; 103.6 type redeclared
Error   [1098] C:Documents and SettingsmelDesktopPIC184550materialsPIC18 Petit FAT File Systemsrc_picc18pff.h; 103.6 conflicting declarations for variable "DIR" (C:Program FilesHI-TECH SoftwarePICC-18PRO9.66includepic18f2550.h:449)
Error   [194] C:Documents and SettingsmelDesktopPIC184550materialsPIC18 Petit FAT File Systemsrc_picc18pff.h; 142.24 ")" expected
Warning [349] C:Documents and SettingsmelDesktopPIC184550materialsPIC18 Petit FAT File Systemsrc_picc18pff.h; 142.39 non-prototyped function declaration for "pf_opendir"
Error   [313] C:Documents and SettingsmelDesktopPIC184550materialsPIC18 Petit FAT File Systemsrc_picc18pff.h; 142.39 function body expected
Error   [194] C:Documents and SettingsmelDesktopPIC184550materialsPIC18 Petit FAT File Systemsrc_picc18pff.h; 143.24 ")" expected
Warning [349] C:Documents and SettingsmelDesktopPIC184550materialsPIC18 Petit FAT File Systemsrc_picc18pff.h; 143.36 non-prototyped function declaration for "pf_readdir"
Error   [313] C:Documents and SettingsmelDesktopPIC184550materialsPIC18 Petit FAT File Systemsrc_picc18pff.h; 143.36 function body expected
Warning [374] C:Documents and SettingsmelDesktopPIC184550materialsPIC18 Petit FAT File Systemsrc_picc18main.c; 18.5 missing basic type; int assumed
Error   [984] C:Documents and SettingsmelDesktopPIC184550materialsPIC18 Petit FAT File Systemsrc_picc18main.c; 18.5 type redeclared
Error   [1098] C:Documents and SettingsmelDesktopPIC184550materialsPIC18 Petit FAT File Systemsrc_picc18main.c; 18.5 conflicting declarations for variable "DIR" (C:Documents and SettingsmelDesktopPIC184550materialsPIC18 Petit FAT File Systemsrc_picc18pff.h:103)
Error   [372] C:Documents and SettingsmelDesktopPIC184550materialsPIC18 Petit FAT File Systemsrc_picc18main.c; 18.5 "," expected

I will attached the whole project I am working and the original project.

Attachments





  • PIC18 Petit FAT File System.rar

  • #2

Advanced Member level 2

Joined
Jul 23, 2009
Messages
606
Helped
45
Reputation

132

Reaction score
65
Trophy points
1,318
Location

philippines

Activity points

6,061


Im not familiar with the variable types they are using and I don’t have idea how to fix those errors..

romel.rar is just a duplicate code from the other attached file. I just commented out the config fuses and build it with hitech v9.66 using PIC18f4550.

———- Post added at 10:32 ———- Previous post was at 10:01 ———-

the compiler is always pointing this out.

main.c

DIR Dir;			/* Directory object */


DIR
is defined in the
pff.h file

/* Directory object structure */

typedef struct _DIR_ 
{
	WORD	index;		/* Current read/write index number */
	BYTE*	fn;			/* Pointer to the SFN (in/out) {file[8],ext[3],status[1]} */
	CLUST	sclust;		/* Table start cluster (0:Static table) */
	CLUST	clust;		/* Current cluster */
	DWORD	sect;		/* Current sector */
} DIR;

and also other error because of that DIR and pointed out this line in pff.h

FRESULT pf_opendir (DIR*, const char*);			/* Open a directory */

———- Post added at 10:50 ———- Previous post was at 10:32 ———-

I think I’ve found the error..

there is a variable name DIR in PIC18f4550.h that is why compiler returns an error.

Error   [1098] C:Documents and SettingsmelDesktopromelpff.h; 104.6 conflicting declarations for variable "DIR" (C:Program FilesHI-TECH SoftwarePICC-18PRO9.66includepic18f4550.h:525)

I looked inside that file and found this..

/ Register: USTAT
extern volatile unsigned char           USTAT               @ 0xF6C;
// bit and bitfield definitions
extern volatile bit PPBI                @ ((unsigned)&USTAT*8)+1;
extern volatile bit DIR                 @ ((unsigned)&USTAT*8)+2;
extern volatile bit ENDP0               @ ((unsigned)&USTAT*8)+3;
extern volatile bit ENDP1               @ ((unsigned)&USTAT*8)+4;
extern volatile bit ENDP2               @ ((unsigned)&USTAT*8)+5;
extern volatile bit ENDP3               @ ((unsigned)&USTAT*8)+6;
extern union {
    struct {
        volatile unsigned                     : 1;
        volatile unsigned PPBI                : 1;
        volatile unsigned DIR                 : 1;
        volatile unsigned ENDP                : 4;
    };
    struct {
        volatile unsigned : 3;
        volatile unsigned ENDP0               : 1;
        volatile unsigned ENDP1               : 1;
        volatile unsigned ENDP2               : 1;
        volatile unsigned ENDP3               : 1;
    };
} USTATbits @ 0xF6C;

there is already a DIR name .. I htink it would be fixed if I will rename my variable to other name.. I will try

Last edited: Aug 22, 2011

  • #3

Part of the problem is the header pic18f2550.h has a «DIR» defined as well:


// Register: USTAT
extern volatile unsigned char USTAT @ 0xF6C;
// bit and bitfield definitions
extern volatile bit PPBI @ ((unsigned)&USTAT*8)+1;
extern volatile bit DIR @ ((unsigned)&USTAT*8)+2;
extern volatile bit ENDP0 @ ((unsigned)&USTAT*8)+3;
extern volatile bit ENDP1 @ ((unsigned)&USTAT*8)+4;
extern volatile bit ENDP2 @ ((unsigned)&USTAT*8)+5;
extern volatile bit ENDP3 @ ((unsigned)&USTAT*8)+6;

I’m still hunting the errors down.

BigDog

  • #4

Advanced Member level 2

Joined
Jul 23, 2009
Messages
606
Helped
45
Reputation

132

Reaction score
65
Trophy points
1,318
Location

philippines

Activity points

6,061


wow!! hehe It builds with no error… it’s all about conflicting variable inside PIC18f4550.h and my structure name… !!!! now solved!

———- Post added at 10:54 ———- Previous post was at 10:53 ———-

Part of the problem is the header pic18f2550.h has a «DIR» defined as well:

I’m still hunting the errors down.

BigDog

I just spotted the culprit! hehe..

———- Post added at 10:56 ———- Previous post was at 10:54 ———-

the conflicting variable is in the USB Status and Control register

REGISTER 17-3: USTAT: USB STATUS REGISTER bit2
page 170 of the datasheet

———- Post added at 11:05 ———- Previous post was at 10:56 ———-

I will marked this now as solved..

Thanks bigdogguro for the help… thanks so much..

  • #5

I have the same issue…i use a PIC18F4550 as well and i was wondering if you can help me?

  • #6

What issue are you referring, compiling the FATFS routines in HiTech C?

Can you elaborate? Post any compiler messages?

BigDog

  • #7

What issue are you referring, compiling the FATFS routines in HiTech C?

Can you elaborate? Post any compiler messages?

BigDog

yep. i use HI-TECH V9.63 and i try to find a FATFS working demo for a PIC18F4550 i was having the same error as romel_emperado in his first post. I have edited the PIC18f4550.h by replacing all «DIR» by «DIRT» and my error was gone :)

but my code actually not working… I was wondering now if a compatibility issue with my SDHC 8G&4G can be the problem…

  • #8

but my code actually not working… I was wondering now if a compatibility issue with my SDHC 8G&4G can be the problem…

Possibly. There have been reports of incompatibilities with some SDHCs. Post the manufacture and model of the SDHCs you are attempting to use in your designs.

Have you tried a smaller capacity SDHC, 2GB or less?

Post or upload your code so that we can review it for possible issues. Also the schematic of your design if available.

BigDog

  • #9

Possibly. There have been reports of incompatibilities with some SDHCs. Post the manufacture and model of the SDHCs you are attempting to use in your designs.

Have you tried a smaller capacity SDHC, 2GB or less?

Post or upload your code so that we can review it for possible issues. Also the schematic of your design if available.

BigDog

just testing out the CK on PORTB1 and a get a pulsating 5Volt… my PIC is powered by a 5V and my SD slot on a 3.3V.. As i can see the SD card is powered by a ~3V and his clock signal should be at ~3V right? what should i do? a voltage divider with a resistor? or there is an option to set the port output voltage on the PIC?

not tested with a smaller SD card…min 4G

  • #10

Here my schematic;

SdCard.png

The base of the code is the one of romel, i have replaced the lcd code by my lcd code and the spi by the builtin spi from HI-TECH

Here is the main.c

#ifndef MAIN_C
#define MAIN_C

#include	<htc.h>
#include	<stdio.h>
#include	<string.h>

#include	"HardwareProfile.h"
#include	"pff.h"
#include	"lcd.h"

// Config word 1
__CONFIG(1, USBPLL & IESODIS & FCMDIS & HSPLL & PLLPOSTDIV2 & PLLDIV5);
// Config word 2
__CONFIG(2, VREGEN & PWRTDIS & BOREN & BORV20 & WDTDIS & WDTPS32K);
// Config word 3
__CONFIG(3, PBDIGITAL & LPT1DIS & MCLREN);
// Config word 4
__CONFIG(4, XINSTDIS & STVREN & LVPDIS & ICPORTDIS & DEBUGDIS);
// Config word 5, 6 and 7 (protection configuration)
__CONFIG(5, UNPROTECT);
__CONFIG(6, UNPROTECT);
__CONFIG(7, UNPROTECT);

FATFS Fs;			/* File system object */
DIR Dir;			/* Directory object */
FILINFO Fno;		/* File information */

unsigned short rb;		/* Return value. */
unsigned char buff[100];

void delay(void);

static void InitialiseSystem(void)
{
	// Default Digital
	ADCON1 = 0x0F;

	// LCD outputs
	TRISD = 0b00000000;

	// Clear all ports LCD
	PORTD = 0b00000000;

	// LCD Ilitialization
	lcdInit();
}

void main(void)
{
	unsigned char i;
	
	InitialiseSystem();

	while(1){
		delay();
		lcdGoto(0, 0);
		lcdPuts("insert card!");
		if (pf_mount(&Fs) ) continue;	/* Initialize FS */
		lcdClearDisplay();
		lcdPuts("initialized");
		while(1){
			if (pf_opendir(&Dir, "")) break;
			while (!pf_readdir(&Dir, &Fno) && Fno.fname[0]) {
				if( strstr(Fno.fname, ".TXT") ){			// TXT file
					lcdClearDisplay();
					lcdGoto(0, 0);
					lcdPuts(Fno.fname);
					if(pf_open(Fno.fname)) continue;		// open file
					if( strstr(Fno.fname, "BLANK") ){
						lcdGoto(0, 1);
						lcdPuts("writing to a blank file");	// (PFF note: "pf_write" cannot expand file size)
						if(pf_write("sample message to SD/MMC card.rn", 0, &rb)) continue;	// write to file
						if(pf_write(0, 0, &rb)) continue;		// Finalize the write process
						lcdPuts("     done.");
					}
					else{
						if(pf_read(buff, 70, &rb)) continue;    // Read data to the buff[]
						lcdGoto(0, 2);
						lcdPuts(buff);	// display txt file content
						for(i=0; i<100; i++) buff[i]=0;			// clear buffer
					}
					delay();
					delay();
					delay();
				}
			}
		}
		
	}
}

void delay(void)
{
	long i=0x3FFFF;
	while(--i);
}

#endif

the modified mmc.c;

/*-----------------------------------------------------------------------*/
/* PFF - Low level disk control module for ATtiny85     (C)ChaN, 2009    */
/*-----------------------------------------------------------------------*/

#include	<htc.h>
#include	<stdio.h>
#include	<string.h>

#include	"HardwareProfile.h"
#include 	"diskio.h"
#include	"lcd.h"

#define _WRITE_FUNC	1

/* Definitions for MMC/SDC command */
#define CMD0	(0x40+0)	/* GO_IDLE_STATE */
#define CMD1	(0x40+1)	/* SEND_OP_COND (MMC) */
#define	ACMD41	(0xC0+41)	/* SEND_OP_COND (SDC) */
#define CMD8	(0x40+8)	/* SEND_IF_COND */
#define CMD12	(0x40+12)	/* STOP_TRANSMISSION */
#define CMD16	(0x40+16)	/* SET_BLOCKLEN */
#define CMD17	(0x40+17)	/* READ_SINGLE_BLOCK */
#define CMD24	(0x40+24)	/* WRITE_BLOCK */
#define CMD55	(0x40+55)	/* APP_CMD */
#define CMD58	(0x40+58)	/* READ_OCR */

/*--------------------------------------------------------------------------

   Module Private Functions

---------------------------------------------------------------------------*/
unsigned char CardType;

static void spi_init(void)
{
	SS_LATA		=	1;
	OpenSPI(SPI_FOSC_64, MODE_11, SMPEND);
}

/*-----------------------------------------------------------------------*/
/* Deselect the card and release SPI bus                                 */
/*-----------------------------------------------------------------------*/

static void release_spi (void)
{
	SS_LATA = 1;
	//rcv_spi
	ReadSPI();
}

/*-----------------------------------------------------------------------*/
/* Wait for card ready                                                   */
/*-----------------------------------------------------------------------*/

static unsigned char wait_ready (void)
{
	unsigned char res;
	unsigned short timeout = 0x1FFF;
	
	do
		res = ReadSPI();
	while ((res != 0xFF) && (--timeout));
		lcd_text(0, 3, "Ready");
	return res;
}

/*-----------------------------------------------------------------------*/
/* Send a command packet to MMC                                          */
/*-----------------------------------------------------------------------*/

static unsigned char send_cmd (
	unsigned char cmd,		/* Command unsigned char */
	unsigned long arg		/* Argument */
)
{
	unsigned char n, res;

	/* Select the card and wait for ready */
	SS_LATA = 1;
	SS_LATA = 0;

	if (wait_ready() != 0xFF) {
		return 0xFF;
	}

	if (cmd & 0x80) {	/* ACMD<n> is the command sequence of CMD55-CMD<n> */
		cmd &= 0x7F;
		//res = send_cmd(CMD55, 0);		// PICC18 Compiler error! (recursive function)	
		/* Send command packet */
		WriteSPI(cmd);						/* Start + Command index */
		WriteSPI((unsigned char)(arg >> 24));		/* Argument[31..24] */
		WriteSPI((unsigned char)(arg >> 16));		/* Argument[23..16] */
		WriteSPI((unsigned char)(arg >> 8));			/* Argument[15..8] */
		WriteSPI((unsigned char)arg);				/* Argument[7..0] */
		n = 0x01;							/* Dummy CRC + Stop */
		if (cmd == CMD0) n = 0x95;			/* Valid CRC for CMD0(0) */
		if (cmd == CMD8) n = 0x87;			/* Valid CRC for CMD8(0x1AA) */
		WriteSPI(n);
	
		/* Receive command response */
		if (cmd == CMD12) ReadSPI();		/* Skip a stuff unsigned char when stop reading */
	
		n = 10;								/* Wait for a valid response in timeout of 10 attempts */
		do
			res = ReadSPI();
		while ((res & 0x80) && --n);
		if (res > 1) return res;
	}
	

	/* Send command packet */
	WriteSPI(cmd);						/* Start + Command index */
	WriteSPI((unsigned char)(arg >> 24));		/* Argument[31..24] */
	WriteSPI((unsigned char)(arg >> 16));		/* Argument[23..16] */
	WriteSPI((unsigned char)(arg >> 8));			/* Argument[15..8] */
	WriteSPI((unsigned char)arg);				/* Argument[7..0] */
	n = 0x01;							/* Dummy CRC + Stop */
	if (cmd == CMD0) n = 0x95;			/* Valid CRC for CMD0(0) */
	if (cmd == CMD8) n = 0x87;			/* Valid CRC for CMD8(0x1AA) */
	WriteSPI(n);

	/* Receive command response */
	if (cmd == CMD12) ReadSPI();		/* Skip a stuff unsigned char when stop reading */

	n = 10;								/* Wait for a valid response in timeout of 10 attempts */
	do
		res = ReadSPI();
	while ((res & 0x80) && --n);
	
	return res;			/* Return with the response value */
}

/*--------------------------------------------------------------------------

   //Public Functions

---------------------------------------------------------------------------*/

/*-----------------------------------------------------------------------*/
/* Initialize Disk Drive                                                 */
/*-----------------------------------------------------------------------*/

DSTATUS disk_initialize (void)
{
	unsigned char n, cmd, ty, ocr[4];
	unsigned short tmr;

	spi_init();
	
#if _WRITE_FUNC
	if (MMC_SEL) disk_writep(0, 0);		/* Finalize write process if it is in progress */
#endif
	for (n = 100; n; n--) ReadSPI();	/* Dummy clocks */

	ty = 0;
	if (send_cmd(CMD0, 0) == 1) {			/* Enter Idle state */
		if (send_cmd(CMD8, 0x1AA) == 1) {	/* SDv2 */
			for (n = 0; n < 4; n++) ocr[n] = ReadSPI();		/* Get trailing return value of R7 resp */
			if (ocr[2] == 0x01 && ocr[3] == 0xAA) {				/* The card can work at vdd range of 2.7-3.6V */
				for (tmr = 12000; tmr && send_cmd(ACMD41, 1UL << 30); tmr--) ;	/* Wait for leaving idle state (ACMD41 with HCS bit) */
				if (tmr && send_cmd(CMD58, 0) == 0) {		/* Check CCS bit in the OCR */
					for (n = 0; n < 4; n++) ocr[n] = ReadSPI();
					ty = (ocr[0] & 0x40) ? CT_SD2 | CT_BLOCK : CT_SD2;	/* SDv2 (HC or SC) */
				}
			}
		}
		else {							/* SDv1 or MMCv3 */
			
			if (send_cmd(ACMD41, 0) <= 1) 	{
				ty = CT_SD1; cmd = ACMD41;	/* SDv1 */
			} else {	/* Proteus 7.x MMC sim model */
				ty = CT_MMC; cmd = CMD1;	/* MMCv3 */
			}
			for (tmr = 25000; tmr && send_cmd(cmd, 0); tmr--) ;	/* Wait for leaving idle state */
			if (!tmr || send_cmd(CMD16, 512) != 0)			/* Set R/W block length to 512 */
				ty = 0;
		}
	}
	CardType = ty;
	release_spi();

	return ty ? 0 : STA_NOINIT;
}

/*-----------------------------------------------------------------------*/
/* Read partial sector                                                   */
/*-----------------------------------------------------------------------*/

DRESULT disk_readp (
	unsigned char *buff,		/* Pointer to the read buffer (NULL:Read bytes are forwarded to the stream) */
	unsigned long lba,		/* Sector number (LBA) */
	unsigned short ofs,		/* unsigned char offset to read from (0..511) */
	unsigned short cnt		/* Number of bytes to read (ofs + cnt mus be <= 512) */
)
{
	DRESULT res;
	unsigned char rc;
	unsigned short bc;

	if (!(CardType & CT_BLOCK)) lba *= 512;		/* Convert to unsigned char address if needed */

	res = RES_ERROR;
	if (send_cmd(CMD17, lba) == 0) {		/* READ_SINGLE_BLOCK */

		bc = 30000;
		do {							/* Wait for data packet in timeout of 100ms */
			rc = ReadSPI();
		} while (rc == 0xFF && --bc);

		if (rc == 0xFE) {				/* A data packet arrived */
			bc = 514 - ofs - cnt;

			/* Skip leading bytes */
			if (ofs) {
				do ReadSPI(); while (--ofs);
			}

			/* Receive a part of the sector */
			if (buff) {	/* Store data to the memory */
				do
					*buff++ = ReadSPI();
				while (--cnt);
			} else {	/* Forward data to the outgoing stream (depends on the project) */
				//do
					//xmit(rcv_spi());	/* (Console output) */
				//while (--cnt);
			}

			/* Skip trailing bytes and CRC */
			do ReadSPI(); while (--bc);

			res = RES_OK;
		}
	}

	release_spi();

	return res;
}

/*-----------------------------------------------------------------------*/
/* Write partial sector                                                  */
/*-----------------------------------------------------------------------*/
#if _WRITE_FUNC

DRESULT disk_writep (
	const unsigned char *buff,	/* Pointer to the bytes to be written (NULL:Initiate/Finalize sector write) */
	unsigned long sa			/* Number of bytes to send, Sector number (LBA) or zero */
)
{
	DRESULT res;
	unsigned short bc;
	static unsigned short wc;

	res = RES_ERROR;

	if (buff) {		/* Send data bytes */
		bc = (unsigned short)sa;
		while (bc && wc) {		/* Send data bytes to the card */
			WriteSPI(*buff++);
			wc--; bc--;
		}
		res = RES_OK;
	} else {
		if (sa) {	/* Initiate sector write process */
			if (!(CardType & CT_BLOCK)) sa *= 512;	/* Convert to unsigned char address if needed */
			if (send_cmd(CMD24, sa) == 0) {			/* WRITE_SINGLE_BLOCK */
				WriteSPI(0xFF); WriteSPI(0xFE);		/* Data block header */
				wc = 512;							/* Set unsigned char counter */
				res = RES_OK;
			}
		} else {	/* Finalize sector write process */
			bc = wc + 2;
			while (bc--) WriteSPI(0);	/* Fill left bytes and CRC with zeros */
			if ((ReadSPI() & 0x1F) == 0x05) {	/* Receive data resp and wait for end of write process in timeout of 300ms */
				for (bc = 65000; ReadSPI() != 0xFF && bc; bc--) ;	/* Wait ready */
				if (bc) res = RES_OK;
			}
			release_spi();
		}
	}

	return res;
}
#endif

HardwareProfile.h

#ifndef HARDWARE_PROFILE_H
#define HARDWARE_PROFILE_H

	// Defines required for the USB stack
    #define self_power          1
    #define USE_USB_BUS_SENSE_IO
	#define USB_BUS_SENSE       1
    #define DEMO_BOARD PICDEM_FS_USB
    #define PICDEM_FS_USB
    #define CLOCK_FREQ 48000000

	// Fosc frequency (48 Mhz)
	#define _XTAL_FREQ 48000000
	
	// Port Controls  (Platform dependent)
	#define SS_TRIA			TRISA5			// sstris = 0
	#define SS_LATA			LATA5			// select = 0 deselect = 1
	#define	MMC_SEL		1	// MMC CS status (true:selected)
 
	// Port "D" LCD Input/Output Pins 
	#define	LCD_RS			RD0
	#define LCD_RW			RD1
	#define LCD_EN			RD2
	#define LCD_RST			RD3
	#define	LCD_DB4			RD4
	#define LCD_DB5			RD5
	#define LCD_DB6			RD6
	#define LCD_DB7			RD7

    // I/O pin definitions
    #define INPUT_PIN 1
    #define OUTPUT_PIN 0
	
#endif

Here my code structure;
diskio.c
lcd.c
main.c
pff.c

diskio.h
HardwareProfile.h
lcd.h
pff.h
diskio.h

  • #11

just testing out the CK on PORTB1 and a get a pulsating 5Volt… my PIC is powered by a 5V and my SD slot on a 3.3V.. As i can see the SD card is powered by a ~3V and his clock signal should be at ~3V right? what should i do? a voltage divider with a resistor? or there is an option to set the port output voltage on the PIC?

Applying 5V signals directly to the SD card is most likely the issue. You may want to test the card with a SD USB reader with a PC to ensure it has not been damage.

I typically use a level translator or bidirectional transceiver like the 74LCX245. A resistive voltage divider may work, but I’ve not employed that technique.

74LCX245 Low Voltage Bidirectional Transceiver.

Having a few level translators or bidirectional transceivers on hand, comes in handy when designing with devices with several operating voltage levels.

Actually, in the case of SD or MMC Socket breakout boards, I usually keep several on hand with 74LCX245s incorporated in the board.

There are numerous manufactures which sell them with bidirectional transceivers builtin.

Gravitech SD/MMC Card Adapter

Gravitech SD/MMC Card Adapter Schematic

I would suggest correcting the voltage mismatch and then retesting your code.

BigDog

  • #12

Status
Not open for further replies.

Similar threads

  • Digital Design and Embedded Programming

  • Microcontrollers

  • This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.

Error and Warning Messages

 2012 Microchip Technology Inc.

DS52053B-page 457

(1059) rewrite loop 

(Code Generator)

This is an internal compiler error. Contact Microchip Technical Support with details.

(1081) static initialization of persistent variable «*» 

(Parser, Code Generator)

A persistent variable has been assigned an initial value. This is somewhat contradictory 
as the initial value will be assigned to the variable during execution of the compiler’s 
startup code; however, the persistent qualifier requests that this variable shall be 
unchanged by the compiler’s startup code.

(1082) size of initialized array element is zero 

(Code Generator)

This is an internal compiler error. Contact Microchip Technical Support with details.

(1088) function pointer «*» is used but never assigned a value 

(Code Generator)

A function call involving a function pointer was made, but the pointer was never 
assigned a target address, for example:

void (*fp)(int);

fp(23);     /* oops — what function does fp point to? */

(1089) recursive function call to «*» 

(Code Generator)

A recursive call to the specified function has been found. The call may be direct or indi-
rect (using function pointers) and may be either a function calling itself, or calling 
another function whose call graph includes the function under consideration.

(1090) variable «*» is not used 

(Code Generator)

This variable is declared but has not been used by the program. Consider removing it 
from the program.

(1091) main function «*» not defined 

(Code Generator)

The main function has not been defined. Every C program must have a function called 
main.

(1094) bad derived type 

(Code Generator)

This is an internal compiler error. Contact Microchip Technical Support with details.

(1095) bad call to typeSub() 

(Code Generator)

This is an internal compiler error. Contact Microchip Technical Support with details.

(1096) type should be unqualified 

(Code Generator)

This is an internal compiler error. Contact Microchip Technical Support with details.

(1097) unknown type string «*» 

(Code Generator)

This is an internal compiler error. Contact Microchip Technical Support with details.

(1098) conflicting declarations for variable «*» (*:*) 

(Parser, Code Generator)

Differing type information has been detected in the declarations for a variable, or 
between a declaration and the definition of a variable, for example:

extern long int test;

int test;    /* oops — which is right? int or long int ? */

(1104) unqualified error 

(Code Generator)

This is an internal compiler error. Contact Microchip Technical Support with details.

Skip to main content

Electronics Forum (Circuits, Projects and Microcontrollers)

Electronics Forum (Circuits, Projects and Microcontrollers)

Welcome to our site!

Electro Tech is an online community (with over 170,000 members) who enjoy talking about and building electronic circuits, projects and gadgets. To participate you need to register. Registration is free. Click here to register now.

  • Welcome to our site! Electro Tech is an online community (with over 170,000 members) who enjoy talking about and building electronic circuits, projects and gadgets. To participate you need to register. Registration is free. Click here to register now.

  • Articles

  • Electronic Circuits

  • Microcontrollers

You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an alternative browser.

Resource icon

Are you needing to learn C!!!

2015-03-27


  • Author

    Ian Rogers


  • Creation date

    Mar 27, 2015

I’m doing this article as I keep telling folk C is dead easy to learn!!

Well!! As I have heard from several members, not quite!!! It really never crossed my mind that after several minutes / hours typing in a program is thwarted by the error window… As I have evolved with C, so has my understanding of various errors that pop up.. I thought (wrongly) that the C errors were in line with assembly errors… Well they kinda are… It seems that C compiler developers speak a different language to the rest of us..

A man named Tony Cunningham compiled a pretty good list here..

http://www.netfunny.com/rhf/jokes/91q3/cerrors.html

I think just to let wannabe C learners see that most of the errors are normal errors, but dressed up to sound «CRITICAL» so we are to just run and hide…

I’m gong to run a couple of examples and show the errors that could be achieved by not complying with the ANSI code…

Small C program

void main(void)
   {
   char x;

   RA4 = 0
   RA4 = 1;

   add(3,4);
   }

int add(int x, int y)
   {
   return x+y;
   }

Okay! I’m happy with that… Press compile..

Build C:UsersIan RogersDocumentsc codeLearning ClearnC for device 12F1840
Using driver C:Program Files (x86)Microchipxc8v1.33binxc8.exe

Make: The target «C:UsersIan RogersDocumentsc codeLearning ClearnC.p1» is out of date.
Executing: «C:Program Files (x86)Microchipxc8v1.33binxc8.exe» —pass1 «C:UsersIan RogersDocumentsc codeLearning ClearnC.c» -q —chip=12F1840 -P —runtime=default —opt=default -N-1 -D__DEBUG=1 -g —asmlist «—errformat=Error [%n] %f; %l.%c %s» «—msgformat=Advisory[%n] %s» «—warnformat=Warning [%n] %f; %l.%c %s»
Error [192] C:UsersIan RogersDocumentsc codeLearning ClearnC.c; 6.1 undefined identifier «RA4»
Error [195] C:UsersIan RogersDocumentsc codeLearning ClearnC.c; 7.1 expression syntax
Warning [361] C:UsersIan RogersDocumentsc codeLearning ClearnC.c; 9.1 function declared implicit int
Error [987] C:UsersIan RogersDocumentsc codeLearning ClearnC.c; 15.1 arguments redeclared
Error [1098] C:UsersIan RogersDocumentsc codeLearning ClearnC.c; 15.1 conflicting declarations for variable «add» (C:UsersIan RogersDocumentsc codeLearning ClearnC.c:14)
(908) exit status = 1

********** Build failed! **********


Whoooh!! Double dutch!!

Okay start from the first error.. 192 undefined identifier «RA4» RA4 hasn’t been defined.. This is the same error in assembly… we need to define RA4 to PORTA.4 we need to include the header just as we do in assembly Fortunately we only need to include the XC header.. this locates and includes the correct header file for us.. It’s worth looking for this header and viewing the search path as it also includes built in functions..

Error 195 expression syntax This covers a multitude of faults.. Mainly typo’s.. In this case I have forgotten the semi colon that ends expressions.. The trouble is the error doesn’t have to be on that line, as there is no semi colon on the previous line the parser continues until it finds one, only then throws an error..

Error 987 arguments redeclared This is a bit of a pig as the declaration could be anywhere.. In this case the add(); function has already been used previously within the main… We would need to

a) declare the function before the main or
b) place main below the function….​

Incidentally the warning 361 has already warned us that there is no declaration function declared implicit int I still don’t understand why?? But as functions normally return an int ( unless otherwise stated ) that would make sense… This warning is always the same.. the compiler has not been told previously about the function so cannot determine call sizes…. Interestingly C has a different stack to assembled code… The mid sized pic16 has an 8 level stack… In C we have to remember all local variables all passing parameters and the functions return pointer.. normally C starts with 255 byte stack if there is room.. You can see why it isn’t wise to use C on a tiny 56 byte ‘o’ ram micro!!

Error 1098 is basically telling us that the first definition of the function add() looks nothing like the real version of the function add(), but we already know this..

Correct the several errors

//include header for sfr's and such
#include<xc.h>

// moved to before main
int add(int x, int y)
   {
   return x+y;
   }

void main(void)
   {
   char x;

   RA4 = 0;   // repair typo
   RA4 = 1;

   add(3,4);
   }

Clean build… One warning explaining that char x was declared by wasn’t used…

I’m going to find out by asking members of the forum what errors they want me to explain and get it on here..

The error I seem to get the most is the implicit int error..

//include header for sfr's and such
#include<xc.h>

char buffer[10];

void main(void)
   {
   int x;

   x = 3567;
   sprintf(buffer,"%d",x);
   }

A valid statement… but sprintf() is declared in the stdio.h so we need to include it.
this code throws up the warning, but then fails to compile with error 1098
conflicting declarations for variable «_sprintf»

We include stdio.h

#include<xc.h>
#include<stdio.h>

char buffer[10];  

void main(void)
   {
   int x;

   x = 3567;
   sprintf(buffer,"%d",x);
   }

But then you may see a warning about the variable «buffer» suspicious conversion..
This warning doesn’t even point you to any fault.. In fact most of the string functions use non ANSI routines to cover the two pointer types..

sprintf is declared… int sprintf ( char * str, const char * format, … );
as you can see we have two types.. char* and const char*.. printf() although similar only has the const char*… Constant usually means code BUT!! as we all know a constant can be a variable… This is just one to watch… This warning can be suppressed in the options..

Type conversion or the lack of it causes major heartache..
Here we have pointers in our add() function..

//include header for sfr's and such
#include<xc.h>

int add(int* x, int* y)
   {
   return x+y;
   }

void main(void)
   {
   int x, y, z;
  
   y = 30;
   x = 10;

   z = add(x,y);
   }

There are more warnings than errors

We have one warning 359 .. illegal conversion of pointer to integer
and two others 358.. illegal conversion of integer to pointer

Then the error 209.. Type conflict

x and y are integer number variables add() expects the location of x and the location of y but receives the value of x and y…

All because a pointer is an addressed variable… The compiler doesn’t know if it is using the data x and y or the data stored at location x or y.. This in assembler would assemble but!!! the results would be far from correct!! When using C we have to tell the compiler exactly what we want the types to do what to operate on and what not to operate on..

int add(int* x, int* y)  // pointers..
   {
   return *x+*y;    //  pointed at..
   }

void main(void)
   {
   int x, y, z;
  
   y = 30;
   x = 10;

   z = add(&x,&y);   // referenced variables
   }

The only warning we get now is that we don’t use z… We fill it, but then don’t use it!

I will expand this within the next few weeks….

  • Articles

  • Electronic Circuits

  • Microcontrollers

  • This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.

Понравилась статья? Поделить с друзьями:
  • Error 1097 labview
  • Error 1093 sql
  • Error 1091 mysql
  • Error 109 fan open circuit
  • Error 109 ariston