PIC18F2220 LED blinking program error - c

I am a beginner in PIC programming. This video I have used to code my first program.
This is the code I have written:
#include <stdio.h>
#include <stdlib.h>
#include "XC8.h"
void main(void)
{
TRISBbits.RB0 = 0;
OSCCON = 0x76;
while(1)
{
LATBbits.LATB0 = ~LATBbits.LATB0;
for (int countDelay=0; countDelay<20; countDelay++) __delay_ms(50);
}
}
And my XC8.h header file is:
// PIC18F2220 Configuration Bit Settings
// 'C' source line config statements
// CONFIG1H
#pragma config OSC = RC // Oscillator Selection bits (External RC oscillator, CLKO function on RA6)
#pragma config FSCM = OFF // Fail-Safe Clock Monitor Enable bit (Fail-Safe Clock Monitor disabled)
#pragma config IESO = OFF // Internal/External Switchover bit (Internal/External Switchover mode disabled)
// CONFIG2L
#pragma config PWRT = OFF // Power-up Timer enable bit (PWRT disabled)
#pragma config BOR = OFF // Brown-out Reset enable bit (Brown-out Reset disabled)
#pragma config BORV = 20 // Brown-out Reset Voltage bits (VBOR set to 2.0V)
// CONFIG2H
#pragma config WDT = ON // Watchdog Timer Enable bit (WDT enabled)
#pragma config WDTPS = 32768 // Watchdog Timer Postscale Select bits (1:32768)
// CONFIG3H
#pragma config CCP2MX = ON // CCP2 MUX bit (CCP2 input/output is multiplexed with RC1)
#pragma config PBAD = ANA // PORTB A/D Enable bit (PORTB<4:0> pins are configured as analog input channels on Reset)
#pragma config MCLRE = OFF // MCLR Pin Enable bit (MCLR disabled; RE3 input is enabled in 40-pin devices only (PIC18F4X20))
// CONFIG4L
#pragma config STVR = ON // Stack Full/Underflow Reset Enable bit (Stack full/underflow will cause Reset)
#pragma config LVP = ON // Single-Supply ICSP Enable bit (Single-Supply ICSP enabled)
// CONFIG5L
#pragma config CP0 = OFF // Code Protection bit (Block 0 (000200-0007FFh) not code-protected)
#pragma config CP1 = OFF // Code Protection bit (Block 1 (000800-000FFFh) not code-protected)
// CONFIG5H
#pragma config CPB = OFF // Boot Block Code Protection bit (Boot block (000000-0001FFh) is not code-protected)
#pragma config CPD = OFF // Data EEPROM Code Protection bit (Data EEPROM is not code-protected)
// CONFIG6L
#pragma config WRT0 = OFF // Write Protection bit (Block 0 (000200-0007FFh) not write-protected)
#pragma config WRT1 = OFF // Write Protection bit (Block 1 (000800-000FFFh) not write-protected)
// CONFIG6H
#pragma config WRTC = OFF // Configuration Register Write Protection bit (Configuration registers (300000-3000FFh) are not write-protected)
#pragma config WRTB = OFF // Boot Block Write Protection bit (Boot block (000000-0001FFh) is not write-protected)
#pragma config WRTD = OFF // Data EEPROM Write Protection bit (Data EEPROM is not write-protected)
// CONFIG7L
#pragma config EBTR0 = OFF // Table Read Protection bit (Block 0 (000200-0007FFh) not protected from table reads executed in other blocks)
#pragma config EBTR1 = OFF // Table Read Protection bit (Block 1 (000800-000FFFh) not protected from table reads executed in other blocks)
// CONFIG7H
#pragma config EBTRB = OFF // Boot Block Table Read Protection bit (Boot block (000000-0001FFh) is not protected from table reads executed in other blocks)
// #pragma config statements should precede project file includes.
// Use project enums instead of #define for ON and OFF.
#define _XTAL_FREQ 8000000
I have followed all the steps as provided in the tutorial but I am getting the following error when I try to build the program.
make -f nbproject/Makefile-default.mk SUBPROJECTS= .build-conf
make[1]: Entering directory 'E:/Projects/Coding/MPLABX/Programming/XC8/XC8.X'
make -f nbproject/Makefile-default.mk dist/default/production/XC8.X.production.hex
make[2]: Entering directory 'E:/Projects/Coding/MPLABX/Programming/XC8/XC8.X'
"C:\Program Files (x86)\Microchip\xc8\v1.42\bin\xc8.exe" --pass1 --chip=18F2220 -Q -G --double=24 --float=24 --emi=wordwrite --opt=+asm,+asmfile,-speed,+space,-debug --addrqual=ignore --mode=free -P -N255 --warn=-3 --asmlist -DXPRJ_default=default --summary=default,-psect,-class,+mem,-hex,-file --output=default,-inhx032 --runtime=default,+clear,+init,-keep,-no_startup,-download,+config,+clib,-plib --output=-mcof,+elf:multilocs --stack=compiled:auto:auto:auto "--errformat=%f:%l: error: (%n) %s" "--warnformat=%f:%l: warning: (%n) %s" "--msgformat=%f:%l: advisory: (%n) %s" -obuild/default/production/XC8.p1 XC8.c
XC8.c:15: error: (192) undefined identifier "TRISBbits"
XC8.c:15: error: (196) struct/union required
XC8.c:16: error: (192) undefined identifier "OSCCON"
XC8.c:20: error: (192) undefined identifier "LATBbits"
XC8.c:20: error: (196) struct/union required
XC8.c:20: error: (196) struct/union required
XC8.c:22: warning: (361) function declared implicit int
(908) exit status = 1
nbproject/Makefile-default.mk:100: recipe for target 'build/default/production/XC8.p1' failed
make[2]: Leaving directory 'E:/Projects/Coding/MPLABX/Programming/XC8/XC8.X'
nbproject/Makefile-default.mk:84: recipe for target '.build-conf' failed
make[1]: Leaving directory 'E:/Projects/Coding/MPLABX/Programming/XC8/XC8.X'
nbproject/Makefile-impl.mk:39: recipe for target '.build-impl' failed
make[2]: *** [build/default/production/XC8.p1] Error 1
make[1]: *** [.build-conf] Error 2
make: *** [.build-impl] Error 2
BUILD FAILED (exit value 2, total time: 467ms)
Hope I have added sufficient input for the query. Since I am new to this section please feel free to ask for further information.

