Programming PIC With C

8m ago
6 Views
1 Downloads
724.63 KB
20 Pages
Last View : 1m ago
Last Download : 3m ago
Upload by : Duke Fulford
Transcription

2/27/2019 Programming PIC with C Spring 2019 EE3954: Microprocessors and Microcontrollers Avinash Karanth Professor, Electrical Engineering and Computer Science Ohio University E-mail: karanth@ohio.edu Acknowledgment: Harsha Chenji, Jim Goble, Maarten Uijt de Haag 1 1 Course Administration Lab 3 this week! Homework 3 to be posted by end of week – due next Friday March 8th No lab next week! 2 2 1

2/27/2019 Reference Sections MPLAB XC8 C Compiler User’s Guide 3 3 C vs Assembler C Code High-level language Assembly Code Assembly Code Low-level language/ Native language Machine Code Machine Code Machine code words EEPROM EEPROM Hardware 4 4 2

2/27/2019 Embedded C Myth Busting – C is not as portable between architectures or compilers as everyone claims ANSI language features ARE portable Processor specific libraries are NOT portable Processor specific code (peripherals, I/O, interrupts, special features) are NOT portable C is NOT as efficient as assembly A good assembly programmer can usually do better than the compiler, no matter the optimization employed - C WILL use more memory 5 5 Source Code to Silicon 6 6 3

2/27/2019 A Simple C Program The line numbers are just for reference. Lines 1 and 3 are preprocessor directives. Just like any other C program, we must have only one main function. This is a very simple program, but it demonstrates how much easier it is to program the PIC in C than Assembly. There is no defined way to do floating point or even multiplication in assembly. You have to write those routines yourself. In C, they are just part of the normal include files. 7 7 A Simple C Program Variables have to be defined before we use them. Harder than MatLab, much easier than assembly. Note that float is a data type. PIC C supports all of the normal data types. Unlike most PCs we will program, we should keep track of the bytes we are using with our data. Floats are 4 bytes, chars 1 byte, ints 2 bytes, etc. Why you say? Because we only have 8 KB of program memory and 1 KB of data memory. 8 8 4

2/27/2019 A Simple C Program The identifiers for our variables follow the normal C convention. They must be composed of combinations of the letters of the alphabet, the numbers 0-9 and the underscore. They are case sensitive. The identifiers cannot use any of the normal ANSI C keywords or any of the 12 additional keywords used by the PIC compiler. These will give you compiler errors at best. 9 9 Literal Constants A literal constant or simply a literal is a value, such as a number, character, or string that may be assigned to a variable or symbolic constant, used as an operand in an arithmetic or logical operation, or as a parameter to a function. Literals are "hard coded" values such as the number 5, the character 'A', or the string, "Hello, world!". Numeric literals may be represented in a variety of formats (decimal, hexadecimal, binary, floating point, etc.) A literal always represents the same value (5 always represents the quantity of five) 10 10 5

2/27/2019 Literal vs. Constants Although most of the C programming world uses the terms constant and literal interchangeably, those with assembly language background will understand them to describe two distinctly different, though related concepts. The numbers 32767 and -32768 are literals. They are actual values and the symbols we use to represent them cannot ever mean anything other than the values they represent. The words MAXINT and MININT are constants. They are symbols used to represent the values we assigned to them (32767 and 32768 respectively), but the symbols could mean anything we want. 11 11 Operators We won’t be covering many of the operators, since you already have covered them in previous classes. The memory addressing operators take the place of the FSR and INDF assembly commands and do a few things extra. The cost is always memory space. 12 12 6

2/27/2019 Statements Statements behave exactly the same way they do in any other C compiler. Unlike C on our lab workstations, you have to be aware of memory limitations. Especially since we are using Microchip’s free compiler. The free version is not vey efficient at unpacking. A while statement may use far more memory than you expect, especially compared to the bit test statements used in the assembler. 13 13 Functions Again, functions behave exactly the same way they do in any other C compiler. Again, you have to be aware of memory limitations. A simple looking expression like the one below could use far more memory than you expect. 14 14 7

2/27/2019 Labs Lab 1 introduced you to the MPLab development environment. Other than the warnings concerning memory, developing in C will make your life much easier. Use of the following configuration slides in setting up your programs will make life easier still. 15 15 MPLab XC8 C Compiler The MPLAB XC8 C Compiler is a free-standing, optimizing ISO C90 (popularly known as ANSI C) compiler. It supports all 8-bit PIC microcontrollers: PIC10, PIC12, PIC16 and PIC18 series devices. It comes in free, standard, and Pro versions. The free version is installed in the labs. You may download this from MicroChip for the PC, Linux, or Mac. 16 16 8

