1222 - Kauno technologijos universitetasekaza/rls/rtos_materials/1222.pdf · Data Types short 1bit...
Transcript of 1222 - Kauno technologijos universitetasekaza/rls/rtos_materials/1222.pdf · Data Types short 1bit...
1222 CCSUsing the CCS C Compiler for Rapid Development of
Microcontroller Applications© 2008 Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 1
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 2
Class Objective
When you finish this class you will:− Be able to use your C knowledge and
write applications using CCS C− Know the ways the CCS C Compiler
speeds up development time− Develop new application and coding
ideas
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 3
AgendaCompiler Overview− Design Goals, Compiler ProductsCompiler Methodology− Differences to ‘Common’ C − Data TypesProgramming Details− Required setup, InterruptsBuilt-In Functions− GPIO, Delays, Serial (Asynch, I2C™, SPI)
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 4
AgendaHands-on Labs
Lab 1: 0 to blinky LED in 60 secondsLab 2: The CCS IDE DebuggerLab 3: Stopwatch using interruptsLab 4: A/D
Compiler Overview
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 6
Design Goals
Ease of use – compile and go!Quick development time (with built-in functions, drivers/libraries, extensive examples)Easy PIC® MCU to PIC MCU migrationOptimization comparable vs. assembly
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 7
CCS Command Line Compiler
Product Line:− PCB – Baseline PIC® MCUs − PCM – Mid-Range PIC MCUs − PCH – PIC18 Family PIC MCUs − PCD – PIC24/dsPIC30/dsPIC33 Family− PCX – PIC32 FamilyIntegrates into MPLAB® IDELinker− Can’t create relocatable objectsLinux and Windows versions
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 8
PCW – Windows IDE
C Aware EditorDebugging (using a CCS ICD)Integrated RTOSLinker and Re-locatable objectsDocument GeneratorStatisticsFlow Chart Editor
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 9
CCS Support PolicyE-Mail / Phone Support− Duration is Unlimited!Updates (new devices, drivers)− Requires Maintenance Contract− Maintenance can be extended at any
periodLarge Customer BaseRapid Releases− Average once per week
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 10
CCS ICDIn-Circuit Programmer/DebuggerSerial & USBControl Software− Windows and LinuxCCS PCW IDE for debuggingICD cable is compatible with Microchip MPLAB® ICD2
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 11
CCS Development Kits
A combined package that gives a user:− C Compiler− Prototyping Board− ICD− Tutorial Book and Examples− Relevant Parts and Cables
Compiler Demonstration
Hands On Lab #1
Blinky LED
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 14
Lab 1 Objectives
Hands-on experience with compilerUse tools and development boardUse CCS Project WizardCreate blinky-LED
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 15
Prototyping Hardware
PIC16F877A− ICD Connection− Pot on AN0− Button on RA4− LEDs on RA5, RB4 and RB5− RS232 driver and mini-connector− Header to all GPIO
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 16
Lab 1: Project WizardProject Wizard Overview
Creates an initial frameworkAssists in the initial configuration of internal peripheralsConfiguration screen for all internal peripheralsWindows IDE Only
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. Class 1222 CCS Slide 17
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 18
Lab 1: Project WizardStep 1 – Start Compiler IDE
Start the CCS Compiler IDE − Double click on the icon labeled ‘PIC
C Compiler’
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 19
Lab 1: Project WizardStep 2 – Start Project Wizard
Start the Project Wizard− File -> New -> Project Wizard
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 20
Lab 1: Project WizardStep 3 – File Name Dialog
File name: C:\masters\1222\Lab1\lab1.cPress Save
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 21
Lab 1: Project WizardStep 4 – Configuration
You will now be in the Project Wizard DialogIn the General Section:− Select 16F877A under Device− Set oscillator to 20000000 Hz− Select ‘High Speed Osc’ under fuse
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. Class 1222 CCS Slide 22
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 23
Lab 1: Project WizardStep 5 – Enter Code
Press the OK button in the Project WizardInside main(), find the line marked:− //TODO: USER CODE
Replace this line with the following code:while(TRUE){
delay_ms(500);output_toggle(PIN_B5);
}
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 24
Lab 1: Project WizardStep 6 – Compile Code
Compile Code − Compile -> Compile
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 25
Lab 1: Project WizardStep 7 – Compile Results
Inspect the output window for compile results− You should get 0 Errors
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 26
Lab 1: Project WizardStep 8 – Load HEX
Load HEX file with CCS ICD− Click on the ‘Program Chip’ icon on
the ‘Compile’ ribbon, select ICD
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 27
Lab 1 Hints
LED will blink at 1Hz rateFollow handoutVerify:− Correct PIC® MCU Selected− Correct FUSEs selected− Correct #use delay() specified− Fix any compile errorsBored? Try “Extra Credit”
Compiler Methodology
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 29
Differences to ‘Common’ CCase in-sensitive− #case will make it case sensitiveVariables not initialized to zero− #zero_ram inits all variables to 0const places variable into ROMBy default, const strings cannot be parameter− SomeFunc(“Hello”) is usually illegal− #device PASS_STRING=IN_RAM#device ANSI
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 30
ANSI Non-Compliance
No fopen(), fclose(), etc− fprintf() supported, methodology a
little differentprintf() formatting string must be known at compile timeRecursion not allowed on all PIC®
MCUs
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 31
Data Types
1bit1bitshortUnsigned 8bitUnsigned 8bitchar
Signed 64bitUnsigned 32bitlong long
IEEE 64bitNO SUPPORTdoubleIEEE 32bitMCHP 32bitfloat
Signed 32bitUnsigned 16bitlongSigned 16bitUnsigned 8bitint
PCDPCB/PCM/PCH
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 32
Data Types#type can change default size− #TYPE SHORT=8, INT=16, LONG=32
Optimization Tips− Use only one float type− Use ‘int’ as much as possibleNon-standard data types− int1 int8 int16− int32 int48* int64*− float32 float48* float64* (PCD ONLY)
− __address__
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 33
Fixed Point Decimal
Decimals with integers, not floats!− Faster, Smaller− 100% precisionStores value in 10y powerDeclaration:[type] _fixed(y) [declarator]int16 _fixed(2) money
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 34
Fixed Point Examples
int16 _fixed(2) money;− Range: 0.00 to 655.35money = 20.50;money += 5; //adds 5.00money += value;printf(“%w”, money);
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 35
RAM AllocationRAM is allocated first come, first served in this order:1. globals2. static3. localCall tree determines which RAM can be reusedUser can force RAM placementStructure/Array cannot be larger than bank
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 36
‘const’ vs. ‘rom’‘const’ has two modes:− #device CONST=ROM DEFAULT− #device CONST=READ_ONLY
‘const’ is always read-only‘rom’ places variable in ROM‘rom’ writable if supported by PIC® MCUExamples− const int lookup[16]={0...15};− const char string[]=“Hello”;− rom char *cptr = “Hello”;
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 37
Borrowed from C++Reference Parameters
Pass address, not value− More Efficient for large structures− Values can be changed in functionDeclare reference parameters with &
void Inc(int &i) {i++;
}
Many times compiler will inline
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 38
Borrowed from C++Default Parameters
Default value passed to function if no value specifiedint1 Get(char *c, int time=200);
Get(&c);− time will be 200
Get(&c, 500);− time will be 500
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 39
Borrowed from C++Function Overloading
Multiple functions, same nameDifferent parametersExample:Three different functions called Inc− int Inc(int *i);− long Inc(long *l);− float Inc(float *f);
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 40
In-Line Assembly#asm − Starts an assembly block
#endasm − Ends an assembly block
_return_− Assign return value− May be corrupted by any C code
after #endasmSupports all opcodesC variables can be accessedAutomatic banking− #asm ASIS - disables auto-
banking
int find_parity (int data){
int count;#asm
movlw 0x8movwf countmovlw 0
loop:xorwf data,wrrf data,fdecfsz count,fgoto loopmovlw 1addwf count,fmovwf _return_
#endasm}
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 41
Output Files
HEX – Compiled ApplicationCOF – Debug ApplicationERR – Compile output messagesLST – C to Assembly comparisonSYM – Memory MapSTA – StatisticsTRE – Call Tree
Programming Details
Required Setup
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 43
Pre-processor
Design Goal: All in front of you− Everything is in the source code− No linker scriptsPre-processor commands change compiler-behaviour:− Methodology− ROM/RAM placement− Library configuration
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 44
#deviceLoads personality for the target PIC®MCU− #device PIC18F4520Can be used to alter low-level specifics− #device ICD=TRUEPIC MCU header files have #deviceIf creating multiple compilation units (linking), must be defined in each file. − Put it in a common include file
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 45
#fuses
Define the configuration bits− #fuses HS, NOWDT, NOLVPTo get list of valid fuses:− In IDE, use View Valid Fuses window− Header file for the device has listTo get a description of each fuse:− In IDE, use View Valid Fuses window− fuses.txt
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 46
#use delayConfigure the built-in libraries for the clock speed for your target− #use delay(clock=value)
value is system clock speed, after PLLOnly needed if using the following:− Serial− Delay
For multiple clock speed applications, you can define this more than once
Programming Details
Memory Placement
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 48
#byte / #word
Force location of RAMint val;#byte val=0xA0
Overlaying variable onto SFR:#byte STATUS=0x03#word TMR1=0x0E
Repeat, but using getenv():#byte STATUS=getenv(“SFR:STATUS”)
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 49
#bit
#bit ident=X.b− Declares boolean at address X, bit b− Examples:
#bit CARRY=STATUS.0#bit CARRY=getenv(“BIT:C”)
Don’t forget:− Compiler will pack ‘int1’ variables− You can use ‘struct’ to pack bits
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 50
#orgFix placement in ROM#org start, end− Place following function/constant in
specified program memory
#org 0x400,0x4FFSomeFunction() { /*code*/ }
#org 0x500, 0x5FFconst someStruct[] = { … }
Hands On Lab #2
Debugging a Calculator Application
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 52
Lab 2 Objectives
Learn basic debugging use− Breakpoints− Watches− ROM and RAM view− Peripheral StatusLearn advanced debugging use− Logging− 1Wire RS232 on RB3
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 53
Lab 2: CCS IDE DebuggerStep 1 – Close All Open Files
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 54
Lab 2: CCS IDE DebuggerStep 2 – Load Example Code
Load Example Code− File->Open− C:\masters\1222\Lab2\lab2.c
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 55
Lab 2: CCS IDE DebuggerStep 3 – Start Debugger
Start Debugger− Debug -> Enable Debugger
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 56
Lab 2: CCS IDE DebuggerDebugger GUI Overview
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 57
Lab 2: CCS IDE DebuggerStep 4 – Load Target Code
Compile Project− Compile -> Compile− Project will be loadedPress GO
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 58
Lab 2: CCS IDE DebuggerStep 5 – 1-Wire RS232
#use rs232(debugger) − 1-Wire RS232 using RB3− 1-Wire Monitor in Debugger:
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 59
Lab 2: CCS IDE DebuggerStep 6 – 1-Wire RS232
Using the Monitor, experiment with the applicationApplication is a simple calculator
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 60
Lab 2: CCS IDE DebuggerStep 7 – Breakpoints
Press STOPAdd a Breakpoint to line 63− printf(“\r\nThe result is %lu”, result)− Put cursor on Line 63, Press + on
Break Tab
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 61
Lab 2: CCS IDE DebuggerStep 8 – Watching
Open Watch Tab, Press +
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 62
Lab 2: CCS IDE DebuggerStep 9 – Watch Dialog
Enter ‘result’ into Expression FieldPress Add Watch
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 63
Lab 2: CCS IDE DebuggerStep 10 – Break Logging
Logs an expression at breakpoint− Breakpoint doesn’t stop executionEnter result into Break Log
Press GO
BREAK TIME!
Programming Detailsaddressmod
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 66
Pop Quiz
You need to store 128 values but your PIC® MCU only
has 80 bytes of RAM.
What do you do?
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 67
addressmod
Application defined storage− What is ‘normal’ storage?typemod, on steroids!Can be used on any data type− Pointers, structs, unions and arrays− ‘const’ and ’rom’ not allowedISO/IEC TR 18037 (Embedded C)
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 68
addressmod Syntaxaddressmod(identifier,[read,write,]start,end)− identifier is the new qualifier − read(int32 addr, int8 *ptr, int8 len)− write(int32 addr, int8 *ptr, int8 len)
The IO method to access this memoryOptional
− start/end are the memory range
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 69
addressmod Declarationaddressmod(nv, read_nv, write_nv,
0, NV_SIZE);
void read_nv(int32 addr, int8 *ram, int8 n)
{ /* read n from addr */ }
void write_nv(int32 addr, int8 *ram, int8 n)
{ /* write n from ram */ }
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 70
addressmod Usage
nv NVBuffer[8192];nv NVID;nv *NVPtr;
#locate NVID=0
NVBuffer[i]=55;*NVPtr++ = 0;
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 71
addressmod Ideas
External RAM / FlashCharacter/Grahic LCD access thru a multi-dimensional arrayDebug/trap critical variables
Programming Details
Interrupts
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 73
Pop Quiz
What does your ISR need to do?
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 74
Interrupt Service Routine
CCS C provides an ISR− Saves status and scratch registers− Checks enable/flags, goes to user
ISR function for that flag− Clears interrupt flag (if needed)− Restores status/scratch registers
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 75
Interrupt Service Routine API
enable_interrupts(INT_*) − enable_interrupts(GLOBAL)− enable_interrupts(INT_TIMER0)disable_interrupts(INT_*) clear_interrupt(INT_*) interrupt_active(INT_*)
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 76
Interrupt Service Routine API
#int_*− The following function will be processed
for that interrupt
#int_timer0void isr_timer0(void){//HANDLE TIMER0 OVERFLOW
}
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 77
Interrupt Service RoutineSpecial Identifiers
#int_global− Function overrides CCS ISR − User must save and restore all
registers altered by their ISR (W, STATUS, scratch used by compiler, etc.)
#int_default− Traps unknown interrupt
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 78
Interrupt Service RoutineOptions
These keywords may follow #int_*:− high – (PIC18) Interrupt is high priority− fast – (PIC18) Same as high, but no save− fast – (PCD) Uses shadow registers− level=(0..7) – (PCD) sets interrupt level − noclear – ISR will not clear interrupt flags#device HIGH_INTS=TRUE− Must set to use high/fast ISR on PIC18
Lab #3
Interrupts
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 80
Lab 3: ObjectivesLearn how to use the CCS ISRLearn how the CCS built-in functions control the Timer0 and GPIOImplement a stop watch that measures button press time.Open C:\masters\1222\Lab3\lab3.c− Complete the lines marked TODO
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 81
Lab 3 HintsHandout has help and finished exampleTIPS:− Press F1 to get compiler help manual− #int_timer0
Following function is called on a Timer 0 overflow− setup_timer_0(RTCC_DIV_256)
Configures Timer 0 to use a divide by 256 prescalar − enable_interrupts(int_xxx)
INT_TIMER0 – Enable Timer 0 InterruptGLOBAL – Enables Global Interrupt
− input(PIN_XX)Returns TRUE if PIN_XX is high, else returns FALSEButton is RA4, or PIN_A4 in CCS
Bored? Try the “Extra Credit”
Programming Details
Built-In Functions
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 83
Built-In Functions
Compiler provides functions to:− Control Peripherals (A/D, Serial, etc)− Perform logic optimized to PICInternal to compiler, not linkedSimplify PIC® MCU to PIC MCU migrationFollow any errata workarounds
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 84
Easy PIC® MCU Migration#if defined(__PIC18__)
#include <18F4520.h>#elif defined(__PIC14__)
#include <16F877A.h>#endif
#fuses HS, NOWDT, NOLVP#use delay(clock=20000000)
Void main(void) {while(TRUE) {
output_toggle(PIN_C0);delay_ms(500);
}}
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 85
getenv()Assists in making portable codeReturns chip information− Program Memory Size− Bulk Erase Size− Configuration Bits SetOptions can be conditionally compiled:#if getenv(“ADC_CHANNELS”) > 0
setup_adc_ports(NO_ANALOGS);#endif
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. Class 1222 CCS Slide 86
Device Database and Editor
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 87
Don’t forget Drivers and Examples!
Drivers provided for complex features or external peripherals− EEPROMs, LCDs, USB, FAT, etc
Many example programs provided to showcase built-in functions/driversAlways kept up to date with latest peripheralsBefore you start a project, examine the libraries and example programs CCS provides you to reduce your development time
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 88
Built-In FunctionsGeneral Purpose Input / Output
output_high(PIN_XX)output_low(PIN_XX)− Sets the pin to desired level− PIN_XX (ex PIN_C0, PIN_B5, etc) are
defined in the device header fileoutput_toggle(PIN_XX)− Toggle high/low state of the pinbool=input(PIN_XX)− Read value of pin
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 89
Built-In FunctionsGeneral Purpose Input / Output
output_X(value)− Sets the port X (A to J) to the desired
valuebyte=input_X()− Read value of port Xset_tris_X(value)val = get_tris_X()− Get/Set the tristate setting
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 90
Built-In FunctionsGeneral Purpose Input / Output
#use standard_io(X)− Output functions set TRIS to output− Input functions set TRIS to input− This is the default operation#use fast_io(X)− Compiler does not alter TRIS#use fixed_io(port_outputs=pins)− #use fixed_io(d_outputs=PIN_D7)
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 91
Built-In FunctionsBit Manipulation
bool=bit_test(var, bit)− Returns the value of the specified bitbit_clear(var, bit)bit_set(var, bit)− Set/clear the specified bitThe above bit_XXX() functions use the PIC® MCU’s bit operation opcodes for maximum efficiency
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 92
Built-In FunctionsDelays
delay_cycles(x)delay_us(x)delay_ms(x)− Uses a series of loops and NOPs− Timing based on #use delay()− Multiple #use delay() allowed
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. Class 1222 CCS Slide 93
#use delay(clock=125000)
//1 second delay @ 125kHzvoid Delay1s125khz(void) {delay_ms(1000);
}
#use delay(clock=8000000)
//1 second delay @ 8MHzVoid Delay1s8Mhz(void) { delay_ms(1000);
}
Built-In Functions
Serial Libraries
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 95
Pop Quiz
You need to add another serial port to your project,
but you have used all of the PIC® MCU’s peripherals.
What do you do?
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 96
UART
Powerful UART library built into compiler#use rs232(baud=xxxx, xmit=PIN_XX,
rcv=PIN_XX, stream=yyyyy)− TX/RX pins can be any pins− Many more options exist
Enable bit, parity, collision detection, open-collector mode, etc.
− Timing is based on #use delay()
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 97
UART (Continued)Standard C I/O, last #use rs232()− printf(“string”, …)− char=getc()− putc(char)
Standard C I/O, streams:− fprintf(stream, “string”, …)− char=fgetc(stream)− putc(char, stream)
bool=kbhit(stream)setup_uart(newBaud, stream)− Dynamically change the UART
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 98
Dual UART Example#use rs232(baud=9600, xmit=PIN_C6, rcv=PIN_C7,
stream=HW_UART)
#use rs232(baud=9600, xmit=PIN_D0, rcv=PIN_B0, stream=SW_UART, disable_ints)
fprintf(HW_UART, “HELLO HARDWARE UART\r\n”);
fprintf(SW_UART, “HELLO SOFTWARE UART\r\n”);
if (kbhit(HW_UART)) {c=fgetc(HW_UART);fputc(c,SW_UART);
}if (kbhit(SW_UART)) {
c=fgetc(SW_UART);fputc(c,HW_UART);
}
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 99
printf() Redirection
printf() can be redirected to a user-defined functionExample:void LCDPut(char c);printf(LCDPut, “%U”, val);
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 100
I2C™ LibraryMultiple I2C channels on any I/O pins#use i2c(master, sda=pin_XX,
scl=pin_XX, address=YY, stream=id)
− The SDA and SCL pins can be any pins− Slave Mode is HW MSSP only− Address Is only needed in slave mode
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 101
I2C™ Library (Continued)
i2c_start()− Can also be used to send a re-start signalchar=i2c_read(ack)− Ack is an optional parameterack = i2c_write(char)bool=i2c_available()− Can only be used with a hardware MSSPi2c_stop()
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 102
SPI
Configurable SPI library#use spi(parameters)− HW or SW pins− Multiple streams− Clock rate and clock mode
configurablein = spi_xfer(STREAM_SPI, out)
Built-in Functions
A/D Converter
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 104
A/D Converter
setup_adc(mode)− Configure and the ADC; mode varies
for each typesetup_adc_ports(config)− Configure the pins for analog or
digital mode#device ADC=X− Assign the ADC result size
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 105
A/D Converter (Continued)
set_adc_channel(channel)− Set the channel for subsequent readsval = read_adc(mode)− ADC_START_ONLY – Start a conversion− ADC_READ_ONLY – Read last
conversion− ADC_START_AND_READ – Full cycleadc_done()− Returns TRUE if conversion is done
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 106
A/D Converter Example//INIT#device ADC=10setup_adc(ADC_CLOCK_INTERNAL );setup_adc_ports(AN0);
//APPLICATIONint16 result;set_adc_channel(0);read_adc(ADC_START_ONLY);
/* do something while A/D is busy */while (!adc_done());result=read_adc(ADC_READ_ONLY);
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 107
Getting Help
So many peripherals, how do I get help?
1. In PCW, Press F1 for context sensitive help
2. Look for section labeled ‘Functional Overviews’
Lab #4
Analog to Digital Conversion
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 109
Lab 4
Read A/D conversionConvert A/D result to 0 to 5 using floatLight LEDs based upon voltageC:\masters\1222\Lab4\lab4.c− Complete the lines marked TODO
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 110
Lab 4 HintsC:\masters\1222\Lab4\lab4.c− Complete the lines marked TODOHandout has help, finished exampleADC Troubles?− Did you enable A/D with setup_adc()?− Did you set the channel?− Is A/D correct, but fixed() math wrong?
Verify readings using debuggerBored? Try “Extra Credit”
Class Summary
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 112
Class Summary
Leaving this class you should:− Be able to use your C knowledge and
write applications using CCS C− Know how to use the CCS software to
load your code onto a PIC® MCU and debug it
− Know the ways the CCS C Compiler speeds up development time with built-in functions, drivers, example files and context sensitive help
Q & A
Thank You!
Please fill out evaluation form.
AppendixFrequently Asked
Questions
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 116
Why do I get out of ROM error, when there is ROM left?
A function must fit into one bankOn 14-bit this is 2KSplit large functions, and main(), into several smaller functions− This is good programming practice
any way!
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 117
How Can I Reduce Code Space?
Use int1 or bit fields for flagsUse fixed point decimal, not floatDivide large functionsAvoid ->, move structure to localUse access bank mode− #device *=8− read_bank(b,o), write_bank(b,o,v)
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 118
Why is My Math Clipped at 8-bits?
Examine the following code:− val16=val8 * val16;The optimizer will use the smallest data type for math, in this case int8Typecasting forces math into proper mode:− val16=(int16) val8 * val16;
AppendixProgramming Details
Miscellaneous
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 120
addressmod Block
#type default=qualifier− Following declarations will use this
qualifier− If qualifier blank, goes back to default
#type default=nv
char buffer[8192];#include <memoryhog.h>
#type default=
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 121
Pre-Processor Miscellaneous
__pcb____pcm____pch____pcd__− Returns the version of specified compiler
__date____time__− Time/Date project was compiled
#id CHECKSUM#id value− Place this value (or checksum) into ID location
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 122
Bit Arrays
Array of bits:− int1 flags[30]={FALSE};− flags[i] = TRUE;− if (flags[10]) { /* some code */ }Bits are packedPointers not supported
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 123
String ParametersString can be function parameterLCDPuts(“Hello”);Example (RAM):
#device PASS_STRINGS=IN_RAMvoid LCDPuts(char *str);
Example (Const RAM):#device PASS_STRINGS=IN_RAM#device CONST=ROMvoid LCDPuts(const char *str);
Example (ROM):void LCDPuts(rom char *str);
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 124
#importImport various files into project.#import(File=name, Type)Type = Relocatable (.o, .cof)− ‘only’ and ‘except’ specifies what C
symbolsType = HEX (.hex)− ‘range’ parameter specifies rangeType = RAW− ‘location’ gets or sets location− ‘size’ parameter gets size
Appendix
Output Files
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 126
Output Files
HEX – Compiled ApplicationCOF – Debug ApplicationERR – Compile output messagesLST – C to Assembly comparisonSYM – Memory MapSTA – StatisticsTRE – Call Tree
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 127
SYM – Memory Map
First section is RAM memory map005-014 main.bufferna main.index‘na’ indicates no RAMFollowing sections include:− Other Input files− ROM memory map− PIC® MCU / Compiler Settings
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 128
STA Statistics
Review ROM/RAM/Stack used.Statistics for each function:
Page ROM % RAM Functions:---- --- --- --- ----------0 26 0 1 @delay_ms10 284 1 3 ee_reset
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 129
STA Statistics
Statistics for each segment:Segment Used Free--------- ----- ----00000-00006 4 4 00008-000B2 172 0 000B4-03FFE 15826 378
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 130
TRE Statistics
Review call tree− Function Name - Segment/ROM – RAM
projectmain 0/84 Ram=0init 0/194 Ram=1
RELAY_INIT 0/16 Ram=0RELAY1_OFF (Inline) Ram=0@delay_ms1 0/26 Ram=1
Segment will be ? if it won’t fit
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 131
Out of ROMFull output:Out of ROM, A segment or the program is too large: XXXXXXSeg w-x, y left, need zSeg 0-3ff, 12C left, need 12F
Tips:− Be aware of processor segment size
Seg 0-3FF, 3FF left, need 412− Optimize code− Split large functions− Reduce stack usage (allows more CALLs)
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 132
How Can I Reduce Code Space?
Use int1 or bit fields for flagsUse fixed point decimal, not floatDivide large functionsAvoid ->, move structure to localUse access bank mode− #device *=8− read_bank(b,o), write_bank(b,o,v)
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 133
Out of RAM
Full error message:Not enough RAM for all variablesReview SYM fileTips:− Be aware of PIC® MCU bank size− Use bit flags− Use local variables (not global)
AppendixOther Built-In Functions
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 135
Internal Data EEPROM
Access internal data EEPROMv = read_eeprom(address)write_eeprom(address, v)
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 136
Read / Write Program Memory
Treat program memory like data EEPROMv=read_program_eeprom(a)write_program_eeprom(a, v)− Size of v depends on architectureread_program_memory(a, ptr, num)write_program_memory(a, ptr, num)erase_program_memory(a)
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 137
Built-In FunctionsByte Manipulation
int8=make8(variable, offset)− Returns one byte from variableint16=make16(i8MSB, i8LSB)int32=make32(iMSB..iLSB)− Returns the combined valueswap(value)− Swaps nibble, saves to value
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 138
Timerssetup_timer_X(mode)− Mode contains configuration info, such as
prescalar, postscalar, period, etc.− setup_timer_1(T1_INTERNAL | T1_DIV_BY_4);
set_timerX(new_count)current_count=get_timerX()− Set/Get Timer count− Word Safe
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 139
Capture / Compare / PWM
setup_ccpX(mode)− Mode contains configuration,
examine header for full options− setup_ccp1(CCP_PWM)
set_pwmX_duty(new_duty)− % = new_duty / (4 * period)
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 140
Peripheral ControlParallel Slave Port
setup_psp(mode)− Mode is PSP_ENABLED or
PSP_DISABLEDfull=psp_output_full()avail=psp_input_full()isOverflowed=psp_overflow()psp_data− A variable mapped to the PSP I/O port
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 141
Built-In FunctionsMiscellaneous
ext_int_edge(which, mode)− ext_int_edge(0, H_TO_L)port_X_pullups(boolean)setup_oscillator(mode, finetune)− finetune is optional− setup_oscillator(OSC_2MHZ)
Appendix
Fixed Memory Placement
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 143
#rom
Place raw data into program memory#rom address={data….data}Application Ideas:− Initialize the internal data EEPROM− Manually set configuration bits− Manually set ID location− Place strings into ROM
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 144
#inline and #separate#inline− Makes following function inline− Best if used with reference parameters#separate− Makes following function separate (called)Generally you should let the optimizer determine if a function should be separate or inline
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 145
#locateForce location of variable#locate ident=X− Assigns the C variable ident to location X− X can be a literal, or variable identifier− If not specified, ident is treated as a byte− Compiler allocates X− Can be any structure or type (not const)
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 146
#locate examples
Overlaying variable onto SFR:#locate STATUS=5
Repeat, but using get_env():#locate STATUS=get_env(“SFR:STATUS”)
Overlaying two variables:char buffer[512];
struct { /*protocol */} header;#locate header=buffer+2
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 147
#byte and #bit
#byte ident=X− Same as #locate, but no allocation#bit ident=X.b− Declares boolean at address X, bit b− Examples:
#bit CARRY=STATUS.0#bit CARRY=get_env(“BIT:C”)
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 148
#rom
Place raw data into program memory#rom address={data….data}Application Ideas:− Place strings into ROM− Initialize the internal data EEPROM− Manually set configuration bits− Manually set ID location
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 149
#inline and #separate#inline− Makes following function inline#separate− Makes following function separate (called)− Disables stack overflow checkGenerally you should let the optimizer determine if a function should be separate or inline
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 150
#org
Create segment, force code into segment.#org start, end− Place following function/constant in
this segment#org start− Continue previous segment
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 151
#org ExampleForce following code into 0x100-0x1FF
#org 0x100, 0x1FFvoid func1(void) {/*code*/}
#org 0x100const cstring[]=“Hello”;
#org 0x100void func2(void) {/*code*/}
//Valid Protoype#seperate void func1(void);
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 152
#org
#org start, end DEFAULT− Forces all following
function/constants into this segment#org DEFAULT− Terminate previous DEFAULT#org start, end { }− Reserve ROM
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 153
#org Example 2Force following code into 0x100-0x1FF
#org 0x100, 0x1FF defaultvoid func1(void) {/*code*/}
const cstring[]=“Hello”;
void func2(void) {/*code*/}
#org default
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 154
#org
View .STA to view current segment usage:
Segment Used Free0000-0003: 4 00004-00FF: 250 20100-01FF: 190 660200-07FF: 1337 199
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 155
#buildCan change reset and interrupt segment#build(segment=start:end)Valid segments:− reset – the location of the reset vector− interrupt – the location of the interrupt vector− memory – external memory for CPU mode
Examples:− #build(reset=0x800, interrupt=0x808)− #build(memory=0x10000:0x1FFFF)
Appendix
Bootloader Example
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 157
Bootloader Overview
Two programs:− Loader− ApplicationEach program #org’dto their own space− Loader in low memory
(0-7FF)− Application high
memory (800-end)
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 158
Bootloader/Application Common Code
#define BOOT_END (0x7FF)
#define APP_START (BOOT_END+1)
#define APP_ISR (APP_START+8)
#define PROGRAM_END
getenv(“PROGRAM_MEMORY”)
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 159
Bootloader ExampleLoader Code
//prevent bootloader from using application#org APP_START , PROGRAM_END { }
#int_globalvoid isr(void) {
//goto interrupt in applicationjump_to_isr(APP_ISR);
}
void main(void) {if (IsBootloadEvent())
Bootload();#asmgoto APP_START#endasm
}
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 160
Bootloader ExampleApplication Code
#import(file=loader.hex, range=0:BOOT_END)
#build(reset=APP_START,interrupt=APP_ISR)
#org 0,BOOT_END { }
#int_timer0void timer(void) { /* do timer0 isr */ }
Void main(void) {/* code */
}
Appendix
RTOS
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 162
RTOS Basics
Multitasking thru time-sharing− Tasks appear to run at same time‘Real Time’Task is in one of three states:− Running− Ready− Blocked
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 163
The CCS RTOS
Cooperative Multitasking Tightly integrated with compilerSupports ALL PIC® MCUs with a TimerAvailable to IDE customers
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 164
RTOS Setup
#use rtos(timer=X, [minor_cycle=cycle_time])− Timer can be any timer available− Minor_Cycle is rate of fastest task− Example:#use rtos(timer=1, minor_cycle=50ms)
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 165
RTOS Tasks
#task(rate=xxxx, [max=yyyy], [queue=z])− Following function is RTOS task− Will be called at specified rate− Max is slowest execution time, used
for budgeting− Queue defines RX message size
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 166
RTOS Start and Stop
rtos_run()− Starts the RTOS− Will not return until rtos_terminate()rtos_terminate()− Stops the RTOS
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 167
#use rtos(timer=1)
#task(rate=100ms, max=5ms)void TaskInput(void){ /* get user input */ }
#task(rate=25ms)void TaskSystem(void){ /* do some stuff */ }
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 168
RTOS Task Control
rtos_enable(task)rtos_disable(task)− Dynamic task control− Enable/Disable the specified task− Task is the function name− All tasks are enabled at start
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 169
RTOS Messaging
rtos_msg_send(task, char)− Sends char to taskavail=rtos_msg_poll()− TRUE if a char is waiting for this taskbyte=rtos_msg_read()− Read next char destined for this task
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 170
RTOS Yielding
rtos_yield()− Stops processing current task− Returns to this point on next cyclertos_await(expression)− rtos_yield() if expression not TRUE
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 171
#task(rate=100ms, max=5ms)void TaskInput(void) {if (KeyReady())rtos_msg_send(TaskSystem,
KeyGet());}
#task(rate=25ms, queue=1)void TaskSystem(void) {
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 172
RTOS SemaphoresSemaphore− Determine shared resource availability − A user defined global variable− Set to non-zero if used− Set to zero if freertos_wait(semaphore)− rtos_yield() until semaphore free− Once free, sets semaphore as usedrtos_signal(semaphore)− Release semaphore
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 173
RTOS Timing Statisticsoverrun=rtos_overrun(task)− TRUE if task took longer than maxrtos_stats(task, rtos_stats)− Get timing statistics for specified task
typedef struct {int32 total; // total ticks used by taskint16 min; // minimum tick time usedint16 max; // maximum tick time usedint16 hns; // us = (ticks*hns)/10
} rtos_stats;
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 174
RTOS Application Ideas
User I/OCommunication Protocols
© 2008 Custom Computer Services Inc., , Microchip Technology Incorporated. All Rights Reserved. 1222 CCS Slide 175
TrademarksThe Microchip name and logo, the Microchip logo, Accuron, dsPIC, KeeLoq, KeeLoq logo, MPLAB, PIC, PICmicro, PICSTART, PRO MATE, rfPIC and SmartShunt are registered trademarks of Microchip Technology Incorporated in the U.S.A. and other countries.FilterLab, Linear Active Thermistor, MXDEV, MXLAB, SEEVAL, SmartSensorand The Embedded Control Solutions Company are registered trademarks of Microchip Technology Incorporated in the U.S.A.Analog-for-the-Digital Age, Application Maestro, CodeGuard, dsPICDEM, dsPICDEM.net, dsPICworks, dsSPEAK, ECAN, ECONOMONITOR, FanSense, In-Circuit Serial Programming, ICSP, ICEPIC, Mindi, MiWi, MPASM, MPLAB Certified logo, MPLIB, MPLINK, mTouch, PICkit, PICDEM, PICDEM.net, PICtail, PIC32 logo, PowerCal, PowerInfo, PowerMate, PowerTool, REAL ICE, rfLAB, Select Mode, Total Endurance, UNI/O, WiperLock and ZENA are trademarks of Microchip Technology Incorporated in the U.S.A. and other countries.SQTP is a service mark of Microchip Technology Incorporated in the U.S.A.All other trademarks mentioned herein are property of their respective companies.© 2008, Microchip Technology Incorporated. All Rights Reserved.