You miss to include #include <xc.h>, instead you just set your configuration bits. The xc.h is the main header file that will include a lot of other header files that finally point to your special controller header file #include <pic18f2220.h>. It's done with #ifdef constructs that your MPLAB IDE should provide because you initially set the controller when creating a new project.
This guide from Microchip is very helpful as beginning because it explains a lot.
If you don't include the <xc.h> header file the register names of your controller are not known to the compiler. That is the reason for your errors.

Related

Data Watchpoints (DWT) on cortex-m4 to detect memory corruption

I am trying to detect memory corruption on a Cortex M4 (STM32F4) using the Data watchpoint and trace (DWT) feature of cortex-m4 boards. I am able to set the watchpoints on a variable but when I access the variable in the code the DebugMon_Handler is not triggerd.
I trying to run the code form the following posts
Can Cortex M4 data watchpoint trigger an interrupt without a debugger
Cortex-M – Debugging runtime memory corruption
I have also added the below lines to trigger DebugMon_Handler interrupt
CoreDebug->DEMCR = CoreDebug_DEMCR_TRCENA_Msk /*enable tracing*/ |
CoreDebug_DEMCR_MON_EN_Msk /*enable debug interrupt*/;
But still the interrupt is not triggered even after writing to test_variable
What am I doing wrong??
COMPLETE CODE:
#include <stdio.h>
#include <stdlib.h>
#include "diag/Trace.h"
//#include "core_cm3.h"
#include "stm32f4xx.h"
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-parameter"
#pragma GCC diagnostic ignored "-Wmissing-declarations"
#pragma GCC diagnostic ignored "-Wreturn-type"
void watchpoint_enable()
{
CoreDebug->DEMCR = CoreDebug_DEMCR_TRCENA_Msk /*enable tracing*/ |
CoreDebug_DEMCR_MON_EN_Msk /*enable debug interrupt*/;
uint32_t test_variable;
trace_printf("enable watch points.... \n");
DWT->COMP1 = &test_variable;
DWT->MASK1 = 0; // match all comparator bits, don't ignore any
DWT->FUNCTION1 = (1 << 11) /*DATAVSIZE 1 - match whole word*/
| (1 << 1) | (1 << 2) /*generate a watchpoint event on write*/;
trace_printf("watch points enabled....\n");
test_variable = 5; // <<----- CPU stops after this line
}
int main(int argc, char *argv[])
{
watchpoint_enable();
}
void DebugMon_Handler(void)
{
trace_printf("Debug handler in action...\n");
}
#pragma GCC diagnostic pop
OUTPUT
enable watch points....
watch points enabled....
EXPECTED OUTPUT
enable watch points....
watch points enabled....
Debug handler in action...
NOTE
I am using STM32F407VG board emulated with QEMU on eclipse.