2/27/2019 MPLab XC8 C Compiler The C language implemented on MPLAB XC8 C Compiler can diverge from the ANSI C Standard in several areas. One divergence is due to limited device memory and no hardware implementation of a data stack. For this reason, recursion is not supported. Another divergence from the Standard is that you cannot reliably use the C sizeof operator with pointer types; however, this operator may be used with pointer variable identifiers. 17 17 Main Template /* * File: newmain.c * Author: Maarten Uijt de Haag * * Created on January 3, 2017 */ // Insert CONFIG bits #define XTAL FREQ 4000000 #include #include #include #include #include // oscillator frequency definition xc.h stdio.h stdlib.h stdint.h stdbool.h // Global variables // Functions int main(int argc, char** argv) { } Can be replaced by void main(void) as well return (EXIT SUCCESS); 18 18 9

2/27/2019 Configuration Bits Assembly: ; Include the PIC16F18875 header file that defines all special purpose registers and core registers #include "p16F18875.inc” ; Set PIC16F18875 Configuration Bit Settings CONFIG CONFIG1, FEXTOSC ECH & RSTOSC EXT1X & CLKOUTEN OFF & CSWEN ON & FCMEN ON CONFIG CONFIG2, MCLRE ON & PWRTE OFF & LPBOREN OFF & BOREN ON & BORV LO & ZCD OFF & PPS1WAY ON & STVREN ON CONFIG CONFIG3, WDTCPS WDTCPS 31 & WDTE OFF & WDTCWS WDTCWS 7 & WDTCCS SC CONFIG CONFIG4, WRT OFF & SCANE available & LVP ON CONFIG CONFIG5, CP OFF & CPD OFF C (in a separate header files: config.h): // CONFIG1 #pragma config FEXTOSC LP // External Oscillator mode selection bits (EC above 8MHz; PFM set to high power) #pragma config RSTOSC HFINT1 // Power-up default value for COSC bits (HFINTOSC (1MHz)) #pragma config CLKOUTEN OFF // Clock Out Enable bit (CLKOUT function is disabled; i/o or oscillator function on OSC2) #pragma config CSWEN ON // Clock Switch Enable bit (Writing to NOSC and NDIV is allowed) #pragma config FCMEN ON // Fail-Safe Clock Monitor Enable bit (FSCM timer enabled)// CONFIG2 #pragma config MCLRE ON // Master Clear Enable bit (MCLR pin is Master Clear function) #pragma config PWRTE OFF // Power-up Timer Enable bit (PWRT disabled) #pragma config LPBOREN OFF // Low-Power BOR enable bit (ULPBOR disabled) #pragma config BOREN ON // Brown-out reset enable bits (Brown-out Reset Enabled, SBOREN bit is ignored) #pragma config BORV LO // Brown-out Reset Voltage Selection (Brown-out Reset Voltage (VBOR) set to 1.9V on LF, and 2.45V on F Devices) #pragma config ZCD OFF // Zero-cross detect disable (Zero-cross detect circuit is disabled at POR.) #pragma config PPS1WAY ON // Peripheral Pin Select one-way control (The PPSLOCK bit can be cleared and set only once in software) #pragma config STVREN ON // Stack Overflow/Underflow Reset Enable bit (Stack Overflow or Underflow will cause a reset)// CONFIG3 #pragma config WDTCPS WDTCPS 31// WDT Period Select bits (Divider ratio 1:65536; software control of WDTPS) #pragma config WDTE OFF // WDT operating mode (WDT enabled regardless of sleep; SWDTEN ignored) #pragma config WDTCWS WDTCWS 7// WDT Window Select bits (window always open (100%); software control; keyed access not required) #pragma config WDTCCS SC // WDT input clock selector (Software Control)// CONFIG4 #pragma config WRT OFF // UserNVM self-write protection bits (Write protection off) #pragma config SCANE available// Scanner Enable bit (Scanner module is available for use) #pragma config LVP ON // Low Voltage Programming Enable bit (Low Voltage programming enabled. MCLR/Vpp pin function is MCLR.)// CONFIG5 #pragma config CP OFF // UserNVM Program memory code protection bit (Program Memory code protection disabled) #pragma config CPD OFF // DataNVM code protection bit (Data EEPROM code protection disabled) 19 How to Access SFRs and Pins Most Special Function Registers (SFRs) and pins are defined in “xc.h” by their official name as specified in the reference manual and datasheet. For example: PORTA, TRISA, RA0, RA1, RCIF, TXSTA, TXIF, GIE, PEIE, SYNC, TXEN, etc. etc. void main(void) { } // Configure the I/O ports TRISB 0b11100001; TRISD 0b00000000; NO BANK SELECTION REQUIRED 20 20 10