How to properly use __delay_ms() in libraries in MICROCHIP XC8?

I'm facing some trouble trying to create a library that calls "__delay_ms()" inside a function. Made extensive search but couldn't find the solution, nor some other explanations. I'm using XC8 v2.30 MPLAB 5.45.
I have a main function that includes the header "qc3.h":
#include <xc.h> // include standard header file
// set Config bits
#pragma config FOSC=INTOSC, PLLEN=OFF, WDTE=OFF, MCLRE=ON,
#pragma config CLKOUTEN=OFF, IESO=OFF, FCMEN=OFF,CP=OFF, CPD=OFF,BOREN=OFF
#pragma config WRT=OFF,STVREN=ON,BORV=LO,LVP=OFF
// Definitions
#define _XTAL_FREQ 500000 // this is used by the __delay_ms(xx) and __delay_us(xx) functions
#include "qc3.h"
#define LED PORTAbits.RA2
//**********************************************************************************
//***************** main routine ***********************************************
//**********************************************************************************
void main ( )
{
// set up oscillator control register
OSCCONbits.SPLLEN=0; // PLL is disabled
OSCCONbits.IRCF=0x07; //set OSCCON IRCF bits to select OSC frequency=500Khz
OSCCONbits.SCS=0x02; //set the SCS bits to select internal oscillator block
// OSCON should be 0x7Ah now.
// Set up I/O pins
ANSELAbits.ANSELA=0; // set all analog pins to digital I/O
ADCON0bits.ADON=0; // turn ADC off
DACCON0bits.DACEN=0; // turn DAC off
// PORT A Assignments (0 = OUTPUT, 1 = INPUT)
TRISAbits.TRISA0 = 0; // RA0 = nc
TRISAbits.TRISA1 = 0; // RA1 = nc
TRISAbits.TRISA2 = 0; // RA2 = nc
TRISAbits.TRISA3 = 0; // RA3 = nc (MCLR)
TRISAbits.TRISA4 = 0; // RA4 = nc
TRISAbits.TRISA5 = 0; // RA5 = nc
QC3_Initialize(); // incia protocolo para handshake
while(1)
{
__delay_ms(100);
LED = 1;
__delay_ms(100);
LED = 0;
}
}
qc3.h:
#ifndef QC3_H_ /* Include guard */
#define QC3_H_
/**
Section: Included Files
*/
#include <xc.h>
#include <stdint.h>
#include <stdbool.h>
#ifdef __cplusplus // Provide C++ Compatibility
extern "C" {
#endif
//Quick Charge 3 Pin defines
#define DP_HIGH PORTAbits.RA0
#define DM_HIGH PORTAbits.RA1
#define DP_LOW PORTAbits.RA5
#define DM_LOW PORTAbits.RA4
void QC3_Initialize(void);
//void onewireWriteBit(int b);
//unsigned char onewireReadBit();
//unsigned char onewireInit();
//unsigned char onewireReadByte();
//void onewireWriteByte(char data);
//unsigned char onewireCRC(unsigned char* addr, unsigned char len);
#ifdef __cplusplus // Provide C++ Compatibility
}
#endif
#endif
qc3.c:
#include "qc3.h"
void QC3_Initialize(void) {
__delay_ms(150);
DP_HIGH = 0;
}
Error:
make -f nbproject/Makefile-default.mk SUBPROJECTS= .build-conf
make[1]: Entering directory 'D:/Google Drive/Projetos/Pedais/Fonte para pedais isolada/QUICK CHARGE/PIC'
make -f nbproject/Makefile-default.mk dist/default/production/PIC.production.hex
make[2]: Entering directory 'D:/Google Drive/Projetos/Pedais/Fonte para pedais isolada/QUICK CHARGE/PIC'
"D:\Program Files\Microchip\xc8\v2.30\bin\xc8-cc.exe" -mcpu=12F1840 -c -mdfp="D:/Program Files/Microchip/MPLABX/v5.45/packs/Microchip/PIC12-16F1xxx_DFP/1.2.63/xc8" -fno-short-double -fno-short-float -O0 -fasmfile -maddrqual=ignore -xassembler-with-cpp -I"head_and_lib" -mwarn=-3 -Wa,-a -DXPRJ_default=default -msummary=-psect,-class,+mem,-hex,-file -ginhx032 -Wl,--data-init -mno-keep-startup -mno-osccal -mno-resetbits -mno-save-resetbits -mno-download -mno-stackcall -std=c99 -gdwarf-3 -mstack=compiled:auto:auto -o build/default/production/head_and_lib/qc3.p1 head_and_lib/qc3.c
"D:\Program Files\Microchip\xc8\v2.30\bin\xc8-cc.exe" -mcpu=12F1840 -c -mdfp="D:/Program Files/Microchip/MPLABX/v5.45/packs/Microchip/PIC12-16F1xxx_DFP/1.2.63/xc8" -fno-short-double -fno-short-float -O0 -fasmfile -maddrqual=ignore -xassembler-with-cpp -I"head_and_lib" -mwarn=-3 -Wa,-a -DXPRJ_default=default -msummary=-psect,-class,+mem,-hex,-file -ginhx032 -Wl,--data-init -mno-keep-startup -mno-osccal -mno-resetbits -mno-save-resetbits -mno-download -mno-stackcall -std=c99 -gdwarf-3 -mstack=compiled:auto:auto -o build/default/production/source/ISOPOWER.p1 source/ISOPOWER.c
make[2]: *** [build/default/production/head_and_lib/qc3.p1] Error 1
make[2]: *** Waiting for unfinished jobs....
head_and_lib/qc3.c:6:3: error: use of undeclared identifier '_XTAL_FREQ'
__delay_ms(150);
^
D:/Program Files/Microchip/MPLABX/v5.45/packs/Microchip/PIC12-16F1xxx_DFP/1.2.63/xc8\pic\include\pic.h:101:51: note: expanded from macro '__delay_ms'
#define __delay_ms(x) _delay((unsigned long)((x)*(_XTAL_FREQ/4000.0)))
^
1 error generated.
(908) exit status = 1
nbproject/Makefile-default.mk:123: recipe for target 'build/default/production/head_and_lib/qc3.p1' failed
make[1]: *** [.build-conf] Error 2
make: *** [.build-impl] Error 2
make[2]: Leaving directory 'D:/Google Drive/Projetos/Pedais/Fonte para pedais isolada/QUICK CHARGE/PIC'
nbproject/Makefile-default.mk:91: recipe for target '.build-conf' failed
make[1]: Leaving directory 'D:/Google Drive/Projetos/Pedais/Fonte para pedais isolada/QUICK CHARGE/PIC'
nbproject/Makefile-impl.mk:39: recipe for target '.build-impl' failed
BUILD FAILED (exit value 2, total time: 913ms)
The compiler complains (use of undeclared identifier '_XTAL_FREQ') but the header in declared AFTER the #define _XTAL_FREQ 500000. Why?
If i remove the delay of the function:
void QC3_Initialize(void) {
__delay_ms(150);
DP_HIGH = 0;
it builds successfully
So. "when" the QC3.c is "called" if it's never declared (even in the ".h" header)?
Why I should declare the ".h" if is the ".c" that includes the ".h"? Shouldn't it be the other way around? Or at least the ".h"
to contain the ".c"?
Seems basic stuff but it's blowing my mind
Thank You
You define _XTAL_FREQ in your C source file containing main() but, since you're calling __delay_ms() in qc3.c (a separate translation unit), that's where that definition needs to exist.
The easiest fix is probably to define it in qc3.h.
you must give _XTAL_FREQ inside the .c file then you may get.

Unknown syntax error in HCS08 MCU

I'm programming a freescale MCU and I'm using codewarrior version 10.5. I just downloaded some code from the distributor's web page, and I'm getting this syntax error in the next lines. Any help wold be appreciated!
/* Initialization of the CPU registers in FLASH */
/* NVPROT: FPS=0x7F,FPDIS=1 */
const volatile NVPROTSTR _NVPROT #0x0000FFBD = { 0xFF };
/* NVOPT: KEYEN=0,FNORED=1,SEC01=1,SEC00=0 */
const volatile NVOPTSTR _NVOPT #0x0000FFBF = { 0x7E };
Also I don't understand the use of # here. Is it any special register? Is it an address?
This is what I get in the console:
**** Build of configuration FLASH for project qg8_test ****
"C:\\Freescale\\CW MCU v10.5\\gnu\\bin\\mingw32-make" -j8 all
'Building file: ../Sources/MCUinit.c'
'Executing target #1 ../Sources/MCUinit.c'
'Invoking: HCS08 Compiler'
"C:/Freescale/CW MCU v10.5/MCU/prog/chc08" -ArgFile"Sources/MCUinit.args" -ObjN="Sources/MCUinit_c.obj" "../Sources/MCUinit.c" -Lm="Sources/MCUinit_c.d" -LmCfg=xilmou
../Sources/MCUinit.c
Command Line: '-ArgFile"Sources/MCUinit.args" -ObjN="Sources/MCUinit_c.obj" "../Sources/MCUinit.c" -Lm="Sources/MCUinit_c.d" -LmCfg=xilmou'
C:/Users/oskra/workspace/qg8_test/Project_Headers\../Sources\MCUinit.c
C:/Users/oskra/workspace/qg8_test/Project_Headers\MC9S08QG8.h
Option -Lm Update: Create new dependency file
Option -Lm: Adding make info to 'Sources/MCUinit_c.d'
C:/Users/oskra/workspace/qg8_test/Project_Headers\../Sources\MCUinit.c:135:error:C2450 Expected: ~ ( IDENT
mingw32-make: *** [Sources/MCUinit_c.obj] Error 1

microC build failure due to struct/union required

this is my main.c program and there was a build failure due to "struct/union required". I'm using pic 13f877a microcontroller. I'll be really greatful if anyone can tell me the reason for this build failure. also there was another warning saying "36.1 function declared implicit int". what does that mean too?
#include<htc.h>
#define _XTAL_FREQ 4000000
__CONFIG(0X3F39);
void main(){
int a;
TRISB = 0b00010000; //RB4 as Input PIN (ECHO)
TRISC = 0b00000000; //C as Output PINs (LED)
T1CON = 0b00010000; //Initialize Timer Module
while(1){
TMR1H = 0; //Sets the Initial Value of Timer
TMR1L = 0; //Sets the Initial Value of Timer
PORTC = 0b00000000;
PORTB.F0 = 1; //TRIGGER HIGH
Delay_us(10); //10uS Delay
PORTB.F0 = 0; //TRIGGER LOW
while(!PORTB.F4){
T1CON.F0 = 1;
}
while(PORTB.F4){
T1CON.F0 = 0;
}
a = (TMR1L | (TMR1H<<8)); //Reads Timer Value
a = a/58; //Converts Time to Distance
a = a + 1; //Distance Calibration
if(a>=2 && a<=400){
//with in the range
PORTC = 0b11111111;
} else {
//out of range
PORTC = 0b00000000;
}
Delay_ms(400);
}
}
Build C:\Users\user\Desktop\SmartDustbin for device 16F877A
Using driver C:\Program Files (x86)\HI-TECH Software\PICC\9.81\bin\picc.exe
Make: The target "C:\Users\user\Desktop\main.p1" is out of date.
Executing: "C:\Program Files (x86)\HI-TECH Software\PICC\9.81\bin\picc.exe" --pass1 C:\Users\user\Desktop\main.c -q --chip=16F877A -P --runtime=default --opt=default -D__DEBUG=1 -g --asmlist "--errformat=Error [%n] %f; %l.%c %s" "--msgformat=Advisory[%n] %s" "--warnformat=Warning [%n] %f; %l.%c %s"
Error [196] C:\Users\user\Desktop\main.c; 15.10 struct/union required
Warning [361] C:\Users\user\Desktop\main.c; 16.1 function declared implicit int
Error [196] C:\Users\user\Desktop\main.c; 17.10 struct/union required
Error [196] C:\Users\user\Desktop\main.c; 19.16 struct/union required
Error [196] C:\Users\user\Desktop\main.c; 20.10 struct/union required
Error [196] C:\Users\user\Desktop\main.c; 22.15 struct/union required
Error [196] C:\Users\user\Desktop\main.c; 23.10 struct/union required
Warning [361] C:\Users\user\Desktop\main.c; 36.1 function declared implicit int
********** Build failed! **********
You claim to be using MicroC, but the command line in your build output clearly shows you're actually using HI-Tech C 9.81, which is outdated and replaced with Microchip's XC8. HI-Tech C does not allow access to single bits in SFR's asif they were struct members, like MicroC does. You can only access registers as a full byte and need to perform bit manipulation yourself. For example, the line:
PORTB.F0 = 1;
Would need to become:
PORTB |= (1 << 0);
Which is the common way to set a single bit in C. It shifts a 1 bit to the required position and OR's it into the destination byte, not altering other bits. Google for bit manipulation in C if you don't yet understand this.
The function declared implicit int errors stem from the fact that the functions delay_us and delay_ms are not declared. HI-tech C uses the macro's __delay_ms and __delay_us. In addition, you will need to define _XTAL_FREQ with your PIC's operating frequency in Hz prior to using the delay macro's.

c library creation for ATMEL328

I am trying to create a library in C for use in a ATMEL 328pu. I have made the source and header files in C but come unstuck when I try to compile the library. I think I need another AVR library containing the types:
TWDR
TWCR
Which are the i2c registers in the ATMEGA328. A shortened version of the error message can be seen below followed by a portion of the .cpp file where the error message refers too.
Error message:
Build: Debug in my_i2c (compiler: GNU GCC Compiler)
Code_blocks/my_i2c/my_i2c/my_i2c.cpp|39|error: use of undeclared identifier 'TWCR'|
Build failed: 19 error(s), 0 warning(s) (0 minute(s), 0 second(s))
Extract from.cpp file:
#include "my_i2c.h"
/////////////////////WRITE BIT////////////////////
void my_i2c :: i2cWriteBit (uint8_t i2cAdd, uint8_t i2cReg, uint8_t i2cBit, bool i2cBool) {
uint8_t writeBuff;
writeBuff = i2cRead(i2cAdd, i2cReg); //read uint8_t
i2cBool == true ? writeBuff |= 1 << i2cBit : writeBuff &= ~(1 << i2cBit);
i2cWrite (i2cAdd, i2cReg, writeBuff);
}
/////////////////////WRITE uint8_t////////////////////
void my_i2c :: i2cWrite (uint8_t i2cAdd, uint8_t i2cReg, uint8_t i2cData) {
/////START CONDITION////
TWCR = 0b10100100; //(TWINT)(TWSTA)(TWEN) - Set START condition
while (!(TWCR & 0b10000000)) { //Wait for TWI to set TWINT
}
Do I need to define the what TWCR and TWDR are for the compiler to understand the functions? and how do I do this, is it like I was thinking by including another library?
You can't refer to an undeclared identifier, that makes it impossible for the compiler to figure out what you mean.
You should probably add
#include <avr/io.h>
to your library's source code.

Resources