2/27/2019 How to Access Pins Multiple options are available to access a PORT pin: Example PORTA pin 1: RA1 PORTAbits.RA1 void main(void) { // Configure the I/O ports TRISA 0x00; TRISB 0xFF; RA1 1; PORTAbits.RA2 1; Input } if(RB3 1) RA3 1; else RA3 0; Outputs Outputs 21 21 Register Usage The assembly code generated from the C source code will use certain registers in the PIC MCU register set and assumes that nothing other than code it generates can alter the contents of these registers. 22 22 11

2/27/2019 Variables Non-standard types Only integer arithmetic 23 23 Variable – Use stdint.h C type stdint.h type Bits Sign Range char uint8 t 8 Unsigned 0 . 255 signed char int8 t 8 Signed -128 . 127 unsigned short or unsigned int uint16 t 16 Unsigned 0 . 65,535 short or int int16 t 16 Signed -32,768 . 32,767 unsigned int uint32 t 32 Unsigned 0 . 4,294,967,295 int int32 t 32 Signed -2,147,483,648 . 2,147,483,647 unsigned long long uint64 t 64 Unsigned 0 . 18,446,744,073,709,551,615 long long int64 t 64 Signed -9,223,372,036,854,775,808 . 9,223,372,036,854,775,807 24 24 12

2/27/2019 Variables char a; int8 t a; short b; int16 t b; short long c; int24 t c: long d; int32 t d; (2 bytes) (3 bytes) (4 bytes) ( a) 0x75 (for example) ( b 1) ( b) 0x76 (for example) 0x75 (for example) ( c 2) ( c 1) ( c) 0x77 (for example) 0x76 (for example) 0x75 (for example) ( d 3) ( d 2) ( d 1) ( d) 0x78 (for example) 0x77 (for example) 0x76 (for example) 0x75 (for example) 25 25 Type Ranges Signed 27-1 -27 Unsigned 216-1 26 26 13

2/27/2019 Use of Functions // Functions char AddTwoNumbersReturnLowByte(int a, int b); // Main Program void main(void) { TRISA 0x00; PORTA AddTwoNumbersReturnLowByte(23456, 12456); } char AddTwoNumbersReturnLowByte(int a, int b); { char ret; 16 bits 2 bytes int c; c a b; ret (char)(0x00FF & c); Logic AND operation return(ret); } Mask most significant byte 27 27 Use of Functions – Pass by Value Output (byte) Arguments are values: Inputs (two bytes each) char AddTwoNumbersReturnLowByte(int a, int b); { char ret; int c; c a b; ret (char)(0x00FF & c); return(ret); } “When passing arguments by value, the only way to return a value back to the caller is via the function’s return value” Alternative: “Pass by reference” and “Pass by address” Return the output (byte) 28 28 14

2/27/2019 ‘bit’ bit flag; holds the values 0 or 1 bit func(void) { } return(RA0); The 1 or 0 value will be returned in the carry flag in the STATUS register Eight bit objects are packed into each byte of memory storage, so they don’t consume large amounts of internal RAM. Operations on bit objects are performed using the single bit instructions (bsf and bcf) wherever possible, thus the generated code to access bit objects is very efficient. 29 29 Arithmetic Operations Operator Description Example Addition a b c; - Subtraction a b – c; Addition and assignment a 16; - Subtraction and assignment b - 32; Shift left by ‘n’ bits a 4; Shift right by ‘n’ bits c 2; & Logical AND a b & c; Logical OR c a b; 30 30 15

2/27/2019 Computed Goto Remember the Notes #3, lookup table (LUT) of a Square function: SQR: brw retlw d’0’ retlw d’1’ retlw d’4’ retlw d’9’ retlw d’16’ retlw d’25’ retlw d’36’ retlw d’49’ retlw d’64’ retlw d’81’ retlw d’100’ 31 31 Computed Goto’s In C we use a ‘switch’ statement; So, the following function/subroutine would return the square for each number (0, ,10) unsigned char Square(char num) { switch(num) { case 0: return(0); case 1: return(1); case 2: return(4); case 3: return(9); case 4: return(16); case 5: return(25); case 6: return(36); case 7: return(49); case 8: return(64); case 9: return(81); default: return(100); } } With the full version of the XC8 compiler (not free), this code will be optimized to a computed goto. 32 32 16

2/27/2019 Timing Loops Remember the 1-second delay loop: DELAY: movlw d'167' ; this is the OUT CNT starting value. movwf out cnt ; store it in OUT CNT register. mid agn movlw d'176' ; this is the MID CNT starting value. movwf mid cnt ; store it in MID CNT register. in agn movlw d'10' ; this is the IN CNT starting value. movwf in cnt ; store it in IN CNT location. in nxt decfsz in cnt,f ; decrement the inner counter value. goto in nxt ; if not zero, go decrement again. decfsz mid cnt,f ; decrement the middle counter. goto in agn ; if middle cntr is not zero, do inner again. decfsz out cnt,f ; decrement the outer counter. goto mid agn ; if outer cntr is not zero, do middle again. return ; if outer counter 0 then done Now is: two underscores, not one // Delay for 1000ms 1second delay ms(1000); Must define the correct oscillator frequency: 33 // oscillator frequency for delay #define XTAL FREQ 10000000 33 Interrupts Can be easily enabled by using enable interrupt function: ei() Can be easily disabled by using diable interrupt function: di() ADIE PEIE ei(); di(); 1; 1; // A/D interrupts will be used // peripheral interrupts are enabled // enable interrupts // disable interrupts Like setting GIE 0; 34 34 17

2/27/2019 Interrupts Use : ‘interrupt’ qualifier // Interrupt-on-change example void interrupt my isr(void) { if(IOCIE && IOCBFbits.IOCBF4) { // perform task required } } IOCBFbits.IOCBF4 0; clear the flag 35 35 Use of Mixed Code Various methods exist for mixing assembly code in with the C source code. Use #asm and #endasm directives unsigned int var; void main(void) { var 1; #asm banksel ( var) rlf ( var), 1 rlf ( var 1), 1 #endasm } Suppose variable ‘var’ is at data memory location 0x74 (chosen by C compiler) Selects the correct data memory bank for the variable ( var) memory location 0x74, ( var 1) is memory location 0x75 36 36 18

2/27/2019 Loops int16 t ii; int8 t array[10]; for(ii 0;ii 10;ii ) { array[ii] ii; } 10-byte character array Check MPLAB X IDE - Window - Output- Disassembly Listing File When defining an array of characters, integers, etc., remember the size limitations of the data memory. For example, int16 t array[100] represents 200 bytes, and will be filing up a large portion of your data memory. 37 37 Loops bit flag; bit flag; flag determineFlag() while(flag) { flag determineFlag(); } do { flag determineFlag(); } while(flag); 38 38 19

2/27/2019 Infinite Loop while(1) { } Condition is always true, program within loops keeps getting executed. 39 39 20

developing in C will make your life much easier. Use of the following configuration slides in setting up your programs will make life easier still. 15 MPLab XC8 C Compiler The MPLAB XC8 C Compiler is a free-standing, optimizing ISO C90 (popularly known as ANSI C) compiler. It supports all 8-bit PIC microcontrollers: PIC10, PIC12 .

Related Documents:

Chapter 7 - The Microchip PIC 129 7.0 The PICMicro Microcontroller 129 7.0.1 Programming the PIC 130 PIC Programmers 131 Development Boards 131 7.0.2 Prototyping the PIC Circuit 132 7.1 PIC Architecture 134 7.1.1 Baseline PIC Family 134 PIC10 Devices 135 PIC12 Devices 135 PIC14 Devices 138 7.1.2 Mi

Aug 27, 2019 · Pic-3 Pic-6 Pic-2 Pic-5 Pic-1 Pic-4 ATTENTION: Make sure that the right wheel (marked R) is attached to the right side and the left wheel (marked L) to the left side (seen from behind the cart in driving direction), as the wheels have built-in one-way clutches. The caddy w

tion of normal logic chips can be squeezed into one PIC program and thus in turn, into one PIC microcontroller. Figure 1.1 shows the steps in developing a PIC program. PIC programming is all to do with numbers, whether binary, decimal or hexa-decimal (base 16; this w

This book looks at programming a PIC microcontroller in C. We’ll study the following aspects of programming the PIC: 1. Looking at some of the background to the program language for micros 2. Creating a project in the Microchip IDE MPLABX 3. Configuring the PIC 4. Setting

Figure 1 PIC 16F88 microcontroller pinout . Laboratory 12: PIC programming part 1. 3 Programming a PIC using MPlab X MPlab X is an integrated development environment, IDE. For our pur

PIC K150 Manual 1-10 The USB PIC K150 microcontroller programmer Hardware version V2.0 File version V2.0 Product Image. Product Description K150 is the latest of a low-cost high-performance PIC programmer, support most popular PIC chip bur

a PIC microcontroller by serial communication. Serial communication between the PC and the PIC microcontroller is enabled by using a DB-9 serial connection between the PC and a PIC development programmer that hosts the PIC microcontroller. Two widely used PIC development programmers are Microchip’s PICS

The PIC Architecture The Basics of the PIC architecture Although it is not essential to know every last detail of how the PIC microcontroller works, it helps to have an understanding of memory, ports, interrupts, and peripherals and how they all interact. Memory The PIC has 2 types of memory: ROM (Read Only Memory) and RAM (Random Access Memory).