Manual Ccs Pic
Manual Ccs Pic
PCD
May 2015
ALL RIGHTS RESERVED.
Copyright Custom Computer Services, Inc. 2015
Table of Contents
Overview ........................................................................................................................................... 1
C Compiler ..................................................................................................................................... 1
PCD ............................................................................................................................................... 1
Technical Support .......................................................................................................................... 1
Directories ..................................................................................................................................... 2
File Formats ................................................................................................................................... 2
Invoking the Command Line Compiler ........................................................................................... 4
PCW Overview .............................................................................................................................. 6
Menu .............................................................................................................................................. 7
Editor Tabs .................................................................................................................................... 7
Slide Out Windows ........................................................................................................................ 7
Editor ............................................................................................................................................. 8
Debugging Windows ...................................................................................................................... 8
Status Bar ...................................................................................................................................... 9
Output Messages........................................................................................................................... 9
Program Syntax .............................................................................................................................. 10
Overall Structure .......................................................................................................................... 10
Comment ..................................................................................................................................... 10
Trigraph Sequences .................................................................................................................... 12
Multiple Project Files.................................................................................................................... 12
Multiple Compilation Units ........................................................................................................... 13
Full Example Program ................................................................................................................. 13
Statements ...................................................................................................................................... 16
Statements .................................................................................................................................. 16
if ................................................................................................................................................... 17
while ............................................................................................................................................ 17
do-while ....................................................................................................................................... 18
for ................................................................................................................................................ 18
switch........................................................................................................................................... 19
return ........................................................................................................................................... 19
goto.............................................................................................................................................. 20
label ............................................................................................................................................. 20
break............................................................................................................................................ 20
continue ....................................................................................................................................... 21
expr.............................................................................................................................................. 21
;.................................................................................................................................................... 21
stmt .............................................................................................................................................. 22
Expressions..................................................................................................................................... 23
Constants .................................................................................................................................... 23
Identifiers ..................................................................................................................................... 24
Operators ..................................................................................................................................... 24
Operator Precedence .................................................................................................................. 26
Data Definitions ............................................................................................................................... 28
Data Definitions ........................................................................................................................... 28
Type Specifiers ............................................................................................................................ 29
ii
Table of Contents
Type Qualifiers............................................................................................................................. 30
Enumerated Types ...................................................................................................................... 31
Structures and Unions ................................................................................................................. 31
typedef ......................................................................................................................................... 33
Non-RAM Data Definitions ........................................................................................................... 33
Using Program Memory for Data ................................................................................................. 35
Named Registers ......................................................................................................................... 37
PreProcessor .................................................................................................................................. 38
PRE-PROCESSOR DIRECTORY ............................................................................................... 38
__address__ ................................................................................................................................ 40
_attribute_x .................................................................................................................................. 40
#asm #endasm #asm asis ........................................................................................................... 41
#bank_dma .................................................................................................................................. 49
#bankx ......................................................................................................................................... 50
#banky ......................................................................................................................................... 50
#bit ............................................................................................................................................... 51
__buildcount__ ............................................................................................................................ 52
#build ........................................................................................................................................... 52
#byte ............................................................................................................................................ 53
#case ........................................................................................................................................... 54
_date_.......................................................................................................................................... 55
#define ......................................................................................................................................... 55
definedinc .................................................................................................................................... 56
#device ........................................................................................................................................ 57
_device_ ...................................................................................................................................... 59
#if expr #else #elif #endif ............................................................................................................. 60
#error ........................................................................................................................................... 61
#export (options) .......................................................................................................................... 61
__file__ ........................................................................................................................................ 63
__filename__ ............................................................................................................................... 63
#fill_rom ....................................................................................................................................... 63
#fuses .......................................................................................................................................... 64
#hexcomment .............................................................................................................................. 65
#id ................................................................................................................................................ 65
#ifdef #ifndef #else #elif #endif .................................................................................................... 66
#ignore_warnings ........................................................................................................................ 67
#import (options) .......................................................................................................................... 67
#include ....................................................................................................................................... 68
#inline .......................................................................................................................................... 69
#int_xxxx ...................................................................................................................................... 70
__line__ ....................................................................................................................................... 73
#list .............................................................................................................................................. 74
#line ............................................................................................................................................. 74
#locate ......................................................................................................................................... 75
#module ....................................................................................................................................... 76
#nolist .......................................................................................................................................... 77
#ocs ............................................................................................................................................. 77
#opt.............................................................................................................................................. 78
iii
PCD_May 2015
#org ............................................................................................................................................. 78
#pin_select .................................................................................................................................. 80
__pcd__ ....................................................................................................................................... 84
#pragma ...................................................................................................................................... 85
#profile ......................................................................................................................................... 85
#recursive .................................................................................................................................... 86
#reserve....................................................................................................................................... 87
#rom ............................................................................................................................................ 87
#separate..................................................................................................................................... 88
#serialize ..................................................................................................................................... 89
#task ............................................................................................................................................ 91
__time__ ...................................................................................................................................... 92
#type ............................................................................................................................................ 92
#undef.......................................................................................................................................... 94
_unicode ...................................................................................................................................... 95
#use capture ................................................................................................................................ 96
#use delay ................................................................................................................................... 98
#use dynamic_memory................................................................................................................ 98
#use fast_io ................................................................................................................................. 99
#use fixed_io ............................................................................................................................... 99
#use i2c ..................................................................................................................................... 100
#use profile() .............................................................................................................................. 101
#use pwm .................................................................................................................................. 102
#use rs232 ................................................................................................................................. 104
#use rtos .................................................................................................................................... 108
#use spi ..................................................................................................................................... 109
#use standard_io ....................................................................................................................... 111
#use timer .................................................................................................................................. 112
#use touchpad ........................................................................................................................... 113
#warning .................................................................................................................................... 114
#word ......................................................................................................................................... 115
#zero_ram ................................................................................................................................. 116
Built-in Functions ........................................................................................................................... 117
BUILT-IN FUNCTIONS .............................................................................................................. 117
abs( ) ......................................................................................................................................... 125
sin( ) cos( ) tan( ) asin( ) acos() atan() sinh() cosh() tanh() atan2() ............................................ 125
adc_done( ) adc_done2( ) ......................................................................................................... 127
assert( ) ..................................................................................................................................... 127
atoe............................................................................................................................................ 128
atof( ) atof48( ) atof64( )............................................................................................................. 129
strtof48() .................................................................................................................................... 129
pin_select() ................................................................................................................................ 130
atoi( ) atol( ) atoi32( ) ................................................................................................................. 131
atol32() atoi48( ) atoi64( ) .......................................................................................................... 131
at_clear_interrupts( ).................................................................................................................. 132
at_disable_interrupts( ) .............................................................................................................. 133
at_enable_interrupts( )............................................................................................................... 133
at_get_capture( ) ....................................................................................................................... 134
iv
Table of Contents
at_get_missing_pulse_delay( ) .................................................................................................. 135
at_get_period( ) ......................................................................................................................... 135
at_get_phase_counter( )............................................................................................................ 136
at_get_resolution( ) .................................................................................................................... 137
at_get_set_point( ) ..................................................................................................................... 137
at_get_set_point_error( ) ........................................................................................................... 138
at_get_status( ) .......................................................................................................................... 138
at_interrupt_active( ) .................................................................................................................. 139
at_set_compare_time( ) ............................................................................................................. 140
at_set_missing_pulse_delay( ) .................................................................................................. 141
at_set_resolution( ) .................................................................................................................... 141
at_set_set_point( ) ..................................................................................................................... 142
at_setup_cc( ) ............................................................................................................................ 143
bit_clear( ) .................................................................................................................................. 144
bit_first( ).................................................................................................................................... 144
bit_last( ) .................................................................................................................................... 145
bit_set( )..................................................................................................................................... 145
bit_test( ).................................................................................................................................... 146
bsearch( ) .................................................................................................................................. 147
calloc( ) ...................................................................................................................................... 148
ceil( ) .......................................................................................................................................... 148
clear_interrupt( ) ........................................................................................................................ 149
cog_status( ) .............................................................................................................................. 149
cog_restart( ) ............................................................................................................................. 150
crc_calc( ) .................................................................................................................................. 150
crc_calc8( ) ................................................................................................................................ 150
crc_calc16( ) .............................................................................................................................. 150
crc_calc32( ) .............................................................................................................................. 150
crc_init(mode) ............................................................................................................................ 151
cwg_status( ) ............................................................................................................................. 152
cwg_restart( ) ............................................................................................................................. 153
dac_write( ) ................................................................................................................................ 153
dci_data_received( ) .................................................................................................................. 154
dci_read( ) ................................................................................................................................. 154
dci_start( ) .................................................................................................................................. 155
dci_transmit_ready( ) ................................................................................................................. 156
dci_write( ) ................................................................................................................................. 157
delay_cycles( ) ........................................................................................................................... 157
delay_ms( ) ................................................................................................................................ 158
delay_us( ) ................................................................................................................................. 159
disable_interrupts( ) ................................................................................................................... 160
div( )........................................................................................................................................... 161
ldiv( ) .......................................................................................................................................... 161
dma_start( ) ............................................................................................................................... 162
dma_status( ) ............................................................................................................................. 163
enable_interrupts( ).................................................................................................................... 163
erase_program_memory ........................................................................................................... 164
ext_int_edge( ) ........................................................................................................................... 165
v
PCD_May 2015
fabs( ) ........................................................................................................................................ 166
getc( ) getch( ) getchar( ) fgetc( ) ............................................................................................ 166
gets( ) fgets( ) ............................................................................................................................ 167
floor( ) ........................................................................................................................................ 168
fmod( ) ....................................................................................................................................... 168
printf( ) fprintf( ) ......................................................................................................................... 169
putc( ) putchar( ) fputc( ) .......................................................................................................... 171
puts( ) fputs( ) ........................................................................................................................... 172
free( ) ......................................................................................................................................... 172
frexp( ) ....................................................................................................................................... 173
scanf( )....................................................................................................................................... 174
get_capture( ) ............................................................................................................................ 176
get_capture( ) ............................................................................................................................ 177
get_capture_ccp1( ) get_capture_ccp2( ) get_capture_ccp3( ) get_capture_ccp4(
) get_capture_ccp5( )................................................................................................................ 177
get_capture32_ccp1( ) get_capture32_ccp2( ) get_capture32_ccp3( )
get_capture32_ccp4( ) get_capture32_ccp5( ) ......................................................................... 179
get_capture_event()................................................................................................................... 180
get_capture_time()..................................................................................................................... 181
get_capture32() ......................................................................................................................... 181
get_hspwm_capture( ) ............................................................................................................... 182
get_motor_pwm_count( ) ........................................................................................................... 183
get_nco_accumulator( ) ............................................................................................................. 183
get_nco_inc_value( ) ................................................................................................................. 184
get_ticks( ) ................................................................................................................................. 184
get_timerA( ) .............................................................................................................................. 185
get_timerB( ) .............................................................................................................................. 185
get_timerx( ) .............................................................................................................................. 186
get_timerxy( ) ............................................................................................................................. 187
get_timer_ccp1( ) get_timer_ccp2( ) get_timer_ccp3( ) get_timer_ccp4( )
get_timer_ccp5( ) ....................................................................................................................... 187
get_tris_x( ) ................................................................................................................................ 189
getc( ) getch( ) getchar( ) fgetc( ) ............................................................................................ 189
getenv( ) .................................................................................................................................... 190
gets( ) fgets( ) ............................................................................................................................ 195
goto_address( ).......................................................................................................................... 196
high_speed_adc_done( ) ........................................................................................................... 197
i2c_init( ) .................................................................................................................................... 198
i2c_isr_state( ) ........................................................................................................................... 198
i2c_poll( ) ................................................................................................................................... 199
i2c_read( ) ................................................................................................................................. 200
i2c_slaveaddr( ) ......................................................................................................................... 201
i2c_speed( ) ............................................................................................................................... 201
i2c_start( ) .................................................................................................................................. 202
i2c_stop( ) .................................................................................................................................. 203
i2c_write( ) ................................................................................................................................. 203
input( ) ....................................................................................................................................... 204
input_change_x( ) ...................................................................................................................... 205
vi
Table of Contents
input_state( ) .............................................................................................................................. 206
input_x( ) .................................................................................................................................... 206
interrupt_active( ) ....................................................................................................................... 207
isalnum(char) isalpha(char) ...................................................................................................... 208
iscntrl(x) isdigit(char)................................................................................................................. 208
isgraph(x) islower(char) isspace(char) isupper(char) isxdigit(char) isprint(x)
ispunct(x) ................................................................................................................................... 208
isamong( ) .................................................................................................................................. 209
itoa( ) ......................................................................................................................................... 210
kbhit( )........................................................................................................................................ 211
label_address( ) ......................................................................................................................... 212
labs( )......................................................................................................................................... 212
ldexp( ) ....................................................................................................................................... 213
log( ) .......................................................................................................................................... 213
log10( ) ...................................................................................................................................... 214
longjmp( ) ................................................................................................................................... 215
make8( ) .................................................................................................................................... 215
make16( ) .................................................................................................................................. 216
make32( ) .................................................................................................................................. 216
malloc( ) ..................................................................................................................................... 217
memcpy( ) memmove( )............................................................................................................. 218
memset( ) .................................................................................................................................. 218
modf( ) ....................................................................................................................................... 219
_mul( ) ....................................................................................................................................... 220
nargs( ) ...................................................................................................................................... 220
offsetof( ) offsetofbit( )................................................................................................................ 221
output_x( ) ................................................................................................................................. 222
output_bit( ) ............................................................................................................................... 223
output_drive( ) ........................................................................................................................... 224
output_float( ) ............................................................................................................................ 224
output_high( ) ............................................................................................................................ 225
output_low( ) .............................................................................................................................. 226
output_toggle( ).......................................................................................................................... 227
perror( )...................................................................................................................................... 227
pid_busy( ) ................................................................................................................................. 228
pid_get_result( ) ......................................................................................................................... 228
pid_read( ) ................................................................................................................................. 229
pid_write( ) ................................................................................................................................. 230
pmp_address(address) .............................................................................................................. 231
pmp_output_full( ) pmp_input_full( ) pmp_overflow( ) pmp_error( ) pmp_timeout(
) ................................................................................................................................................. 232
pmp_read( ) ............................................................................................................................... 233
pmp_write( ) ............................................................................................................................... 234
port_x_pullups ( ) ....................................................................................................................... 235
pow( ) pwr( ) .............................................................................................................................. 236
printf( ) fprintf( ) .......................................................................................................................... 236
profileout() ................................................................................................................................. 238
psp_output_full( ) psp_input_full( ) psp_overflow( ) ................................................................. 239
vii
PCD_May 2015
psp_read( ) ................................................................................................................................ 240
psp_write( ) ................................................................................................................................ 241
putc( ) putchar( ) fputc( ) .......................................................................................................... 241
putc_send( ); .............................................................................................................................. 242
fputc_send( ); ............................................................................................................................. 242
puts( ) fputs( ) ........................................................................................................................... 243
pwm_off() ................................................................................................................................... 244
pwm_on() ................................................................................................................................... 244
pwm_set_duty() ......................................................................................................................... 245
pwm_set_duty_percent.............................................................................................................. 245
pwm_set_frequency................................................................................................................... 246
qei_get_count( ) ......................................................................................................................... 247
qei_set_count( ) ......................................................................................................................... 247
qei_status( ) ............................................................................................................................... 248
qsort( ) ....................................................................................................................................... 248
rand( ) ........................................................................................................................................ 249
rcv_buffer_bytes( ) ..................................................................................................................... 250
rcv_buffer_full( ) ......................................................................................................................... 250
read_adc( ) read_adc2( ) .......................................................................................................... 251
read_configuration_memory( ) ................................................................................................... 252
read_eeprom( ) .......................................................................................................................... 253
read_extended_ram( ) ............................................................................................................... 253
read_program_memory( ) .......................................................................................................... 254
read_high_speed_adc( ) ............................................................................................................ 255
read_rom_memory( ) ................................................................................................................. 257
read_sd_adc( )........................................................................................................................... 257
realloc( )..................................................................................................................................... 258
release_io() ................................................................................................................................ 259
reset_cpu( ) ............................................................................................................................... 259
restart_cause( ).......................................................................................................................... 260
restart_wdt( ) ............................................................................................................................. 260
rotate_left( ) ............................................................................................................................... 261
rotate_right( ) ............................................................................................................................. 262
rtc_alarm_read( ) ....................................................................................................................... 263
rtc_alarm_write( ) ....................................................................................................................... 263
rtc_read( ) .................................................................................................................................. 264
rtc_write( ).................................................................................................................................. 265
rtos_await( ) ............................................................................................................................... 265
rtos_disable( ) ............................................................................................................................ 266
rtos_enable( ) ............................................................................................................................ 266
rtos_msg_poll( ) ......................................................................................................................... 267
rtos_msg_read( ) ....................................................................................................................... 267
rtos_msg_send( ) ....................................................................................................................... 268
rtos_overrun( ) ........................................................................................................................... 268
rtos_run( ) .................................................................................................................................. 269
rtos_signal( ) .............................................................................................................................. 270
rtos_stats( ) ................................................................................................................................ 270
rtos_terminate( ) ........................................................................................................................ 271
viii
Table of Contents
rtos_wait( ) ................................................................................................................................. 271
rtos_yield( ) ................................................................................................................................ 272
set_adc_channel( ) .................................................................................................................... 273
set_adc_channel2( ) .................................................................................................................. 273
set_analog_pins( ) ..................................................................................................................... 273
scanf( )....................................................................................................................................... 274
set_ccp1_compare_time( ) set_ccp2_compare_time( ) set_ccp3_compare_time( )
set_ccp4_compare_time( ) set_ccp5_compare_time( ) ............................................................. 277
set_cog_blanking( ) ................................................................................................................... 278
set_cog_dead_band( ) ............................................................................................................... 279
set_cog_phase( ) ....................................................................................................................... 280
set_compare_time( ) .................................................................................................................. 280
set_hspwm_duty( ) .................................................................................................................... 281
set_hspwm_event( ) .................................................................................................................. 282
set_hspwm_override( ) .............................................................................................................. 283
set_hspwm_phase( ) ................................................................................................................. 283
set_motor_pwm_duty( ) ............................................................................................................. 284
set_motor_pwm_event( ) ........................................................................................................... 285
set_motor_unit( )........................................................................................................................ 285
set_nco_inc_value( ).................................................................................................................. 286
set_pullup( ) ............................................................................................................................... 287
set_pwm1_duty( ) set_pwm2_duty( ) set_pwm3_duty( ) set_pwm4_duty( )
set_pwm5_duty( ) ...................................................................................................................... 288
set_rtcc( ) set_timer0( ) set_timer1( ) set_timer2( ) set_timer3( ) set_timer4( )
set_timer5( ) .............................................................................................................................. 290
set_ticks( ) ................................................................................................................................. 291
setup_sd_adc_calibration( ) ....................................................................................................... 291
set_sd_adc_channel( ) .............................................................................................................. 292
set_timerA( ) .............................................................................................................................. 293
set_timerB( ) .............................................................................................................................. 293
set_timerx( ) ............................................................................................................................... 294
set_timerxy( ) ............................................................................................................................. 294
set_rtcc( ) set_timer0( ) set_timer1( ) set_timer2( ) set_timer3( ) set_timer4( )
set_timer5( ) .............................................................................................................................. 295
set_timer_ccp1( ) set_timer_ccp2( ) set_timer_ccp3( ) set_timer_ccp4( )
set_timer_ccp5( ) ....................................................................................................................... 296
set_timer_period_ccp1( ) set_timer_period_ccp2( ) set_timer_period_ccp3( )
set_timer_period_ccp4( ) set_timer_period_ccp5( ).................................................................. 297
set_tris_x( ) ................................................................................................................................ 299
set_uart_speed( )....................................................................................................................... 299
setjmp( )..................................................................................................................................... 300
setup_adc(mode) ....................................................................................................................... 301
setup_adc2(mode) ..................................................................................................................... 301
setup_adc_ports( ) ..................................................................................................................... 302
setup_adc_ports2( ) ................................................................................................................... 302
setup_adc_reference( ).............................................................................................................. 303
setup_at( ) ................................................................................................................................. 303
setup_capture( )......................................................................................................................... 304
ix
PCD_May 2015
setup_ccp1( ) setup_ccp2( ) setup_ccp3( ) setup_ccp4( ) setup_ccp5( )
setup_ccp6( ) ............................................................................................................................. 305
setup_clc1() setup_clc2() setup_clc3() setup_clc4() ............................................................... 307
setup_comparator( ) .................................................................................................................. 308
setup_compare( )....................................................................................................................... 309
setup_crc(mode) ........................................................................................................................ 309
setup_cog( ) ............................................................................................................................... 310
setup_crc( ) ................................................................................................................................ 311
setup_cwg( ) .............................................................................................................................. 312
setup_dac( ) ............................................................................................................................... 313
setup_dci( ) ................................................................................................................................ 314
setup_dma( ) ............................................................................................................................. 315
setup_high_speed_adc( ) .......................................................................................................... 315
setup_high_speed_adc_pair( ) .................................................................................................. 316
setup_hspwm_blanking( ) .......................................................................................................... 317
setup_hspwm_chop_clock( ) ..................................................................................................... 318
setup_hspwm_trigger( ) ............................................................................................................. 319
setup_hspwm_unit( ) ................................................................................................................. 320
setup_hspwm( ) ......................................................................................................................... 321
setup_hspwm_unit_chop_clock( ).............................................................................................. 321
setup_low_volt_detect( ) ............................................................................................................ 323
setup_motor_pwm( ) .................................................................................................................. 323
setup_oscillator( ) ...................................................................................................................... 324
setup_pid( )................................................................................................................................ 325
setup_pmp(option,address_mask)............................................................................................. 326
setup_power_pwm_pins( ) ......................................................................................................... 327
setup_psp(option,address_mask) .............................................................................................. 328
setup_pwm1( ) setup_pwm2( ) setup_pwm3( ) setup_pwm4( ) .............................................. 329
setup_qei( ) ................................................................................................................................ 330
setup_rtc( ) ................................................................................................................................ 331
setup_rtc_alarm( )...................................................................................................................... 331
setup_sd_adc( ) ......................................................................................................................... 332
setup_smtx( ) ............................................................................................................................. 333
setup_spi( ) setup_spi2( ) .......................................................................................................... 333
setup_timerx( ) ........................................................................................................................... 334
setup_timer_A( ) ........................................................................................................................ 336
setup_timer_B( ) ........................................................................................................................ 336
setup_timer_0( )......................................................................................................................... 337
setup_timer_1( )......................................................................................................................... 338
setup_timer_2( )......................................................................................................................... 338
setup_timer_3( )......................................................................................................................... 339
setup_timer_4( )......................................................................................................................... 340
setup_timer_5( )......................................................................................................................... 341
setup_uart( ) .............................................................................................................................. 341
setup_vref( ) .............................................................................................................................. 342
setup_wdt( ) ............................................................................................................................... 343
setup_zdc( ) ............................................................................................................................... 344
shift_left( ) .................................................................................................................................. 344
x
Table of Contents
shift_right( ) ................................................................................................................................ 345
sleep( )....................................................................................................................................... 346
smtx_read( ) .............................................................................................................................. 347
smtx_reset_timer( ) .................................................................................................................... 348
smtx_start( ) ............................................................................................................................... 349
smtx_status( ) ............................................................................................................................ 349
smtx_stop( ) ............................................................................................................................... 350
smtx_write( ) .............................................................................................................................. 350
smtx_update( ) ........................................................................................................................... 351
spi_data_is_in( ) spi_data_is_in2( ) .......................................................................................... 352
spi_init() ..................................................................................................................................... 352
spi_prewrite(data); ..................................................................................................................... 353
spi_read( ) spi_read2( ) .......................................................................................................... 353
spi_read3( ) ............................................................................................................................... 353
spi_read4( ) ............................................................................................................................... 353
spi_read_16() ............................................................................................................................ 354
spi_read2_16() .......................................................................................................................... 354
spi_read3_16() .......................................................................................................................... 354
spi_read4_16() .......................................................................................................................... 354
spi_speed .................................................................................................................................. 355
spi_write( ) spi_write2( )............................................................................................................ 356
spi_write3( ) ............................................................................................................................... 356
spi_write4( ) ............................................................................................................................... 356
spi_xfer( ) ................................................................................................................................... 357
SPII_XFER_IN() ........................................................................................................................ 357
sprintf( ) ..................................................................................................................................... 358
sqrt( ) ......................................................................................................................................... 359
srand( ) ...................................................................................................................................... 359
STANDARD STRING FUNCTIONS( ) memchr( ) memcmp( ) strcat( ) strchr( )
strcmp( ) strcoll( ) strcspn( ) strerror( ) stricmp( ) strlen( ) strlwr( ) strncat( )
strncmp( ) strncpy( ) strpbrk( ) strrchr( ) strspn( ) strstr( ) strxfrm( ) .......................................... 360
strcpy( ) strcopy( ) ...................................................................................................................... 362
strtod( ) strtof( ) strtof48( ) ........................................................................................................ 362
strtok( ) ...................................................................................................................................... 363
strtol( ) ....................................................................................................................................... 364
strtoul( ) ..................................................................................................................................... 365
swap( ) ....................................................................................................................................... 366
tolower( ) toupper( ) ................................................................................................................... 366
touchpad_getc( ) ........................................................................................................................ 367
touchpad_hit( ) ........................................................................................................................... 368
touchpad_state( ) ....................................................................................................................... 369
tx_buffer_available() .................................................................................................................. 370
tx_buffer_bytes() ........................................................................................................................ 371
tx_buffer_full( ) ........................................................................................................................... 371
va_arg( ) .................................................................................................................................... 372
va_end( ) ................................................................................................................................... 373
va_start ...................................................................................................................................... 374
write_configuration_memory( ) .................................................................................................. 374
xi
PCD_May 2015
write_eeprom( ).......................................................................................................................... 375
write_extended_ram( ) ............................................................................................................... 376
write_program_memory( ) ......................................................................................................... 377
zdc_status( ) .............................................................................................................................. 378
Standard C Include Files ............................................................................................................... 379
errno.h ....................................................................................................................................... 379
float.h ......................................................................................................................................... 379
limits.h ....................................................................................................................................... 380
locale.h ...................................................................................................................................... 381
setjmp.h ..................................................................................................................................... 381
stddef.h ...................................................................................................................................... 381
stdio.h ........................................................................................................................................ 381
stdlib.h ....................................................................................................................................... 382
Software License Agreement ........................................................................................................ 383
SOFTWARE LICENSE AGREEMENT ...................................................................................... 383
xii
OVERVIEW
C Compiler
PCD Overview
Technical Support
Directories
File Formats
Invoking the Command Line Compiler
PCD
PCD is a C Compiler for Microchip's 24bit opcode family of microcontrollers, which include the
dsPIC30, dsPIC33 and PIC24 families. The compiler is specifically designed to meet the unique
needs of the dsPIC microcontroller. This allows developers to quickly design applications
software in a more readable, high-level language.
The compiler can efficiently implement normal C constructs, input/output operations, and bit
twiddling operations. All normal C data types are supported along with special built in functions to
perform common functions in the MPU with ease.
Extended constructs like bit arrays, multiple address space handling and effective implementation
of constant data in Rom make code generation very effective.
Technical Support
Compiler, software, and driver updates are available to download at:
http://www.ccsinfo.com/download
Compilers come with 30 or 60 days of download rights with the initial purchase. One year
maintenance plans may be purchased for access to updates as released.
PCD_May 2015
The intent of new releases is to provide up-to-date support with greater ease of use and minimal, if
any, transition difficulty.
To ensure any problem that may occur is corrected quickly and diligently, it is recommended to
send an email to: [email protected] or use the Technical Support Wizard in PCW. Include the
version of the compiler, an outline of the problem and attach any files with the email request. CCS
strives to answer technical support timely and thoroughly.
Technical Support is available by phone during business hours for urgent needs or if email
responses are not adequate. Please call 262-522-6500 x32.
Directories
The compiler will search the following directories for Include files.
File Formats
.c
.h
2
Overview
.pjt
.ccspjt
.lst
.sym
.sta
.tre
W5=W4>>8
This is the symbol map which shows each register location and what program variables
are stored in each location.
The statistics file shows the RAM, ROM, and STACK usage. It provides information on
the source codes structural and textual complexities using Halstead and McCabe
metrics.
The tree file shows the call tree. It details each function and what functions it calls along
with the ROM and RAM usage for each function.
The compiler generates standard HEX files that are compatible with all programmers.
.hex
The compiler can output 8-bet hex, 16-bit hex, and binary files.
This is a binary containing machine code and debugging information.
.cof
.cod
.rtf
.rvf
.dgr
.esym
.xsym
.o
.osym
The debug files may be output as Microchip .COD file for MPLAB 1-5, Advanced
Transdata .MAP file, expanded .COD file for CCS debugging or MPLAB 6 and up .xx
.COF file. All file formats and extensions may be selected via Options File Associations
option in Windows IDE.
This is a binary file containing debug information.
The output of the Documentation Generator is exported in a Rich Text File format which
can be viewed using the RTF editor or Wordpad.
The Rich View Format is used by the RTF Editor within the IDE to view the Rich Text
File.
The .DGR file is the output of the flowchart maker.
These files are generated for the IDE users. The file contains Identifiers and Comment
information. This data can be used for automatic documentation generation and for the
IDE helpers.
Relocatable object file
This file is generated when the compiler is set to export a relocatable object file. This file
3
PCD_May 2015
is a .sym file for just the one unit.
.err
Compiler error file
.ccsload used to link Windows 8 apps to CCSLoad
.ccssiow used to link Windows 8 apps to Serial Port Monitor
CCSC
[options]
[cfilename]
Valid options:
+FB
Select PCB (12 bit)
Do
-Dnot create debug file
+FM
Select PCM (14 bit)
+DS
Standard .COD format debug file
+FH
Select PCH (PIC18XXX)
+DM
.MAP format debug file
+Yx
Optimization level x (0-9)
+DC
Expanded .COD format debug file
+FD
Select PCD
+DF
Enables the output of an COFF debug file.
(dsPIC30/dsPIC33/PIC24)
+FS
Select SXC (SX)
+EO
Old error file format
+ES
Standard error file
-T
Do not generate a tree file
+T
Create call tree (.TRE)
-A
Do not create stats file (.STA)
+A
Create stats file (.STA)
-EW
Suppress warnings (use with +EA)
+EW
Show warning messages
-E
Only show first error
+EA
Show all error messages
+EX
Error/warning message format uses GCC's "brief
and all warnings
format" (compatible with GCC editor environments)
The xxx in the following are optional. If included it sets the file extension:
+LNxxx
Normal list file
+O8xxx
8-bit Intel HEX output file
+LSxxx
MPASM format list file
+OWxxx
16-bit Intel HEX output file
+LOxxx
Old MPASM list file
+OBxxx
Binary output file
+LYxxx
Symbolic list file
-O
Do not create object file
-L
Do not create list file
+P
+Pxx
+PN
+PE
+Z
+DF
I+="..."
I="..."
Overview
include file paths.
-P
+M
-M
+J
-J
+ICD
#xxx="yyy"
+Gxxx="yyy
"
+?
-?
Same as #xxx="yyy"
+STDOUT
+SETUP
sourceline=
+V
+Q
A / character may be used in place of a + character. The default options are as follows:
+FM +ES +J +DC +Y9 -T -A +M +LNlst +O8hex -P -Z
If @filename appears on the CCSC command line, command line options will be read from the
specified file. Parameters may appear on multiple lines in the file.
If the file CCSC.INI exists in the same directory as CCSC.EXE, then command line parameters are
read from that file before they are processed on the command line.
Examples:
CCSC +FM C:\PICSTUFF\TEST.C
CCSC +FM +P +T TEST.C
PCD_May 2015
PCW Overview
The PCW IDE provides the user an easy to use editor and environment for
developing microcontroller applications. The IDE comprises of many components,
which are summarized below. For more information and details, use the Help>PCW
in the compiler..
Many of these windows can be re-arranged and docked into different positions.
Overview
Menu
All of the IDE's functions are on the main menu. The main
menu is divided into separate sections, click on a section title
('Edit', 'Search', etc) to change the section. Double clicking on
the section, or clicking on the chevron on the right, will cause
the menu to minimize and take less space.
Editor Tabs
All of the open files are listed here. The active file, which is the
file currently being edited, is given a different highlight than the
other files. Clicking on the X on the right closes the active file.
Right clicking on a tab gives a menu of useful actions for that
file.
PCD_May 2015
Editor
The editor is the main work area of the IDE and the place
where the user enters and edits source code. Right clicking in
this area gives a menu of useful actions for the code being
edited.
Debugging Windows
Debugger control
is done in the
debugging
windows. These
windows allow
you set
breakpoints,
single step, watch
variables and
more.
Overview
Status Bar
The status bar gives the user helpful information like the cursor
position, project open and file being edited.
Output Messages
Output messages are displayed here. This includes messages
from the compiler during a build, messages from the
programmer tool during programming or the results from find
and searching.
PROGRAM SYNTAX
Overall Structure
A program is made up of the following four elements in a file:
Comment
Pre-Processor Directive
Data Definition
Function Definition
Statements
Expressions
Every C program must contain a main function which is the starting point of the program execution.
The program can be split into multiple functions according to the their purpose and the functions
could be called from main or the sub-functions. In a large project functions can also be placed in
different C files or header files that can be included in the main C file to group the related functions
by their category. CCS C also requires to include the appropriate device file using #include
directive to include the device specific functionality. There are also some preprocessor directives
like #fuses to specify the fuses for the chip and #use delay to specify the clock speed. The
functions contain the data declarations,definitions,statements and expressions. The compiler also
provides a large number of standard C libraries as well as other device drivers that can be included
and used in the programs. CCS also provides a large number of built-in functions to access the
various peripherals included in the PIC microcontroller.
Comment
Comments Standard Comments
A comment may appear anywhere within a file except within a quoted string. Characters between /*
and */ are ignored. Characters after a // up to the end of the line are ignored.
Comments for Documentation Generator
The compiler recognizes comments in the source code based on certain markups. The compiler
recognizes these special types of comments that can be later exported for use in the
documentation generator. The documentation generator utility uses a user selectable template to
export these comments and create a formatted output document in Rich Text File Format. This
utility is only available in the IDE version of the compiler. The source code markups are as follows.
Global Comments
These are named comments that appear at the top of your source code. The comment names are
case sensitive and they must match the case used in the documentation template.
For example:
10
Program Syntax
//*PURPOSE This program implements a Bootloader.
//*AUTHOR John Doe
A '//' followed by an * will tell the compiler that the keyword which follows it will be the named
comment. The actual comment that follows it will be exported as a paragraph to the documentation
generator.
Multiple line comments can be specified by adding a : after the *, so the compiler will not
concatenate the comments that follow. For example:
/**:CHANGES
05/16/06 Added PWM loop
05/27.06 Fixed Flashing problem
*/
Variable Comments
A variable comment is a comment that appears immediately after a variable declaration. For
example:
int seconds; // Number of seconds since last entry
long day, // Current day of the month, /* Current Month */
long year;
// Year
Function Comments
A function comment is a comment that appears just before a function declaration. For example:
// The following function initializes outputs
void function_foo()
{
init_outputs();
}
11
PCD_May 2015
Trigraph Sequences
The compiler accepts three character sequences instead of some special
characters not available on all keyboards as follows:
Sequence
Same as
??=
#
??(
[
??/
\
??)
]
??'
^
??<
{
??!
|
??>
}
??~
main.c
x.c
y.c
z.c
#include <x.h>
#include <y.h>
#include <z.h>
In this example there are 8 files and one compilation unit. Main.c is the only file compiled.
Note that the #module directive can be used in any include file to limit the visibility of the symbol in
that file.
To separately compile your files see the section "multiple compilation units".
12
Program Syntax
//////////////////////////////////
/////////////////////
/// This program displays the min
and max of 30,
///
/// comments that explains what
the program does, ///
/// and A/D samples over the RS232 interface.
///
//////////////////////////////////
/////////////////////
#include <16F887.h>
//
preprocessor directive that
// selects the chip PIC16F887
#fuses NOPROTECT
// Code
protection turned off
#use delay(crystal=20mhz)
// preprocessor
directive that
// specifies the clock type
and speed
13
PCD_May 2015
Program Syntax
min=value;
if(value>max)
// Find largest
sample
max=value;
}
printf("\n\rMin: %2X
%2X\n\r",min,max);
} while (TRUE);
}
Max:
15
STATEMENTS
Statements
STATEMENT
if (expr) stmt; [else stmt;]
Example
if (x==25)
x=0;
else
x=x+1;
while (get_rtcc()!=0)
putc(n);
do {
putc(c=getc());
} while (c!=0);
for (i=1;i<=10;++i)
printf(%u\r\n,i);
switch (cmd) {
case 0: printf(cmd 0);break;
case 1: printf(cmd 1);break;
default: printf(bad cmd);break;
}
return (5);
goto loop;
loop: i++;
break;
continue;
i=1;
;
{a=1;
b=1;}
int i;
16
Statements
if
if-else
The if-else statement is used to make decisions.
The syntax is:
if (expr)
stmt-1;
[else
stmt-2;]
The expression is evaluated; if it is true stmt-1 is done. If it is false then stmt-2 is done.
else-if
This is used to make multi-way decisions.
The syntax is:
if (expr)
stmt;
[else if (expr)
stmt;]
...
[else
stmt;]
The expressions are evaluated in order; if any expression is true, the statement associated with it is
executed and it terminates the chain. If none of the conditions are satisfied the last else part is
executed.
Example:
if (x==25)
x=1;
else
x=x+1;
Also See: Statements
while
While is used as a loop/iteration statement.
The syntax is:
while (expr)
statement
17
PCD_May 2015
The expression is evaluated and the statement is executed until it becomes false in which case the
execution continues after the statement.
Example:
while (get_rtcc()!=0)
putc('n');
Also See: Statements
do-while
do-while: Differs from while and for loop in that the
termination condition is checked at the bottom of the loop
rather than at the top and so the body of the loop is always
executed at least once. The syntax is:
do
statement
while (expr);
The statement is executed; the expr is evaluated. If true, the
same is repeated and when it becomes false the loop
terminates.
Also See: Statements , While
for
For is also used as a loop/iteration statement.
The syntax is:
for (expr1;expr2;expr3)
statement
The expressions are loop control statements. expr1 is the
initialization, expr2 is the termination check and expr3 is reinitialization. Any of them can be omitted.
Example:
for (i=1;i<=10;++i)
printf("%u\r\n",i);
Also See: Statements
18
Statements
switch
Switch is also a special multi-way decision maker.
The syntax is
switch (expr) {
case const1: stmt sequence;
break;
...
[default:stmt]
}
This tests whether the expression matches one of the constant values and branches accordingly.
If none of the cases are satisfied the default case is executed. The break causes an immediate exit,
otherwise control falls through to the next case.
Example:
switch (cmd) {
case 0:printf("cmd 0");
break;
case 1:printf("cmd 1");
break;
default:printf("bad cmd");
break; }
Also See: Statements
return
return
A return statement allows an immediate exit from a switch or a loop or function and also returns a
value.
The syntax is:
return(expr);
Example:
return (5);
Also See: Statements
19
PCD_May 2015
goto
goto
The goto statement cause an unconditional branch to the label.
The syntax is:
goto label;
A label has the same form as a variable name, and is followed by a colon. The goto's
are used sparingly, if at all.
Example:
goto loop;
Also See: Statements
\
label
label
The label a goto jumps to.
The syntax is:
label: stmnt;
Example:
loop: i++;
Also See: Statements
break
break.
The break statement is used to exit out of a control loop. It provides an early exit from
while, for ,do and switch.
The syntax is
break;
It causes the innermost enclosing loop (or switch) to be exited immediately.
Example:
break;
Also See: Statements
20
Statements
continue
The continue statement causes the next iteration of the enclosing loop(While, For,
Do) to begin.
The syntax is:
continue;
It causes the test part to be executed immediately in case of do and while and the
control passes the
re-initialization step in case of for.
Example:
continue;
Also See: Statements
expr
The syntax is:
expr;
Example:
i=1;
Also See: Statements
;
Statement: ;
Example:
;
Also See: Statements
21
PCD_May 2015
stmt
Zero or more semi-colon separated.
The syntax is:
{[stmt]}
Example:
{a=1;
b=1;}
Also See: Statements
22
EXPRESSIONS
Constants
123
Decimal
123L
123LL
0123
Octal
0x123
Hex
0b010010
Binary
123.456
Floating Point
123F
123.4E-5
'x'
Character
'\010'
Octal Character
'\xA5
Hex Character
'\c'
PCD_May 2015
\v
\?
\'
\"
\\
"abcdef"
Identifiers
ABCDE
ID[X]
ID[X][X]
ID.ID
ID->ID
Up to 32 characters beginning with a nonnumeric. Valid characters are A-Z, 0-9 and _
(underscore). By default not case sensitive Use
#CASE to turn on.
Single Subscript
Multiple Subscripts
Structure or union reference
Structure or union reference
Operators
+
+=
[]
&=
&
&
^=
24
Addition Operator
Addition assignment operator, x+=y, is the
same as x=x+y
Array subscrip operator
Bitwise and assignment operator, x&=y, is the
same as x=x&y
Address operator
Bitwise and operator
Bitwise exclusive or assignment operator,
x^=y, is the same as x=x^y
Expressions
^
l=
l
?:
-/=
/
==
>
>=
++
*
!=
<<=
<
<<
<=
&&
!
ll
.
%=
%
*=
*
~
>>=
PCD_May 2015
>>
->
-=
sizeof
Operator Precedence
PIN DESCENDING PRECEDENCE
(expr)
exor++
expr->expr
++expr
expr++
- -expr
!expr
+expr
~expr
(type)expr
*expr
&value
expr*expr
expr+expr
expr<<expr
expr<expr
expr/expr
expr%expr
expr==expr
expr&expr
expr^expr
expr | expr
expr&& expr
expr || expr
expr!=expr
expr-expr
expr>>expr
expr<=expr
expr>expr
lvalue+=expr lvalue-=expr
lvalue*=expr
lvalue/=expr
26
lvalue%=expr
expr.expr
expr - -
Associativity
Left to Right
Left to Right
-expr
Right to Left
Right
sizeof(type)
to Left
Left to Right
expr>=expr
Left to Right
Left to Right
Left to Right
Left to Right
Left to Right
Left to Right
Left to Right
Left to Right
Left to Right
Right
to Left
Right
to Left
Right
to Left
Expressions
lvalue>>=expr
lvalue<<=exp
lvalue&=expr
r
lvalue^=expr
lvalue|=expr
expr, expr
(Operators on the same line are equal in precedence)
Right
to Left
Right
to Left
Left to Right
27
DATA DEFINITIONS
Data Definitions
This section describes what the basic data types and specifiers are and how variables
can be declared using those types. In C all the variables should be declared before
they are used. They can be defined inside a function (local) or outside all functions
(global). This will affect the visibility and life of the variables.
A declaration consists of a type qualifier and a type specifier, and is followed by a list
of one or more variables of that type.
For example:
int a,b,c,d;
mybit e,f;
mybyte g[3][2];
char *h;
colors j;
struct data_record data[10];
static int i;
extern long j;
Variables can also be declared along with the definitions of the special types.
For example:
//are variables of
that type
SEE ALSO:
Type Specifiers/ Basic Types
Type Qualifiers
Enumerated Types
Structures & Unions
typedef
Named Registers
28
Data Definitions
Type Specifiers
Basic Types
TypeSpecifier
Size
Unsigned
int1
1 bit number
0 to 1
int8
8 bit number
0 to 255
int16
16 bit number
0 to 65535
int32
32 bit number
0 to 4294967295
int48
48 bit number
0 to
281474976710655
int64
64 bit number
N/A
32 bit float
-1.5 x 10
-2.9 x 10
39
64 bit float
-5.0 x 10
324
float32
float48
float64
C Standard Type
short
char
int
long
long long
float
double
Range
Signed
N/A
Digits
1/2
-128 to 127
45
2-3
-32768 to 32767
4-5
-2147483648 to 2147483647
-140737488355328 to
140737488355327
-9223372036854775808 to
9223372036854775807
to 3.4 x 10
38
to 1.7 x 10
14-15
18-19
7-8
38
to 1.7 x 10
9-10
11-12
308
15-16
Default Type
signed int8
signed int8
signed int16
signed int32
signed int64
float32
Note: All types by default are signed; however, may be preceded by unsigned or
signed (Except int64 may only be signed) . Short and long may have the keyword INT
following them with no effect. Also see #TYPE to change the default size.
SHORT INT1 is a special type used to generate very efficient code for bit operations
and I/O. Arrays of bits (INT1 or SHORT ) in RAM are now supported. Pointers to
bits are not permitted. The device header files contain defines for BYTE as an int8
and BOOLEAN as an int1.
Integers are stored in little endian format. The LSB is in the lowest address. Float
formats are described in common questions.
29
PCD_May 2015
SEE ALSO: Declarations, Type Qualifiers, Enumerated Types, Structures & Unions,
typedef, Named Registers
Type Qualifiers
Type-Qualifier
static
auto
Variable exists only while the procedure is active. This is the default
and AUTO need not be used.
double
extern
register
_ fixed(n)
unsigned
signed
Data can be negative or positive. This is the default data type if not
specified.
volatile
Tells the compiler optimizer that this variable can be changed at any
point during execution.
const
rom
roml
30
Data Definitions
Built-in basic type. Type void is used to indicate no specific type in
places where a type is required.
void
readonly
_bif
__attribute__
SEE ALSO: Declarations, Type Specifiers, Enumerated Types, Structures & Unions, typedef,
Named Registers
Enumerated Types
enum enumeration type: creates a list of integer constants.
enum
[id]
{ [ id [ = cexpr]] }
SEE ALSO: Declarations, Type Specifiers, Type Qualifiers, Structures & Unions, typedef, Named
Registers
[:bits];
} [id]
31
PCD_May 2015
One or more,
semi-colon
separated
Zero
or more
For example:
struct data_record {
int
int
int
a[2];
b : 2; /*2 bits */
c : 3; /*3 bits*/
int d;
} data_var;
Field Allocation
- Fields are allocated in the order they appear.
- The low bits of a byte are filled first.
- Fields 16 bits and up are aligned to a even byte boundary. Some Bits may by unused.
- No Field will span from an odd byte to an even byte unless the field width is a multiple of 16 bits.
Union type: holds objects of different types and sizes, with
the compiler keeping track of size and alignment
requirements. They provide a way to manipulate different
kinds of data in a single area of storage.
union[*] [id] {
type-qualifier [*] id
One or more,
semi-colon
separated
[:bits];
} [id]
Zero
or more
For example:
union u_tab {
int ival;
long lval;
float fval;
};
32
Data Definitions
typedef
If typedef is used with any of the basic or special types it
creates a new type name that can be used in declarations. The
identifier does not allocate space but rather may be used as a
type specifier in other data definitions.
typedef
For example:
//
to
//
//
to
//
SEE ALSO: Declarations, Type Specifiers, Type Qualifiers, Structures & Unions,
Enumerated Types, Named Registers
PCD_May 2015
Example:
void DataEE_Read(int32 addr, int8 * ram, int bytes) {
int i;
for(i=0;i<bytes;i++,ram++,addr++)
*ram=read_eeprom(addr);
}
void DataEE_Write(int32 addr, int8 * ram, int bytes) {
int i;
for(i=0;i<bytes;i++,ram++,addr++)
write_eeprom(addr,*ram);
}
addressmod (DataEE,DataEE_read,DataEE_write,5,0xff);
// would define a region called DataEE between
// 0x5 and 0xff in the chip data EEprom.
void main (void)
{
int DataEE test;
int x,y;
x=12;
test=x; // writes x to the Data EEPROM
y=test; // Reads the Data EEPROM
}
Note: If the area is defined in RAM then read and write functions are
not required, the variables assigned in the memory region defined by
the addressmod can be treated as a regular variable in all valid
expressions. Any structure or data type can be used with an
34
Data Definitions
addressmod. Pointers can also be made to an addressmod data type.
The #type directive can be used to make this memory region as default
for variable allocations.
The syntax is :
#type default=addressmodname
declarations that
For example:
Type default=emi
addressmod name defined
char buffer[8192];
#include <memoryhog.h>
#type default=
//emi is the
For example:
Placing data into ROM
const int table[16]={0,1,2...15}
The #org preprocessor can be used to place the constant to specified address blocks.
For example:
The constant ID will be at 1C00.
#ORG 0x1C00, 0x1C0F
CONST CHAR ID[10]= {"123456789"};
35
PCD_May 2015
Note: Some extra code will precede the 123456789.
The function label_address can be used to get the address of the constant. The constant variable
can be accessed in the code. This is a great way of storing constant data in large programs.
Variable length constant strings can be stored into program memory.
A special method allows the use of pointers to ROM. This method does not contain extra code at
the start of the structure as does constant.
For example:
char rom commands[] = {put|get|status|shutdown};
ROML may be used instead of ROM if you only to use even memory locations.
The compiler allows a non-standard C feature to implement a constant array of variable length
strings.
The syntax is:
const char id[n] [*] = { "string", "string" ...};
#ROM directive:
Another method is to use #rom to assign data to program memory.
The syntax is:
#rom address = {data, data, , data}
For example:
Places 1,2,3,4 to ROM addresses starting at 0x1000
#rom 0x1000 = {1, 2, 3, 4}
Data Definitions
- Reads count bytes from program memory at address to RAM at dataptr. Every
fourth byte of data is read as 0x00
Named Registers
The CCS C Compiler supports the new syntax for filing a variable at the location of a
processor register. This syntax is being proposed as a C extension for embedded
use. The same functionality is provided with the non-standard #byte, #word, #bit
and #locate.
The syntax is:
register _name type id;
Or
register constant type id;
name is a valid SFR name with an underscore before it.
Examples:
register _status int8 status_reg;
register _T1IF int8 timer_interrupt;
register 0x04 int16 file_select_register;
37
PREPROCESSOR
PRE-PROCESSOR DIRECTORY
Pre-processor directives all begin with a # and are followed by a specific command. Syntax is
dependent on the command. Many commands do not allow other syntactical elements on the
remainder of the line. A table of commands and a description is listed on the previous page.
Several of the pre-processor directives are extensions to standard C. C provides a pre-processor
directive that compilers will accept and ignore or act upon the following data. This implementation
will allow any pre-processor directives to begin with #PRAGMA. To be compatible with other
compilers, this may be used before non-standard features.
Examples:
Both of the following are valid
#INLINE
#PRAGMA INLINE
__address__ ................................................................................................................................ 40
_attribute_x .................................................................................................................................. 40
#asm #endasm #asm asis ........................................................................................................... 41
#bank_dma .................................................................................................................................. 49
#bankx ......................................................................................................................................... 50
#banky ......................................................................................................................................... 50
#bit ............................................................................................................................................... 51
__buildcount__ ............................................................................................................................ 52
#build ........................................................................................................................................... 52
#byte ............................................................................................................................................ 53
#case ........................................................................................................................................... 54
_date_.......................................................................................................................................... 55
#define ......................................................................................................................................... 55
definedinc .................................................................................................................................... 56
#device ........................................................................................................................................ 57
_device_ ...................................................................................................................................... 59
#if expr #else #elif #endif ............................................................................................................. 60
#error ........................................................................................................................................... 61
#export (options) .......................................................................................................................... 61
__file__ ........................................................................................................................................ 63
__filename__ ............................................................................................................................... 63
#fill_rom ....................................................................................................................................... 63
#fuses .......................................................................................................................................... 64
#hexcomment .............................................................................................................................. 65
38
PreProcessor
#id ................................................................................................................................................ 65
#ifdef #ifndef #else #elif #endif .................................................................................................... 66
#ignore_warnings ........................................................................................................................ 67
#import (options) .......................................................................................................................... 67
#include ....................................................................................................................................... 68
#inline .......................................................................................................................................... 69
#int_xxxx ...................................................................................................................................... 70
__line__ ....................................................................................................................................... 73
#list .............................................................................................................................................. 74
#line ............................................................................................................................................. 74
#locate ......................................................................................................................................... 75
#module ....................................................................................................................................... 76
#nolist .......................................................................................................................................... 77
#ocs ............................................................................................................................................. 77
#opt.............................................................................................................................................. 78
#org ............................................................................................................................................. 78
#pin_select .................................................................................................................................. 80
__pcd__ ....................................................................................................................................... 84
#pragma ...................................................................................................................................... 85
#profile ......................................................................................................................................... 85
#recursive .................................................................................................................................... 86
#reserve....................................................................................................................................... 87
#rom ............................................................................................................................................ 87
#separate..................................................................................................................................... 88
#serialize ..................................................................................................................................... 89
#task ............................................................................................................................................ 91
__time__ ...................................................................................................................................... 92
#type ............................................................................................................................................ 92
#undef.......................................................................................................................................... 94
_unicode ...................................................................................................................................... 95
#use capture ................................................................................................................................ 96
#use delay ................................................................................................................................... 98
#use dynamic_memory................................................................................................................ 98
#use fast_io ................................................................................................................................. 99
#use fixed_io ............................................................................................................................... 99
#use i2c ..................................................................................................................................... 100
#use profile() .............................................................................................................................. 101
#use pwm .................................................................................................................................. 102
#use rs232 ................................................................................................................................. 104
#use rtos .................................................................................................................................... 108
#use spi ..................................................................................................................................... 109
#use standard_io ....................................................................................................................... 111
#use timer .................................................................................................................................. 112
#use touchpad ........................................................................................................................... 113
#warning .................................................................................................................................... 114
#word ......................................................................................................................................... 115
#zero_ram ................................................................................................................................. 116
39
PCD_May 2015
__address__
A predefined symbol __address__ may be used to indicate a
type that must hold a program memory address.
For example:
___address__ testa = 0x1000
and
_attribute_x
Syntax:
Elements:
__attribute__x
x is the attribute you want to apply. Valid values for x are as follows:
((packed))
By default each element in a struct or union are padded to be evenly
spaced by the size of 'int'. This is to prevent an address fault when
accessing an element of struct. See the following example:
struct
{
int8 a;
int16 b;
} test;
On architectures where 'int' is 16bit (such as dsPIC or PIC24
PICmicrocontrollers), 'test' would take 4 bytes even though it is
comprised of3 bytes. By applying the 'packed' attribute to this struct
then it would take 3 bytes as originally intended:
struct __attribute__((packed))
{
int8 a;
int16 b;
} test;
Care should be taken by the user when accessing individual
elements of a packed struct creating a pointer to 'b' in 'test' and
attempting to dereference that pointer would cause an address fault.
Any attempts to read/write 'b' should be done in context of 'test' so
the compiler knows it is packed:
test.b = 5;
((aligned(y))
By default the compiler will alocate a variable in the first free
memory location. The aligned attribute will force the compiler to
40
PreProcessor
Purpose
Examples:
Example Files:
Elements:
Examples:
Example Files:
FFT.c
41
PCD_May 2015
Also See:
None
ADD
Wa,Wb,Wd
ADD
ADD
ADD
ADD
ADD
ADD
ADD.B
ADD
ADD.B
ADD.B
ADD.B
ADD.B
ADD.B
ADDC
f,W
lit10,Wd
Wa,lit5,Wd
f,F
acc
Wd,{lit4},acc
lit10,Wd
Wd,{lit4},acc
lit10,Wd
f,F
Wa,Wb,Wd
Wa,lit5,Wd
f,W
f,W
Wd
=
Wa+
Wb
W0 = f+Wd
Wd = lit10+Wd
Wd = lit5+Wa
f = f+Wd
Acc = AccA+AccB
Acc = Acc+(Wa shifted slit4)
Wd = lit10+Wd (byte)
Acc = Acc+(Wa shifted slit4)
Wd = lit10+Wd (byte)
f = f+Wd (byte)
Wd = Wa+Wb (byte)
Wd = lit5+Wa (byte)
W0 = f+Wd (byte)
W
d
=
ADDC
ADDC
ADDC
ADDC
ADDC.B
ADDC.B
ADDC.B
ADDC.B
ADDC.B
AND
AND
42
lit10,Wd
Wa,lit5,Wd
f,F
Wa,Wb,Wd
lit10,Wd
Wa,Wb,Wd
Wa,lit5,Wd
f,W
f,F
Wa,Wb,Wd
lit10,Wd
f
+
W
a
+
C
Wd = lit10+Wd+C
Wd = lit5+Wa+C
Wd = f+Wa+C
Wd = Wa+Wb+C
Wd = lit10+Wd+C (byte)
Wd = Wa+Wb+C (byte)
Wd = lit5+Wa+C (byte)
Wd = f+Wa+C (byte)
Wd = f+Wa+C (byte)
Wd = Wa.&.Wb
Wd = lit10.&.Wd
PreProcessor
AND
AND
AND
AND.B
AND.B
AND.B
AND.B
AND.B
ASR
ASR
ASR
ASR
ASR
ASR.B
ASR.B
ASR.B
BCLR
BCLR
BCLR.B
BRA
BRA
BRA BZ
BRA C
BRA GE
BRA GEU
BRA GT
BRA GTU
BRA LE
BRA LEU
BRA LT
BRA LTU
BRA N
BRA NC
BRA NN
BRA NOV
BRA NZ
BRA OA
BRA OB
BRA OV
BRA SA
BRA SB
BRA Z
BREAK
BSET
BSET
BSET.B
BSW.C
BSW.Z
f,W
f,F
Wa,lit5,Wd
f,W
Wa,Wb,Wd
lit10,Wd
f,F
Wa,lit5,Wd
f,W
f,F
Wa,Wd
Wa,lit4,Wd
Wa,Wb,Wd
f,F
f,W
Wa,Wd
f,B
Wd,B
Wd,B
a
Wd
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
Wd,B
f,B
Wd,B
Wa,Wd
Wa,Wd
W0 = f.&.Wa
f = f.&.Wa
Wd = lit5.&.Wa
W0 = f.&.Wa (byte)
Wd = Wa.&.Wb (byte)
Wd = lit10.&.Wd (byte)
f = f.&.Wa (byte)
Wd = lit5.&.Wa (byte)
W0 = f >> 1 arithmetic
f = f >> 1 arithmetic
Wd = Wa >> 1 arithmetic
Wd = Wa >> lit4 arithmetic
Wd = Wa >> Wb arithmetic
f = f >> 1 arithmetic (byte)
W0 = f >> 1 arithmetic (byte)
Wd = Wa >> 1 arithmetic (byte)
f.bit = 0
Wa.bit = 0
Wa.bit = 0 (byte)
Branch unconditionally
Branch PC+Wa
Branch if Zero
Branch if Carry (no borrow)
Branch if greater than or equal
Branch if unsigned greater than or equal
Branch if greater than
Branch if unsigned greater than
Branch if less than or equal
Branch if unsigned less than or equal
Branch if less than
Branch if unsigned less than
Branch if negative
Branch if not carry (Borrow)
Branch if not negative
Branch if not Overflow
Branch if not Zero
Branch if Accumulator A overflow
Branch if Accumulator B overflow
Branch if Overflow
Branch if Accumulator A Saturate
Branch if Accumulator B Saturate
Branch if Zero
ICD Break
Wa.bit = 1
f.bit = 1
Wa.bit = 1 (byte)
Wa.Wb = C
Wa.Wb = Z
43
PCD_May 2015
BTG
BTG
BTG.B
BTSC
BTSC
BTSS
BTSS
BTST
BTST.C
BTST.C
BTST.Z
BTST.Z
BTSTS
BTSTS.C
BTSTS.Z
CALL
CALL
CLR
CLR
CLR
CLR
CLR.B
CLR.B
CLR.B
CLRWDT
COM
COM
COM
COM.B
COM.B
COM.B
CP
CP
CP
CP.B
CP.B
CP.B
CP0
CP0
CP0.B
CP0.B
CPB
CPB
CPB
CPB.B
CPB.B
CPB.B
CPSEQ
44
Wd,B
f,B
Wd,B
f,B
Wd,B
f,B
Wd,B
f,B
Wa,Wd
Wd,B
Wd,B
Wa,Wd
f,B
Wd,B
Wd,B
a
Wd
f,F
acc,da,dc,pi
f,W
Wd
f,W
Wd
f,F
f,F
f,W
Wa,Wd
f,W
Wa,Wd
f,F
W,f
Wa,Wd
Wd,lit5
W,f
Wa,Wd
Wd,lit5
Wd
W,f
Wd
W,f
Wd,lit5
Wa,Wd
W,f
Wa,Wd
Wd,lit5
W,f
Wa,Wd
Wa.bit = ~Wa.bit
f.bit = ~f.bit
Wa.bit = ~Wa.bit (byte)
Skip if f.bit = 0
Skip if Wa.bit4 = 0
Skip if f.bit = 1
Skip if Wa.bit = 1
Z = f.bit
C = Wa.Wb
C = Wa.bit
Z = Wa.bit
Z = Wa.Wb
Z = f.bit; f.bit = 1
C = Wa.bit; Wa.bit = 1
Z = Wa.bit; Wa.bit = 1
Call subroutine
Call [Wa]
f=0
Acc = 0; prefetch=0
W0 = 0
Wd = 0
W0 = 0 (byte)
Wd = 0 (byte)
f = 0 (byte)
Clear WDT
f = ~f
W0 = ~f
Wd = ~Wa
W0 = ~f (byte)
Wd = ~Wa (byte)
f = ~f (byte)
Status set for f - W0
Status set for Wb Wa
Status set for Wa lit5
Status set for f - W0 (byte)
Status set for Wb Wa (byte)
Status set for Wa lit5 (byte)
Status set for Wa 0
Status set for f 0
Status set for Wa 0 (byte)
Status set for f 0 (byte)
Status set for Wa lit5 C
Status set for Wb Wa C
Status set for f W0 - C
Status set for Wb Wa C (byte)
Status set for Wa lit5 C (byte)
Status set for f W0 - C (byte)
Skip if Wa = Wb
PreProcessor
CPSEQ.B
CPSGT
CPSGT.B
CPSLT
CPSLT.B
CPSNE
CPSNE.B
DAW.B
DEC
DEC
DEC
DEC.B
DEC.B
DEC.B
DEC2
DEC2
DEC2
DEC2.B
DEC2.B
DEC2.B
DISI
DIV.S
DIV.SD
DIV.U
DIV.UD
DIVF
DO
DO
ED
EDAC
EXCH
FBCL
FEX
FF1L
FF1R
GOTO
GOTO
INC
INC
INC
INC.B
INC.B
INC.B
INC2
INC2
INC2
INC2.B
INC2.B
Wa,Wd
Wa,Wd
Wa,Wd
Wa,Wd
Wa,Wd
Wa,Wd
Wa,Wd
Wd
Wa,Wd
f,W
f,F
f,F
f,W
Wa,Wd
Wa,Wd
f,W
f,F
Wa,Wd
f,W
f,F
lit14
Wa,Wd
Wa,Wd
Wa,Wd
Wa,Wd
Wa,Wd
lit14,a
Wd,a
Wd*Wd,acc,da,db
Wd*Wd,acc,da,db
Wa,Wd
Wa,Wd
Wa,Wd
Wa,Wd
a
Wd
f,W
Wa,Wd
f,F
Wa,Wd
f,F
f,W
f,W
Wa,Wd
f,F
f,W
f,F
Skip if Wa = Wb (byte)
Skip if Wa > Wb
Skip if Wa > Wb (byte)
Skip if Wa < Wb
Skip if Wa < Wb (byte)
Skip if Wa != Wb
Skip if Wa != Wb (byte)
Wa = decimal adjust Wa
Wd = Wa 1
W0 = f 1
f = f 1
f = f 1 (byte)
W0 = f 1 (byte)
Wd = Wa 1 (byte)
Wd = Wa 2
W0 = f 2
f = f 2
Wd = Wa 2 (byte)
W0 = f 2 (byte)
f = f 2 (byte)
Disable Interrupts lit14 cycles
Signed 16/16-bit integer divide
Signed 16/16-bit integer divide (dword)
UnSigned 16/16-bit integer divide
UnSigned 16/16-bit integer divide (dword)
Signed 16/16-bit fractional divide
Do block lit14 times
Do block Wa times
Euclidean Distance (No Accumulate)
Euclidean Distance
Swap Wa and Wb
Find bit change from left (Msb) side
ICD Execute
Find first one from left (Msb) side
Find first one from right (Lsb) side
GoTo
GoTo [Wa]
W0 = f + 1
Wd = Wa + 1
f=f+1
Wd = Wa + 1 (byte)
f = f + 1 (byte)
W0 = f + 1 (byte)
W0 = f + 2
Wd = Wa + 2
f=f+2
W0 = f + 2 (byte)
f = f + 2 (byte)
45
PCD_May 2015
INC2.B
IOR
IOR
IOR
IOR
IOR
IOR.B
IOR.B
IOR.B
IOR.B
IOR.B
LAC
LNK
LSR
LSR
LSR
LSR
LSR
LSR.B
LSR.B
LSR.B
MAC
MAC
MOV
MOV
MOV
MOV
MOV
MOV
MOV
MOV
MOV
MOV.B
MOV.B
MOV.B
MOV.B
MOV.B
MOV.B
MOV.B
MOV.D
MOV.D
MOVSAC
MPY
MPY
MPY.N
MSC
MUL
MUL.B
46
Wa,Wd
lit10,Wd
f,F
f,W
Wa,lit5,Wd
Wa,Wb,Wd
Wa,Wb,Wd
f,W
lit10,Wd
Wa,lit5,Wd
f,F
Wd,{lit4},acc
lit14
f,W
Wa,lit4,Wd
Wa,Wd
f,F
Wa,Wb,Wd
f,W
f,F
Wa,Wd
Wd*Wd,acc,da,dc
Wd*Wc,acc,da,dc,pi
W,f
f,W
f,F
Wd,?
Wa+lit,Wd
?,Wd
lit16,Wd
Wa,Wd
Wa,Wd+lit
lit8,Wd
W,f
f,W
f,F
Wa+lit,Wd
Wa,Wd+lit
Wa,Wd
Wa,Wd
Wa,Wd
acc,da,dc,pi
Wd*Wc,acc,da,dc
Wd*Wd,acc,da,dc
Wd*Wc,acc,da,dc
Wd*Wc,acc,da,dc,pi
W,f
W,f
Wd = Wa + 2 (byte)
Wd = lit10 | Wd
f = f | Wa
W0 = f | Wa
Wd = Wa.|.lit5
Wd = Wa.|.Wb
Wd = Wa.|.Wb (byte)
W0 = f | Wa (byte)
Wd = lit10 | Wd (byte)
Wd = Wa.|.lit5 (byte)
f = f | Wa (byte)
Acc = Wa shifted slit4
Allocate Stack Frame
W0 = f >> 1
Wd = Wa >> lit4
Wd = Wa >> 1
f = f >> 1
Wd = Wb >> Wa
W0 = f >> 1 (byte)
f = f >> 1 (byte)
Wd = Wa >> 1 (byte)
Acc = Acc + Wa * Wa; {prefetch}
Acc = Acc + Wa * Wb; {[W13] = Acc}; {prefetch}
f = Wa
W0 = f
f=f
F = Wa
Wd = [Wa +Slit10]
Wd = f
Wd = lit16
Wd = Wa
[Wd + Slit10] = Wa
Wd = lit8 (byte)
f = Wa (byte)
W0 = f (byte)
f = f (byte)
Wd = [Wa +Slit10] (byte)
[Wd + Slit10] = Wa (byte)
Wd = Wa (byte)
Wd:Wd+1 = Wa:Wa+1
Wd:Wd+1 = Wa:Wa+1
Move ? to ? and ? To ?
Acc = Wa*Wb
Square to Acc
Acc = -(Wa*Wb)
Acc = Acc Wa*Wb
W3:W2 = f * Wa
W3:W2 = f * Wa (byte)
PreProcessor
MUL.SS
MUL.SU
MUL.SU
MUL.US
MUL.UU
MUL.UU
NEG
PUSH
PUSH.D
PUSH.S
PWRSAV
RCALL
RCALL
REPEAT
REPEAT
RESET
RETFIE
RETLW
RETLW.B
RETURN
RLC
RLC
RLC
RLC.B
RLC.B
RLC.B
RLNC
RLNC
RLNC
RLNC.B
RLNC.B
RLNC.B
RRC
RRC
RRC
RRC.B
RRC.B
RRC.B
RRNC
RRNC
RRNC
RRNC.B
RRNC.B
RRNC.B
SAC
SAC.R
SE
SETM
Wa,Wd
Wa,Wd
Wa,lit5,Wd
Wa,Wd
Wa,Wd
Wa,lit5,Wd
f,F
Wd
Wd
lit1
a
Wd
lit14
Wd
lit10,Wd
lit10,Wd
Wa,Wd
f,F
f,W
f,F
f,W
Wa,Wd
Wa,Wd
f,F
f,W
f,W
Wa,Wd
f,F
f,F
Wa,Wd
f,W
f,W
f,F
Wa,Wd
f,F
f,W
Wa,Wd
f,F
Wa,Wd
f,W
acc,{lit4},Wd
acc,{lit4},Wd
Wa,Wd
Wd
PCD_May 2015
SETM
SETM.B
SETM.B
SETM.B
SFTAC
SFTAC
SL
SL
SL
SL
SL
SL.B
SL.B
SL.B
SSTEP
SUB
SUB
SUB
SUB
SUB
SUB
SUB.B
SUB.B
SUB.B
SUB.B
SUB.B
SUBB
SUBB
SUBB
SUBB
SUBB
SUBB.B
SUBB.B
SUBB.B
SUBB.B
SUBB.B
SUBBR
SUBBR
SUBBR
SUBBR
SUBBR.B
SUBBR.B
SUBBR.B
SUBBR.B
SUBR
SUBR
SUBR
SUBR
48
f,F
Wd
f,W
f,F
acc,Wd
acc,lit5
f,W
Wa,Wb,Wd
Wa,lit4,Wd
Wa,Wd
f,F
f,W
Wa,Wd
f,F
f,F
f,W
Wa,Wb,Wd
Wa,lit5,Wd
acc
lit10,Wd
Wa,lit5,Wd
lit10,Wd
f,W
Wa,Wb,Wd
f,F
f,W
Wa,Wb,Wd
f,F
Wa,lit5,Wd
lit10,Wd
lit10,Wd
Wa,Wb,Wd
f,F
Wa,lit5,Wd
f,W
Wa,lit5,Wd
f,W
f,F
Wa,Wb,Wd
f,F
f,W
Wa,Wb,Wd
Wa,lit5,Wd
Wa,lit5,Wd
f,F
Wa,Wb,Wd
f,W
W0 = 0xFFFF
Wd = 0xFFFF (byte)
W0 = 0xFFFF (byte)
W0 = 0xFFFF (byte)
Arithmetic shift Acc by (Wa)
Arithmetic shift Acc by Slit6
W0 = f << 1
Wd = Wa << Wb
Wd = Wa << lit4
Wd = Wa << 1
f = f << 1
W0 = f << 1 (byte)
Wd = Wa << 1 (byte)
f = f << 1 (byte)
ICD Single Step
f = f W0
W0 = f W0
Wd = Wa Wb
Wd = Wa lit5
Acc = AccA AccB
Wd = Wd lit10
Wd = Wa lit5 (byte)
Wd = Wd lit10 (byte)
W0 = f W0 (byte)
Wd = Wa Wb (byte)
f = f W0 (byte)
W0 = f W0 C
Wd = Wa Wb C
f = f W0 C
Wd = Wa lit5 - C
Wd = Wd lit10 C
Wd = Wd lit10 C (byte)
Wd = Wa Wb C (byte)
f = f W0 C (byte)
Wd = Wa lit5 - C (byte)
W0 = f W0 C (byte)
Wd = lit5 Wa - C
W0 = W0 f C
f = W0 f C
Wd = Wa Wb - C
f = W0 f C (byte)
W0 = W0 f C (byte)
Wd = Wa Wb - C (byte)
Wd = lit5 Wa - C (byte)
Wd = lit5 Wb
f = W0 f
Wd = Wa Wb
W0 = W0 f
PreProcessor
SUBR.B
SUBR.B
SUBR.B
SUBR.B
SWAP
SWAP.B
TBLRDH
TBLRDH.B
TBLRDL
TBLRDL.B
TBLWTH
TBLWTH.B
TBLWTL
TBLWTL.B
ULNK
URUN
XOR
XOR
XOR
XOR
XOR
XOR.B
XOR.B
XOR.B
XOR.B
XOR.B
ZE
Wa,Wb,Wd
f,F
Wa,lit5,Wd
f,W
Wd
Wd
Wa,Wd
Wa,Wd
Wa,Wd
Wa,Wd
Wa,Wd
Wa,Wd
Wa,Wd
Wa,Wd
Wa,Wb,Wd
f,F
f,W
Wa,lit5,Wd
lit10,Wd
lit10,Wd
f,W
Wa,lit5,Wd
Wa,Wb,Wd
f,F
Wa,Wd
Wd = Wa Wb (byte)
f = W0 f (byte)
Wd = lit5 Wb (byte)
W0 = W0 f (byte)
Wa = byte or nibble swap Wa
Wa = byte or nibble swap Wa (byte)
Wd = ROM[Wa] for odd ROM
Wd = ROM[Wa] for odd ROM (byte)
Wd = ROM[Wa] for even ROM
Wd = ROM[Wa] for even ROM (byte)
ROM[Wa] = Wd for odd ROM
ROM[Wa] = Wd for odd ROM (byte)
ROM[Wa] = Wd for even ROM
ROM[Wa] = Wd for even ROM (byte)
Deallocate Stack Frame
ICD Run
Wd = Wa ^ Wb
f = f ^ W0
W0 = f ^ W0
Wd = Wa ^ lit5
Wd = Wd ^ lit10
Wd = Wd ^ lit10 (byte)
W0 = f ^ W0 (byte)
Wd = Wa ^ lit5 (byte)
Wd = Wa ^ Wb (byte)
f = f ^ W0 (byte)
Wd = Wa & FF
#bank_dma
Syntax:
#BANK_DMA
Elements:
None
Purpose:
Tells the compiler to assign the data for the next variable, array or structure
into DMA bank
Examples:
#bank_dma
struct {
int r_w;
int c_w;
long unused :2;
long data: 4;
}a_port;
//the data for a_port will be forced into memory bank
DMA
Example Files:
None
49
PCD_May 2015
Also See:
None
#bankx
Syntax:
#BANKX
Elements:
None
Purpose:
Tells the compiler to assign the data for the next variable, array, or structure
into Bank X.
Examples:
#bankx
struct {
int r_w;
int c_d;
long unused : 2;
long data : 4;
} a_port;
// The data for a_port will be forced into memory bank x.
Example Files:
None
Also See:
None
#banky
Syntax:
#BANKY
Elements:
None
Purpose:
Tells the compiler to assign the data for the next variable, array, or structure
into Bank Y.
50
PreProcessor
Examples:
#banky
struct {
int r_w;
int c_d;
long unused : 2;
long data : 4;
} a_port;
// The data for a_port will be forced into memory bank y.
Example Files:
None
Also See:
None
#bit
Syntax:
#BIT id = x.y
Elements:
id is a valid C identifier,
x is a constant or a C variable,
y is a constant 0-7 (for 8-bit PICs)
y is a constant 0-15 (for 16-bit PICs)
Purpose:
A new C variable (one bit) is created and is placed in memory at byte x and bit
y. This is useful to gain access in C directly to a bit in the processors special
function register map. It may also be used to easily access a bit of a standard C
variable.
Examples:
Example
Files:
ex_glint.c
Also See:
51
PCD_May 2015
__buildcount__
Only defined if Options>Project Options>Global Defines has
global defines enabled.
This id resolves to a number representing the number of
successful builds of the project.
#build
Syntax:
Elements:
#BUILD(segment = address)
#BUILD(segment = address, segment = address)
#BUILD(segment = start:end)
#BUILD(segment = start: end, segment = start: end)
#BUILD(nosleep)
#BUILD(segment = size) : For STACK use only
#BUILD(ALT_INTERRUPT)
#BUILD(AUX_MEMORY)
segment is one of the following memory segments which may be assigned a
location: RESET, INTERRUPT , or STACK
address is a ROM location memory address. Start and end are used to specify a
range in memory to be used. Start is the first ROM location and end is the last
ROM location to be used.
RESET will move the compiler's reset vector to the specified location.
INTERRUPT will move the compiler's interrupt service routine to the specified
location. This just changes the location the compiler puts it's reset and ISR, it
doesn't change the actual vector of the PIC. If you specify a range that is larger
than actually needed, the extra space will not be used and prevented from use by
the compiler.
STACK configures the range (start and end locations) used for the stack, if not
specified the compiler uses the last 256 bytes. The STACK can be specified by
only using the size parameters. In this case, the compiler uses the last RAM
locations on the chip and builds the stack below it.
ALT_INTERRUPT will move the compiler's interrupt service routine to the alternate
location, and configure the PIC to use the alternate location.
nosleep is used to prevent the compiler from inserting a sleep at the end of main()
Bootload produces a bootloader-friendly hex file (in order, full block size).
52
PreProcessor
NOSLEEP_LOCK is used instead of A sleep at the end of a main A infinite loop.
Purpose:
Examples:
Example
Files:
Also See:
None
#LOCATE, #RESERVE, #ROM, #ORG
#byte
Syntax:
#byte id = x
Elements:
id is a valid C identifier,
x is a C variable or a constant
Purpose:
If the id is already known as a C variable then this will locate the variable at
address x. In this case the variable type does not change from the original
definition. If the id is not known a new C variable is created and placed at address
x with the type int (8 bit)
Warning: In both cases memory at x is not exclusive to this variable. Other
variables may be located at the same location. In fact when x is a variable, then
id and x share the same memory location.
53
PCD_May 2015
Examples:
#byte
#byte
struct {
short int r_w;
short int c_d;
int data
: 6 ; } E _port;
#byte a_port = 0x2DA
...
a_port.c_d = 1;
Example
Files:
Also See:
ex_glint.c
#bit, #locate, #reserve, #word, Named Registers, Type Specifiers, Type Qualifiers,
Enumerated Types, Structures & Unions, Typedef
#case
Syntax:
#CASE
Elements:
None
Purpose:
Will cause the compiler to be case sensitive. By default the compiler is case
insensitive. When linking multiple compilation units, this directive must appear
exactly the same in each compilation unit.
Warning: Not all the CCS example programs, headers and drivers have been
tested with case sensitivity turned on.
Examples:
#case
int STATUS;
void func() {
int status;
...
STATUS = status; // Copy local status to
//global
}
Example
Files:
Also See:
54
ex_cust.c
None
PreProcessor
_date_
Syntax:
__DATE__
Elements:
None
Purpose:
This pre-processor identifier is replaced at compile time with the date of the compile in
the form: "31-JAN-03"
Examples:
Example
Files:
Also See:
None
None
#define
Syntax:
#define id text
or
#define id(x,y...) text
Elements:
Purpose:
Used to provide a simple string replacement of the ID with the given text from this
point of the program and on.
In the second form (a C macro) the local identifiers are matched up with similar
identifiers in the text and they are replaced with text passed to the macro where it
is used.
If the text contains a string of the form #idx then the result upon evaluation will be
the parameter id concatenated with the string x.
If the text contains a string of the form #idx#idy then parameter idx is
concatenated with parameter idy forming a new identifier.
Within the define text two special operators are supported:
#x is the stringize operator resulting in "x"
x##y is the concatination operator resulting in xy
The varadic macro syntax is supported where the last parameter is specified as ...
and the local identifier used is __va_args__. In this case, all remaining
55
PCD_May 2015
arguments are combined with the commas.
Examples:
#define BITS 8
a=a+BITS;
//same as
a=a+8;
a=(a<<4);
#define isequal(a,b)
(primary_##a[b]==backup_##a[b])
// usage iseaqual(names,5) is the same as
// (primary_names[5]==backup_names[5])
#define str(s) #s
#define part(device) #include str(device##.h)
// usage part(16F887) is the same as
// #include "16F887.h"
#define DBG(...)
Example
Files:
Also See:
fprintf(debug,__VA_ARGS__)
ex_stwt.c, ex_macro.c
#UNDEF, #IFDEF, #IFNDEF
definedinc
Syntax:
Parameters:
Returns:
Function:
This function checks the type of the variable or function being passed in
and returns a specific C status based on the type.
Availability:
Requires:
Examples:
All devices
None.
int x, y = 0;
56
PreProcessor
y = definedinc( x );
Example Files:
None
Also See:
None
#device
Syntax:
Elements:
Chip Options-
PCD_May 2015
%f=.
OVERLOAD=KEYWORD
OVERLOAD=AUTO
PASS_STRINGS=IN_RAM
CONST=READ_ONLY
CONST=ROM
NESTED_INTERRUPTS=TR
UE
NORETFIE
NO_DIGITAL_INIT
Both chip and options are optional, so multiple #DEVICE lines may be used to fully
define the device. Be warned that a #DEVICE with a chip identifier, will clear all
previous #DEVICE and #FUSE settings.
Compilation mode selectionThe #DEVICE directive supports compilation mode selection. The valid keywords
are CCS2, CCS3, CCS4 and ANSI. The default mode is CCS4. For the CCS4 and
ANSI mode, the compiler uses the default fuse settings NOLVP, PUT for chips with
these fuses. The NOWDT fuse is default if no call is made to restart_wdt().
58
CCS4
ANSI
Default data type is SIGNED all other modes default is UNSIGNED. Compilation
is case sensitive, all other modes are case insensitive.
PreProcessor
Purpose:
CCS2
CCS3
var16 = NegConst8 is compiled as: var16 = NegConst8 & 0xff (no sign extension)
. The overload keyword is required.
CCS2 only
The default #DEVICE ADC is set to the resolution of the part, all other modes
default to 8.
onebit = eightbits is compiled as onebit = (eightbits != 0)
All other modes compile as: onebit = (eightbits & 1)
Chip Options -Defines the target processor. Every program must have exactly one
#DEVICE with a chip. When linking multiple compilation units, this directive must
appear exactly the same in each compilation unit.
Compilation mode selection - The compilation mode selection allows existing
code to be compiled without encountering errors created by compiler compliance.
As CCS discovers discrepancies in the way expressions are evaluated according to
ANSI, the change will generally be made only to the ANSI mode and the next major
CCS release.
Examples:
Chip Options#device
#device
#device
#device
DSPIC33FJ64GP306
PIC24FJ64GA002 ICD=TRUE
ADC=10
ICD=TRUE ADC=10
Example
Files:
Also See:
None
None
_device_
Syntax:
__DEVICE__
Elements:
None
Purpose:
This pre-processor identifier is defined by the compiler with the base number of
the current device (from a #DEVICE). The base number is usually the number
after the C in the part number. For example the PIC16C622 has a base number of
622.
59
PCD_May 2015
Examples:
#if __device__==71
SETUP_ADC_PORTS( ALL_DIGITAL );
#endif
Example
Files:
Also See:
None
#DEVICE
#if expr
code
#elif expr //Optional, any number may be used
code
#else
//Optional
code
#endif
Elements:
Purpose:
The pre-processor evaluates the constant expression and if it is nonzero will process the lines up to the optional #ELSE or the #ENDIF.
Note: you may NOT use C variables in the #IF. Only preprocessor
identifiers created via #define can be used.
The preprocessor expression DEFINED(id) may be used to return 1 if
the id is defined and 0 if it is not.
== and != operators now accept a constant string as both operands.
This allows for compile time comparisons and can be used with
GETENV() when it returns a string result.
Examples:
Example Files:
ex_extee.c
Also See:
60
PreProcessor
#error
Syntax:
#ERROR text
#ERROR / warning text
#ERROR / information text
text is optional and may be any text
Elements:
Purpose:
Examples:
#if BUFFER_SIZE>16
#error Buffer size is too large
#endif
#error
Macro test: min(x,y)
Example Files:
ex_psp.c
Also See:
#WARNING
#export (options)
Syntax:
#EXPORT (options)
Elements:
FILE=filname
The filename which will be generated upon compile. If not given, the filname will be
the name of the file you are compiling, with a .o or .hex extension (depending on
output format).
ONLY=symbol+symbol+.....+symbol
Only the listed symbols will be visible to modules that import or link this relocatable
object file. If neither ONLY or EXCEPT is used, all symbols are exported.
EXCEPT=symbol+symbol+.....+symbol
All symbols except the listed symbols will be visible to modules that import or link
this relocatable object file. If neither ONLY or EXCEPT is used, all symbols are
exported.
RELOCATABLE
61
PCD_May 2015
CCS relocatable object file format. Must be imported or linked before loading into a
PIC. This is the default format when the #EXPORT is used.
HEX
Intel HEX file format. Ready to be loaded into a PIC. This is the default format
when no #EXPORT is used.
RANGE=start:stop
Only addresses in this range are included in the hex file.
OFFSET=address
Hex file address starts at this address (0 by default)
ODD
Only odd bytes place in hex file.
EVEN
Only even bytes placed in hex file.
Purpose:
This directive will tell the compiler to either generate a relocatable object file or a
stand-alone HEX binary. A relocatable object file must be linked into your
application, while a stand-alone HEX binary can be programmed directly into the
PIC.
The command line compiler and the PCW IDE Project Manager can also be used to
compile/link/build modules and/or projects.
Multiple #EXPORT directives may be used to generate multiple hex files. this may
be used for 8722 like devices with external memory.
Examples:
#EXPORT(RELOCATABLE, ONLY=TimerTask)
void TimerFunc1(void) { /* some code */ }
void TimerFunc2(void) { /* some code */ }
void TimerFunc3(void) { /* some code */ }
void TimerTask(void)
{
TimerFunc1();
TimerFunc2();
TimerFunc3();
}
/*
This source will be compiled into a relocatable object, but the
object this is being linked to can only see TimerTask()
*/
Example
Files:
See Also:
None
62
PreProcessor
__file__
Syntax:
__FILE__
Elements:
None
Purpose:
Examples:
if(index>MAX_ENTRIES)
printf("Too many entries, source file: "
__FILE__ " at line " __LINE__ "\r\n");
Example Files:
assert.h
Also See:
_ _ line_ _
__filename__
Syntax:
__FILENAME__
Elements:
None
Purpose:
Examples:
if(index>MAX_ENTRIES)
printf("Too many entries, source file: "
__FILENAME__ " at line " __LINE__ "\r\n");
Example Files:
None
Also See:
_ _ line_ _
#fill_rom
Syntax:
#fill_rom value
Elements:
Purpose:
This directive specifies the data to be used to fill unused ROM locations. When
linking multiple compilation units, this directive must appear exactly the same in
each compilation unit.
63
PCD_May 2015
Examples:
#fill_rom 0x36
Example
Files:
Also See:
None
#ROM
#fuses
Syntax:
#FUSES options
Elements:
options vary depending on the device. A list of all valid options has been put at
the top of each devices .h file in a comment for reference. The PCW device edit
utility can modify a particular devices fuses. The PCW pull down menu VIEW |
Valid fuses will show all fuses with their descriptions.
Some common options are:
LP, XT, HS, RC
WDT, NOWDT
PROTECT, NOPROTECT
PUT, NOPUT (Power Up Timer)
BROWNOUT, NOBROWNOUT
Purpose:
This directive defines what fuses should be set in the part when it is
programmed. This directive does not affect the compilation; however, the
information is put in the output files. If the fuses need to be in Parallax format, add
a PAR option. SWAP has the special function of swapping (from the Microchip
standard) the high and low BYTES of non-program data in the Hex file. This is
required for some device programmers.
Some fuses are set by the compiler based on other compiler directives. For
example, the oscillator fuses are set up by the #USE delay directive. The debug,
No debug and ICSPN Fuses are set by the #DEVICE ICD=directive.
Some processors allow different levels for certain fuses. To access these levels,
assign a value to the fuse.
When linking multiple compilation units be aware this directive applies to the final
object file. Later files in the import list may reverse settings in previous files.
To eliminate all fuses in the output files use:
#FUSES none
To manually set the fuses in the output files use:
#FUSES 1 = 0xC200 // sets config word 1 to 0xC200
64
PreProcessor
Examples:
#fuses
Example
Files:
Also See:
None
HS,NOWDT
None
#hexcomment
Syntax:
Elements:
None
Purpose:
Examples:
Example
Files:
Also See:
None
None
#id
Syntax:
#ID number 32
#ID number, number, number, number
#ID "filename"
#ID CHECKSUM
Elements:
Purpose:
This directive defines the ID word to be programmed into the part. This
directive does not affect the compilation but the information is put in the
output file.
The first syntax will take a 32 -bit number and put one byte in each of the
four ID bytes in the traditional manner. The second syntax specifies the
65
PCD_May 2015
exact value to be used in each of the four ID bytes .
When a filename is specified the ID is read from the file. The format must
be simple text with a CR/LF at the end. The keyword CHECKSUM
indicates the device checksum should be saved as the ID.
Examples:
#id 0x12345678
#id 0x12, 0x34, 0x45, 0x67
#id "serial.num"
#id CHECKSUM
Example Files:
ex_cust.c
Also See:
None
#IFDEF id
code
#ELIF
code
#ELSE
code
#ENDIF
#IFNDEF id
code
#ELIF
code
#ELSE
code
#ENDIF
Elements:
Purpose:
This directive acts much like the #IF except that the preprocessor simply
checks to see if the specified ID is known to the preprocessor (created
with a #DEFINE). #IFDEF checks to see if defined and #IFNDEF checks
to see if it is not defined.
Examples:
#define debug
...
#ifdef DEBUG
printf("debug point a");
#endif
66
PreProcessor
Example Files:
ex_sqw.c
Also See:
#IF
#ignore_warnings
Syntax:
#ignore_warnings ALL
#IGNORE_WARNINGS NONE
#IGNORE_WARNINGS warnings
Elements:
Purpose:
This function will suppress warning messages from the compiler. ALL indicates no
warning will be generated. NONE indicates all warnings will be generated. If
numbers are listed then those warnings are suppressed.
Examples:
#ignore_warnings 203
while(TRUE) {
#ignore_warnings NONE
Example
Files:
Also See:
None
Warning messages
#import (options)
Syntax:
#IMPORT (options)
Elements:
FILE=filname
The filename of the object you want to link with this compilation.
ONLY=symbol+symbol+.....+symbol
Only the listed symbols will imported from the specified relocatable object
file. If neither ONLY or EXCEPT is used, all symbols are imported.
EXCEPT=symbol+symbol+.....+symbol
The listed symbols will not be imported from the specified relocatable object
file. If neither ONLY or EXCEPT is used, all symbols are imported.
RELOCATABLE
CCS relocatable object file format. This is the default format when the
#IMPORT is used.
67
PCD_May 2015
COFF
COFF file format from MPASM, C18 or C30.
HEX
Imported data is straight hex data.
RANGE=start:stop
Only addresses in this range are read from the hex file.
LOCATION=id
The identifier is made a constant with the start address of the imported
data.
SIZE=id
The identifier is made a constant with the size of the imported data.
Purpose:
This directive will tell the compiler to include (link) a relocatable object with
this unit during compilation. Normally all global symbols from the specified
file will be linked, but the EXCEPT and ONLY options can prevent certain
symbols from being linked.
The command line compiler and the PCW IDE Project Manager can also be
used to compile/link/build modules and/or projects.
Examples:
#IMPORT(FILE=timer.o, ONLY=TimerTask)
void main(void)
{
while(TRUE)
TimerTask();
}
/*
timer.o is linked with this compilation, but only TimerTask()
is visible in scope from this object.
*/
Example Files:
None
See Also:
#include
Syntax:
68
#INCLUDE <filename>
or
#INCLUDE "filename"
PreProcessor
Elements:
Purpose:
Text from the specified file is used at this point of the compilation. If a
full path is not specified the compiler will use the list of directories
specified for the project to search for the file. If the filename is in "" then
the directory with the main source file is searched first. If the filename is
in <> then the directory with the main source file is searched last.
Examples:
#include
<16C54.H>
#include
<C:\INCLUDES\COMLIB\MYRS232.C>
Example Files:
ex_sqw.c
Also See:
None
#inline
Syntax:
#INLINE
Elements:
None
Purpose:
Tells the compiler that the function immediately following the directive is
to be implemented INLINE. This will cause a duplicate copy of the code
to be placed everywhere the function is called. This is useful to save
stack space and to increase speed. Without this directive the compiler
will decide when it is best to make procedures INLINE.
Examples:
#inline
swapbyte(int &a, int &b) {
int t;
t=a;
a=b;
b=t;
}
Example Files:
ex_cust.c
69
PCD_May 2015
Also See:
#SEPARATE
#int_xxxx
Syntax:
70
#INT_AC1
#INT_AC2
#INT_AC3
#INT_AC4
#INT_ADC1
#INT_ADC2
#INT_ADCP0
#INT_ADCP1
#INT_ADCP2
#INT_ADCP3
#INT_ADCP4
#INT_ADCP5
#INT_ADDRERR
#INT_C1RX
#INT_C1TX
#INT_C2RX
#INT_C2TX
#INT_CAN1
#INT_CAN2
#INT_CNI
#INT_COMP
#INT_CRC
#INT_DCI
#INT_DCIE
#INT_DMA0
#INT_DMA1
#INT_DMA2
#INT_DMA3
#INT_DMA4
#INT_DMA5
#INT_DMA6
#INT_DMA7
#INT_DMAERR
PreProcessor
#INT_EEPROM
#INT_EX1
#INT_EX4
#INT_EXT0
#INT_EXT1
#INT_EXT2
#INT_EXT3
#INT_EXT4
#INT_FAULTA
#INT_FAULTA2
#INT_FAULTB
#INT_IC1
#INT_IC2
#INT_IC3
#INT_IC4
#INT_IC5
#INT_IC6
#INT_IC7
#INT_IC8
#INT_LOWVOLT
#INT_LVD
#INT_MATHERR
#INT_MI2C
#INT_MI2C2
#INT_OC1
#INT_OC2
#INT_OC3
#INT_OC4
#INT_OC5
#INT_OC6
#INT_OC7
#INT_OC8
#INT_OSC_FAIL
#INT_PMP
#INT_PMP2
#INT_PWM1
#INT_PWM2
#INT_PWM3
#INT_PWM4
Write complete
External Interrupt 1
External Interrupt 4
External Interrupt 0
External interrupt #1
External interrupt #2
External interrupt #3
External interrupt #4
PWM Fault A
PWM Fault A 2
PWM Fault B
Input Capture #1
Input Capture #2
Input Capture #3
Input Capture #4
Input Capture #5
Input Capture #6
Input Capture #7
Input Capture #8
Low voltage detected
Low voltage detected
Arithmetic error trap
Master I2C activity
Master2 I2C activity
Output Compare #1
Output Compare #2
Output Compare #3
Output Compare #4
Output Compare #5
Output Compare #6
Output Compare #7
Output Compare #8
System oscillator failed
Parallel master port
Parallel master port 2
PWM generator 1 time based interrupt
PWM generator 2 time based interrupt
PWM generator 3 time based interrupt
PWM generator 4 time based interrupt
71
PCD_May 2015
#INT_PWMSEM
#INT_QEI
#INT_RDA
#INT_RDA2
#INT_RTC
#INT_SI2C
#INT_SI2C2
#INT_SPI1
#INT_SPI1E
#INT_SPI2
#INT_SPI2E
#INT_SPIE
#INT_STACKERR
#INT_TBE
#INT_TBE2
#INT_TIMER1
#INT_TIMER2
#INT_TIMER3
#INT_TIMER4
#INT_TIMER5
#INT_TIMER6
#INT_TIMER7
#INT_TIMER8
#INT_TIMER9
#INT_UART1E
#INT_UART2E
#INT_AUX
Elements:
Purpose:
72
PreProcessor
An interrupt marked FAST uses the shadow feature to save registers. Only one
interrupt may be marked fast. Any registers used in the FAST interrupt beyond the
shadow registers is the responsibility of the user to save and restore.
Level=n specifies the level of the interrupt.
Enable_interrupts specifies the levels that are enabled. The default is level 0 and
level 7 is never disabled. High is the same as level = 7.
A summary of the different kinds of dsPIC/PIC24 interrupts:
#INT_xxxx
Normal (low priority) interrupt. Compiler saves/restores key registers.
This interrupt will not interrupt any interrupt in progress.
#INT_xxxx FAST
Compiler does a FAST save/restore of key registers.
Only one is allowed in a program.
#INT_xxxx HIGHLevel=3
Interrupt is enabled when levels 3 and below are enabled.
#INT_GLOBAL
Compiler generates no interrupt code. User function is located
at address 8 for user interrupt handling.
#INT_xxxx ALT
Interrupt is placed in Alternate Interrupt Vector instead of Default Interrupt
Vector.
Examples:
#int_ad
adc_handler() {
adc_active=FALSE;
}
#int_timer1 noclear
isr() {
...
}
Example
Files:
Also See:
None
enable_interrupts(), disable_interrupts(), #INT_DEFAULT,
__line__
Syntax:
__line__
Elements:
None
73
PCD_May 2015
Purpose:
Examples:
if(index>MAX_ENTRIES)
printf("Too many entries, source file: "
__FILE__" at line " __LINE__ "\r\n");
Example Files:
assert.h
Also See:
_ _ file_ _
#list
Syntax:
#LIST
Elements:
None
Purpose:
Examples:
#NOLIST
// Don't clutter up the list file
#include <cdriver.h>
#LIST
Example Files:
16c74.h
Also See:
#NOLIST
#line
Syntax:
Elements:
Purpose:
Examples:
1. void main(){
#line 10
// specifies the line number that
// should be reported for
74
PreProcessor
// the following line of input
2. #line 7 "hello.c"
// line number in the source file
// hello.c and it sets the
// line 7 as current line
// and hello.c as current file
Example Files:
None
Also See:
None
#locate
Syntax:
#LOCATE id=x
Elements:
id is a C variable,
x is a constant memory address
Purpose:
Examples:
Example
Files:
Also See:
ex_glint.c
#byte, #bit, #reserve, #word, Named Registers, Type Specifiers, Type Qualifiers,
Enumerated Types, Structures & Unions, Typedef
75
PCD_May 2015
#module
Syntax:
#MODULE
Elements:
None
Purpose:
All global symbols created from the #MODULE to the end of the file will
only be visible within that same block of code (and files #INCLUDE
within that block). This may be used to limit the scope of global
variables and functions within include files. This directive also applies to
pre-processor #defines.
Note: The extern and static data qualifiers can also be used to denote
scope of variables and functions as in the standard C methodology.
#MODULE does add some benefits in that pre-processor #DEFINE can
be given scope, which cannot normally be done in standard C
methodology.
Examples:
int GetCount(void);
void SetCount(int newCount);
#MODULE
int g_count;
#define G_COUNT_MAX 100
int GetCount(void) {return(g_count);}
void SetCount(int newCount) {
if (newCount>G_COUNT_MAX)
newCount=G_COUNT_MAX;
g_count=newCount;
}
/*
the functions GetCount() and SetCount() have global scope,
but the variable g_count and the #define G_COUNT_MAX only
has scope to this file.
*/
Example Files:
None
See Also:
76
PreProcessor
#nolist
Syntax:
#NOLIST
Elements:
None
Purpose:
Stops inserting source lines into the .LST file (until a #LIST)
Examples:
#NOLIST
// Don't clutter up the list file
#include <cdriver.h>
#LIST
Example Files:
16c74.h
Also See:
#LIST
#ocs
Syntax:
#OCS x
Elements:
Purpose:
Examples:
#include <18F4520.h>
#device ICD=TRUE
#OCS 20 MHz
#use rs232(debugger)
void main(){
-------;
}
Example Files:
None
Also See:
#USE DELAY
77
PCD_May 2015
#opt
Syntax:
#OPT n
Elements:
Purpose:
The optimization level is set with this directive. This setting applies to
the entire program and may appear anywhere in the file. The default is
9 for normal.
Examples:
#opt 5
Example Files:
None
Also See:
None
#org
Syntax:
Elements:
start is the first ROM location (word address) to use, end is the last ROM
location, segment is the start ROM location from a previous #ORG
Purpose:
This directive will fix the following function, constant or ROM declaration
into a specific ROM area. End may be omitted if a segment was
previously defined if you only want to add another function to the
segment.
Follow the ORG with a { } to only reserve the area with nothing inserted
by the compiler.
The RAM for a ORG'd function may be reset to low memory so the local
variables and scratch variables are placed in low memory. This should
only be used if the ORG'd function will not return to the caller. The RAM
used will overlap the RAM of the main program. Add a AUTO=0 at the
78
PreProcessor
end of the #ORG line.
If the keyword DEFAULT is used then this address range is used for all
functions user and compiler generated from this point in the file until a
#ORG DEFAULT is encountered (no address range). If a compiler
function is called from the generated code while DEFAULT is in effect the
compiler generates a new version of the function within the specified
address range.
#ORG may be used to locate data in ROM. Because CONSTANT are
implemented as functions the #ORG should proceed the CONSTANT and
needs a start and end address. For a ROM declaration only the start
address should be specified.
When linking multiple compilation units be aware this directive applies to
the final object file. It is an error if any #ORG overlaps between files
unless the #ORG matches exactly.
Examples:
Example Files:
loader.c
Also See:
#ROM
79
PCD_May 2015
#pin_select
Syntax:
#PIN_SELECT function=pin_xx
Elements:
NULL
C1OUT
C2OUT
C3OUT
C4OUT
U1TX
U1RTS
U2TX
U2RTS
U3TX
U3RTS
U4TX
U4RTS
SDO1
SCK1OUT
SS1OUT
SDO2
SCK2OUT
SS2OUT
SDO3
SCK3OUT
SS3OUT
SDO4
SCK4OUT
SS4OUT
OC1
OC2
OC3
OC4
OC5
OC6
80
NULL
Comparator 1 Output
Comparator 2 Output
Comparator 3 Output
Comparator 4 Output
UART1 Transmit
UART1 Request to Send
UART2 Transmit
UART2 Request to Send
UART3 Transmit
UART3 Request to Send
UART4 Transmit
UART4 Request to Send
SPI1 Data Output
SPI1 Clock Output
SPI1 Slave Select
Output
SPI2 Data Output
SPI2 Clock Output
SPI2 Slave Select
Output
SPI3 Data Output
SPI3 Clock Output
SPI3 Slave Select
Output
SPI4 Data Output
SPI4 Clock Output
SPI4 Slave Select
Output
Output Compare 1
Output Compare 2
Output Compare 3
Output Compare 4
Output Compare 5
Output Compare 6
PreProcessor
OC7
OC8
OC9
OC10
OC11
OC12
OC13
OC14
OC15
OC16
C1TX
C2TX
CSDO
CSCKOUT
COFSOUT
UPDN1
UPDN2
CTPLS
SYNCO1
SYNCO2
REFCLKO
CMP1
CMP2
CMP3
CMP4
PWM4H
PWM4L
QEI1CCMP
QEI2CCMP
MDOUT
DCIDO
DCISCKOUT
DCIFSOUT
INT1
INT2
INT3
INT4
Output Compare 7
Output Compare 8
Output Compare 9
Output Compare 10
Output Compare 11
Output Compare 12
Output Compare 13
Output Compare 14
Output Compare 15
Output Compare 16
CAN1 Transmit
CAN2 Transmit
DCI Serial Data Output
DCI Serial Clock Output
DCI Frame Sync Output
QEI1 Direction Status
Output
QEI2 Direction Status
Output
CTMU Output Pulse
PWM Synchronization
Output Signal
PWM Secondary
Synchronization Output
Signal
REFCLK Output Signal
Analog Comparator
Output 1
Analog Comparator
Output 2
Analog Comparator
Output 3
Analog Comparator
Output 4
PWM4 High Output
PWM4 Low Output
QEI1 Counter
Comparator Output
QEI2 Counter
Comparator Output
DSM Modulator Output
DCI Serial Data Output
DCI Serial Clock Output
DCI Frame Sync Output
External Interrupt 1 Input
External Interrupt 2 Input
External Interrupt 3 Input
External Interrupt 4 Input
81
PCD_May 2015
T1CK
T2CK
T3CK
T4CK
T5CK
T6CK
T7CK
T8CK
T9CK
IC1
IC2
IC3
IC4
IC5
IC6
IC7
IC8
IC9
IC10
IC11
IC12
IC13
IC14
IC15
IC16
C1RX
C2RX
OCFA
OCFB
OCFC
U1RX
U1CTS
U2RX
U2CTS
U3RX
U3CTS
82
PreProcessor
U4RX
U4CTS
SDI1
SCK1IN
SS1IN
SDI2
SCK2IN
SS2IN
SDI3
SCK3IN
SS3IN
SDI4
SCK4IN
SS4IN
CSDI
CSCK
COFS
FLTA1
FLTA2
QEA1
QEA2
QEB1
QEB2
INDX1
INDX2
HOME1
HOME2
FLT1
FLT2
FLT3
FLT4
FLT5
FLT6
FLT7
FLT8
SYNCI1
SYNCI2
DCIDI
DCISCKIN
DCIFSIN
DTCMP1
DTCMP2
DTCMP3
UART4 Receive
UART4 Clear to Send
SPI1 Data Input
SPI1 Clock Input
SPI1 Slave Select Input
SPI2 Data Input
SPI2 Clock Input
SPI2 Slave Select Input
SPI3 Data Input
SPI3 Clock Input
SPI3 Slave Select Input
SPI4 Data Input
SPI4 Clock Input
SPI4 Slave Select Input
DCI Serial Data Input
DCI Serial Clock Input
DCI Frame Sync Input
PWM1 Fault Input
PWM2 Fault Input
QEI1 Phase A Input
QEI2 Phase A Input
QEI1 Phase B Input
QEI2 Phase B Input
QEI1 Index Input
QEI2 Index Input
QEI1 Home Input
QEI2 Home Input
PWM1 Fault Input
PWM2 Fault Input
PWM3 Fault Input
PWM4 Fault Input
PWM5 Fault Input
PWM6 Fault Input
PWM7 Fault Input
PWM8 Fault Input
PWM Synchronization
Input 1
PWM Synchronization
Input 2
DCI Serial Data Input
DCI Serial Clock Input
DCI Frame Sync Input
PWM Dead Time
Compensation 1 Input
PWM Dead Time
Compensation 2 Input
PWM Dead Time
Compensation 3 Input
83
PCD_May 2015
DTCMP4
DTCMP5
DTCMP6
DTCMP7
Examples:
#pin_select U1TX=PIN_C6
#pin_select U1RX=PIN_C7
#pin_select INT1=PIN_B0
Example
Files:
Also See:
None
None
__pcd__
Syntax:
__PCD__
Elements:
None
Purpose:
Examples:
#ifdef __pcd__
#device dsPIC33FJ256MC710
#endif
Example Files:
ex_sqw.c
Also See:
None
84
PreProcessor
#pragma
Syntax:
#PRAGMA cmd
Elements:
Purpose:
Examples:
#pragma device
Example Files:
ex_cust.c
Also See:
None
PIC16C54
#profile
Syntax:
#profile options
Elements:
functi
ons,
param
eters
profileo
ut
paths
off
on
PCD_May 2015
Purpose:
Large programs on the microcontroller may generate lots of profile data, which
may make it difficult to debug or follow. By using #profile the user can
dynamically control which points of the program are being profiled, and limit
data to what is relevant to the user.
Examples:
#profile off
void BigFunction(void)
{
// BigFunction code goes here.
// Since #profile off was called above,
// no profiling will happen even for other
// functions called by BigFunction().
}
#profile on
Example Files:
ex_profile.c
Also See:
#recursive
Syntax:
#RECURSIVE
Elements:
None
Purpose:
Tells the compiler that the procedure immediately following the directive
will be recursive.
Examples:
#recursive
int factorial(int num) {
if (num <= 1)
return 1;
return num * factorial(num-1);
}
Example Files:
None
Also See:
None
86
PreProcessor
#reserve
Syntax:
#RESERVE address
or
#RESERVE address, address, address
or
#RESERVE start:end
Elements:
address is a RAM address, start is the first address and end is the last address
Purpose:
Examples:
#DEVICE dsPIC30F2010
#RESERVE
0x800:0x80B3
Example
Files:
Also See:
ex_cust.c
#ORG
#rom
Syntax:
Elements:
Purpose:
Allows the insertion of data into the .HEX file. In particular, this may be
used to program the '84 data EEPROM, as shown in the following
example.
Note that if the #ROM address is inside the program memory space,
the directive creates a segment for the data, resulting in an error if a
#ORG is over the same area. The #ROM data will also be counted as
used program memory space.
The type option indicates the type of each item, the default is 16 bits.
Using char as the type treats each item as 7 bits packing 2 chars into
every pcm 14-bit word.
When linking multiple compilation units be aware this directive applies
87
PCD_May 2015
to the final object file.
Some special forms of this directive may be used for verifying program
memory:
#ROM address = checksum
This will put a value at address such that the entire program memory
will sum to 0x1248
#ROM address = crc16
This will put a value at address that is a crc16 of all the program
memory except the specified address
#ROM address = crc8
This will put a value at address that is a crc16 of all the program
memory except the specified address
Examples:
Example Files:
None
Also See:
#ORG
#separate
Syntax:
#SEPARATE options
Elements:
88
PreProcessor
function.
You cannot use STDCALL with the ARG, DND or AVOID parameters.
If you do not specify one of these options, the compiler will determine
the best configuration, and will usually not use the stack for function
parameters (usually scratch space is allocated for parameters).
Purpose:
Examples:
Example Files:
ex_cust.c
Also See:
#INLINE
#serialize
Syntax:
Elements:
PCD_May 2015
number in a USB descriptor.
Use only one of the next three options:
file="filename.txt" - The file x is used to read the initial serial number
from, and this file is updated by the ICD programmer. It is assumed this
is a one line file with the serial number. The programmer will increment
the serial number.
listfile="filename.txt" - The file x is used to read the initial serial
number from, and this file is updated by the ICD programmer. It is
assumed this is a file one serial number per line. The programmer will
read the first line then delete that line from the file.
next="x" - The serial number X is used for the first load, then the hex
file is updated to increment x by one.
Other optional parameters:
prompt="text" - If specified the user will be prompted for a serial
number on each load. If used with one of the above three options then
the default value the user may use is picked according to the above
rules.
log=xxx - A file may optionally be specified to keep a log of the date,
time, hex file name and serial number each time the part is programmed.
If no id=xxx is specified then this may be used as a simple log of all
loads of the hex file.
Purpose:
Examples:
90
PreProcessor
#serialize(dataee=0, string=2,next="AB",prompt="Put in
Serial number")
Example Files:
None
Also See:
None
#task
(The RTOS is only included with the PCW, PCWH, and PCWHD software packages.)
Each RTOS task is specified as a function that has no parameters and no return. The #TASK
directive is needed just before each RTOS task to enable the compiler to tell which functions are
RTOS tasks. An RTOS task cannot be called directly like a regular function can.
Syntax:
#TASK (options)
Elements:
Purpose:
This directive tells the compiler that the following function is an RTOS
task.
The rate option is used to specify how often the task should execute.
This must be a multiple of the minor_cycle option if one is specified in
the #USE RTOS directive.
The max option is used to specify how much processor time a task will
use in one execution of the task. The time specified in max must be
equal to or less than the time specified in the minor_cycle option of the
#USE RTOS directive before the project will compile successfully. The
91
PCD_May 2015
compiler does not have a way to enforce this limit on processor time, so
a programmer must be careful with how much processor time a task
uses for execution. This option does not need to be specified.
The queue option is used to specify the number of bytes to be reserved
for the task to receive messages from other tasks or functions. The
default queue value is 0.
Examples:
Also See:
#USE RTOS
__time__
Syntax:
__TIME__
Elements:
None
Purpose:
Examples:
Example Files:
None
Also See:
None
#type
Syntax:
92
#TYPE standard-type=size
#TYPE default=area
#TYPE unsigned
#TYPE signed
#TYPE char=signed
#TYPE char=unsigned
#TYPE ARG=Wx:Wy
#TYPE DND=Wx:Wy
#TYPE AVOID=Wx:Wy
#TYPE RECURSIVE
#TYPE CLASSIC
PreProcessor
Elements:
Purpose:
By default the compiler treats SHORT as 8 bits , INT as 16 bits, and LONG as 32
bits. The traditional C convention is to have INT defined as the most efficient size for
the target processor. This is why it is 16 bits on the dsPIC/PIC24 . In order to help
with code compatibility a #TYPE directive may be used to allow these types to be
changed. #TYPE can redefine these keywords.
Note that the commas are optional. Be warned CCS example programs and
include files may not work right if you use #TYPE in your program.
Classic will set the type sizes to be compatible with CCS PIC programs.
This directive may also be used to change the default RAM area used for variable
storage. This is done by specifying default=area where area is a addressmod
address space.
When linking multiple compilation units be aware this directive only applies to the
current compilation unit.
The #TYPE directive allows the keywords UNSIGNED and SIGNED to set the
default data type.
The ARG parameter tells the compiler that all functions can use those working
registers to receive parameters. The DND parameters tells the compiler that all
functions should not change those working registers (not use them for scratch
space). The AVOID parameter tells the compiler to not use those working registers
for passing variables to functions. If you are using recursive functions, then it will
use the stack for passing variables when there is not enough working registers to
hold variables; if you are not using recursive functions, the compiler will allocate
scratch space for holding variables if there is not enough working registers.
#SEPARATE can be used to set these parameters on an individual basis.
The RECURSIVE option tells the compiler that ALL functions can be recursive.
#RECURSIVE can also be used to assign this status on an individual basis.
Examples:
#TYPE
#TYPE default=area
addressmod (user_ram_block, 0x100, 0x1FF);
#type default=user_ram_block
93
PCD_May 2015
// 0x100-0x1FF
#type default=
#TYPE SIGNED
#TYPE
#TYPE
#TYPE
#TYPE
RECURSIVE
ARG=W0:W7
AVOID=W8:W15
DND=W8:W15
...
void main()
{
int variable1;
...
...
}
Example
Files:
Also See:
ex_cust.c
None
#undef
Syntax:
#UNDEF id
Elements:
Purpose:
Examples:
#if MAXSIZE<100
#undef MAXSIZE
#define MAXSIZE 100
#endif
Example Files:
None
Also See:
#DEFINE
94
PreProcessor
_unicode
Syntax:
__unicode( constant-string )
Elements:
Unicode format string
Purpose
This macro will convert a standard ASCII string to a Unicode
format string by inserting a \000 after each character and
removing the normal C string terminator.
For example: _unicode("ABCD")
will return:
"A\00B\000C\000D" (8 bytes total with the
terminator)
Since the normal C terminator is not used for these strings you
need to do one of the following for variable length strings:
string = _unicode(KEYWORD) "\000\000";
OR
string = _unicode(KEYWORD);
string_size = sizeof(_unicode(KEYWORD));
Examples:
#define USB_DESC_STRING_TYPE 3
#define USB_STRING(x)
(sizeof(_unicode(x))+2),USB_DESC_STRING_TYPE,_unicode(x)
#define USB_ENGLISH_STRING 4,USB_DESC_STRING_TYPE,0x09,0x04
//Microsoft Defined
for US-English
char const USB_STRING_DESC[]=[
USB_ENGLISH_STRING,
USB_STRING("CCS"),
USB_STRING("CCS HID DEMO")
};
Example Files:
usb_desc_hid.h
95
PCD_May 2015
#use capture
Syntax:
Elements:
#USE CAPTURE(options)
ICx/CCPx
Which CCP/Input Capture module to us.
INPUT = PIN_xx
Specifies which pin to use. Useful for device with
remappable pins, this will cause compiler to automatically
assign pin to peripheral.
TIMER=x
Specifies the timer to use with capture unit. If not
specified default to timer 1 for PCM and PCH compilers
and timer 3 for PCD compiler.
TICK=x
The tick time to setup the timer to. If not specified it will
be set to fastest as possible or if same timer was already
setup by a previous stream it will be set to that tick time.
If using same timer as previous stream and different tick
time an error will be generated.
FASTEST
Use instead of TICK=x to set tick time to fastest as
possible.
SLOWEST
Use instead of TICK=x to set tick time to slowest as
possible.
CAPTURE_RISING
Specifies the edge that timer value is captured on.
Defaults to CAPTURE_RISING.
CAPTURE_FALLING
Specifies the edge that timer value is captured on.
Defaults to CAPTURE_RISING.
CAPTURE_BOTH
PCD only. Specifies the edge that timer value is captured
on. Defaults to CAPTURE_RISING.
PRE=x
Specifies number of rising edges before capture event
occurs. Valid options are 1, 4 and 16, default to 1 if not
specified. Options 4 and 16 are only valid when using
CAPTURE_RISING, will generate an error is used with
96
PreProcessor
CAPTURE_FALLING or CAPTURE_BOTH.
ISR=x
PCD only. Specifies the number of capture events to
occur before generating capture interrupt. Valid options
are 1, 2, 3 and 4, defaults to 1 is not specified. Option 1
is only valid option when using CAPTURE_BOTH, will
generate an error if trying to use 2, 3 or 4 with it.
STREAM=id
Associates a stream identifier with the capture module.
The identifier may be used in functions like
get_capture_time().
DEFINE=id
Creates a define named id which specifies the number of
capture per second. Default define name if not specified
is CAPTURES_PER_SECOND. Define name must start
with an ASCII letter 'A' to 'Z', an ASCII letter 'a' to 'z' or an
ASCII underscore ('_').
Purpose:
Examples:
#USE
CAPTURE(INPUT=PIN_C2,CAPTURE_RISING,TIMER=
1,FASTEST)
Example
Files:
Also See:
None.
get_capture_time(), get_capture_event()
97
PCD_May 2015
#use delay
Syntax:
Elements:
Also See:
delay_ms(), delay_us()
#use dynamic_memory
Syntax:
#USE DYNAMIC_MEMORY
Elements:
None
Purpose:
98
PreProcessor
Examples:
#USE DYNAMIC_MEMORY
void main ( ){
}
Example
Files:
Also See:
ex_malloc.c
None
#use fast_io
Syntax:
Elements:
port is A, B, C, D, E, F, G, H, J or ALL
Purpose:
Affects how the compiler will generate code for input and output instructions that
follow. This directive takes effect until another #use xxxx_IO directive is
encountered. The fast method of doing I/O will cause the compiler to perform I/O
without programming of the direction register. The compiler's default operation is
the opposite of this command, the direction I/O will be set/cleared on each I/O
operation. The user must ensure the direction register is set correctly via
set_tris_X(). When linking multiple compilation units be aware this directive only
applies to the current compilation unit.
Examples:
#use fast_io(A)
Example
Files:
Also See:
ex_cust.c
#USE FIXED_IO, #USE STANDARD_IO, set_tris_X() , General Purpose I/O
#use fixed_io
Syntax:
Elements:
port is A-G, pin is one of the pin constants defined in the devices .h file.
Purpose:
This directive affects how the compiler will generate code for input and output
instructions that follow. This directive takes effect until another #USE XXX_IO
directive is encountered. The fixed method of doing I/O will cause the compiler to
generate code to make an I/O pin either input or output every time it is used. The
pins are programmed according to the information in this directive (not the
operations actually performed). This saves a byte of RAM used in standard I/O.
99
PCD_May 2015
When linking multiple compilation units be aware this directive only applies to the
current compilation unit.
Examples:
Example
Files:
Also See:
None
#USE FAST_IO, #USE STANDARD_IO, General Purpose I/O
#use i2c
Syntax:
Elements:
SLAVE
SCL=pin
SDA=pin
ADDRESS=nn
FAST
FAST=nnnnnn
SLOW
RESTART_WDT
FORCE_HW
FORCE_SW
NOFLOAT_HIGH
SMBUS
STREAM=id
100
NO_STRETCH
MASK=nn
I2C1
PreProcessor
I2C2
NOINIT
CCS offers support for the hardware-based I2CTM and a software-based master
I2CTM device.(For more information on the hardware-based I2C module, please
consult the datasheet for your target device; not all PICs support I2C TM.
The I2C library contains functions to implement an I2C bus. The #USE I2C remains
in effect for the I2C_START, I2C_STOP, I2C_READ, I2C_WRITE and I2C_POLL
functions until another USE I2C is encountered. Software functions are generated
unless the FORCE_HW is specified. The SLAVE mode should only be used with the
built-in SSP. The functions created with this directive are exported when using
multiple compilation units. To access the correct function use the stream identifier.
Examples:
Example
Files:
Also See:
#use profile()
Syntax:
#use profile(options)
Elements:
TIMER
PCD_May 2015
1
BAUD=
x
Purpose:
Tell the compiler to add the code profiler run-time in the microcontroller and configure
the link and clock.
Examples:
Example
Files:
Also See:
ex_profile.c
#profile(), profileout(), Code Profile overview
#use pwm
Syntax:
Elements:
TIMER=x
FREQUENCY=x
102
PreProcessor
PERIOD=x
BITS=x
DUTY=x
PWM_ON
PWM_OFF
STREAM=id
Purpose:
This directive tells the compiler to setup a PWM on the specified pin using the
specified frequency, period, duty cycle and resolution. The #USE DELAY directive
must appear before this directive can be used. This directive enables use of built-in
functions such as set_pwm_duty_percent(), set_pwm_frequency(),
set_pwm_period(), pwm_on() and pwm_off().
Examples:
None
103
PCD_May 2015
Also See:
#use rs232
Syntax:
Elements:
104
BAUD=x
XMIT=pin
RCV=pin
FORCE_SW
BRGH1OK
ENABLE=pin
DEBUGGER
RESTART_WDT
INVERT
PARITY=X
Where x is N, E, or O.
BITS =X
FLOAT_HIGH
PreProcessor
ERRORS
SAMPLE_EARLY
RETURN=pin
MULTI_MASTER
LONG_DATA
DISABLE_INTS
STOP=X
TIMEOUT=X
SYNC_SLAVE
SYNC_MASTER
PCD_May 2015
the data in/out.
SYNC_MATER_CONT
UART1
UART1A
UART2
UART2A
NOINIT
ICD
UART3
UART4
ICD
TRANSMIT_BUFFER=x
106
PreProcessor
TXISR
NOTXISR
RTS_LEVEL=x
CTS = PIN_xx
CTS_LEVEL=x
FLOW_CONTROL_MODE
SIMPLEX_MODE
Purpose:
This directive tells the compiler the baud rate and pins used for serial I/O. This
directive takes effect until another RS232 directive is encountered. The #USE
DELAY directive must appear before this directive can be used. This directive
107
PCD_May 2015
enables use of built-in functions such as GETC, PUTC, and PRINTF. The functions
created with this directive are exported when using multiple compilation units. To
access the correct function use the stream identifier.
When using parts with built-in UART and the UART pins are specified, the SCI will
be used. If a baud rate cannot be achieved within 3% of the desired value using the
current clock rate, an error will be generated. The definition of the RS232_ERRORS
is as follows:
No UART:
Bit 7 is 9th bit for 9 bit data mode (get and put).
Bit 6 set to one indicates a put failed in float high mode.
With a UART:
Used only by get:
Copy of RCSTA register except:
Bit 0 is used to indicate a parity error.
Warning:
The PIC UART will shut down on overflow (3 characters received by the hardware
with a GETC() call). The "ERRORS" option prevents the shutdown by detecting the
condition and resetting the UART.
Examples:
Example
Files:
Also See:
ex_cust.c
getc(), putc(), printf(), setup_uart( ), RS2332 I/O overview
#use rtos
(The RTOS is only included with the PCW and PCWH packages.)
The CCS Real Time Operating System (RTOS) allows a PIC
micro controller to run regularly scheduled tasks without the
need for interrupts. This is accomplished by a function
(RTOS_RUN()) that acts as a dispatcher. When a task is
scheduled to run, the dispatch function gives control of the
processor to that task. When the task is done executing or
does not need the processor anymore, control of the
processor is returned to the dispatch function which then will
give control of the processor to the next task that is scheduled
to execute at the appropriate time. This process is called
cooperative multi-tasking.
108
PreProcessor
Syntax:
Elements:
Purpose:
This directive tells the compiler which timer on the PIC to use for monitoring and
when to grant control to a task. Changes to the specified timer's prescaler will effect
the rate at which tasks are executed.
This directive can also be used to specify the longest time that a task will ever take to
execute with the minor_cycle option. This simply forces all task execution rates to be
a multiple of the minor_cycle before the project will compile successfully. If the this
option is not specified the compiler will use a minor_cycle value that is the smallest
possible factor of the execution rates of the RTOS tasks.
If the statistics option is specified then the compiler will keep track of the minimum
processor time taken by one execution of each task, the maximum processor time
taken by one execution of each task, and the total processor time used by each task.
When linking multiple compilation units, this directive must appear exactly the same
in each compilation unit.
Examples:
Also See:
#TASK
#use spi
Syntax:
Elements:
PCD_May 2015
CLOCK_LOW=n
DI=pin
DO=pin
CLK=pin
MODE=n
ENABLE=pin
LOAD=pin
DIAGNOSTIC=pin
SAMPLE_RISE
SAMPLE_FALL
BITS=n
SAMPLE_COUNT=n
LOAD_ACTIVE=n
ENABLE_ACTIVE=n
IDLE=n
ENABLE_DELAY=n
DATA_HOLD=n
LSB_FIRST
MSB_FIRST
STREAM=id
SPI1
SPI2
FORCE_HW
SPI3
SPI4
NOINIT
XFER16
Purpose:
The SPI library contains functions to implement an SPI bus. After setting all of the
proper parameters in #USE SPI, the spi_xfer() function can be used to both transfer
and receive data on the SPI bus.
The SPI1 and SPI2 options will use the SPI hardware onboard the PIC. The most
common pins present on hardware SPI are: DI, DO, and CLK. These pins dont
need to be assigned values through the options; the compiler will automatically
assign hardware-specific values to these pins. Consult your PICs data sheet as to
where the pins for hardware SPI are. If hardware SPI is not used, then software SPI
will be used. Software SPI is much slower than hardware SPI, but software SPI can
use any pins to transfer and receive data other than just the pins tied to the PICs
hardware SPI pins.
The MODE option is more or less a quick way to specify how the stream is going to
sample data. MODE=0 sets IDLE=0 and SAMPLE_RISE. MODE=1 sets IDLE=0
and SAMPLE_FALL. MODE=2 sets IDLE=1 and SAMPLE_FALL. MODE=3 sets
110
PreProcessor
IDLE=1 and SAMPLE_RISE. There are only these 4 MODEs.
SPI cannot use the same pins for DI and DO. If needed, specify two streams: one to
send data and another to receive data.
The pins must be specified with DI, DO, CLK or SPIx, all other options are defaulted
as indicated above.
Examples:
Example
Files:
Also See:
None
spi_xfer()
#use standard_io
Syntax:
Elements:
port is A, B, C, D, E, F, G, H, J or ALL
Purpose:
This directive affects how the compiler will generate code for input and output
instructions that follow. This directive takes effect until another #USE XXX_IO
directive is encountered. The standard method of doing I/O will cause the compiler
to generate code to make an I/O pin either input or output every time it is used. On
the 5X processors this requires one byte of RAM for every port set to standard I/O.
Standard_io is the default I/O method for all ports.
When linking multiple compilation units be aware this directive only applies to the
current compilation unit.
Examples:
#use standard_io(A)
Example
Files:
Also See:
ex_cust.c
#USE FAST_IO, #USE FIXED_IO, General Purpose I/O
111
PCD_May 2015
#use timer
Syntax:
Elements:
TIMER=x
Sets the timer to use as the tick timer. x is a valid timer that the PIC has. Default
value is 1 for Timer 1.
TICK=xx
Sets the desired time for 1 tick. xx can be used with ns(nanoseconds), us
(microseconds), ms (milliseconds), or s (seconds). If the desired tick time can't be
achieved it will set the time to closest achievable time and will generate a warning
specifying the exact tick time. The default value is 1us.
BITS=x
Sets the variable size used by the get_ticks() and set_ticks() functions for returning
and setting the tick time. x can be 8 for 8 bits, 16 for 16 bits, 32 for 32bits or 64 for
64 bits. The default is 32 for 32 bits.
ISR
Uses the timer's interrupt to increment the upper bits of the tick timer. This mode
requires the the global interrupt be enabled in the main program.
NOISR
The get_ticks() function increments the upper bits of the tick timer. This requires
that the get_ticks() function be called more often then the timer's overflow rate.
NOISR is the default mode of operation.
STREAM=id
Associates a stream identifier with the tick timer. The identifier may be used in
functions like get_ticks().
DEFINE=id
Creates a define named id which specifies the number of ticks that will occur in one
second. Default define name if not specified is TICKS_PER_SECOND. Define
name must start with an ASCII letter 'A' to 'Z', an ASCII letter 'a' to 'z' or an ASCII
underscore ('_').
COUNTER or COUNTER=x
Sets up specified timer as a counter instead of timer. x specifies the prescallar to
setup counter with, default is1 if x is not specified specified. The function get_ticks()
will return the current count and the function set_ticks() can be used to set count to
a specific starting value or to clear counter.
Purpose:
112
This directive creates a tick timer using one of the PIC's timers. The tick timer is
initialized to zero at program start. This directive also creates the define
TICKS_PER_SECOND as a floating point number, which specifies that number of
PreProcessor
ticks that will occur in one second.
Examples:
#USE TIMER(TIMER=1,TICK=1ms,BITS=16,NOISR)
unsigned int16 tick_difference(unsigned int16 current, unsigned int16
previous) {
return(current - previous);
}
void main(void) {
unsigned int16 current_tick, previous_tick;
current_tick = previous_tick = get_ticks();
while(TRUE) {
current_tick = get_ticks();
if(tick_difference(current_tick, previous_tick) > 1000) {
output_toggle(PIN_B0);
previous_tick = current_tick;
}
}
}
Example
Files:
Also See:
None
get_ticks(), set_ticks()
#use touchpad
Syntax:
Elements:
RANGE=x
Sets the oscillator charge/discharge current range. If x is L, current is nominally 0.1
microamps. If x is M, current is nominally 1.2 microamps. If x is H, current is
nominally 18 microamps. Default value is H (18 microamps).
THRESHOLD=x
x is a number between 1-100 and represents the percent reduction in the nominal
frequency that will generate a valid key press in software. Default value is 6%.
SCANTIME=xxMS
xx is the number of milliseconds used by the microprocessor to scan for one key
press. If utilizing multiple touch pads, each pad will use xx milliseconds to scan for
one key press. Default is 32ms.
PIN=char
If a valid key press is determined on PIN, the software will return the character
113
PCD_May 2015
char in the function touchpad_getc(). (Example: PIN_B0='A')
SOURCETIME=xxus (CTMU only)
xx is thenumber of microseconds each pin is sampled for by ADC during each scan
time period. Default is 10us.
Purpose:
This directive will tell the compiler to initialize and activate the Capacitive Sensing
Module (CSM)or Charge Time Measurement Unit (CTMU) on the microcontroller.
The compiler requires use of the TIMER0 and TIMER1 modules for CSM and
Timer1 ADC modules for CTMU, and global interrupts must still be activated in the
main program in order for the CSM or CTMU to begin normal operation. For most
applications, a higher RANGE, lower THRESHOLD, and higher SCANTIME will
result better key press detection. Multiple PIN's may be declared in options, but
they must be valid pins used by the CSM or CTMU. The user may also generate a
TIMER0 ISR with TIMER0's interrupt occuring every SCANTIME milliseconds. In
this case, the CSM's or CTMU's ISR will be executed first.
Examples:
Example
Files:
Also See:
None
touchpad_state( ), touchpad_getc( ), touchpad_hit( )
#warning
Syntax:
#WARNING text
Elements:
Purpose:
114
PreProcessor
Examples:
Example Files:
ex_psp.c
Also See:
#ERROR
#word
Syntax:
#WORD id = x
Elements:
id is a valid C identifier,
x is a C variable or a constant
Purpose:
If the id is already known as a C variable then this will locate the variable at address
x. In this case the variable type does not change from the original definition. If the id
is not known a new C variable is created and placed at address x with the type
int16
Warning: In both cases memory at x is not exclusive to this variable. Other
variables may be located at the same location. In fact when x is a variable, then id
and x share the same memory location.
Examples:
Example
Files:
Also See:
None
#bit, #byte, #locate, #reserve, Named Registers, Type Specifiers, Type Qualifiers,
Enumerated Types, Structures & Unions, Typedef
115
PCD_May 2015
#zero_ram
Syntax:
#ZERO_RAM
Elements:
None
Purpose:
This directive zero's out all of the internal registers that may be used to hold
variables before program execution begins.
Examples:
#zero_ram
void main() {
}
Example
Files:
Also See:
116
ex_cust.c
None
BUILT-IN FUNCTIONS
BUILT-IN FUNCTIONS
The CCS compiler provides a lot of built-in functions to access and use the PIC microcontroller's
peripherals. This makes it very easy for the users to configure and use the peripherals without
going into in depth details of the registers associated with the functionality. The functions
categorized by the peripherals associated with them are listed on the next page. Click on the
function name to get a complete description and parameter and return value descriptions.
abs( ) ......................................................................................................................................... 125
sin( ) cos( ) tan( ) asin( ) acos() atan() sinh() cosh() tanh() atan2() ............................................ 125
adc_done( ) adc_done2( ) ......................................................................................................... 127
assert( ) ..................................................................................................................................... 127
atoe............................................................................................................................................ 128
atof( ) atof48( ) atof64( )............................................................................................................. 129
strtof48() .................................................................................................................................... 129
pin_select() ................................................................................................................................ 130
atoi( ) atol( ) atoi32( ) ................................................................................................................. 131
atol32() atoi48( ) atoi64( ) .......................................................................................................... 131
at_clear_interrupts( ).................................................................................................................. 132
at_disable_interrupts( ) .............................................................................................................. 133
at_enable_interrupts( )............................................................................................................... 133
at_get_capture( ) ....................................................................................................................... 134
at_get_missing_pulse_delay( ) .................................................................................................. 135
at_get_period( ) ......................................................................................................................... 135
at_get_phase_counter( )............................................................................................................ 136
at_get_resolution( ) .................................................................................................................... 137
at_get_set_point( ) ..................................................................................................................... 137
at_get_set_point_error( ) ........................................................................................................... 138
at_get_status( ) .......................................................................................................................... 138
at_interrupt_active( ) .................................................................................................................. 139
at_set_compare_time( ) ............................................................................................................. 140
at_set_missing_pulse_delay( ) .................................................................................................. 141
at_set_resolution( ) .................................................................................................................... 141
at_set_set_point( ) ..................................................................................................................... 142
at_setup_cc( ) ............................................................................................................................ 143
bit_clear( ) .................................................................................................................................. 144
bit_first( ).................................................................................................................................... 144
bit_last( ) .................................................................................................................................... 145
bit_set( )..................................................................................................................................... 145
bit_test( ).................................................................................................................................... 146
bsearch( ) .................................................................................................................................. 147
117
PCD_May 2015
calloc( ) ...................................................................................................................................... 148
ceil( ) .......................................................................................................................................... 148
clear_interrupt( ) ........................................................................................................................ 149
cog_status( ) .............................................................................................................................. 149
cog_restart( ) ............................................................................................................................. 150
crc_calc( ) .................................................................................................................................. 150
crc_calc8( ) ................................................................................................................................ 150
crc_calc16( ) .............................................................................................................................. 150
crc_calc32( ) .............................................................................................................................. 150
crc_init(mode) ............................................................................................................................ 151
cwg_status( ) ............................................................................................................................. 152
cwg_restart( ) ............................................................................................................................. 153
dac_write( ) ................................................................................................................................ 153
dci_data_received( ) .................................................................................................................. 154
dci_read( ) ................................................................................................................................. 154
dci_start( ) .................................................................................................................................. 155
dci_transmit_ready( ) ................................................................................................................. 156
dci_write( ) ................................................................................................................................. 157
delay_cycles( ) ........................................................................................................................... 157
delay_ms( ) ................................................................................................................................ 158
delay_us( ) ................................................................................................................................. 159
disable_interrupts( ) ................................................................................................................... 160
div( )........................................................................................................................................... 161
ldiv( ) .......................................................................................................................................... 161
dma_start( ) ............................................................................................................................... 162
dma_status( ) ............................................................................................................................. 163
enable_interrupts( ).................................................................................................................... 163
erase_program_memory ........................................................................................................... 164
ext_int_edge( ) ........................................................................................................................... 165
fabs( ) ........................................................................................................................................ 166
getc( ) getch( ) getchar( ) fgetc( ) ............................................................................................ 166
gets( ) fgets( ) ............................................................................................................................ 167
floor( ) ........................................................................................................................................ 168
fmod( ) ....................................................................................................................................... 168
printf( ) fprintf( ) ......................................................................................................................... 169
putc( ) putchar( ) fputc( ) .......................................................................................................... 171
puts( ) fputs( ) ........................................................................................................................... 172
free( ) ......................................................................................................................................... 172
frexp( ) ....................................................................................................................................... 173
scanf( )....................................................................................................................................... 174
get_capture( ) ............................................................................................................................ 176
get_capture( ) ............................................................................................................................ 177
get_capture_ccp1( ) get_capture_ccp2( ) get_capture_ccp3( ) get_capture_ccp4(
) get_capture_ccp5( )................................................................................................................ 177
get_capture32_ccp1( ) get_capture32_ccp2( ) get_capture32_ccp3( )
get_capture32_ccp4( ) get_capture32_ccp5( ) ......................................................................... 179
get_capture_event()................................................................................................................... 180
get_capture_time()..................................................................................................................... 181
118
Built-in Functions
get_capture32() ......................................................................................................................... 181
get_hspwm_capture( ) ............................................................................................................... 182
get_motor_pwm_count( ) ........................................................................................................... 183
get_nco_accumulator( ) ............................................................................................................. 183
get_nco_inc_value( ) ................................................................................................................. 184
get_ticks( ) ................................................................................................................................. 184
get_timerA( ) .............................................................................................................................. 185
get_timerB( ) .............................................................................................................................. 185
get_timerx( ) .............................................................................................................................. 186
get_timerxy( ) ............................................................................................................................. 187
get_timer_ccp1( ) get_timer_ccp2( ) get_timer_ccp3( ) get_timer_ccp4( )
get_timer_ccp5( ) ....................................................................................................................... 187
get_tris_x( ) ................................................................................................................................ 189
getc( ) getch( ) getchar( ) fgetc( ) ............................................................................................ 189
getenv( ) .................................................................................................................................... 190
gets( ) fgets( ) ............................................................................................................................ 195
goto_address( ).......................................................................................................................... 196
high_speed_adc_done( ) ........................................................................................................... 197
i2c_init( ) .................................................................................................................................... 198
i2c_isr_state( ) ........................................................................................................................... 198
i2c_poll( ) ................................................................................................................................... 199
i2c_read( ) ................................................................................................................................. 200
i2c_slaveaddr( ) ......................................................................................................................... 201
i2c_speed( ) ............................................................................................................................... 201
i2c_start( ) .................................................................................................................................. 202
i2c_stop( ) .................................................................................................................................. 203
i2c_write( ) ................................................................................................................................. 203
input( ) ....................................................................................................................................... 204
input_change_x( ) ...................................................................................................................... 205
input_state( ) .............................................................................................................................. 206
input_x( ) .................................................................................................................................... 206
interrupt_active( ) ....................................................................................................................... 207
isalnum(char) isalpha(char) ...................................................................................................... 208
iscntrl(x) isdigit(char)................................................................................................................. 208
isgraph(x) islower(char) isspace(char) isupper(char) isxdigit(char) isprint(x)
ispunct(x) ................................................................................................................................... 208
isamong( ) .................................................................................................................................. 209
itoa( ) ......................................................................................................................................... 210
kbhit( )........................................................................................................................................ 211
label_address( ) ......................................................................................................................... 212
labs( )......................................................................................................................................... 212
ldexp( ) ....................................................................................................................................... 213
log( ) .......................................................................................................................................... 213
log10( ) ...................................................................................................................................... 214
longjmp( ) ................................................................................................................................... 215
make8( ) .................................................................................................................................... 215
make16( ) .................................................................................................................................. 216
make32( ) .................................................................................................................................. 216
119
PCD_May 2015
malloc( ) ..................................................................................................................................... 217
memcpy( ) memmove( )............................................................................................................. 218
memset( ) .................................................................................................................................. 218
modf( ) ....................................................................................................................................... 219
_mul( ) ....................................................................................................................................... 220
nargs( ) ...................................................................................................................................... 220
offsetof( ) offsetofbit( )................................................................................................................ 221
output_x( ) ................................................................................................................................. 222
output_bit( ) ............................................................................................................................... 223
output_drive( ) ........................................................................................................................... 224
output_float( ) ............................................................................................................................ 224
output_high( ) ............................................................................................................................ 225
output_low( ) .............................................................................................................................. 226
output_toggle( ).......................................................................................................................... 227
perror( )...................................................................................................................................... 227
pid_busy( ) ................................................................................................................................. 228
pid_get_result( ) ......................................................................................................................... 228
pid_read( ) ................................................................................................................................. 229
pid_write( ) ................................................................................................................................. 230
pmp_address(address) .............................................................................................................. 231
pmp_output_full( ) pmp_input_full( ) pmp_overflow( ) pmp_error( ) pmp_timeout(
) ................................................................................................................................................. 232
pmp_read( ) ............................................................................................................................... 233
pmp_write( ) ............................................................................................................................... 234
port_x_pullups ( ) ....................................................................................................................... 235
pow( ) pwr( ) .............................................................................................................................. 236
printf( ) fprintf( ) .......................................................................................................................... 236
profileout() ................................................................................................................................. 238
psp_output_full( ) psp_input_full( ) psp_overflow( ) ................................................................. 239
psp_read( ) ................................................................................................................................ 240
psp_write( ) ................................................................................................................................ 241
putc( ) putchar( ) fputc( ) .......................................................................................................... 241
putc_send( ); .............................................................................................................................. 242
fputc_send( ); ............................................................................................................................. 242
puts( ) fputs( ) ........................................................................................................................... 243
pwm_off() ................................................................................................................................... 244
pwm_on() ................................................................................................................................... 244
pwm_set_duty() ......................................................................................................................... 245
pwm_set_duty_percent.............................................................................................................. 245
pwm_set_frequency................................................................................................................... 246
qei_get_count( ) ......................................................................................................................... 247
qei_set_count( ) ......................................................................................................................... 247
qei_status( ) ............................................................................................................................... 248
qsort( ) ....................................................................................................................................... 248
rand( ) ........................................................................................................................................ 249
rcv_buffer_bytes( ) ..................................................................................................................... 250
rcv_buffer_full( ) ......................................................................................................................... 250
read_adc( ) read_adc2( ) .......................................................................................................... 251
120
Built-in Functions
read_configuration_memory( ) ................................................................................................... 252
read_eeprom( ) .......................................................................................................................... 253
read_extended_ram( ) ............................................................................................................... 253
read_program_memory( ) .......................................................................................................... 254
read_high_speed_adc( ) ............................................................................................................ 255
read_rom_memory( ) ................................................................................................................. 257
read_sd_adc( )........................................................................................................................... 257
realloc( )..................................................................................................................................... 258
release_io() ................................................................................................................................ 259
reset_cpu( ) ............................................................................................................................... 259
restart_cause( ).......................................................................................................................... 260
restart_wdt( ) ............................................................................................................................. 260
rotate_left( ) ............................................................................................................................... 261
rotate_right( ) ............................................................................................................................. 262
rtc_alarm_read( ) ....................................................................................................................... 263
rtc_alarm_write( ) ....................................................................................................................... 263
rtc_read( ) .................................................................................................................................. 264
rtc_write( ) .................................................................................................................................. 265
rtos_await( ) ............................................................................................................................... 265
rtos_disable( ) ............................................................................................................................ 266
rtos_enable( ) ............................................................................................................................ 266
rtos_msg_poll( ) ......................................................................................................................... 267
rtos_msg_read( ) ....................................................................................................................... 267
rtos_msg_send( ) ....................................................................................................................... 268
rtos_overrun( ) ........................................................................................................................... 268
rtos_run( ) .................................................................................................................................. 269
rtos_signal( ) .............................................................................................................................. 270
rtos_stats( ) ................................................................................................................................ 270
rtos_terminate( ) ........................................................................................................................ 271
rtos_wait( ) ................................................................................................................................. 271
rtos_yield( ) ................................................................................................................................ 272
set_adc_channel( ) .................................................................................................................... 273
set_adc_channel2( ) .................................................................................................................. 273
set_analog_pins( ) ..................................................................................................................... 273
scanf( )....................................................................................................................................... 274
set_ccp1_compare_time( ) set_ccp2_compare_time( ) set_ccp3_compare_time( )
set_ccp4_compare_time( ) set_ccp5_compare_time( ) ............................................................. 277
set_cog_blanking( ) ................................................................................................................... 278
set_cog_dead_band( ) ............................................................................................................... 279
set_cog_phase( ) ....................................................................................................................... 280
set_compare_time( ) .................................................................................................................. 280
set_hspwm_duty( ) .................................................................................................................... 281
set_hspwm_event( ) .................................................................................................................. 282
set_hspwm_override( ) .............................................................................................................. 283
set_hspwm_phase( ) ................................................................................................................. 283
set_motor_pwm_duty( ) ............................................................................................................. 284
set_motor_pwm_event( ) ........................................................................................................... 285
set_motor_unit( )........................................................................................................................ 285
121
PCD_May 2015
set_nco_inc_value( ).................................................................................................................. 286
set_pullup( ) ............................................................................................................................... 287
set_pwm1_duty( ) set_pwm2_duty( ) set_pwm3_duty( ) set_pwm4_duty( )
set_pwm5_duty( ) ...................................................................................................................... 288
set_rtcc( ) set_timer0( ) set_timer1( ) set_timer2( ) set_timer3( ) set_timer4( )
set_timer5( ) .............................................................................................................................. 290
set_ticks( ) ................................................................................................................................. 291
setup_sd_adc_calibration( ) ....................................................................................................... 291
set_sd_adc_channel( ) .............................................................................................................. 292
set_timerA( ) .............................................................................................................................. 293
set_timerB( ) .............................................................................................................................. 293
set_timerx( ) ............................................................................................................................... 294
set_timerxy( ) ............................................................................................................................. 294
set_rtcc( ) set_timer0( ) set_timer1( ) set_timer2( ) set_timer3( ) set_timer4( )
set_timer5( ) .............................................................................................................................. 295
set_timer_ccp1( ) set_timer_ccp2( ) set_timer_ccp3( ) set_timer_ccp4( )
set_timer_ccp5( ) ....................................................................................................................... 296
set_timer_period_ccp1( ) set_timer_period_ccp2( ) set_timer_period_ccp3( )
set_timer_period_ccp4( ) set_timer_period_ccp5( ).................................................................. 297
set_tris_x( ) ................................................................................................................................ 299
set_uart_speed( )....................................................................................................................... 299
setjmp( )..................................................................................................................................... 300
setup_adc(mode) ....................................................................................................................... 301
setup_adc2(mode) ..................................................................................................................... 301
setup_adc_ports( ) ..................................................................................................................... 302
setup_adc_ports2( ) ................................................................................................................... 302
setup_adc_reference( ).............................................................................................................. 303
setup_at( ) ................................................................................................................................. 303
setup_capture( )......................................................................................................................... 304
setup_ccp1( ) setup_ccp2( ) setup_ccp3( ) setup_ccp4( ) setup_ccp5( )
setup_ccp6( ) ............................................................................................................................. 305
setup_clc1() setup_clc2() setup_clc3() setup_clc4() ............................................................... 307
setup_comparator( ) .................................................................................................................. 308
setup_compare( )....................................................................................................................... 309
setup_crc(mode) ........................................................................................................................ 309
setup_cog( ) ............................................................................................................................... 310
setup_crc( ) ................................................................................................................................ 311
setup_cwg( ) .............................................................................................................................. 312
setup_dac( ) ............................................................................................................................... 313
setup_dci( ) ................................................................................................................................ 314
setup_dma( ) ............................................................................................................................. 315
setup_high_speed_adc( ) .......................................................................................................... 315
setup_high_speed_adc_pair( ) .................................................................................................. 316
setup_hspwm_blanking( ) .......................................................................................................... 317
setup_hspwm_chop_clock( ) ..................................................................................................... 318
setup_hspwm_trigger( ) ............................................................................................................. 319
setup_hspwm_unit( ) ................................................................................................................. 320
setup_hspwm( ) ......................................................................................................................... 321
122
Built-in Functions
setup_hspwm_unit_chop_clock( ).............................................................................................. 321
setup_low_volt_detect( ) ............................................................................................................ 323
setup_motor_pwm( ) .................................................................................................................. 323
setup_oscillator( ) ...................................................................................................................... 324
setup_pid( ) ................................................................................................................................ 325
setup_pmp(option,address_mask)............................................................................................. 326
setup_power_pwm_pins( ) ......................................................................................................... 327
setup_psp(option,address_mask) .............................................................................................. 328
setup_pwm1( ) setup_pwm2( ) setup_pwm3( ) setup_pwm4( ) .............................................. 329
setup_qei( ) ................................................................................................................................ 330
setup_rtc( ) ................................................................................................................................ 331
setup_rtc_alarm( )...................................................................................................................... 331
setup_sd_adc( ) ......................................................................................................................... 332
setup_smtx( ) ............................................................................................................................. 333
setup_spi( ) setup_spi2( ) .......................................................................................................... 333
setup_timerx( ) ........................................................................................................................... 334
setup_timer_A( ) ........................................................................................................................ 336
setup_timer_B( ) ........................................................................................................................ 336
setup_timer_0( )......................................................................................................................... 337
setup_timer_1( )......................................................................................................................... 338
setup_timer_2( )......................................................................................................................... 338
setup_timer_3( )......................................................................................................................... 339
setup_timer_4( )......................................................................................................................... 340
setup_timer_5( )......................................................................................................................... 341
setup_uart( ) .............................................................................................................................. 341
setup_vref( ) .............................................................................................................................. 342
setup_wdt( ) ............................................................................................................................... 343
setup_zdc( ) ............................................................................................................................... 344
shift_left( ) .................................................................................................................................. 344
shift_right( ) ................................................................................................................................ 345
sleep( )....................................................................................................................................... 346
smtx_read( ) .............................................................................................................................. 347
smtx_reset_timer( ) .................................................................................................................... 348
smtx_start( ) ............................................................................................................................... 349
smtx_status( ) ............................................................................................................................ 349
smtx_stop( ) ............................................................................................................................... 350
smtx_write( ) .............................................................................................................................. 350
smtx_update( ) ........................................................................................................................... 351
spi_data_is_in( ) spi_data_is_in2( ) .......................................................................................... 352
spi_init() ..................................................................................................................................... 352
spi_prewrite(data); ..................................................................................................................... 353
spi_read( ) spi_read2( ) .......................................................................................................... 353
spi_read3( ) ............................................................................................................................... 353
spi_read4( ) ............................................................................................................................... 353
spi_read_16() ............................................................................................................................ 354
spi_read2_16() .......................................................................................................................... 354
spi_read3_16() .......................................................................................................................... 354
spi_read4_16() .......................................................................................................................... 354
123
PCD_May 2015
spi_speed .................................................................................................................................. 355
spi_write( ) spi_write2( )............................................................................................................ 356
spi_write3( ) ............................................................................................................................... 356
spi_write4( ) ............................................................................................................................... 356
spi_xfer( ) ................................................................................................................................... 357
SPII_XFER_IN() ........................................................................................................................ 357
sprintf( ) ..................................................................................................................................... 358
sqrt( ) ......................................................................................................................................... 359
srand( ) ...................................................................................................................................... 359
STANDARD STRING FUNCTIONS( ) memchr( ) memcmp( ) strcat( ) strchr( )
strcmp( ) strcoll( ) strcspn( ) strerror( ) stricmp( ) strlen( ) strlwr( ) strncat( )
strncmp( ) strncpy( ) strpbrk( ) strrchr( ) strspn( ) strstr( ) strxfrm( ) .......................................... 360
strcpy( ) strcopy( ) ...................................................................................................................... 362
strtod( ) strtof( ) strtof48( ) ........................................................................................................ 362
strtok( ) ...................................................................................................................................... 363
strtol( ) ....................................................................................................................................... 364
strtoul( ) ..................................................................................................................................... 365
swap( ) ....................................................................................................................................... 366
tolower( ) toupper( ) ................................................................................................................... 366
touchpad_getc( ) ........................................................................................................................ 367
touchpad_hit( ) ........................................................................................................................... 368
touchpad_state( ) ....................................................................................................................... 369
tx_buffer_available() .................................................................................................................. 370
tx_buffer_bytes() ........................................................................................................................ 371
tx_buffer_full( ) ........................................................................................................................... 371
va_arg( ) .................................................................................................................................... 372
va_end( ) ................................................................................................................................... 373
va_start ...................................................................................................................................... 374
write_configuration_memory( ) .................................................................................................. 374
write_eeprom( ).......................................................................................................................... 375
write_extended_ram( ) ............................................................................................................... 376
write_program_memory( ) ......................................................................................................... 377
zdc_status( ) .............................................................................................................................. 378
124
Built-in Functions
abs( )
Syntax:
value = abs(x)
Parameters:
Returns:
Function:
Availability:
All devices
Requires:
#INCLUDE <stdlib.h>
Examples:
Example Files:
None
Also See:
labs()
Parameters:
Returns:
rad is a float with a precision equal to val representing an angle in Radians -pi/2
to pi/2
val is a float with a precision equal to rad within the range -1.0 to 1.0.
125
PCD_May 2015
rad1 is a float with a precision equal to val representing an angle in Radians 0 to
pi
rad2 is a float with a precision equal to val representing an angle in Radians -pi to
pi
Result is a float with a precision equal to value
Function:
Availability:
All devices
Requires:
#INCLUDE <math.h>
Examples:
float phase;
// Output one sine wave
for(phase=0; phase<2*3.141596; phase+=0.01)
set_analog_voltage( sin(phase)+1 );
Example
Files:
Also See:
ex_tank.c
126
Built-in Functions
adc_done( ) adc_done2( )
Syntax:
value = adc_done();
value = adc_done2( );
Parameters:
None
Returns:
Function:
Availability:
Requires:
None
Examples:
int16 value;
setup_adc_ports(sAN0|sAN1, VSS_VDD);
setup_adc(ADC_CLOCK_DIV_4|ADC_TAD_MUL_8);
set_adc_channel(0);
read_adc(ADC_START_ONLY);
int1 done = adc_done();
while(!done) {
done = adc_done();
}
value = read_adc(ADC_READ_ONLY);
printf(A/C value = %LX\n\r, value);
}
Example
Files:
Also See:
None
setup_adc(), set_adc_channel(), setup_adc_ports(), read_adc(),
ADC Overview
assert( )
Syntax:
assert (condition);
Parameters:
Returns:
Nothing
127
PCD_May 2015
Function:
This function tests the condition and if FALSE will generate an error
message on STDERR (by default the first USE RS232 in the
program). The error message will include the file and line of the
assert(). No code is generated for the assert() if you #define
NODEBUG. In this way you may include asserts in your code for
testing and quickly eliminate them from the final program.
Availability:
All devices
Requires:
Examples:
assert( number_of_entries<TABLE_SIZE );
// If number_of_entries is >= TABLE_SIZE then
// the following is output at the RS232:
// Assertion failed, file myfile.c, line 56
Example
Files:
Also See:
None
#USE RS232, RS232 I/O Overview
atoe
Syntax:
atoe(string);
Parameters:
Returns:
Function:
Availability:
Requires:
#INCLUDE <stdlib.h>
Examples:
128
Built-in Functions
Example
Files:
Also See:
None
atoi(), atol(), atoi32(), atof(), printf()
Parameters:
Returns:
Function:
Availability:
All devices
Requires:
#INCLUDE <stdlib.h>
Examples:
Example
Files:
Also See:
ex_tank.c
atoi(), atol(), atoi32(), printf()
129
PCD_May 2015
pin_select()
Syntax:
Parameters:
Returns:
Availability:
Requires:
Examples:
130
Built-in Functions
Example Files:
Also See:
None.
#pin_select
ivalue = atoi(string)
or
lvalue = atol(string)
or
i32value = atoi32(string)
or
i48value=atoi48(string)
or
i64value=atoi64(string)
or
L32vale=atol32(string)
Parameters:
Returns:
Function:
Availability:
All devices
Requires:
#INCLUDE <stdlib.h>
Examples:
char string[10];
int x;
strcpy(string,"123");
x = atoi(string);
// x is now 123
Example
Files:
Also See:
input.c
printf()
131
PCD_May 2015
at_clear_interrupts( )
Syntax:
at_clear_interrupts(interrupts);
Parameters:
Returns:
Nothing
Function:
To disable the Angular Timer interrupt flags. More than one interrupt can be
cleared at a time by or'ing multiple constants together in a single call, or calling
function multiple times for each interrupt to clear.
Availability:
Requires:
Examples:
#INT-AT1
void1_isr(void)
[
if(at_interrupt_active(AT_PERIOD_INTERRUPT))
[
handle_period_interrupt();
at_clear_interrupts(AT_PERIOD_INTERRUPT);
]
if(at_interrupt(active(AT_PHASE_INTERRUPT);
[
handle_phase_interrupt();
at_clear_interrupts(AT_PHASE_INTERRUPT);
]
]
Example
Files:
Also See:
None
132
Built-in Functions
at_disable_interrupts( )
Syntax:
at_disable_interrupts(interrupts);
Parameters:
Returns:
Nothing
Function:
To disable the Angular Timer interrupts. More than one interrupt can be disabled
at a time by or'ing multiple constants together in a single call, or calling function
multiple times for eadch interrupt to be disabled.
Availability:
Requires:
Examples:
at_disable_interrupts(AT_PHASE_INTERRUPT);
at_disable_interrupts(AT_PERIOD_INTERRUPT|AT_CC1_INTERRUPT);
Example
Files:
Also See:
None
at_set_resolution(), at_get_resolution(), at_set_missing_pulse_delay(),
at_get_missing_pulse_delay(), at_get_period(), at_get_phase_counter(),
at_set_set_point(), at_get_set_point(), at_get_set_point_error(),
at_enable_interrupts(), at_clear_interrupts(), at_interrupt_active(), at_setup_cc(),
at_set_compare_time(), at_get_capture(), at_get_status(), setup_at()
at_enable_interrupts( )
Syntax:
at_enable_interrupts(interrupts);
Parameters:
PCD_May 2015
AT_PERIOD_INTERRUPT
AT_CC3_INTERRUPT
AT_CC2_INTERRUPT
AT_CC1_INTERRUPT
Returns:
Nothing
Function:
To enable the Angular Timer interrupts. More than one interrupt can be enabled at
a time by or'ing multiple constants together in a single call, or calling function
multiple times for each interrupt to be enabled.
Availability:
Requires:
Examples:
at_enable_interrupts(AT_PHASE_INTERRUPT);
at_enable_interrupts(AT_PERIOD_INTERRUPT|AT_CC1_INTERRUPT);
Example
Files:
Also See:
None
setup_at(), at_set_resolution(), at_get_resolution(), at_set_missing_pulse_delay(),
at_get_missing_pulse_delay(), at_get_phase_counter(), at_set_set_point(),
at_get_set_point(), at_get_set_point(), at_get_set_point_error(),
at_disable_interrupts(), at_clear_interrupts(), at_interrupt_active(), at_setup_cc(),
at_set_compare_time(), at_get_capture(), at_get_status()
at_get_capture( )
Syntax:
result=at_get_capture(which);;
Parameters:
Returns:
A 16-bit integer
Function:
Availability:
Requires:
Nothing
Examples:
result1=at_get_capture(1);
result2=at_get_capture(2);
134
Built-in Functions
Example
Files:
Also See:
None
setup_at(), at_set_resolution(), at_get_resolution(), at_set_missing_pulse_delay(),
at_get_missing_pulse_delay(), at_get_phase_counter(), at_set_set_point(),
at_get_set_point(), at_get_set_point(), at_get_set_point_error(),
at_enable_interrupts(), at_disable_interrupts(), at_clear_interrupts(),
at_interrupt_active(), at_setup_cc(), at_set_compare_time(), at_get_status()
at_get_missing_pulse_delay( )
Syntax:
result=at_get_missing_pulse_delay();
Parameters:
None.
Returns:
A 16-bit integer
Function:
Availability:
Requires:
Nothing
Examples:
result=at_get_missing_pulse_delay();
Example
Files:
Also See:
None
at_set_resolution(), at_get_resolution(), at_set_missing_pulse_delay(),
at_get_period(), at_get_phase_counter(), at_set_set_point(), at_get_set_point(),
at_get_set_point_error(), at_enable_interrupts(), at_disable_interrupts(),
at_clear_interrupts(), at_interrupt_active(), at_setup_cc(), at_set_compare_time(),
at_get_capture(), at_get_status(), setup_at()
at_get_period( )
Syntax:
result=at_get_period();
Parameters:
None.
Returns:
A 16-bit integer. The MSB of the returned value specifies whether the period
counter rolled over one or more times. 1 - counter rolled over at least once, 0 135
PCD_May 2015
value returned is valid.
Function:
Availability:
Requires:
Nothing
Examples:
result=at_get_period();
Example
Files:
Also See:
None
at_set_resolution(), at_get_resolution(), at_set_missing_pulse_delay(),
at_get_missing_pulse_delay(), at_get_phase_counter(), at_set_set_point(),
at_get_set_point(), at_get_set_point_error(), at_enable_interrupts(),
at_disable_interrupts(), at_clear_interrupts(), at_interrupt_active(), at_setup_cc(),
at_set_compare_time(), at_get_capture(), at_get_status(), setup_at()
at_get_phase_counter( )
Syntax:
result=at_get_phase_counter();
Parameters:
None.
Returns:
A 16-bit integer.
Function:
Availability:
Requires:
Nothing
Examples:
result=at_get_phase_counter();
Example
Files:
Also See:
None
136
Built-in Functions
at_get_resolution( )
Syntax:
result=at_get_resolution();
Parameters:
None
Returns:
A 16-bit integer
Function:
Availability:
Requires:
Nothing
Examples:
result=at_get_resolution();
Example
Files:
Also See:
None
at_set_resolution(), at_set_missing_pulse_delay(), at_get_missing_pulse_delay(),
at_get_period(), at_get_phase_counter(), at_set_set_point(), at_get_set_point(),
at_get_set_point_error(), at_enable_interrupts(), at_disable_interrupts(),
at_clear_interrupts(), at_interrupt_active(), at_setup_cc(), at_set_compare_time(),
at_get_capture(), at_get_status(), setup_at()
at_get_set_point( )
Syntax:
result=at_get_set_point();
Parameters:
None
Returns:
A 16-bit integer
Function:
Availability:
Requires:
Nothing
Examples:
result=at_get_set_point();
137
PCD_May 2015
Example
Files:
Also See:
None
at_set_resolution(), at_get_resolution(), at_set_missing_pulse_delay(),
at_get_missing_pulse_delay(), at_get_period(), at_get_phase_counter(),
at_set_set_point(), at_get_set_point_error(), at_enable_interrupts(),
at_disable_interrupts(), at_clear_interrupts(), at_interrupt_active(), at_setup_cc(),
at_set_compare_time(), at_get_capture(), at_get_status(), setup_at()
at_get_set_point_error( )
Syntax:
result=at_get_set_point_error();
Parameters:
None
Returns:
A 16-bit integer
Function:
To get the Angular Timer Set Point Error, the error of the measured period value
compared to the threshold setting.
Availability:
Requires:
Nothing
Examples:
result=at_get_set_point_error();
Example
Files:
Also See:
None
at_set_resolution(), at_get_resolution(), at_set_missing_pulse_delay(),
at_get_missing_pulse_delay(), at_get_period(), at_get_phase_counter(),
at_set_set_point(), at_get_set_point(), at_enable_interrupts(),
at_disable_interrupts(), at_clear_interrupts(), at_interrupt_active(), at_setup_cc(),
at_set_compare_time(), at_get_capture(), at_get_status(), setup_at()
at_get_status( )
Syntax:
result=at_get_status();
Parameters:
None
138
Built-in Functions
Returns:
An 8-bit integer. The possible results are defined in the device's header file as:
AT_STATUS_PERIOD_AND_PHASE_VALID
AT_STATUS_PERIOD_LESS_THEN_PREVIOUS
Function:
Availability:
Requires:
Nothing
Examples:
if((at_get_status()&AT_STATUS_PERIOD_AND_PHASE_VALID)==
AT_STATUS_PERIOD_AND_PHASE_VALID
[
Period=at_get_period();
Phase=at_get_phase();
]
Example
Files:
Also See:
None
at_set_resolution(), at_get_resolution(), at_set_missing_pulse_delay(),
at_get_missing_pulse_delay(), at_get_period(), at_get_phase_counter(),
at_set_set_point(), at_get_set_point(), at_get_set_point_error(),
at_enable_interrupts(), at_disable_interrupts(), at_clear_interrupts(),
at_interrupt_active(), at_setup_cc(), at_set_compare_time(), at_get_capture(),
setup_at()
at_interrupt_active( )
Syntax:
result=at_interrupt_active(interrupt);
Parameters:
Returns:
TRUE if the specified AT interrupt's flag is set, interrupt is active, or FALSE if the
flag is clear, interrupt is not active.
Function:
Availability:
PCD_May 2015
Requires:
Examples:
#INT-AT1
void1_isr(void)
[
if(at_interrupt_active(AT_PERIOD_INTERRUPT))
[
handle_period_interrupt();
at_clear_interrupts(AT_PERIOD_INTERRUPT);
]
if(at_interrupt(active(AT_PHASE_INTERRUPT);
[
handle_phase_interrupt();
at_clear_interrupts(AT_PHASE_INTERRUPT);
]
]
Example
Files:
Also See:
None
at_set_resolution(), at_get_resolution(), at_set_missing_pulse_delay(),
at_get_missing_pulse_delay(), at_get_period(), at_get_phase_counter(),
at_set_set_point(), at_get_set_point(), at_get_set_point_error(),
at_enable_interrupts(), at_disable_interrupts(), at_clear_interrupts(), at_setup_cc(),
at_set_compare_time(), at_get_capture(), at_get_status(), setup_at()
at_set_compare_time( )
Syntax:
at_set_compare_time(which, compare_time);
Parameters:
Returns:
Nothing
Function:
Availability:
Requires:
Examples:
at_set_compare_time(1,0x1FF);
at_set_compare_time(3,compare_time);
140
Built-in Functions
Example
Files:
Also See:
None
at_set_resolution(), at_get_resolution(), at_set_missing_pulse_delay(),
at_get_missing_pulse_delay(), at_get_period(), at_get_phase_counter(),
at_set_set_point(), at_get_set_point(), at_get_set_point_error(),
at_enable_interrupts(), at_disable_interrupts(), at_clear_interrupts(),
at_interrupt_active(), at_setup_cc(), at_get_capture(), at_get_status(), setup_at()
at_set_missing_pulse_delay( )
Syntax:
at_set_missing_pulse_delay(pulse_delay);
Parameters:
pulse_delay - a signed 16-bit constant or variable to set the missing pulse delay.
Returns:
Nothing
Function:
Availability:
Requires:
Nothing
Examples:
at_set_missing_pulse_delay(pulse_delay);
Example
Files:
Also See:
None
at_set_resolution(), at_get_resolution(), at_get_missing_pulse_delay(),
at_get_period(), at_get_phase_counter(), at_set_set_point(), at_get_set_point(),
at_get_set_point_error(), at_enable_interrupts(), at_disable_interrupts(),
at_clear_interrupts(), at_interrupt_active(), at_setup_cc(), at_set_compare_time(),
at_get_capture(), at_get_status(), setup_at()
at_set_resolution( )
Syntax:
at_set_resolution(resolution);
Parameters:
Returns:
Nothing
141
PCD_May 2015
Function:
Availability:
Requires:
Nothing
Examples:
at_set_resolution(resolution);
Example
Files:
Also See:
None
at_get_resolution(), at_set_missing_pulse_delay(), at_get_missing_pulse_delay(),
at_get_period(), at_get_phase_counter(), at_set_set_point(), at_get_set_point(),
at_get_set_point_error(), at_enable_interrupts(), at_disable_interrupts(),
at_clear_interrupts(), at_interrupt_active(), at_setup_cc(), at_set_compare_time(),
at_get_capture(), at_get_status(), setup_at()
at_set_set_point( )
Syntax:
at_set_set_point(set_point);
Parameters:
set_point - a 16-bit constant or variable to set the set point. The set point
determines the threshold setting that the period is compared against for error
calculation.
Returns:
Nothing
Function:
Availability:
Requires:
Nothing
Examples:
at_set_set_point(set_point);
Example
Files:
Also See:
None
.
142
Built-in Functions
at_setup_cc( )
Syntax:
at_setup_cc(which, settings);
Parameters:
Returns:
Nothing
Function:
Availability:
Requires:
Examples:
at_setup_cc(1,AT_CC_ENABLED|AT_CC_CAPTURE_MODE|
AT_CAPTURE_FALLING_EDGE|AT_CAPTURE_INPUT_ATCAP);
at_setup_cc(2,AT_CC_ENABLED|AT_CC_CAPTURE_MODE|
AT_CC_ACTIVE_HIGH);
Example
Files:
Also See:
None
at_set_resolution(), at_get_resolution(), at_set_missing_pulse_delay(),
at_get_missing_pulse_delay(), at_get_period(), at_get_phase_counter(),
at_set_set_point(), at_get_set_point(), at_get_set_point_error(),
at_enable_interrupts(), at_disable_interrupts(), at_clear_interrupts(),
at_interrupt_active(), at_set_compare_time(), at_get_capture(), at_get_status(),
setup_at()
143
PCD_May 2015
bit_clear( )
Syntax:
bit_clear(var, bit)
Parameters:
Returns:
undefined
Function:
Simply clears the specified bit in the given variable. The least
significant bit is 0. This function is the similar to: var &= ~(1<<bit);
Availability:
All devices
Requires:
Nothing
Examples:
int x;
x=5;
bit_clear(x,2);
// x is now 1
Example
Files:
Also See:
ex_patg.c
bit_set(), bit_test()
bit_first( )
Syntax:
Parameters:
value is a 0 to 1 to be shifted in
var is a 16 bit integer.
An 8 bit integer
Returns:
Function:
Availability:
30F/33F/24-bit devices
Requires:
Nothing
Examples:
144
Built-in Functions
Example Files:
None
Also See:
bit_last( )
Syntax:
Parameters:
Returns:
Function:
The first function will find the first occurrence of value in the var starting
with the most significant bit.
The second function will note the most significant bit of var and then
search for the first different bit.
Both functions return a 0 based result.
Availability:
30F/33F/24-bit devices
Requires:
Nothing
Examples:
//Bit pattern
//11101110 11111111
Int16 var = 0xEEFF;
Int8 N = 0;
//N is assigned 12
N = bit_last (0, var);
//N is assigned 12
N = bit_last(var);
Example Files:
None
Also See:
bit_set( )
Syntax:
bit_set(var, bit)
Parameters:
PCD_May 2015
Returns:
Undefined
Function:
Sets the specified bit in the given variable. The least significant bit is 0.
This function is the similar to: var |= (1<<bit);
Availability:
All devices
Requires:
Nothing
Examples:
int x;
x=5;
bit_set(x,3);
// x is now 13
Example Files:
ex_patg.c
Also See:
bit_clear(), bit_test()
bit_test( )
Syntax:
Parameters:
Returns:
0 or 1
Function:
Tests the specified bit in the given variable. The least significant bit is 0. This
function is much more efficient than, but otherwise similar to:
((var & (1<<bit)) != 0)
Availability:
All devices
Requires:
Nothing
Examples:
Example
146
ex_patg.c
Built-in Functions
Files:
Also See:
bit_clear(), bit_set()
bsearch( )
Syntax:
Parameters:
Returns:
Function:
Availability:
All devices
Requires:
#INCLUDE <stdlib.h>
Examples:
int nums[5]={1,2,3,4,5};
int compar(const void *arg1,const void *arg2);
void main() {
int *ip, key;
key = 3;
ip = bsearch(&key, nums, 5, sizeof(int), compar);
}
int compar(const void *arg1,const void *arg2) {
if ( * (int *) arg1 < ( * (int *) arg2) return 1
else if ( * (int *) arg1 == ( * (int *) arg2) return 0
else return 1;
}
Example Files:
None
Also See:
qsort()
147
PCD_May 2015
calloc( )
Syntax:
ptr=calloc(nmem, size)
Parameters:
Returns:
Function:
Availability:
All devices
Requires:
#INCLUDE <stdlibm.h>
Examples:
int * iptr;
iptr=calloc(5,10);
// iptr will point to a block of memory of
// 50 bytes all initialized to 0.
Example Files:
None
Also See:
ceil( )
Syntax:
Parameters:
Returns:
Function:
Availability:
All devices
Requires:
#INCLUDE<math.h>
Examples:
Example Files:
148
None
Built-in Functions
Also See:
floor()
clear_interrupt( )
Syntax:
clear_interrupt(level)
Parameters:
Returns:
undefined
Function:
Clears the interrupt flag for the given level. This function is designed for
use with a specific interrupt, thus eliminating the GLOBAL level as a
possible parameter. Some chips that have interrupt on change for
individual pins allow the pin to be specified like INT_RA1.
Availability:
All devices
Requires:
Nothing
Examples:
clear_interrupt(int_timer1);
Example Files:
None
Also See:
cog_status( )
Syntax:
value=cog_status();
Parameters:
None
Returns:
Function:
Availability:
Examples:
if(cog_status()==COG_AUTO_SHUTDOWN)
cog_restart();
149
PCD_May 2015
Example Files:
None
Also See:
setup_cog(), set_cog_dead_band(),
set_cog_blanking(), set_cog_phase(),
cog_restart()
cog_restart( )
Syntax:
cog_restart();
Parameters:
None
Returns:
Function:
Nothing
To restart the Complementary Output
Generator (COG) module after an autoshutdown
event occurs, when not using auto-restart
option of module.
All devices with a COG module.
Availability:
Examples:
if(cog_status()==COG_AUTO_SHUTDOWN)
cog_restart();
Example Files:
None
Also See:
setup_cog(), set_cog_dead_band(),
set_cog_blanking(), set_cog_phase(),
cog_status()
crc_calc( )
crc_calc8( )
crc_calc16( )
crc_calc32( )
Syntax:
150
Built-in Functions
Result = crc_calc8(ptr,len,[width]);
Result = crc_calc16(data,[width]);
Result = crc_calc16(ptr,len,[width]);
Result = crc_calc32(data,[width]);
Result = crc_calc32(ptr,len,[width]);
Parameters:
//same as crc_calc( )
//same as crc_calc( )
data- This is one double word, word or byte that needs to be processed
when using
crc_calc16( ), or crc_calc8( ), crc_calc32( )
ptr- is a pointer to one or more double words, words or bytes of data
len- number of double words, words or bytes to process for function calls
crc_calc16( ), or crc_calc8( ), crc_calc32( )
width- optional parameter used to specify the input data bit width to use
with the functions crc_calc16( ), and crc_calc8( ), crc_calc32( ) Only
available on devices with a 32-bit CRC peripheral.
If not specified, it defaults to the width of the return value of the function,
8-bit for crc_calc8( ), 16-bit for crc_calc16( ) and 32-bit for crc_calc32( ).
For devices with a 16-bit for CRC the input data bit width is the same as
the return bit width, crc_calc16( ) and 8-bit crc_calc8( ).
Returns:
Function:
This will process one data double word, word or byte or len double words,
words or bytes of data using the CRC engine.
Availability:
Requires:
Nothing
Examples:
int16 data[8];
Result = crc_calc(data,8);
Example Files:
None
Also See:
setup_crc(); crc_init()
crc_init(mode)
Syntax:
crc_init (data);
Parameters:
data - This will setup the initial value used by write CRC shift register.
151
PCD_May 2015
Most commonly, this register is set to 0x0000 for start of a new CRC
calculation.
Returns:
undefined
Function:
Configures the CRCWDAT register with the initial value used for CRC
calculations.
Availability:
Requires:
Nothing
Examples:
Example Files:
None
Also See:
cwg_status( )
Syntax:
value = cwg_status( );
Parame
ters:
Returns
:
Functio
n:
None
Availabi
lity:
Exampl
es:
Exampl
e Files:
Also
See:
None
152
if(cwg_status( ) == CWG_AUTO_SHUTDOWN)
cwg_restart( );
setup_cwg( ), cwg_restart( )
Built-in Functions
cwg_restart( )
Syntax:
cwg_restart( );
Parame
ters:
Returns
:
Functio
n:
None
Availabi
lity:
Exampl
es:
Exampl
e Files:
Also
See:
None
Nothing
To restart the CWG module after an auto-shutdown event
occurs, when not using auto-raster option of module.
if(cwg_status( ) == CWG_AUTO_SHUTDOWN)
cwg_restart( );
setup_cwg( ), cwg_status( )
dac_write( )
Syntax:
dac_write (value)
dac_write (channel, value)
Parameters:
Returns:
undefined
Function:
This function will write a 8-bit integer to the specified DAC channel.
This function will write a 16-bit integer to the specified DAC channel.
Availability:
Requires:
Nothing
Examples:
int i = 0;
setup_dac(DAC_VDD | DAC_OUTPUT);
while(1){
153
PCD_May 2015
i++;
dac_write(i);
}
int i = 0;
setup_dac(DAC_RIGHT_ON, 5);
while(1){
i++;
dac_write(DAC_RIGHT | i);
}
Also See:
dci_data_received( )
Syntax:
dci_data_received()
Parameters:
none
Returns:
Function:
Use this function to poll the receive buffers. It acts as a kbhit() function for DCI.
Availability:
Requires:
None
Examples:
while(1)
{
if(dci_data_received())
{
//read data, load buffers, etc
}
}
Example Files:
Also See:
None
DCI Overview, setup_dci( ), dci_start( ), dci_write( ), dci_read( ),
dci_transmit_ready( )
dci_read( )
Syntax:
Parameters:
left_channel- A pointer to a signed int16 that will hold the incoming audio data for
154
Built-in Functions
the left channel (on a stereo system). This data is received on the bus before the
right channel data (for situations where left & right channel does have meaning)
Returns:
Function:
right_channel- A pointer to a signed int16 that will hold the incoming audio data for
the right channel (on a stereo system). This data is received on the bus after the
data in left channel.
undefined
Use this function to read two data words. Do not use this function with DMA. This
function is provided mainly for applications involving a stereo codec.
Availability:
If your application does not use both channels but only receives on a slot (see
setup_dci), use only the left channel.
Only available on devices with DCI
Requires:
None
Examples:
while(1)
{
dci_read(&left_channel, &right_channel);
dci_write(&left_channel, &right_channel);
}
Example
Files:
Also See:
None
DCI Overview, setup_dci( ), dci_start( ), dci_write( ), dci_transmit_ready( ),
dci_data_received( )
dci_start( )
Syntax:
dci_start();
Parameters:
None
Returns:
undefined
Function:
Availability:
Requires:
None
155
PCD_May 2015
Examples:
dci_initialize((I2S_MODE | DCI_MASTER |
DCI_CLOCK_OUTPUT | SAMPLE_RISING_EDGE |
UNDERFLOW_LAST |
MULTI_DEVICE_BUS),DCI_1WORD_FRAME |
DCI_16BIT_WORD | DCI_2WORD_INTERRUPT,
RECEIVE_SLOT0 | RECEIVE_SLOT1, TRANSMIT_SLOT0 |
TRANSMIT_SLOT1, 6000);
dci_start();
Example
Files:
None
Also See:
dci_transmit_ready( )
Syntax:
dci_transmit_ready()
Parameters:
None
Returns:
Function:
Availability:
Requires:
None
Examples:
while(1)
{
if(dci_transmit_ready())
{
//transmit data, load buffers, etc
}
}
Example Files:
None
Also See:
156
Built-in Functions
dci_write( )
Syntax:
dci_write(left_channel, right_channel);
Parameters:
left channel- A pointer to a signed int16 that holds the outgoing audio data for the
left channel (on a stereo system). This data is transmitted on the bus before the
right channel data (for situations where left & right channel does have meaning)
Returns:
Function:
right channel- A pointer to a signed int16 that holds the outgoing audio data for the
right channel (on a stereo system). This data is transmitted on the bus after the
data in left channel.
undefined
Use this function to transmit two data words. Do not use this function with DMA.
This function is provided mainly for applications involving a stereo codec.
Availability:
If your application does not use both channels but only transmits on a slot (see
setup_dci()), use only the left channel. If you transmit more than two slots, call this
function multiple times.
Only available on devices with DCI
Requires:
None
Examples:
while(1)
{
dci_read(&left_channel, &right_channel);
dci_write(&left_channel, &right_channel);
}
None
Example
Files:
Also See:
delay_cycles( )
Syntax:
delay_cycles (count)
Parameters:
Returns:
undefined
157
PCD_May 2015
Function:
Availability:
All devices
Requires:
Nothing
Examples:
Example Files:
ex_cust.c
Also See:
delay_us(), delay_ms()
delay_ms( )
Syntax:
delay_ms (time)
Parameters:
Returns:
undefined
Function:
Availability:
All devices
Requires:
#USE DELAY
158
Built-in Functions
Examples:
Example Files:
ex_sqw.c
Also See:
delay_us( )
Syntax:
delay_us (time)
Parameters:
Returns:
undefined
Function:
Availability:
All devices
Requires:
#USE DELAY
Examples:
#use delay(clock=20000000)
do {
output_high(PIN_B0);
delay_us(duty);
output_low(PIN_B0);
delay_us(period-duty);
159
PCD_May 2015
} while(TRUE);
Example Files:
ex_sqw.c
Also See:
disable_interrupts( )
Syntax:
disable_interrupts (name)
disable_interrupts (INTR_XX)
disable_interrupts (expression)
Parameters:
Returns:
Function:
Disables the interrupt for the given name. Valid specific names are the
same as are used in #INT_xxx and are listed in the devices .h file. Note
that it is not necessary to disable interrupts inside an interrupt service
routine since interrupts are automatically disabled.
INTR_GLOBAL Disables all interrupts that can be disabled
INTR_NORMAL Use normal vectors for the ISR
INTR_ALTERNATE Use alternate vectors for the ISR
INTR_LEVEL0 .. INTR_LEVEL7 Disables interrupts at this level and
below, enables interrupts above this level
INTR_CN_PIN | PIN_xx Disables a CN pin interrupts
expression Disables interrupts during evaluation of the expression.
Availability:
Requires:
Examples:
160
Built-in Functions
disable_interrupts( memcpy(buffer1,buffer2,10 ) ) ;
enable_interrupts(ADC_DONE);
enable_interrupts(RB_CHANGE);
// these enable the interrupts
Example Files:
None
Also See:
div( )
ldiv( )
Syntax:
idiv=div(num, denom)
ldiv =ldiv(lnum, ldenom)
Parameters:
Returns:
idiv is a structure of type div_t and lidiv is a structure of type ldiv_t. The
div function returns a structure of type div_t, comprising of both the
quotient and the remainder. The ldiv function returns a structure of type
ldiv_t, comprising of both the quotient and the remainder.
Function:
The div and ldiv function computes the quotient and remainder of the
division of the numerator by the denominator. If the division is inexact,
the resulting quotient is the integer or long of lesser magnitude that is
the nearest to the algebraic quotient. If the result cannot be represented,
the behavior is undefined; otherwise quot*denom(ldenom)+rem shall
equal num(lnum).
Availability:
All devices.
Requires:
#INCLUDE <STDLIB.H>
Examples:
div_t idiv;
ldiv_t lidiv;
idiv=div(3,2);
//idiv will contain quot=1 and rem=1
lidiv=ldiv(300,250);
//lidiv will contain lidiv.quot=1 and lidiv.rem=50
161
PCD_May 2015
Example Files:
None
Also See:
None
dma_start( )
Syntax:
Parameters:
Returns:
void
Function:
Starts the DMA transfer for the specified channel in the specified mode of
operation.
Availability:
Requires:
Nothing
Examples:
Example Files:
None
Also See:
setup_dma(), dma_status()
162
Built-in Functions
dma_status( )
Syntax:
Value = dma_status(channel);
Parameters:
Returns:
Function:
This function will return the status of the specified channel in the DMA
module.
Availability:
Requires:
Nothing
Examples:
Int8 value;
value = dma_status(3); // This will return the status of
channel 3 of the DMA module.
Example Files:
None
Also See:
setup_dma(), dma_start().
enable_interrupts( )
Syntax:
enable_interrupts (name)
enable_interrupts (INTR_XX)
Parameters:
Returns:
undefined
Function:
Name -Enables the interrupt for the given name. Valid specific names are
the same as are used in #INT_xxx and are listed in the devices .h file.
INTR_GLOBAL Enables all interrupt levels (same as INTR_LEVEL0)
INTR_NORMAL Use normal vectors for the ISR
163
PCD_May 2015
INTR_ALTERNATE Use alternate vectors for the ISR
INTR_LEVEL0 .. INTR_LEVEL7 Enables interrupts at this level and
above, interrupts at lower levels are disabled
INTR_CN_PIN | PIN_xx Enables a CN pin interrupts
Availability:
Requires:
Examples:
enable_interrupts(INT_TIMER0);
enable_interrupts(INT_TIMER1);
enable_interrupts(INTR_CN_PIN|Pin_B0);
Example Files:
None
Also See:
erase_program_memory
Syntax:
erase_program_memory (address);
Parameters:
Returns:
undefined
Function:
Availability:
All devices
Requires:
Nothing
Examples:
164
Built-in Functions
erase_program_memory(address); // erase block of memory from 0x2000
to 0x2400 for a PIC24HJ/FJ /33FJ device, or erase 0x2000 to 0x2040
for a dsPIC30F chip
Example
Files:
Also See:
None
write program memory(), Program Eeprom Overview
ext_int_edge( )
Syntax:
Parameters:
Returns:
undefined
Function:
Determines when the external interrupt is acted upon. The edge may be
L_TO_H or H_TO_L to specify the rising or falling edge.
Availability:
Requires:
Examples:
Example Files:
ex_wakup.c
Also See:
165
PCD_May 2015
fabs( )
Syntax:
result=fabs (value)
Parameters:
Returns:
Function:
Availability:
All devices.
Requires:
#INCLUDE <math.h>
Examples:
double result;
result=fabs(-40.0)
// result is 40.0
Example Files:
None
Also See:
abs(), labs()
getc( )
getch( )
getchar( )
fgetc( )
Syntax:
value = getc()
value = fgetc(stream)
value=getch()
value=getchar()
Parameters:
Returns:
An 8 bit character
Function:
This function waits for a character to come in over the RS232 RCV pin and returns
the character. If you do not want to hang forever waiting for an incoming character
use kbhit() to test for a character available. If a built-in USART is used the hardware
can buffer 3 characters otherwise GETC must be active while the character is being
received by the PIC.
If fgetc() is used then the specified stream is used where getc() defaults to STDIN
166
Built-in Functions
(the last USE RS232).
Availability:
All devices
Requires:
#USE RS232
Examples:
printf("Continue (Y,N)?");
do {
answer=getch();
}while(answer!='Y' && answer!='N');
#use rs232(baud=9600,xmit=pin_c6,
rcv=pin_c7,stream=HOSTPC)
#use rs232(baud=1200,xmit=pin_b1,
rcv=pin_b0,stream=GPS)
#use rs232(baud=9600,xmit=pin_b3,
stream=DEBUG)
...
while(TRUE) {
c=fgetc(GPS);
fputc(c,HOSTPC);
if(c==13)
fprintf(DEBUG,"Got a CR\r\n");
}
Example
Files:
Also See:
ex_stwt.c
putc(), kbhit(), printf(), #USE RS232, input.c, RS232 I/O Overview
gets( ) fgets( )
Syntax:
gets (string)
value = fgets (string, stream)
Parameters:
Returns:
undefined
Function:
Reads characters (using getc()) into the string until a RETURN (value
13) is encountered. The string is terminated with a 0. Note that INPUT.C
has a more versatile get_string function.
If fgets() is used then the specified stream is used where gets() defaults
to STDIN (the last USE RS232).
167
PCD_May 2015
Availability:
All devices
Requires:
#USE RS232
Examples:
char string[30];
printf("Password: ");
gets(string);
if(strcmp(string, password))
printf("OK");
Example Files:
None
Also See:
floor( )
Syntax:
Parameters:
Returns:
Function:
Availability:
All devices.
Requires:
#INCLUDE <math.h>
Examples:
Example Files:
None
Also See:
ceil()
fmod( )
Syntax:
168
Built-in Functions
Parameters:
Returns:
result is a float with precision equal to input parameters val1 and val2
Function:
Returns the floating point remainder of val1/val2. Returns the value val1 i*val2 for some integer i such that, if val2 is nonzero, the result has the
same sign as val1 and magnitude less than the magnitude of val2.
Availability:
All devices.
Requires:
#INCLUDE <math.h>
Examples:
float result;
result=fmod(3,2);
// result is 1
Example Files:
None
Also See:
None
printf( )
fprintf( )
Syntax:
printf (string)
or
printf (cstring, values...)
or
printf (fname, cstring, values...)
fprintf (stream, cstring, values...)
Parameters:
Returns:
undefined
Function:
PCD_May 2015
value is to be formatted and output. Longs in the printf may be 16 or 32
bit. A %% will output a single %. Formatting rules for the % follows.
See the Expressions > Constants and Trigraph sections of this manual
for other escape character that may be part of the string.
If fprintf() is used then the specified stream is used where printf() defaults
to STDOUT (the last USE RS232).
Format:
The format takes the generic form %nt. n is optional and may be 1-9 to
specify how many characters are to be outputted, or 01-09 to indicate
leading zeros, or 1.1 to 9.9 for floating point and %w output. t is the type
and may be one of the following:
c
Character
s
String or character
u
Unsigned int
d
Signed int
Lu
Long unsigned int
Ld
Long signed int
x
Hex int (lower case)
X
Hex int (upper case)
Lx
Hex long int (lower case)
LX
Hex long int (upper case)
f
Float with truncated decimal
g
Float with rounded decimal
e
Float in exponential format
w
Unsigned int with decimal place inserted. Specify two
numbers for n. The first is a total field width. The
second is the desired number of decimal places.
Example formats:
Specifier
Value=0x12
%03u
018
%u
18
%2u
18
%5
18
%d
18
%x
12
%X
12
%4X
0012
%3.1w
1.8
* Result is undefined - Assume garbage.
Availability:
All Devices
Requires:
170
Value=0xfe
254
254
*
254
-2
fe
FE
00FE
25.4
Built-in Functions
Examples:
byte x,y,z;
printf("HiThere");
printf("RTCCValue=>%2x\n\r",get_rtcc());
printf("%2u %X %4X\n\r",x,y,z);
printf(LCD_PUTC, "n=%u",n);
Example Files:
ex_admm.c, ex_lcdkb.c
Also See:
atoi(), puts(), putc(), getc() (for a stream example), RS232 I/O Overview
putc( )
putchar( )
fputc( )
Syntax:
putc (cdata)
putchar (cdata)
fputc(cdata, stream)
Parameters:
Returns:
undefined
Function:
This function sends a character over the RS232 XMIT pin. A #USE
RS232 must appear before this call to determine the baud rate and pin
used. The #USE RS232 remains in effect until another is encountered
in the file.
If fputc() is used then the specified stream is used where putc() defaults
to STDOUT (the last USE RS232).
Availability:
All devices
Requires:
#USE RS232
Examples:
putc('*');
for(i=0; i<10; i++)
putc(buffer[i]);
putc(13);
Example Files:
ex_tgetc.c
Also See:
PCD_May 2015
puts( )
fputs( )
Syntax:
puts (string).
fputs (string, stream)
Parameters:
Returns:
undefined
Function:
Sends each character in the string out the RS232 pin using putc(). After
the string is sent a CARRIAGE-RETURN (13) and LINE-FEED (10) are
sent. In general printf() is more useful than puts().
If fputs() is used then the specified stream is used where puts() defaults
to STDOUT (the last USE RS232)
Availability:
All devices
Requires:
#USE RS232
Examples:
Example Files:
None
Also See:
free( )
Syntax:
free(ptr)
Parameters:
Returns:
No value
Function:
172
Built-in Functions
deallocated by a call to free or realloc function, the behavior is undefined.
Availability:
All devices.
Requires:
#INCLUDE <stdlibm.h>
Examples:
int * iptr;
iptr=malloc(10);
free(iptr)
// iptr will be deallocated
Example Files:
None
Also See:
frexp( )
Syntax:
Parameters:
Returns:
Function:
Availability:
All devices.
Requires:
#INCLUDE <math.h>
Examples:
float result;
signed int exp;
result=frexp(.5,&exp);
// result is .5 and exp is 0
Example Files:
None
Also See:
173
PCD_May 2015
scanf( )
Syntax:
scanf(cstring);
scanf(cstring, values...)
fscanf(stream, cstring, values...)
Parameters:
Returns:
Function:
Reads in a string of characters from the standard RS-232 pins and formats the
string according to the format specifiers. The format specifier character (%) used
within the string indicates that a conversion specification is to be done and the value
is to be saved into the corresponding argument variable. A %% will input a single
%. Formatting rules for the format specifier as follows:
If fscanf() is used, then the specified stream is used, where scanf() defaults to
STDIN (the last USE RS232).
Format:
The format takes the generic form %nt. n is an option and may be 1-99 specifying
the field width, the number of characters to be inputted. t is the type and maybe
one of the following:
174
Lu
Built-in Functions
Ld
Lo
x or X
Lx or LX
Li
f,g or e
Assigns the number of characters read thus far by the call to scanf()
to the corresponding argument. The corresponding argument
shall be a pointer to an unsigned integer.
An optional assignment-suppressing character (*) can be used after
the format specifier to indicate that the conversion specification is
to be done, but not saved into a corresponding variable. In this
case, no corresponding argument variable should be passed to
175
PCD_May 2015
the scanf() function.
A string composed of ordinary non-white space characters is
executed by reading the next character of the string. If one of the
inputted characters differs from the string, the function fails and
exits. If a white-space character precedes the ordinary non-white
space characters, then white-space characters are first read in
until a non-white space character is read.
White-space characters are skipped, except for the conversion
specifiers [, c or n, unless a white-space character precedes the [
or c specifiers.
Availability:
All Devices
Requires:
#USE RS232
Examples:
char name[2-];
unsigned int8 number;
signed int32 time;
if(scanf("%u%s%ld",&number,name,&time))
printf"\r\nName: %s, Number: %u, Time: %ld",name,number,time);
Example
Files:
Also See:
None
RS232 I/O Overview, getc(), putc(), printf()
get_capture( )
Syntax:
value = get_capture(x)
Parameters:
Returns:
Function:
This function obtains the last capture time from the indicated CCP module
Availability:
Requires:
None
Examples:
Example Files:
176
ex_ccpmp.c
Built-in Functions
Also See:
setup_ccpx( )
get_capture( )
Syntax:
Parameters:
Returns:
Function:
If wait is true, the current capture values in the result buffer are cleared, and the
next result to be sent to the buffer is returned. If wait is false, the default setting, the
first value currently in the buffer is returned. However, the buffer will only hold four
results while waiting for them to be read, so if read isn't being called for every
capture event, when wait is false, the buffer will fill with old capture values and any
new results will be lost.
Availability:
Requires:
None
Examples:
setup_timer3(TMR_INTERNAL | TMR_DIV_BY_8);
setup_capture(2, CAPTURE_FE | CAPTURE_TIMER3);
while(TRUE) {
timerValue = get_capture(2, TRUE);
printf(Capture 2 occurred at: %LU, timerValue);
}
Example
Files:
Also See:
None
setup_capture( ), setup_compare( ), Input Capture Overview
get_capture_ccp1( )
get_capture_ccp2( )
get_capture_ccp3( )
177
PCD_May 2015
get_capture_ccp4( )
get_capture_ccp5( )
Syntax:
value=get_capture_ccpx(wait);
Parameters:
wait -signifies if the compiler should read the oldest result in the buffer or
the next result in the buffer or the next result to enter the buffer.
Returns:
Function:
If wait is true, the current capture values in the result buffer are cleared,
and the next result to be sent, the buffer is returned. If wait is false, the
default setting, the first value currently in the buffer is return. However, the
buffer will only hold four results while waiting for them to be read. If read is
not being called for every capture event, when wait is false, the buffer will
fill with old capture values and any new result will be lost.
Availability:
Requires:
Nothing
Examples:
Example Files:
178
None
Built-in Functions
Also See:
get_capture32_ccp1( )
get_capture32_ccp2( )
get_capture32_ccp3( )
get_capture32_ccp4( )
get_capture32_ccp5( )
Syntax:
value=get_capture32_ccpx(wait);
Parameters:
wait -signifies if the compiler should read the oldest result in the buffer or
the next result in the buffer or the next result to enter the buffer.
Returns:
Function:
If wait is true, the current capture values in the result buffer are cleared,
and the next result to be sent, the buffer is returned. If wait is false, the
default setting, the first value currently in the buffer is return. However, the
buffer will only hold two results while waiting for them to be read. If read is
not being called for every capture event, when wait is false, the buffer will
fill with old capture values and any new result will be lost.
Availability:
Requires:
Nothing
179
PCD_May 2015
Examples:
Example Files:
None
Also See:
get_capture_event()
Syntax:
result = get_capture_event([stream]);
Parameters:
Returns:
Function:
Availability:
All devices.
Requires:
#USE CAPTURE
Examples:
#USE CAPTURE(INPUT=PIN_C2,CAPTURE_RISING,TIMER=1,FASTEST)
if(get_capture_event())
result = get_capture_time();
Example Files:
Also See:
None
#use_capture, get_capture_time()
180
Built-in Functions
get_capture_time()
Syntax:
result = get_capture_time([stream]);
Parameters:
Returns:
Function:
Availability:
All devices.
Requires:
#USE CAPTURE
Examples:
#USE CAPTURE(INPUT=PIN_C2,CAPTURE_RISING,TIMER=1,FASTEST)
result = get_capture_time();
Example Files:
None
Also See:
#use_capture, get_capture_event()
get_capture32()
Syntax:
result = get_capture32(x,[wait]);
Parameters:
x is 1-16 and defines which input capture result buffer modules to read from.
wait is an optional parameter specifying if the compiler should read the oldest
result in
the bugger or the next result to enter the buffer.
Returns:
Function:
PCD_May 2015
waiting for them
to be read, so if get_capture32 is not being called for every capture event. When
wait is false,
the buffer will fill with old capture values and any new results will be lost.
Availability:
Requires:
Nothing
Examples:
Example Files:
Also See:
None
setup_capture(), setup_compare(), get_capture(), Input Capture Overview
get_hspwm_capture( )
Syntax:
result=get_hspwm_capture(unit);
Parameters:
Returns:
Unsigned in16 value representing the capture PWM time base value.
Function:
Availability:
Gets the captured PWM time base value from the leading edge detection on the
current-limit input.
Only on devices with a built-in High Speed PWM module
(dsPIC33FJxxGSxxx, dsPIC33EPxxxMUxxx, dsPIC33EPxxxMCxxx,
and dsPIC33EVxxxGMxxx devices)
Requires:
None
Examples:
result=get_hspwm_capture(1);
Example
Files:
Also See:
None
182
Built-in Functions
set_hspwm_event(),
setup_hspwm_blanking(), setup_hspwm_trigger(), set_hspwm_override(),
setup_hspwm_chop_clock(), setup_hspwm_unit_chop_clock()
setup_hspwm(), setup_hspwm_secondary()
get_motor_pwm_count( )
Syntax:
Data16 = get_motor_pwm_count(pwm);
Parameters:
Returns:
16 bits of data
Function:
Availability:
Requires:
None
Examples:
Data16 = get_motor_pmw_count(1);
Example Files:
Also See:
None
setup_motor_pwm(), set_motor_unit(), set_motor_pwm_event(),
set_motor_pwm_duty();
get_nco_accumulator( )
Syntax:
value =get_nco_accumulator( );
Parameters:
none
Returns:
Availability:
Examples:
value = get_nco_accumulator( );
Example Files:
None
Also See:
setup_nco( ), set_nco_inc_value( ),
get_nco_inc_value( )
183
PCD_May 2015
get_nco_inc_value( )
Syntax:
value =get_nco_inc_value( );
Parameters:
None
Returns:
Availability:
Examples:
value = get_nco_inc_value( );
Example Files:
None
Also See:
setup_nco( ), set_nco_inc_value( ),
get_nco_accumulator( )
get_ticks( )
Syntax:
value = get_ticks([stream]);
Parameters:
Returns:
Function:
Returns the current tick value of the tick timer. The size returned depends on the
size of the tick timer.
Availability:
All devices.
Requires:
#USE TIMER(options)
Examples:
#USE TIMER(TIMER=1,TICK=1ms,BITS=16,NOISR)
void main(void) {
unsigned int16 current_tick;
current_tick = get_ticks();
}
Example
Files:
184
None
Built-in Functions
Also See:
get_timerA( )
Syntax:
value=get_timerA();
Parameters:
none
Returns:
Function:
Returns the current value of the timer. All timers count up. When a timer
reaches the maximum value it will flip over to 0 and continue counting (254,
255, 0, 1, 2, ).
Availability:
Requires:
Nothing
Examples:
set_timerA(0);
while(timerA < 200);
Example Files:
none
Also See:
get_timerB( )
Syntax:
value=get_timerB();
Parameters:
none
Returns:
Function:
Returns the current value of the timer. All timers count up. When a timer
reaches the maximum value it will flip over to 0 and continue counting
(254, 255, 0, 1, 2, ).
Availability:
Requires:
Nothing
Examples:
set_timerB(0);
185
PCD_May 2015
while(timerB < 200);
Example Files:
none
Also See:
get_timerx( )
Syntax:
value=get_timer1( )
value=get_timer2( )
value=get_timer3( )
value=get_timer4( )
value=get_timer5( )
value=get_timer6( )
value=get_timer7( )
value=get_timer8( )
value=get_timer9( )
Parameters:
None
Returns:
Function:
Availability:
Requires:
Nothing
Examples:
Example Files:
ex_stwt.c
Also See:
186
Built-in Functions
get_timerxy( )
Syntax:
value=get_timer23( )
value=get_timer45( )
value=get_timer67( )
value=get_timer89( )
Parameters:
Void
Returns:
Function:
Availability:
This function is available on all devices that have a valid 32 bit enabled
timers. Timers 2 & 3, 4 & 5, 6 & 7 and 8 & 9 may be used. The target
device must have one of these timer sets. The target timers must be
enabled as 32 bit.
Requires:
Nothing
Examples:
Example Files:
ex_stwt.c
Also See:
get_timer_ccp1( )
get_timer_ccp2( )
get_timer_ccp3( )
get_timer_ccp4( )
get_timer_ccp5( )
Syntax:
value32=get_timer_ccpx();
value16=get_timer_ccpx(which);
187
PCD_May 2015
Parameters:
Returns:
Function:
This function gets the timer values for the CCP module.
Availability:
Requires:
Nothing
Examples:
Example Files:
None
Also See:
188
Built-in Functions
get_tris_x( )
Syntax:
value = get_tris_A();
value = get_tris_B();
value = get_tris_C();
value = get_tris_D();
value = get_tris_E();
value = get_tris_F();
value = get_tris_G();
value = get_tris_H();
value = get_tris_J();
value = get_tris_K()
Parameters:
None
Returns:
Function:
Availability:
All devices.
Requires:
Nothing
Examples:
tris_a = GET_TRIS_A();
Example Files:
None
Also See:
getc( )
getch( )
getchar( )
fgetc( )
Syntax:
value = getc()
value = fgetc(stream)
value=getch()
value=getchar()
Parameters:
189
PCD_May 2015
Returns:
An 8 bit character
Function:
This function waits for a character to come in over the RS232 RCV pin and returns
the character. If you do not want to hang forever waiting for an incoming character
use kbhit() to test for a character available. If a built-in USART is used the hardware
can buffer 3 characters otherwise GETC must be active while the character is being
received by the PIC.
If fgetc() is used then the specified stream is used where getc() defaults to STDIN
(the last USE RS232).
Availability:
All devices
Requires:
#USE RS232
Examples:
printf("Continue (Y,N)?");
do {
answer=getch();
}while(answer!='Y' && answer!='N');
#use rs232(baud=9600,xmit=pin_c6,
rcv=pin_c7,stream=HOSTPC)
#use rs232(baud=1200,xmit=pin_b1,
rcv=pin_b0,stream=GPS)
#use rs232(baud=9600,xmit=pin_b3,
stream=DEBUG)
...
while(TRUE) {
c=fgetc(GPS);
fputc(c,HOSTPC);
if(c==13)
fprintf(DEBUG,"Got a CR\r\n");
}
Example
Files:
Also See:
ex_stwt.c
putc(), kbhit(), printf(), #USE RS232, input.c, RS232 I/O Overview
getenv( )
Syntax:
Parameters:
Returns:
190
Built-in Functions
Function:
FUSE_VALID:fffff
INT:iiiii
ID
DEVICE
CLOCK
VERSION
VERSION_STRING
PROGRAM_MEMORY
STACK
SCRATCH
DATA_EEPROM
EEPROM_ADDRESS
READ_PROGRAM
ADC_CHANNELS
ADC_RESOLUTION
ICD
SPI
191
PCD_May 2015
192
USB
CAN
I2C_SLAVE
I2C_MASTER
PSP
COMP
VREF
LCD
UART
AUART
CCPx
TIMERx
FLASH_WRITE_SIZE
FLASH_ERASE_SIZE
BYTES_PER_ADDRESS
BITS_PER_INSTRUCTION
RAM
Built-in Functions
SFR:name
BIT:name
SFR_VALID:name
BIT_VALID:name
PIN:PB
UARTx_RX
UARTx_TX
SPIx_DI
SPIxDO
SPIxCLK
ETHERNET
QEI
PCD_May 2015
194
DAC
DSP
DCI
DMA
CRC
CWG
NCO
CLC
DSM
OPAMP
RTC
CAP_SENSE
EXTERNAL_MEMORY
INSTRUCTION_CLOCK
ENH16
ENH24
IC
ICx
OC
Built-in Functions
OCx
RAM_START
PSV
Availability:
All devices
Requires:
Nothing
Examples:
#IF getenv("VERSION")<3.050
#ERROR Compiler version too old
#ENDIF
for(i=0;i<getenv("DATA_EEPROM");i++)
write_eeprom(i,0);
#IF getenv("FUSE_VALID:BROWNOUT")
#FUSE BROWNOUT
#ENDIF
#byte status_reg=GETENV(SFR:STATUS)
#bit carry_flag=GETENV(BIT:C)
Example Files:
None
Also See:
None
gets( ) fgets( )
Syntax:
gets (string)
value = fgets (string, stream)
195
PCD_May 2015
Parameters:
Returns:
undefined
Function:
Reads characters (using getc()) into the string until a RETURN (value
13) is encountered. The string is terminated with a 0. Note that INPUT.C
has a more versatile get_string function.
If fgets() is used then the specified stream is used where gets() defaults
to STDIN (the last USE RS232).
Availability:
All devices
Requires:
#USE RS232
Examples:
char string[30];
printf("Password: ");
gets(string);
if(strcmp(string, password))
printf("OK");
Example Files:
None
Also See:
goto_address( )
Syntax:
goto_address(location);
Parameters:
Returns:
Nothing
Function:
Availability:
All devices
Requires:
Nothing
Examples:
196
Built-in Functions
if(input(LOAD_REQUEST))
goto_address(LOADER);
Example Files:
setjmp.h
Also See:
label_address( )
high_speed_adc_done( )
Syntax:
value = high_speed_adc_done([pair]);
Parameters:
pair Optional parameter that determines which ADC pair's ready flag to check. If
not used all ready flags are checked.
Returns:
An int16. If pair is used 1 will be return if ADC is done with conversion, 0 will be
return if still busy. If pair isn't use it will return a bit map of which conversion are
ready to be read. For example a return value of 0x0041 means that ADC pair 6,
AN12 and AN13, and ADC pair 0, AN0 and AN1, are ready to be read.
Function:
Availability:
Requires:
None
Examples:
int16 result[2]
setup_high_speed_adc_pair(1, INDIVIDUAL_SOFTWARE_TRIGGER);
setup_high_speed_adc( ADC_CLOCK_DIV_4);
read_high_speed_adc(1, ADC_START_ONLY);
while(!high_speed_adc_done(1));
read_high_speed_adc(1, ADC_READ_ONLY, result);
printf(AN2 value = %LX, AN3 value = %LX\n\r,result[0],result[1]);
Example
Files:
Also See:
None
setup_high_speed_adc(), setup_high_speed_adc_pair(), read_high_speed_adc()
197
PCD_May 2015
i2c_init( )
Syntax:
i2c_init([stream],baud);
Parameters:
Returns:
Nothing
Function:
Availability:
All devices.
Requires:
#USE I2C
Examples:
Example Files:
None
Also See:
i2c_isr_state( )
Syntax:
state = i2c_isr_state();
state = i2c_isr_state(stream);
Parameters:
None
Returns:
198
Built-in Functions
the I2C address.
1-0x7F - Master has written data; i2c_read() will immediately return the
data
0x80 - Address match received with R/W bit set; perform i2c_read( ) to
read the I2C address, and use i2c_write( ) to pre-load the transmit buffer
for the next transaction (next I2C read performed by master will read this
byte).
0x81-0xFF - Transmission completed and acknowledged; respond with
i2c_write() to pre-load the transmit buffer for the next transation (the next
I2C read performed by master will read this byte).
Function:
Returns the state of I2C communications in I2C slave mode after an SSP
interrupt. The return value increments with each byte received or sent.
If 0x00 or 0x80 is returned, an i2C_read( ) needs to be performed to read
the I2C address that was sent (it will match the address configured by
#USE I2C so this value can be ignored)
Availability:
Requires:
#USE I2C
Examples:
#INT_SSP
void i2c_isr() {
state = i2c_isr_state();
if(state== 0 ) i2c_read();
i@c_read();
if(state == 0x80)
i2c_read(2);
if(state >= 0x80)
i2c_write(send_buffer[state - 0x80]);
else if(state > 0)
rcv_buffer[state - 1] = i2c_read();
}
Example Files:
ex_slave.c
Also See:
i2c_poll( )
Syntax:
i2c_poll()
i2c_poll(stream)
Parameters:
PCD_May 2015
Returns:
1 (TRUE) or 0 (FALSE)
Function:
The I2C_POLL() function should only be used when the built-in SSP is
used. This function returns TRUE if the hardware has a received byte in
the buffer. When a TRUE is returned, a call to I2C_READ() will
immediately return the byte that was received.
Availability:
Requires:
#USE I2C
Examples:
if(i2c-poll())
buffer [index]=i2c-read();//read data
Example Files:
None
Also See:
i2c_read( )
Syntax:
data = i2c_read();
data = i2c_read(ack);
data = i2c_read(stream, ack);
Parameters:
Returns:
Function:
Reads a byte over the I2C interface. In master mode this function will
generate the clock and in slave mode it will wait for the clock. There is
no timeout for the slave, use i2c_poll() to prevent a lockup. Use
restart_wdt() in the #USE I2C to strobe the watch-dog timer in the
slave mode while waiting.
Availability:
All devices.
Requires:
#USE I2C
200
Built-in Functions
Examples:
i2c_start();
i2c_write(0xa1);
data1 = i2c_read(TRUE);
data2 = i2c_read(FALSE);
i2c_stop();
Example Files:
Also See:
i2c_slaveaddr( )
Syntax:
I2C_SlaveAddr(addr);
I2C_SlaveAddr(stream, addr);
Parameters:
Returns:
Nothing
Function:
This functions sets the address for the I2C interface in slave mode.
Availability:
Requires:
#USE I2C
Examples:
i2c_SlaveAddr(0x08);
i2c_SlaveAddr(i2cStream1, 0x08);
Example Files:
ex_slave.c
Also See:
i2c_speed( )
Syntax:
i2c_speed (baud)
i2c_speed (stream, baud)
Parameters:
201
PCD_May 2015
Returns:
Nothing.
Function:
This function changes the I2c bit rate at run time. This only works if the
hardware I2C module is being used.
Availability:
All devices.
Requires:
#USE I2C
Examples:
I2C_Speed (400000);
Example Files:
none
Also See:
i2c_start( )
Syntax:
i2c_start()
i2c_start(stream)
i2c_start(stream, restart)
Parameters:
Returns:
undefined
Function:
Issues a start condition when in the I2C master mode. After the start
condition the clock is held low until I2C_WRITE() is called. If another
I2C_start is called in the same function before an i 2c_stop is called,
then a special restart condition is issued. Note that specific I2C
protocol depends on the slave device. The I2C_START function will
now accept an optional parameter. If 1 the compiler assumes the bus
is in the stopped state. If 2 the compiler treats this I2C_START as a
restart. If no parameter is passed a 2 is used only if the compiler
compiled a I2C_START last with no I2C_STOP since.
Availability:
All devices.
Requires:
#USE I2C
202
Built-in Functions
Examples:
i2c_start();
i2c_write(0xa0);
i2c_write(address);
i2c_start();
i2c_write(0xa1);
data=i2c_read(0);
i2c_stop();
Example Files:
Also See:
//
//
//
//
//
Device address
Data to device
Restart
to change data direction
Now read from slave
i2c_stop( )
Syntax:
i2c_stop()
i2c_stop(stream)
Parameters:
Returns:
undefined
Function:
Availability:
All devices.
Requires:
#USE I2C
Examples:
i2c_start();
i2c_write(0xa0);
i2c_write(5);
i2c_write(12);
i2c_stop();
Example Files:
Also See:
//
//
//
//
//
Start condition
Device address
Device command
Device data
Stop condition
i2c_write( )
Syntax:
i2c_write (data)
i2c_write (stream, data)
203
PCD_May 2015
Parameters:
Returns:
Function:
Sends a single byte over the I2C interface. In master mode this function
will generate a clock with the data and in slave mode it will wait for the
clock from the master. No automatic timeout is provided in this
function. This function returns the ACK bit. The LSB of the first write
after a start determines the direction of data transfer (0 is master to
slave). Note that specific I2C protocol depends on the slave device.
Availability:
All devices.
Requires:
#USE I2C
Examples:
long cmd;
...
i2c_start();
// Start condition
i2c_write(0xa0);// Device address
i2c_write(cmd);// Low byte of command
i2c_write(cmd>>8);// High byte of command
i2c_stop();
// Stop condition
Example Files:
Also See:
input( )
Syntax:
Parameters:
Pin to read. Pins are defined in the devices .h file. The actual value is a
bit address. For example, port a (byte 0x2C2 ) bit 3 would have a value
of 0x2C2*8+3 or 5651 . This is defined as follows: #define PIN_A3 5651
.
The PIN could also be a variable. The variable must have a value equal
to one of the constants (like PIN_A1) to work properly. The tristate
register is updated unless the FAST_IO mode is set on port A. note that
doing I/O with a variable instead of a constant will take much longer
time.
204
Built-in Functions
Returns:
Function:
This function returns the state of the indicated pin. The method of I/O is
dependent on the last USE *_IO directive. By default with standard I/O
before the input is done the data direction is set to input.
Availability:
All devices.
Requires:
Examples:
while ( !input(PIN_B1) );
// waits for B1 to go high
if( input(PIN_A0) )
printf("A0 is now high\r\n");
int16 i=PIN_B1;
while(!i);
//waits for B1 to go high
Example Files:
ex_pulse.c
Also See:
input_change_x( )
Syntax:
value = input_change_a( );
value = input_change_b( );
value = input_change_c( );
value = input_change_d( );
value = input_change_e( );
value = input_change_f( );
value = input_change_g( );
value = input_change_h( );
value = input_change_j( );
value = input_change_k( );
Parameters:
None
Returns:
Function:
This function reads the level of the pins on the port and compares them to the
results the last time the input_change_x( ) function was called. A 1 is returned if
the value has changed, 0 if the value is unchanged.
205
PCD_May 2015
Availability:
All devices.
Requires:
None
Examples:
pin_check = input_change_b( );
Example
Files:
Also See:
None
input( ), input_x( ), output_x( ), #USE FIXED_IO, #USE FAST_IO, #USE
STANDARD_IO, General Purpose I/O
input_state( )
Syntax:
value = input_state(pin)
Parameters:
pin to read. Pins are defined in the devices .h file. The actual value is a bit
address. For example, port a (byte 0x2C2 ) bit 3 would have a value of
0x2C2*8+3 or 5651 . This is defined as follows: #define PIN_A3 5651 .
Returns:
Bit specifying whether pin is high or low. A 1 indicates the pin is high and a
0 indicates it is low.
Function:
This function reads the level of a pin without changing the direction of the
pin as INPUT() does.
Availability:
All devices.
Requires:
Nothing
Examples:
level = input_state(pin_A3);
printf("level: %d",level);
Example Files:
None
Also See:
input_x( )
Syntax:
206
value = input_a()
Built-in Functions
value = input_b()
value = input_c()
value = input_d()
value = input_e()
value = input_f()
value = input_g()
value = input_h()
value = input_j()
value = input_k()
Parameters:
None
Returns:
Function:
Inputs an entire word from a port. The direction register is changed in accordance
with the last specified #USE *_IO directive. By default with standard I/O before the
input is done the data direction is set to input.
Availability:
All devices.
Requires:
Nothing
Examples:
data = input_b();
Example
Files:
Also See:
ex_psp.c
input(), output_x(), #USE FIXED_IO, #USE FAST_IO, #USE STANDARD_IO
interrupt_active( )
Syntax:
interrupt_active (interrupt)
Parameters:
Returns:
Boolean value
Function:
The function checks the interrupt flag of the specified interrupt and returns
true in case the flag is set.
Availability:
Requires:
Examples:
interrupt_active(INT_TIMER0);
interrupt_active(INT_TIMER1);
207
PCD_May 2015
Example Files:
None
Also See:
isalnum(char)
isalpha(char)
iscntrl(x)
isdigit(char)
isgraph(x)
islower(char)
isspace(char)
isupper(char)
isxdigit(char)
isprint(x)
ispunct(x)
Syntax:
value = isalnum(datac)
value = isalpha(datac)
value = isdigit(datac)
value = islower(datac)
value = isspace(datac)
value = isupper(datac)
value = isxdigit(datac)
value = iscntrl(datac)
value = isgraph(datac)
value = isprint(datac)
value = punct(datac)
Parameters:
Returns:
0 (or FALSE) if datac dose not match the criteria, 1 (or TRUE) if datac
does match the criteria.
Function:
208
Built-in Functions
isalpha(x)
isdigit(x)
islower(x)
isupper(x)
isspace(x)
isxdigit(x)
iscntrl(x)
isgraph(x)
isprint(x)
ispunct(x)
X is 'A'..'Z' or 'a'..'z
X is '0'..'9'
X is 'a'..'z'
X is 'A'..'Z
X is a space
X is '0'..'9', 'A'..'F', or 'a'..'f
X is less than a space
X is greater than a space
X is greater than or equal to a space
X is greater than a space and not a letter or
number
Availability:
All devices.
Requires:
#INCLUDE <ctype.h>
Examples:
char id[20];
...
if(isalpha(id[0])) {
valid_id=TRUE;
for(i=1;i<strlen(id);i++)
valid_id=valid_id && isalnum(id[i]);
} else
valid_id=FALSE;
Example Files:
ex_str.c
Also See:
isamong()
isamong( )
Syntax:
Parameters:
value is a character
cstring is a constant sting
Returns:
Function:
Availability:
All devices
Requires:
Nothing
Examples:
char x= 'x';
209
PCD_May 2015
...
if ( isamong ( x,
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ") )
printf ("The character is valid");
Example Files:
#INCLUDE <ctype.h>
Also See:
itoa( )
Syntax:
Parameters:
Returns:
Function:
Availability:
All devices
Requires:
#INCLUDE <stdlib.h>
Examples:
int32 x=1234;
char string[5];
itoa(x,10, string);
// string is now 1234
Example Files:
None
Also See:
None
210
Built-in Functions
kbhit( )
Syntax:
value = kbhit()
value = kbhit (stream)
Parameters:
Returns:
0 (or FALSE) if getc() will need to wait for a character to come in, 1 (or
TRUE) if a character is ready for getc()
Function:
If the RS232 is under software control this function returns TRUE if the
start bit of a character is being sent on the RS232 RCV pin. If the RS232
is hardware this function returns TRUE if a character has been received
and is waiting in the hardware buffer for getc() to read. This function may
be used to poll for data without stopping and waiting for the data to
appear. Note that in the case of software RS232 this function should be
called at least 10 times the bit rate to ensure incoming data is not lost.
Availability:
All devices.
Requires:
#USE RS232
Examples:
char timed_getc() {
long timeout;
timeout_error=FALSE;
timeout=0;
while(!kbhit()&&(++timeout<50000)) // 1/2
// second
delay_us(10);
if(kbhit())
return(getc());
else {
timeout_error=TRUE;
return(0);
}
}
Example Files:
ex_tgetc.c
Also See:
211
PCD_May 2015
label_address( )
Syntax:
value = label_address(label);
Parameters:
Returns:
Function:
This function obtains the address in ROM of the next instruction after the
label. This is not a normally used function except in very special
situations.
Availability:
All devices.
Requires:
Nothing
Examples:
start:
a = (b+c)<<2;
end:
printf("It takes %lu ROM locations.\r\n",
label_address(end)-label_address(start));
Example Files:
setjmp.h
Also See:
goto_address()
labs( )
Syntax:
Parameters:
Returns:
Function:
Availability:
All devices.
Requires:
#INCLUDE <stdlib.h>
Examples:
Example Files:
None
Also See:
abs()
212
Built-in Functions
ldexp( )
Syntax:
Parameters:
Returns:
Function:
Availability:
All devices.
Requires:
#INCLUDE <math.h>
Examples:
float result;
result=ldexp(.5,0);
// result is .5
Example Files:
None
Also See:
log( )
Syntax:
Parameters:
Returns:
Function:
PCD_May 2015
log: when the argument is negative
Availability:
All devices
Requires:
#INCLUDE <math.h>
Examples:
lnx = log(x);
Example Files:
None
Also See:
log10( )
Syntax:
Parameters:
Returns:
Function:
Availability:
All devices
Requires:
#INCLUDE <math.h>
Examples:
Example Files:
None
Also See:
214
Built-in Functions
longjmp( )
Syntax:
Parameters:
Returns:
Function:
Availability:
All devices
Requires:
#INCLUDE <setjmp.h>
Examples:
longjmp(jmpbuf, 1);
Example Files:
None
Also See:
setjmp()
make8( )
Syntax:
i8 = MAKE8(var, offset)
Parameters:
Returns:
An 8 bit integer
Function:
Extracts the byte at offset from var. Same as: i8 = (((var >> (offset*8)) &
0xff) except it is done with a single byte move.
Availability:
All devices
Requires:
Nothing
Examples:
int32 x;
int y;
y = make8(x,3);
// Gets MSB of x
215
PCD_May 2015
Example Files:
None
Also See:
make16(), make32()
make16( )
Syntax:
Parameters:
Returns:
A 16 bit integer
Function:
Availability:
All devices
Requires:
Nothing
Examples:
long x;
int hi,lo;
x = make16(hi,lo);
Example Files:
ltc1298.c
Also See:
make8(), make32()
make32( )
Syntax:
Parameters:
Returns:
A 32 bit integer
Function:
216
Built-in Functions
Availability:
All devices
Requires:
Nothing
Examples:
int32 x;
int y;
long z;
x = make32(1,2,3,4);
// x is 0x01020304
y=0x12;
z=0x4321;
x = make32(y,z);
// x is 0x00124321
x = make32(y,y,z);
Example Files:
ex_freqc.c
Also See:
make8(), make16()
// x is 0x12124321
malloc( )
Syntax:
ptr=malloc(size)
Parameters:
Returns:
Function:
The malloc function allocates space for an object whose size is specified
by size and whose value is indeterminate.
Availability:
All devices
Requires:
#INCLUDE <stdlibm.h>
Examples:
int * iptr;
iptr=malloc(10);
// iptr will point to a block of memory of 10 bytes.
Example Files:
None
Also See:
217
PCD_May 2015
memcpy( ) memmove( )
Syntax:
Parameters:
Returns:
undefined
Function:
Availability:
All devices
Requires:
Nothing
Examples:
Example Files:
None
Also See:
strcpy(), memset()
memset( )
Syntax:
Parameters:
218
Built-in Functions
Returns:
undefined
Function:
Availability:
All devices
Requires:
Nothing
Examples:
memset(arrayA, 0, sizeof(arrayA));
memset(arrayB, '?', sizeof(arrayB));
memset(&structA, 0xFF, sizeof(structA));
Example Files:
None
Also See:
memcpy()
modf( )
Syntax:
Parameters:
Returns:
Function:
The modf function breaks the argument value into integral and
fractional parts, each of which has the same sign as the argument. It
stores the integral part as a float in the object integral.
Availability:
All devices
Requires:
#INCLUDE <math.h>
Examples:
Example Files:
None
Also See:
None
219
PCD_May 2015
_mul( )
Syntax:
prod=_mul(val1, val2);
Parameters:
Returns:
val1
val2
prod
8
8
16
16*
16
32
32*
32
64
48*
48
64**
* or less
** large numbers will overflow with wrong results
Function:
Availability:
All devices
Requires:
Nothing
Examples:
Example
Files:
Also See:
None
None
nargs( )
Syntax:
Parameters:
The function can take variable parameters. The user can use stdarg
library to create functions that take variable parameters.
Returns:
Function dependent.
Function:
The stdarg library allows the user to create functions that supports
variable arguments.
The function that will accept a variable number of arguments must have
220
Built-in Functions
at least one actual, known parameters, and it may have more. The
number of arguments is often passed to the function in one of its actual
parameters. If the variable-length argument list can involve more that one
type, the type information is generally passed as well. Before processing
can begin, the function creates a special argument pointer of type va_list.
Availability:
All devices
Requires:
#INCLUDE <stdarg.h>
Examples:
Example Files:
None
Also See:
offsetof( ) offsetofbit( )
Syntax:
Parameters:
Returns:
An 8 bit byte
Function:
These functions return an offset into a structure for the indicated field.
offsetof returns the offset in bytes and offsetofbit returns the offset in bits.
221
PCD_May 2015
Availability:
All devices
Requires:
#INCLUDE <stddef.h>
Examples:
struct
time_structure {
int hour, min, sec;
int zone : 4;
intl daylight_savings;
}
x = offsetof(time_structure, sec);
// x will be 2
x = offsetofbit(time_structure, sec);
// x will be 16
x = offsetof (time_structure,
daylight_savings);
// x will be 3
x = offsetofbit(time_structure,
daylight_savings);
// x will be 28
Example Files:
None
Also See:
None
output_x( )
Syntax:
output_a (value)
output_b (value)
output_c (value)
output_d (value)
output_e (value)
output_f (value)
output_g (value)
output_h (value)
output_j (value)
output_k (value)
Parameters:
Returns:
undefined
Function:
Availability:
All devices, however not all devices have all ports (A-E)
222
Built-in Functions
Requires:
Nothing
Examples:
OUTPUT_B(0xf0);
Example Files:
ex_patg.c
Also See:
output_bit( )
Syntax:
Parameters:
Pins are defined in the devices .h file. The actual number is a bit
address. For example, port a (byte 0x2C2 ) bit 3 would have a value of
0x2C2*8+3 or 5651 . This is defined as follows: #define PIN_A3 5651 .
The PIN could also be a variable. The variable must have a value equal
to one of the constants (like PIN_A1) to work properly. The tristate
register is updated unless the FAST_IO mode is set on port A. Note that
doing I/O with a variable instead of a constant will take much longer
time.
Value is a 1 or a 0.
Returns:
undefined
Function:
Availability:
All devices.
Requires:
Examples:
223
PCD_May 2015
ouput_bit(i,shift_left(&data,1,input(PIN_B1)));
//same as above example, but
//uses a variable instead of a constant
Example Files:
Also See:
output_drive( )
Syntax:
output_drive(pin)
Parameters:
Pins are defined in the devices .h file. The actual value is a bit address. For
example, port a (byte 0x2C2 ) bit 3 would have a value of 0x2C2*8+3 or
5651 . This is defined as follows: #DEFINE PIN_A3 5651 .
Returns:
undefined
Function:
Availability:
All devices.
Requires:
Examples:
Example Files:
None
Also See:
output_float( )
Syntax:
output_float (pin)
Parameters:
Pins are defined in the devices .h file. The actual value is a bit
address. For example, port a (byte 0x2C2 ) bit 3 would have a value of
0x2C2*8+3 or 5651 . This is defined as follows: #DEFINE PIN_A3 5651
. The PIN could also be a variable to identify the pin. The variable must
have a value equal to one of the constants (like PIN_A1) to work
224
Built-in Functions
properly. Note that doing I/O with a variable instead of a constant will
take much longer time.
Returns:
undefined
Function:
Sets the specified pin to the input mode. This will allow the pin to float
high to represent a high on an open collector type of connection.
Availability:
All devices.
Requires:
Examples:
Example Files:
None
Also See:
output_high( )
Syntax:
output_high (pin)
Parameters:
Pin to write to. Pins are defined in the devices .h file. The actual value
is a bit address. For example, port a (byte 0x2C2 ) bit 3 would have a
value of 0x2C2*8+3 or 5651 . This is defined as follows: #DEFINE
PIN_A3 5651 . The PIN could also be a variable. The variable must
have a value equal to one of the constants (like PIN_A1) to work
properly. The tristate register is updated unless the FAST_IO mode is
set on port A. Note that doing I/O with a variable instead of a constant
will take much longer time.
Returns:
undefined
Function:
Sets a given pin to the high state. The method of I/O used is dependent
on the last USE *_IO directive.
Availability:
All devices.
Requires:
225
PCD_May 2015
Examples:
output_high(PIN_A0);
output_low(PIN_A1);
Example Files:
ex_sqw.c
Also See:
output_low( )
Syntax:
output_low (pin)
Parameters:
Pins are defined in the devices .h file. The actual value is a bit
address. For example, port a (byte 0x2C2 ) bit 3 would have a value of
0x2C2*8+3 or 5651 . This is defined as follows: #DEFINE PIN_A3 5651 .
The PIN could also be a variable. The variable must have a value equal
to one of the constants (like PIN_A1) to work properly. The tristate
register is updated unless the FAST_IO mode is set on port A. Note that
doing I/O with a variable instead of a constant will take much longer
time.
Returns:
undefined
Function:
Sets a given pin to the ground state. The method of I/O used is
dependent on the last USE *_IO directive.
Availability:
All devices.
Requires:
Examples:
output_low(PIN_A0);
Int16i=PIN_A1;
output_low(PIN_A1);
Example Files:
ex_sqw.c
Also See:
226
Built-in Functions
output_toggle( )
Syntax:
output_toggle(pin)
Parameters:
Pins are defined in the devices .h file. The actual value is a bit
address. For example, port a (byte 0x2C2 ) bit 3 would have a value of
0x2C2*8+3 or 5651 . This is defined as follows: #DEFINE PIN_A3 5651 .
Returns:
Undefined
Function:
Availability:
All devices.
Requires:
Examples:
output_toggle(PIN_B4);
Example Files:
None
Also See:
perror( )
Syntax:
perror(string);
Parameters:
Returns:
Nothing
Function:
This function prints out to STDERR the supplied string and a description
of the last system error (usually a math error).
Availability:
All devices.
Requires:
Examples:
x = sin(y);
if(errno!=0)
perror("Problem in find_area");
Example Files:
None
Also See:
PCD_May 2015
pid_busy( )
Syntax:
result = pid_busy();
Parameters:
None
Returns:
Function:
Availability:
Requires:
Nothing
Examples:
pid__get_result(PID_START_ONLY, ADCResult);
while(pid_busy());
pid_get_result(PID_READ_ONLY, &PIDResult);
Example Files:
None
Also See:
pid_get_result( )
Syntax:
Parameters:
228
Built-in Functions
set_point -a 16-bit variable or constant representing the set point of the
control system, the value the input from the control system is compared
against to determine the error in the system.
input - a 16-bit variable or constant representing the input from the control
system.
output - a structure that the output of the PID module will be saved to.
Either pass the address of the structure as the parameter, or a pointer to
the structure as the parameter.
Returns:
Nothing
Function:
To pass the set point and input from the control system to the PID module,
start the PID calculation and get the result of the PID calculation. The PID
calculation starts, automatically when the input is written to the PID
module's input registers.
Availability:
Requires:
Examples:
Example Files:
None
Also See:
//Start
//Start
//Read
pid_read( )
Syntax:
pid_read(register, &output);
Parameters:
PCD_May 2015
PID_ADDR_Z2
PID_ADDR_K1
PID_ADDR_K2
PID_ADDR_K3
Nothing
Function:
To read the current value of the Accumulator, Output, Z1, Z2, Set Point, K1,
K2 or K3 PID registers. If the PID is busy with a calculation the function will
wait for module to finish calculation before reading the specified register.
Availability:
Requires:
Examples:
pid_read(PID_ADDR_Z1, &value_z1);
Example Files:
None
Also See:
pid_write( )
Syntax:
pid_write(register, &input);
Parameters:
230
Built-in Functions
PID_ADDR_K3
input -a 16-bit variable, 32-bit variable or structure that contains the data to
be written. The size depends on the registers that are being written. Either
pass the address of the variable or structure as the parameter, or a pointer
to the variable or structure as the parameter.
Returns:
Nothing
Function:
To write a new value for the Accumulator, Output, Z1, Z2, Set Point, K1, K2
or K3 PID registers. If the PID is busy with a calculation the function will
wait for module to finish the calculation before writing the specified register.
Availability:
Requires:
Examples:
pid_write(PID_ADDR_Z1, &value_z1);
Example Files:
None
Also See:
pmp_address(address)
Syntax:
pmp_address ( address );
Parameters:
address- The address which is a 16 bit destination address value. This will setup the
address register on the PMP module and is only used in Master mode.
Returns:
undefined
Function:
Configures the address register of the PMP module with the destination address
during Master mode operation. The address can be either 14, 15 or 16 bits based on
the multiplexing used for the Chip Select Lines 1 and 2.
Availability:
Requires:
Nothing.
231
PCD_May 2015
Examples:
Example
Files:
Also See:
None
setup_pmp(), pmp_address(), pmp_read(), psp_read(), psp_write(), pmp_write(),
psp_output_full(), psp_input_full(), psp_overflow(), pmp_output_full(),
pmp_input_full(),pmp_overflow().
See header file for device selected.
pmp_output_full( )
pmp_input_full( )
pmp_overflow( )
pmp_error( )
pmp_timeout( )
Syntax:
result = pmp_output_full()
result = pmp_input_full()
result = pmp_overflow()
result = pmp_eror( )
result = pmp_timeout( )
Parameters:
None
Returns:
A 0 (FALSE) or 1 (TRUE)
Function:
These functions check the Parallel Port for the indicated conditions and
return TRUE or FALSE.
Availability:
Requires:
Nothing.
Examples:
while (pmp_output_full()) ;
pmp_data = command;
while(!pmp_input_full()) ;
if ( pmp_overflow() )
error = TRUE;
else
data = pmp_data;
232
//PMP only
//PMP only
//PMP only
//EPMP only
//EPMP only
Built-in Functions
Example Files:
Also See:
None
setup_pmp(), pmp_write(), pmp_read()
pmp_read( )
Syntax:
result = pmp_read ( );
result = pmp_read8(address);
result = pmp_read16(address);
pmp_read8(address,pointer,count);
pmp_read16(address,pointer,count);
Parameters:
Returns:
Function:
For PMP module, this will read a byte from the next buffer location. For
EPMP module, reads one byte/word or count bytes of data from the address
mapped to the EDS memory location. The address is used in conjunction
with the offset address set with the setup_pmp_cs1( ) and setup_pmp_cs2( )
functions to determine which address lines are high or low during the read.
Availability:
Only the devices with a built in Parallel Master Port module or an Enhanced
Parallel Master Port module.
Requires:
Nothing.
Examples:
result = pmp_read();
233
PCD_May 2015
Example Files:
None
Also See:
pmp_write( )
Syntax:
Parameters:
pmp_write (data);
pmp_write8(address,data);
Port
pmp_write8(address,pointer,data);
Port
pmp_write16(address,data);
Port
pmp_write16(address,pointer,data);
Port
Returns:
Undefined.
Function:
For PMP modules, this will write a byte of data to the next buffer location.
For EPMP modules writes one byte/word or count bytes of data from the
address mapped to the EDS memory location. The address is used in
conjunction with the offset address set with the setup_pmp_cs1( ) and
setup_pmp_cs2( ) functions to determine which address lines are high or
low during write.
Availability:
Only the devices with a built in Parallel Master Port module or Enhanced
Parallel Master Port modules.
Requires:
Nothing.
234
Built-in Functions
Examples:
pmp_write( data );
pmp_write8(0x8000,data);
pmp_write16(0x8002,ptr,16);
Example Files:
Also See:
None
setup_pmp(), setup_pmp_csx(), pmp_address(), pmp_read(), psp_read(),
psp_write(), pmp_write(), psp_output_full(), psp_input_full(), psp_overflow(),
pmp_output_full(), pmp_input_full(), pmp_overflow(), pmp_error(),
pmp_timeout(), psp_error(), psp_timeout()
port_x_pullups ( )
Syntax:
port_a_pullups (value)
port_b_pullups (value)
port_d_pullups (value)
port_e_pullups (value)
port_j_pullups (value)
port_x_pullups (upmask)
port_x_pullups (upmask, downmask)
Parameters:
value is TRUE or FALSE on most parts, some parts that allow pullups to be
specified on individual pins permit an 8 bit int here, one bit for each port pin.
upmask for ports that permit pullups to be specified on a pin basis. This
mask indicates what pins should have pullups activated. A 1 indicates the
pullups is on.
downmask for ports that permit pulldowns to be specified on a pin basis.
This mask indicates what pins should have pulldowns activated. A 1
indicates the pulldowns is on.
Returns:
undefined
Function:
Sets the input pullups. TRUE will activate, and a FALSE will deactivate.
Availability:
Requires:
Nothing
235
PCD_May 2015
Examples:
port_a_pullups(FALSE);
Example Files:
ex_lcdkb.c, kbd.c
Also See:
pow( ) pwr( )
Syntax:
f = pow (x,y)
f = pwr (x,y)
Parameters:
Returns:
Function:
Availability:
All Devices
Requires:
#INCLUDE <math.h>
Examples:
Example Files:
None
Also See:
None
printf( ) fprintf( )
Syntax:
236
printf (string)
or
printf (cstring, values...)
or
printf (fname, cstring, values...)
Built-in Functions
fprintf (stream, cstring, values...)
Parameters:
Returns:
undefined
Function:
Outputs a string of characters to either the standard RS-232 pins (first two
forms) or to a specified function. Formatting is in accordance with the
string argument. When variables are used this string must be a
constant. The % character is used within the string to indicate a variable
value is to be formatted and output. Longs in the printf may be 16 or 32
bit. A %% will output a single %. Formatting rules for the % follows.
See the Expressions > Constants and Trigraph sections of this manual for
other escape character that may be part of the string.
If fprintf() is used then the specified stream is used where printf() defaults
to STDOUT (the last USE RS232).
Format:
The format takes the generic form %nt. n is optional and may be 1-9 to
specify how many characters are to be outputted, or 01-09 to indicate
leading zeros, or 1.1 to 9.9 for floating point and %w output. t is the type
and may be one of the following:
c
Character
s
String or character
u
Unsigned int
d
Signed int
Lu
Long unsigned int
Ld
Long signed int
x
Hex int (lower case)
X
Hex int (upper case)
Lx
Hex long int (lower case)
LX
Hex long int (upper case)
f
Float with truncated decimal
g
Float with rounded decimal
e
Float in exponential format
w
Unsigned int with decimal place inserted. Specify two
numbers for n. The first is a total field width. The
second is the desired number of decimal places.
Example formats:
237
PCD_May 2015
Specifier
Value=0x12
%03u
018
%u
18
%2u
18
%5
18
%d
18
%x
12
%X
12
%4X
0012
%3.1w
1.8
* Result is undefined - Assume garbage.
Value=0xfe
254
254
*
254
-2
fe
FE
00FE
25.4
Availability:
All Devices
Requires:
Examples:
byte x,y,z;
printf("HiThere");
printf("RTCCValue=>%2x\n\r",get_rtcc());
printf("%2u %X %4X\n\r",x,y,z);
printf(LCD_PUTC, "n=%u",n);
Example Files:
ex_admm.c, ex_lcdkb.c
Also See:
atoi(), puts(), putc(), getc() (for a stream example), RS232 I/O Overview
profileout()
Syntax:
profileout(string);
profileout(string, value);
profileout(value);
Parameters:
string is any constant string, and value can be any constant or variable
integer. Despite the length of string the user specifies here, the code profile
run-time will actually only send a one or two byte identifier tag to the code
profile tool to keep transmission and execution time to a minimum.
Undefined
Returns:
Function:
238
Typically the code profiler will log and display function entry
and exits, to show the call sequence and profile the execution
time of the functions. By using profileout(), the user can add
any message or display any variable in the code profile tool.
Most messages sent by profileout() are displayed in the 'Data
Messages' and 'Call Sequence' screens of the code profile
tool.
Built-in Functions
Any device.
Requires:
Examples:
Example Files:
ex_profile.c
Also See:
psp_output_full( )
psp_input_full( )
psp_overflow( )
Syntax:
result = psp_output_full()
result = psp_input_full()
result = psp_overflow()
result = psp_error();
result = psp_timeout();
//EPMP only
//EPMP only
Parameters:
None
Returns:
A 0 (FALSE) or 1 (TRUE)
Function:
These functions check the Parallel Slave Port (PSP) for the indicated
239
PCD_May 2015
conditions and return TRUE or FALSE.
Availability:
Requires:
Nothing
Examples:
while (psp_output_full()) ;
psp_data = command;
while(!psp_input_full()) ;
if ( psp_overflow() )
error = TRUE;
else
data = psp_data;
Example Files:
ex_psp.c
Also See:
psp_read( )
Syntax:
Result = psp_read ( );
Result = psp_read ( address );
Parameters:
Returns:
A byte of data.
Function:
psp_read() will read a byte of data from the next buffer location and
psp_read ( address ) will read the buffer location address.
Availability:
Only the devices with a built in Parallel Master Port module of Enhanced
Parallel Master Port module.
Requires:
Nothing.
Examples:
Result = psp_read();
Result = psp_read(3);
Example Files:
Also See:
None
setup_pmp(), pmp_address(), pmp_read(), psp_read(), psp_write(),
pmp_write(), psp_output_full(), psp_input_full(), psp_overflow(),
pmp_output_full(), pmp_input_full(),pmp_overflow().
See header file for device selected.
240
Built-in Functions
psp_write( )
Syntax:
psp_write ( data );
psp_write( address, data );
Parameters:
Returns:
Undefined.
Function:
This will write a byte of data to the next buffer location or will write a byte to
the specified buffer location.
Availability:
Only the devices with a built in Parallel Master Port module or Enhanced
Parallel Master Port module.
Requires:
Nothing.
Examples:
psp_write( data );
Example Files:
Also See:
None
setup_pmp(), pmp_address(), pmp_read(), psp_read(), psp_write(),
pmp_write(), psp_output_full(), psp_input_full(), psp_overflow(),
pmp_output_full(), pmp_input_full(),pmp_overflow().
See header file for device selected.
putc( )
putchar( )
fputc( )
Syntax:
putc (cdata)
putchar (cdata)
fputc(cdata, stream)
Parameters:
Returns:
undefined
Function:
This function sends a character over the RS232 XMIT pin. A #USE
241
PCD_May 2015
RS232 must appear before this call to determine the baud rate and pin
used. The #USE RS232 remains in effect until another is encountered in
the file.
If fputc() is used then the specified stream is used where putc() defaults
to STDOUT (the last USE RS232).
Availability:
All devices
Requires:
#USE RS232
Examples:
putc('*');
for(i=0; i<10; i++)
putc(buffer[i]);
putc(13);
Example Files:
ex_tgetc.c
Also See:
putc_send( );
fputc_send( );
Syntax:
putc_send();
fputc_send(stream);
Parameters:
Returns:
Function:
242
Built-in Functions
If there is data to send it will then test the CTS flow control line and if at its
active state it will enable the TBEx interrupt. When using the TXISR mode
the TBEx interrupt takes care off moving data from the transmit buffer into
the hardware TX buffer.
If using software RS232, only useful if using CTS flow control, it will check
if there is data in transmit buffer to send. If there is data it will then check
the CTS flow control line, and if at its active state it will clock out the next
data byte.
Availability:
All devices
Requires:
Examples:
#USE RS232
#USE_RS232(UART1,BAUD=9600,TRANSMIT_BUFFER=50,NOTXISR)
printf(Testing Transmit Buffer);
while(TRUE){
putc_send();
}
None
Example Files:
Also See:
puts( )
fputs( )
Syntax:
puts (string).
fputs (string, stream)
Parameters:
Returns:
undefined
Function:
Sends each character in the string out the RS232 pin using putc(). After
the string is sent a CARRIAGE-RETURN (13) and LINE-FEED (10) are
sent. In general printf() is more useful than puts().
If fputs() is used then the specified stream is used where puts() defaults
to STDOUT (the last USE RS232)
Availability:
All devices
Requires:
#USE RS232
243
PCD_May 2015
Examples:
Example Files:
None
Also See:
pwm_off()
Syntax:
pwm_off([stream]);
Parameters:
Returns:
Nothing.
Function:
Availability:
All devices.
Requires:
Examples:
#USE PWM
#USE PWM(OUTPUT=PIN_C2, FREQUENCY=10kHz, DUTY=25)
while(TRUE){
if(kbhit()){
c = getc();
if(c=='F')
pwm_off();
}
}
Example Files:
None
Also See:
pwm_on()
Syntax:
Parameters:
Returns:
244
pwm_on([stream]);
stream optional parameter specifying the stream defined in
#USE PWM.
Nothing.
Built-in Functions
Function:
Availability:
Requires:
Examples:
#USE PWM
#USE PWM(OUTPUT=PIN_C2, FREQUENCY=10kHz, DUTY=25)
while(TRUE){
if(kbhit()){
c = getc();
if(c=='O')
pwm_on();
}
}
Example Files:
Also See:
None
#use_pwm, pwm_off(), pwm_set_duty_percent(),
pwm_set_duty, pwm_set_frequency()
pwm_set_duty()
Syntax:
Parameters:
pwm_set_duty([stream],duty);
stream optional parameter specifying the stream defined in
#USE PWM.
duty an int16 constant or variable specifying the new PWM high time.
Returns:
Nothing.
Function:
To change the duty cycle of the PWM signal. The duty cycle
percentage depends on the period of the PWM signal. This
function is faster than pwm_set_duty_percent(), but requires
you to know what the period of the PWM signal is.
Availability:
All devices.
Requires:
#USE PWM
Examples:
Example Files:
Also See:
None
#use_pwm, pwm_on, pwm_off(), pwm_set_frequency(),
pwm_set_duty_percent()
pwm_set_duty_percent
Syntax:
Parameters:
pwm_set_duty_percent([stream]), percent
stream optional parameter specifying the stream defined in #USE PWM.
percent- an int16 constant or variable ranging from 0 to 1000 specifying the
245
PCD_May 2015
Returns:
Function:
Availability:
Requires:
Examples:
#USE PWM
Example Files:
Also See:
None
#use_pwm, pwm_on(), pwm_off(), pwm_set_frequency(),
pwm_set_duty()
pwm_set_frequency
Syntax:
pwm_set_frequency([stream],frequency);
Parameters:
Returns:
Nothing.
Function:
Availability:
All devices.
Requires:
#USE PWM
Examples:
Example Files:
None
Also See:
246
Built-in Functions
qei_get_count( )
Syntax:
Parameters:
Returns:
void
Function:
Availability:
Requires:
Nothing.
Examples:
value = qei_get_counter();
Example Files:
None
Also See:
qei_set_count( )
Syntax:
Parameters:
Returns:
void
Function:
Availability:
Requires:
Nothing.
Examples:
qei_set_counter(value);
Example Files:
None
Also See:
247
PCD_May 2015
qei_status( )
Syntax:
Parameters:
Returns:
void
Function:
Availability:
Requires:
Nothing.
Examples:
status = qei_status();
Example Files:
None
Also See:
qsort( )
Syntax:
Parameters:
Returns:
None
Function:
Performs the shell-metzner sort (not the quick sort algorithm). The
contents of the array are sorted into ascending order according to a
comparison function pointed to by compare.
Availability:
All devices
Requires:
#INCLUDE <stdlib.h>
Examples:
248
Built-in Functions
void main() {
qsort ( nums, 5, sizeof(int), compar);
}
int compar(void *arg1,void *arg2) {
if ( * (int *) arg1 < ( * (int *) arg2) return 1
else if ( * (int *) arg1 == ( * (int *) arg2) return 0
else return 1;
}
Example Files:
ex_qsort.c
Also See:
bsearch()
rand( )
Syntax:
re=rand()
Parameters:
None
Returns:
A pseudo-random integer.
Function:
Availability:
All devices
Requires:
#INCLUDE <STDLIB.H>
Examples:
int I;
I=rand();
Example Files:
None
Also See:
srand()
249
PCD_May 2015
rcv_buffer_bytes( )
Syntax:
value = rcv_buffer_bytes([stream]);
Parameters:
Returns:
Function:
Function to determine the number of bytes in receive buffer that still need
to be retrieved.
Availability:
All devices
Requires:
#USE RS232
Examples:
#USE_RS232(UART1,BAUD=9600,RECEIVE_BUFFER=10
0)
void main(void) {
char c;
if(rcv_buffer_bytes() > 10)
c = getc();
}
Example Files:
None
Also See:
rcv_buffer_full( )
Syntax:
value = rcv_buffer_full([stream]);
Parameters:
Returns:
250
Built-in Functions
Function:
Availability:
All devices
Requires:
#USE RS232
Examples:
#USE_RS232(UART1,BAUD=9600,RECEIVE_BUFFER=1
00)
void main(void) {
char c;
if(rcv_buffer_full())
c = getc();
}
Example Files:
None
Also See:
read_adc( )
read_adc2( )
Syntax:
Parameters:
Returns:
Function:
This function will read the digital value from the analog to digital
converter. Calls to setup_adc(), setup_adc_ports() and
set_adc_channel() should be made sometime before this function is
called. The range of the return value depends on number of bits in the
chips A/D converter and the setting in the #DEVICE ADC= directive as
follows:
#DEVICE
10 bit
12 bit
ADC=8
00-FF
00-FF
ADC=10
0-3FF
0-3FF
ADC=11
x
x
251
PCD_May 2015
ADC=12
ADC=16
Note: x is not defined
0-FFC
0-FFC0
0-FFF
0-FFF0
Availability:
Requires:
Examples:
int16 value;
setup_adc_ports(sAN0|sAN1, VSS_VDD);
setup_adc(ADC_CLOCK_DIV_4|ADC_TAD_MUL_8);
while (TRUE)
{
set_adc_channel(0);
value = read_adc();
printf(Pin AN0 A/C value = %LX\n\r, value);
delay_ms(5000);
set_adc_channel(1);
read_adc(ADC_START_ONLY);
...
value = read_adc(ADC_READ_ONLY);
printf("Pin AN1 A/D value = %LX\n\r", value);
}
Example
Files:
ex_admm.c,
read_configuration_memory( )
Syntax:
read_configuration_memory([offset], ramPtr, n)
Parameters:
Returns:
undefined
Function:
Availability:
All
Requires:
Nothing
Examples:
int data[6];
252
Built-in Functions
read_configuration_memory(data,6);
Example Files:
None
Also See:
read_eeprom( )
Syntax:
Parameters:
Returns:
An 16 bit int
Function:
Availability:
Requires:
Nothing
Examples:
#define LAST_VOLUME 10
volume = read_EEPROM (LAST_VOLUME);
Example Files:
None
Also See:
read_extended_ram( )
Syntax:
read_extended_ram(page,address,data,count);
253
PCD_May 2015
Parameters:
Returns:
Undefined
Function:
Availability:
Requires:
Nothing
Examples:
Example Files:
None
Also See:
read_program_memory( )
Syntax:
Parameters:
Returns:
undefined
Function:
Availability:
Requires:
Nothing
Examples:
char buffer[64];
read_external_memory(0x40000, buffer, 64);
Example Files:
None
Also See:
254
Built-in Functions
read_high_speed_adc( )
Syntax:
read_high_speed_adc(pair,mode,result);
read or
read_high_speed_adc(pair,result);
read
read_high_speed_adc(pair);
only
read_high_speed_adc(mode,result);
read or
read_high_speed_adc(result);
read
read_high_speed_adc();
Parameters:
Undefined
Function:
255
PCD_May 2015
When using this function to perform a global start and read,
global start only, or global read only. The function will
perform the following steps:
1.
Determine which ADC pairs are set for
GLOBAL_SOFTWARE_TRIGGER.
2.
Clear the corresponding ready flags (if
doing a start).
3.
Set the global software trigger (if doing a
start).
4.
Read the corresponding ADC pairs in
order from lowest to highest (if doing a read).
5.
Clear the corresponding ready flags (if
doing a read).
When using this function to perform a individual read only.
The function can read the ADC result from any trigger
source.
Availability:
Requires:
Examples:
Example Files:
None
Also See:
setup_high_speed_adc(), setup_high_speed_adc_pair(),
high_speed_adc_done()
256
Built-in Functions
read_rom_memory( )
Syntax:
Parameters:
Returns:
undefined
Function:
Reads count bytes from program memory at address to dataptr. Due to the 24
bit program instruction size on the PCD devices, three bytes are read from each
address location.
Availability:
Requires:
Nothing
Examples:
char buffer[64];
read_program_memory(0x40000, buffer, 64);
Example
Files:
Also See:
None
write_eeprom(), read_eeprom(), Program eeprom overview
read_sd_adc( )
Syntax:
value = read_sd_adc();
Parameters:
None
Returns:
Function:
To poll the SDRDY bit and if set return the signed 32 bit value stored in the
SD1RESH and SD1RESL registers, and clear the SDRDY bit. The result returned
depends on settings made with the setup_sd_adc() function, but will always be a
signed int32 value with the most significant bits being meaningful. Refer to
Section 66, 16-bit Sigma-Delta A/D Converter, of the PIC24F Family Reference
Manual for more information on the module and the result format.
Availability:
Only devices with a Sigma-Delta Analog to Digital Converter (SD ADC) module.
257
PCD_May 2015
Examples:
value = read_sd_adc()
Example
Files:
Also See:
None
setup_sd_adc(), set_sd_adc_calibration(), set_sd_adc_channel()
realloc( )
Syntax:
Parameters:
Returns:
Function:
The realloc function changes the size of the object pointed to by the ptr
to the size specified by the size. The contents of the object shall be
unchanged up to the lesser of new and old sizes. If the new size is
larger, the value of the newly allocated space is indeterminate. If ptr is a
null pointer, the realloc function behaves like malloc function for the
specified size. If the ptr does not match a pointer earlier returned by the
calloc, malloc or realloc, or if the space has been deallocated by a call
to free or realloc function, the behavior is undefined. If the space cannot
be allocated, the object pointed to by ptr is unchanged. If size is zero
and the ptr is not a null pointer, the object is to be freed.
Availability:
All devices
Requires:
#INCLUDE <stdlibm.h>
Examples:
int * iptr;
iptr=malloc(10);
realloc(iptr,20)
// iptr will point to a block of memory of 20 bytes, if
available.
Example Files:
None
Also See:
258
Built-in Functions
release_io()
Syntax:
release_io();
Parameters:
none
Returns:
Function:
nothing
The function releases the I/O pins after the device wakes up from deep
sleep, allowing
the state of the I/O pins to change
Availability:
Requires:
Nothing
Examples:
Example Files:
None
Also See:
sleep()
reset_cpu( )
Syntax:
reset_cpu()
Parameters:
None
Returns:
Function:
Availability:
All devices
Requires:
Nothing
Examples:
if(checksum!=0)
reset_cpu();
Example Files:
None
259
PCD_May 2015
Also See:
None
restart_cause( )
Syntax:
value = restart_cause()
Parameters:
None
Returns:
A value indicating the cause of the last processor reset. The actual
values are device dependent. See the device .h file for specific values
for a specific device. Some example values are:
RESTART_POWER_UP, RESTART_BROWNOUT, RESTART_WDT
and RESTART_MCLR
Function:
Availability:
All devices
Requires:
Examples:
switch ( restart_cause() ) {
case RESTART_BROWNOUT:
case RESTART_WDT:
case RESTART_MCLR:
handle_error();
}
Example Files:
ex_wdt.c
Also See:
restart_wdt(), reset_cpu()
restart_wdt( )
Syntax:
restart_wdt()
Parameters:
None
Returns:
undefined
260
Built-in Functions
Function:
Enable/Disable
Timeout time
restart
Availability:
All devices
Requires:
#FUSES
Examples:
#fuses WDT
PCB/PCM
#fuses
setup_wdt()
restart_wdt()
PCH
setup_wdt()
#fuses
restart_wdt()
// PCB/PCM example
// See setup_wdt for a
// PIC18 example
main() {
setup_wdt(WDT_2304MS);
while (TRUE) {
restart_wdt();
perform_activity();
}
}
Example
Files:
Also See:
ex_wdt.c
#FUSES, setup_wdt(), WDT or Watch Dog Timer
Overview
rotate_left( )
Syntax:
Parameters:
Returns:
undefined
261
PCD_May 2015
Function:
Availability:
All devices
Requires:
Nothing
Examples:
x = 0x86;
rotate_left( &x, 1);
// x is now 0x0d
Example Files:
None
Also See:
rotate_right( )
Syntax:
Parameters:
Returns:
undefined
Function:
Availability:
All devices
Requires:
Nothing
Examples:
struct {
int cell_1
int cell_2
int cell_3
int cell_4
rotate_right(
rotate_right(
rotate_right(
rotate_right(
// cell_1->4,
Example Files:
None
262
: 4;
: 4;
: 4;
: 4; } cells;
&cells, 2);
&cells, 2);
&cells, 2);
&cells, 2);
2->1, 3->2 and 4-> 3
Built-in Functions
Also See:
rtc_alarm_read( )
Syntax:
rtc_alarm_read(&datetime);
Parameters:
Returns:
Structure used in read and write functions are defined in the device
header file
as rtc_time_t
void
Function:
Reads the date and time from the alarm in the RTCC module to structure
datetime.
Availability:
Requires:
Nothing.
Examples:
rtc_alarm_read(&datetime);
Example Files:
None
Also See:
rtc_alarm_write( )
Syntax:
rtc_alarm_write(&datetime);
Parameters:
Returns:
void
263
PCD_May 2015
Function:
Writes the date and time to the alarm in the RTCC module as specified
in the structure date time.
Availability:
Requires:
Nothing.
Examples:
rtc_alarm_write(&datetime);
Example Files:
None
Also See:
rtc_read( )
Syntax:
rtc_read(&datetime);
Parameters:
datetime- A structure that will contain the values returned by the RTCC
module.
Structure used in read and write functions are defined in the device
header file as rtc_time_t.
Returns:
void
Function:
Reads the current value of Time and Date from the RTCC module and
stores the structure date time.
Availability:
Requires:
Nothing.
Examples:
rtc_read(&datetime);
Example Files:
ex_rtcc.c
Also See:
264
Built-in Functions
rtc_write( )
Syntax:
rtc_write(&datetime);
Parameters:
Returns:
void
Function:
Writes the date and time to the RTCC module as specified in the structure
date time.
Availability:
Requires:
Nothing.
Examples:
rtc_write(&datetime);
Example Files:
ex_rtcc.c
Also See:
rtos_await( )
The RTOS is only included in the PCW, PCWH and PCWHD software packages.
Syntax:
rtos_await (expre)
Parameters:
Returns:
None
Function:
This function can only be used in an RTOS task. This function waits for
expre to be true before continuing execution of the rest of the code of
the RTOS task. This function allows other tasks to execute while the task
waits for expre to be true.
Availability:
All devices
Requires:
#USE RTOS
265
PCD_May 2015
Examples:
rtos_await(kbhit());
Also See:
None
rtos_disable( )
The RTOS is only included in the PCW, PCWH, and PCWHD software packages.
Syntax:
rtos_disable (task)
Parameters:
Returns:
None
Function:
This function disables a task which causes the task to not execute until
enabled by rtos_enable(). All tasks are enabled by default.
Availability:
All devices
Requires:
#USE RTOS
Examples:
rtos_disable(toggle_green)
Also See:
rtos enable()
rtos_enable( )
The RTOS is only included in the PCW, PCWH, and PCWHD software packages.
Syntax:
rtos_enable (task)
Parameters:
Returns:
None
Function:
Availability:
All devices
266
Built-in Functions
Requires:
#USE RTOS
Examples:
rtos_enable(toggle_green);
Also See:
rtos disable()
rtos_msg_poll( )
The RTOS is only included in the PCW, PCWH and PCWHD software packages.
Syntax:
i = rtos_msg_poll()
Parameters:
None
Returns:
Function:
This function can only be used inside an RTOS task. This function
returns the number of messages that are in the queue for the task that
the rtos_msg_poll() function is used in.
Availability:
All devices
Requires:
#USE RTOS
Examples:
if(rtos_msg_poll())
Also See:
rtos_msg_read( )
The RTOS is only included in the PCW, PCWH and PCWHD software packages.
Syntax:
b = rtos_msg_read()
Parameters:
None
Returns:
Function:
This function can only be used inside an RTOS task. This function reads
267
PCD_May 2015
in the next (message) of the queue for the task that the rtos_msg_read()
function is used in.
Availability:
All devices
Requires:
#USE RTOS
Examples:
if(rtos_msg_poll()) {
b = rtos_msg_read();
Also See:
rtos_msg_send( )
The RTOS is only included in the PCW, PCWH and PCWHD software packages.
Syntax:
rtos_msg_send(task, byte)
Parameters:
Returns:
None
Function:
This function can be used anytime after rtos_run() has been called.
This function sends a byte long message (byte) to the task identified by
task.
Availability:
All devices
Requires:
#USE RTOS
Examples:
if(kbhit())
{
rtos_msg_send(echo, getc());
}
Also See:
rtos_msg_poll(), rtos_msg_read()
rtos_overrun( )
The RTOS is only included in the PCW, PCWH and PCWHD software packages.
Syntax:
268
rtos_overrun([task])
Built-in Functions
Parameters:
Returns:
A 0 (FALSE) or 1 (TRUE)
Function:
This function returns TRUE if the specified task took more time to
execute than it was allocated. If no task was specified, then it returns
TRUE if any task ran over it's alloted execution time.
Availability:
All devices
Requires:
#USE RTOS(statistics)
Examples:
rtos_overrun()
Also See:
None
rtos_run( )
The RTOS is only included in the PCW, PCWH, and PCWHD software packages.
Syntax:
rtos_run()
Parameters:
None
Returns:
None
Function:
This function begins the execution of all enabled RTOS tasks. This
function controls the execution of the RTOS tasks at the allocated rate for
each task. This function will return only when rtos_terminate() is called.
Availability:
All devices
Requires:
#USE RTOS
Examples:
rtos_run()
Also See:
rtos terminate()
269
PCD_May 2015
rtos_signal( )
The RTOS is only included in the PCW, PCWH and PCWHD software packages.
Syntax:
rtos_signal (sem)
Parameters:
Returns:
None
Function:
Availability:
All devices
Requires:
#USE RTOS
Examples:
rtos_signal(uart_use)
Also See:
rtos wait()
rtos_stats( )
The RTOS is only included in the PCW, PCWH and PCWHD software packages.
Syntax:
rtos_stats(task,&stat)
Parameters:
270
Built-in Functions
Returns:
(ticks*hns_per_tick)/10
};
Undefined
Function:
Availability:
All devices
Requires:
#USE RTOS(statistics)
Examples:
rtos_stats(echo, &stats)
Also See:
None
rtos_terminate( )
The RTOS is only included in the PCW, PCWH and PCWHD software packages.
Syntax:
rtos_terminate()
Parameters:
None
Returns:
None
Function:
This function ends the execution of all RTOS tasks. The execution of the
program will continue with the first line of code after the rtos_run() call in
the program. (This function causes rtos_run() to return.)
Availability:
All devices
Requires:
#USE RTOS
Examples:
rtos_terminate()
Also See:
rtos run()
rtos_wait( )
The RTOS is only included in the PCW, PCWH and PCWHD software packages.
Syntax:
rtos_wait (sem)
271
PCD_May 2015
Parameters:
Returns:
None
Function:
This function can only be used by an RTOS task. This function waits for
sem to be greater than 0 (shared resource is available), then
decrements sem to claim usage of the shared resource and continues
the execution of the rest of the code the RTOS task. This function
allows other tasks to execute while the task waits for the shared
resource to be available.
Availability:
All devices
Requires:
#USE RTOS
Examples:
rtos_wait(uart_use)
Also See:
rtos signal()
rtos_yield( )
The RTOS is only included in the PCW, PCWH and PCWHD software packages.
Syntax:
rtos_yield()
Parameters:
None
Returns:
None
Function:
This function can only be used in an RTOS task. This function stops
the execution of the current task and returns control of the processor to
rtos_run(). When the next task executes, it will start it's execution on
the line of code after the rtos_yield().
Availability:
All devices
Requires:
#USE RTOS
Examples:
void yield(void)
{
printf(Yielding...\r\n);
rtos_yield();
printf(Executing code after yield\r\n);
}
272
Built-in Functions
Also See:
None
set_adc_channel( )
set_adc_channel2( )
Syntax:
Parameters:
chan is the channel number to select. Channel numbers start at 0 and are
labeled in the data sheet AN0, AN1. For devices with a differential ADC it sets the
positive channel to use.
neg is optional and is used for devices with a differential ADC only. It sets the
negative channel to use, channel numbers can be 0 to 6 or VSS. If no parameter
is used the negative channel will be set to VSS by default.
Returns:
undefined
Function:
Specifies the channel to use for the next read_adc() call. Be aware that you must
wait a short time after changing the channel before you can get a valid read. The
time varies depending on the impedance of the input source. In general 10us is
good for most applications. You need not change the channel before every read if
the channel does not change.
Availability:
Requires:
Nothing
Examples:
set_adc_channel(2);
value = read_adc();
Example
Files:
Also See:
ex_admm.c
read_adc(), setup_adc(), setup_adc_ports(), ADC Overview
set_analog_pins( )
Syntax:
273
PCD_May 2015
Parameters:
pin - pin to set as an analog pin. Pins are defined in the device's .h file. The
actual value is a bit address. For example, bit 3 of port A at address 5, would
have a value of 5*8+3 or 43. This is defined as follows:
#define PIN_A3 43
Returns:
undefined
Function:
To set which pins are analog and digital. Usage of function depends on method
device has for setting pins to analog or digital. For devices with ANSELx, x being
the port letter, registers the function is used as described above. For all other
devices the function works the same as setup_adc_ports() function.
Refer to the setup_adc_ports() page for documentation on how to use.
Availability:
Requires:
Nothing
Examples:
set_analog_pins(PIN_A0,PIN_A1,PIN_E1,PIN_B0,PIN_B5);
Example
Files:
Also See:
scanf( )
Syntax:
scanf(cstring);
scanf(cstring, values...)
fscanf(stream, cstring, values...)
Parameters:
Returns:
Function:
Reads in a string of characters from the standard RS-232 pins and formats the
string according to the format specifiers. The format specifier character (%) used
within the string indicates that a conversion specification is to be done and the
value is to be saved into the corresponding argument variable. A %% will input a
274
Built-in Functions
single %. Formatting rules for the format specifier as follows:
If fscanf() is used, then the specified stream is used, where scanf() defaults to
STDIN (the last USE RS232).
Format:
The format takes the generic form %nt. n is an option and may be 1-99
specifying the field width, the number of characters to be inputted. t is the type
and maybe one of the following:
c
Lu
Ld
Lo
x or X
Lx or LX
PCD_May 2015
Li
f,g or e
Availability:
276
All Devices
Built-in Functions
Requires:
#USE RS232
Examples:
char name[2-];
unsigned int8 number;
signed int32 time;
if(scanf("%u%s%ld",&number,name,&time))
printf"\r\nName: %s, Number: %u, Time: %ld",name,number,time);
Example
Files:
Also See:
None
RS232 I/O Overview, getc(), putc(), printf()
set_ccp1_compare_time( )
set_ccp2_compare_time( )
set_ccp3_compare_time( )
set_ccp4_compare_time( )
set_ccp5_compare_time( )
Syntax:
set_ccpx_compare_time(time);
set_ccpx_compare_time(timeA, timeB);
Parameters:
277
PCD_May 2015
Returns:
Undefined
Function:
This function sets the compare value for the CCP module. If the CCP
module is performing a single edge compare in 16-bit mode, then the
CCPxRBL register is not used. If 32-bit mode, the CCPxRBL is the most
significant word of the compare time. If the CCP module is performing
dual edge compare to generate an output pulse, then timeA, CCPxRAL
register, signifies the start of the pulse, and timeB, CCPxRBL register
signifies the pulse termination time.
Availability:
Requires:
Nothing
Examples:
setup_ccp1(CCP_COMPARE_PULSE);
set_timer_period_ccp1(800);
set_ccp1_compare_time(200,300);
starting at time
//generate a pulse
// 200 and ending at
time 300
Example Files:
None
Also See:
set_cog_blanking( )
Syntax:
278
set_cog_blanking(falling_time, rising_time);
Built-in Functions
Parameters:
Returns:
Nothing
Function:
To set the falling and rising edge blanking times on the Complementary
Output Generator (COG) module. The time is based off the source clock of the COG
module, the times are either a 4-bit or 6-bit value, depending on the device, refer to the
device's datasheet for the correct width.
Availability:
Examples:
set_cog_blanking(10,10);
Example Files:
None
Also See:
set_cog_dead_band( )
Syntax:
set_cog_dead_band(falling_time, rising_time);
Parameters:
Returns
:
Function:
Nothing
Availability:
Examples:
set_cog_dead_band(16,32);
Example Files:
None
Also See:
To set the falling and rising edge dead-band times on the Complementary
Output Generator (COG) module. The time is based off the source clock of the COG
module, the times are either a 4-bit or 6-bit value, depending on the device, refer to the
device's datasheet for the correct width.
279
PCD_May 2015
set_cog_phase( )
Syntax:
set_cog_phase(rising_time);
set_cog_phase(falling_time, rising_time);
Parameters:
Returns:
Nothing
Function:
To set the falling and rising edge phase times on the Complementary
Output Generator (COG) module. The time is based off the source clock of the COG
module, the times are either a 4-bit or 6-bit value, depending on the device.
Some devices only have a rising edge delay, refer to the device's datasheet.
Availability:
Examples:
set_cog_phase(10,10);
Example Files:
None
Also See:
set_compare_time( )
Syntax:
Parameters:
x is 1-16 and defines which output compare module to set time for
ocr is the compare time for the primary compare register.
ocrs is the optional compare time for the secondary register. Used for
dual compare mode.
Returns:
None
Function:
This function sets the compare value for the output compare module. If
the output compare module is to perform only a single compare than the
ocrs register is not used. If the output compare module is using double
compare to generate an output pulse, the ocr signifies the start of the
pulse and ocrs defines the pulse termination time.
Availability:
280
Built-in Functions
Requires:
Nothing
Examples:
Example Files:
Also See:
None
get_capture( ), setup_compare( ), Output Compare, PWM Overview
set_hspwm_duty( )
Syntax:
setup_hspwm_duty(duty);
set_hspwm_duty(unit, primary, [secondary]);
Parameters:
Returns:
undefined
Function:
Availability:
Requires:
Examples:
set_hspwm_duty(0x7FFF);
master duty cycle
set_hspwm_duty(1, 0x3FFF);
cycle
Example Files:
None
Also See:
PCD_May 2015
setup_hspwm_blanking(), setup_hspwm_trigger(),
set_hspwm_override(),
get_hspwm_capture(), setup_hspwm_chop_clock(),
setup_hspwm_unit_chop_clock()
setup_hspwm(), setup_hspwm_secondary()
set_hspwm_event( )
set_hspwm_event_secondary( )
Syntax:
Parameters:
set_hspwm_event(settings, compare_time);
set_shwpm_event_secondary(settings, compare_time);
available
//if
settings - special event timer setting or'd with a value from 1 to 16 to set
the prescaler. The following are the settings available for the special
event time:
HSPWM_SPECIAL_EVENT_INT_ENABLED
HSPWM_SPECIAL_EVENT_INT_DISABLED
compare_time - the compare time for the special event to occur.
Returns:
undefined
Function:
Availability:
Requires:
Examples:
set_hspwm_event(HSPWM_SPECIAL_EVENT_INT_ENABLED,0x1000);
Example Files:
None
Also See:
282
Built-in Functions
set_hspwm_override( )
Syntax:
set_hspwm_override(unit, setting);
Parameters:
Returns:
Undefined
Function:
Availability:
Requires:
None
Examples:
setup_hspwm_override(1,HSPWM_FORCE_H_1|HSPWM_FORCE_L_0);
Example
Files:
Also See:
None
setup_hspwm_unit(), set_hspwm_phase(), set_hspwm_duty(),
set_hspwm_event(),
setup_hspwm_blanking(), setup_hspwm_trigger(), get_hspwm_capture(),
setup_hspwm_chop_clock(), setup_hspwm_unit_chop_clock()
setup_hspwm(), setup_hspwm_secondary()
set_hspwm_phase( )
Syntax:
Parameters:
PCD_May 2015
secondary - An optional 16-bit constant or variable to set the secondary duty
cycle. Secondary duty cycle is only used in Independent PWM mode. Not
available on all devices, refer to device datasheet for availability.
Returns:
undefined
Function:
Availability:
Requires:
Examples:
set_hspwm(1,0x1000,0x8000);
Example
Files:
Also See:
None
setup_hspwm_unit(), set_hspwm_duty(), set_hspwm_event(),
setup_hspwm_blanking(), setup_hspwm_trigger(), set_hspwm_override(),
get_hspwm_capture(), setup_hspwm_chop_clock(),
setup_hspwm_unit_chop_clock()
setup_hspwm(), setup_hspwm_secondary()
set_motor_pwm_duty( )
Syntax:
set_motor_pwm_duty(pwm,group,time);
Parameters:
Returns:
void
Function:
Availability:
Requires:
None
Examples:
set_motor_pmw_duty(1,0,0x55);
cycle value
284
Built-in Functions
Example Files:
None
Also See:
set_motor_pwm_event( )
Syntax:
set_motor_pwm_event(pwm,time);
Parameters:
Returns:
void
Function:
Availability:
Requires:
None
Examples:
set_motor_pmw_event(pwm,time);
Example Files:
None
Also See:
set_motor_unit( )
Syntax:
set_motor_unit(pwm,unit,options, active_deadtime,
inactive_deadtime);
Parameters:
PCD_May 2015
active_deadtime- Set the active deadtime for the unit
inactive_deadtime- Set the inactive deadtime for the unit
Returns:
void
Function:
Availability:
Requires:
None
Examples:
set_motor_unit(pwm,unit,MPWM_INDEPENDENT | MPWM_FORCE_L_1,
active_deadtime, inactive_deadtime);
Example Files:
None
Also See:
get_motor_pwm_count(), set_motor_pwm_event(),
set_motor_pwm_duty(), setup_motor_pwm()
set_nco_inc_value( )
Syntax:
set_nco_inc_value(value);
Parameters:
Returns:
Undefined
Function:
Availability:
Examples:
set_nco_inc_value(inc_value);
increment value
Example
Files:
Also See:
None
286
Built-in Functions
set_open_drain_a(value)
set_open_drain_b(value)
set_open_drain_c(value)
set_open_drain_d(value)
set_open_drain_e(value)
set_open_drain_f(value)
set_open_drain_g(value)
set_open_drain_h(value)
set_open_drain_j(value)
Syntax:
set_open_drain_a(value)
set_open_drain_b(value)
set_open_drain_c(value)
set_open_drain_d(value)
set_open_drain_e(value)
set_open_drain_f(value)
set_open_drain_g(value)
set_open_drain_h(value)
set_open_drain_j(value)
set_open_drain_k(value)
Parameters:
Returns:
Nothing
Function
Availability
Examples:
Example Files:
set_pullup( )
Syntax:
set_Pullup(state, [ pin])
287
PCD_May 2015
Parameters:
Pins are defined in the devices .h file. If no pin is provided in the function call,
then all of the pins are set to the passed in state.
State is either true or false.
Returns:
undefined
Function:
Sets the pin's pull up state to the passed in state value. If no pin is included in the
function call, then all valid pins are set to the passed in state.
Availability:
All devices.
Requires:
Examples:
set_pullup(true, PIN_B0);
//Sets pin B0's pull up state to true
set_pullup(false);
//Sets all pin's pull up state to false
Example
Files:
Also See:
None
None
set_pwm1_duty( )
set_pwm2_duty( )
set_pwm3_duty( )
set_pwm4_duty( )
set_pwm5_duty( )
Syntax:
set_pwmX_duty (value)
Parameters:
Returns:
undefined
Function:
.
PIC24FxxKLxxx devices, writes the 10-bit value to the PWM to set
the duty. An 8-bit value may be used if the most significant bits are
not required. The 10-bit value is then used to determine the duty
288
Built-in Functions
cycle of the PWM signal as follows:
duty cycle = value / [ 4 * (PRx +1 ) ]
Where PRx is the maximum value timer 2 or 4 will count to before
rolling over.
PIC24FxxKMxxx devices, wires the 16-bit value to the PWM to set
the duty. The 16-bit value is then used to determine the duty cycle
of the PWM signal as follows:
duty cycle=value/(CCPxPRL+1)
Where CCPxPRL is the maximum value timer 2 will count to before
toggling the output pin.
Availability:
Requires:
None
Examples:
PIC24FxxKLxxx Devices:
// 32 MHz clock
unsigned int16 duty;
setup_timer2(T2_DIV_BY_4, 199, 1);
setup_ccp1(CCP_PWM);
//period=50us
duty=400;
//duty=400/[4*(199+1)]=0
.5=50%
set_pwm1_duty(duty);
PIC24FxxKMxxx Devices:
// 32 MHz clock
unsigned int16 duty;
setup_ccp1(CCP_PWM);
set_timer_period_ccp1(799);
//period=50us
duty=400;
//duty=400/(799+1)=0.5=50
%
set_pwm1_duty(duty);
Example Files:
ex_pwm.c
Also See:
289
PCD_May 2015
set_rtcc( )
set_timer0( )
set_timer1( )
set_timer2( )
set_timer3( )
set_timer4( )
set_timer5( )
Syntax:
set_timer0(value)
set_timer1(value)
set_timer2(value)
set_timer3(value)
set_timer4(value)
set_timer5(value)
Parameters:
Returns:
undefined
Function:
Sets the count value of a real time clock/counter. RTCC and Timer0
are the same. All timers count up. When a timer reaches the
maximum value it will flip over to 0 and continue counting (254, 255,
0, 1, 2...)
Availability:
Requires:
Nothing
Examples:
290
or set_rtcc (value)
// 256-(.000035/(4/20000000))
Built-in Functions
Example Files:
ex_patg.c
Also See:
set_ticks( )
Syntax:
Parameters:
set_ticks([stream],value);
stream optional parameter specifying the stream defined in #USE
TIMER
value a 8, 16, 32 or 64 bit integer, specifying the new value of the tick
timer. (int8, int16, int32 or int64)
Returns:
void
Function:
Sets the new value of the tick timer. Size passed depends on the size of
the tick timer.
Availability:
All devices.
Requires:
#USE TIMER(options)
Examples:
#USE TIMER(TIMER=1,TICK=1ms,BITS=16,NOISR)
void main(void) {
unsigned int16 value = 0x1000;
set_ticks(value);
}
Example Files:
Also See:
None
#USE TIMER, get_ticks()
setup_sd_adc_calibration( )
Syntax:
setup_sd_adc_calibration(model);
Parameters:
mode- selects whether to enable or disable calibration mode for the SD ADC
module. The following defines are made in the device's .h file:
1 SDADC_START_CALIBRATION_MODE
2 SDADC_END_CALIBRATION_MODE
291
PCD_May 2015
Returns:
Nothing
Function:
Availability:
Examples:
Example
Files:
Also See:
None
setup_sd_adc(), read_sd_adc(), set_sd_adc_channel()
set_sd_adc_channel( )
Syntax:
setup_sd_adc(channel);
Parameters:
channel- sets the SD ADC channel to read. Channel can be 0 to read the
difference between CH0+ and CH0-, 1 to read the difference between CH1+ and
CH1-, or one of the following:
1
SDADC_CH1SE_SVSS
2
SDADC_REFERENCE
Returns:
Nothing
Function:
To select the channel that the Sigma-Delta Analog to Digital Converter (SD ADC)
performs the conversion on.
Availability:
Examples:
set_sd_adc_channel(0);
Example
Files:
Also See:
None
292
Built-in Functions
set_timerA( )
Syntax:
set_timerA(value);
Parameters:
Returns:
undefined
Function:
Sets the current value of the timer. All timers count up. When a timer
reaches the maximum value it will flip over to 0 and continue counting
(254, 255, 0, 1, 2, ).
Availability:
Requires:
Nothing
Examples:
Example Files:
none
Also See:
set_timerB( )
Syntax:
set_timerB(value);
Parameters:
Returns:
undefined
Function:
Sets the current value of the timer. All timers count up. When a timer
reaches the maximum value it will flip over to 0 and continue counting
(254, 255, 0, 1, 2, ).
Availability:
Requires:
Nothing
Examples:
293
PCD_May 2015
set_timerB(81); // 256-(.000035/(4/20000000))
Example Files:
none
Also See:
set_timerx( )
Syntax:
set_timerX(value)
Parameters:
Returns:
Function:
Availability:
Requires:
Examples:
if(EventOccured())
set_timer2(0);//reset the timer.
Example
Files:
Also See:
None
Timer Overview, setup_timerX(), get_timerXY() , set_timerX() ,
set_timerXY()
set_timerxy( )
Syntax:
set_timerXY(value)
Parameters:
Returns:
void
Function:
Availability:
294
Built-in Functions
Requires:
Nothing
Examples:
if(get_timer45() == THRESHOLD)
set_timer(THRESHOLD + 0x1000);//skip those timer
values
Example Files:
None
Also See:
set_rtcc( )
set_timer0( )
set_timer1( )
set_timer2( )
set_timer3( )
set_timer4( )
set_timer5( )
Syntax:
set_timer0(value)
set_timer1(value)
set_timer2(value)
set_timer3(value)
set_timer4(value)
set_timer5(value)
or set_rtcc (value)
Parameters:
Returns:
undefined
Function:
Sets the count value of a real time clock/counter. RTCC and Timer0
are the same. All timers count up. When a timer reaches the
maximum value it will flip over to 0 and continue counting (254, 255,
0, 1, 2...)
Availability:
PCD_May 2015
Timers 1 & 2 - Most but not all PCM devices
Timer 3 - Only PIC18XXX and some pick devices
Timer 4 - Some PCH devices
Timer 5 - Only PIC18XX31
Requires:
Nothing
Examples:
// 256-(.000035/(4/20000000))
Example Files:
ex_patg.c
Also See:
set_timer_ccp1( )
set_timer_ccp2( )
set_timer_ccp3( )
set_timer_ccp4( )
set_timer_ccp5( )
Syntax:
set_timer_ccpx(time);
set_timer_ccpx(timeL, timeH);
Parameters:
time - may be a 32-bit constant or variable. Sets the timer value for
the CCPx module when in 32-bit mode.
timeL - may be a 16-bit constant or variable to set the value of the
lower timer when CCP module is set for 16-bit mode.
timeH - may be a 16-bit constant or variable to set the value of the
upper timer when CCP module is set for 16-bit mode.
Returns:
296
Undefined
Built-in Functions
Function:
This function sets the timer values for the CCP module. TimeH is
optional parameter when using 16-bit mode, defaults to zero if not
specified.
Availability:
Requires:
Nothing
Examples:
setup_ccp1(CCP_TIMER);
set_timer_ccp1(100,200);
and upper timer
Example Files:
None
Also See:
set_timer_period_ccp1( )
set_timer_period_ccp2( )
set_timer_period_ccp3( )
set_timer_period_ccp4( )
set_timer_period_ccp5( )
Syntax:
set_timer_period_ccpx(time);
set_timer_period_ccpx(timeL, timeH);
297
PCD_May 2015
Parameters:
time - may be a 32-bit constant or variable. Sets the timer period for the
CCPx module when in 32-bit mode.
timeL - is a 16-bit constant or variable to set the period of the lower
timer when CCP module is set for 16-bit mode.
timeH - is a 16-bit constant or variable to set the period of the upper
timer when CCP module is set for 16-bit mode.
Returns:
Undefined
Function:
This function sets the timer periods for the CCP module. When setting
up CCP module in 32-bit function is only needed when using Timer
mode. Period register are not used when module is setup for 32-bit
compare mode, period is always 0xFFFFFFFF. TimeH is optional
parameter when using 16-bit mode, default to zero if not specified.
Availability:
Requires:
Nothing
Examples:
setup_ccp1(CCP_TIMER);
mode
set_timer_period_ccp1(800,2000);
to 800 and
2000
Example Files:
None
Also See:
298
Built-in Functions
set_tris_x( )
Syntax:
set_tris_a (value)
set_tris_b (value)
set_tris_c (value)
set_tris_d (value)
set_tris_e (value)
set_tris_f (value)
set_tris_g (value)
set_tris_h (value)
set_tris_j (value)
set_tris_k (value)
Parameters:
value is an 16 bit int with each bit representing a bit of the I/O port.
Returns:
undefined
Function:
Availability:
All devices (however not all devices have all I/O ports)
Requires:
Nothing
Examples:
SET_TRIS_B( 0x0F );
// B7,B6,B5,B4 are outputs
// B15,B14,B13,B12,B11,B10,B9,B8, B3,B2,B1,B0 are
inputs
Example Files:
lcd.c
Also See:
set_uart_speed( )
Syntax:
Parameters:
PCD_May 2015
stream is an optional stream identifier.
clock is an optional parameter to indicate what the current clock is if
it is different from the #use delay value
Returns:
undefined
Function:
Changes the baud rate of the built-in hardware RS232 serial port at
run-time.
Availability:
Requires:
#USE RS232
Examples:
input_b() & 3 ) {
0 : set_uart_speed(2400);
1 : set_uart_speed(4800);
2 : set_uart_speed(9600);
3 : set_uart_speed(19200);
break;
break;
break;
break;
Example Files:
loader.c
Also See:
setjmp( )
Syntax:
Parameters:
env: The data object that will receive the current environment
Returns:
Function:
Availability:
All devices
Requires:
#INCLUDE <setjmp.h>
300
Built-in Functions
Examples:
result = setjmp(jmpbuf);
Example Files:
None
Also See:
longjmp()
setup_adc(mode)
setup_adc2(mode)
Syntax:
Parameters:
setup_adc (mode);
setup_adc2(mode);
mode- Analog to digital mode. The valid options vary depending on
the device. See the devices .h file for all options. Some typical
options include:
ADC_OFF
ADC_CLOCK_INTERNAL
ADC_CLOCK_DIV_32
ADC_CLOCK_INTERNAL The ADC will use an internal
clock
ADC_CLOCK_DIV_32 The ADC will use the external
clock scaled down by 32
ADC_TAD_MUL_16 The ADC sample time will be 16
times the ADC conversion time
Returns:
undefined
Function:
Configures the ADC clock speed and the ADC sample time. The
ADC converters have a maximum speed of operation, so ADC clock
needs to be scaled accordingly. In addition, the sample time can be
set by using a bitwise OR to concatenate the constant to the
argument.
Availability:
Requires:
Examples:
setup_adc_ports( ALL_ANALOG );
setup_adc(ADC_CLOCK_INTERNAL );
set_adc_channel( 0 );
value = read_adc();
setup_adc( ADC_OFF );
Example Files:
ex_admm.c
301
PCD_May 2015
Also See:
setup_adc_ports( )
setup_adc_ports2( )
Syntax:
setup_adc_ports (value)
setup_adc_ports (ports, [reference])
setup_adc_ports (ports, [reference])
Parameters:
Returns:
undefined
Function:
Sets up the ADC pins to be analog, digital, or a combination and the voltage
reference to use when computing the ADC value. The allowed analog pin
combinations vary depending on the chip and are defined by using the bitwise OR
to concatenate selected pins together. Check the device include file for a
complete list of available pins and reference voltage settings. The constants
ALL_ANALOG and NO_ANALOGS are valid for all chips. Some other example
pin definitions are:
sAN1 | sAN2 AN1 and AN2 are analog, remaining pins are digital
sAN0 | sAN3 AN0 and AN3 are analog, remaining pins are digital
Availability:
Requires:
Examples:
Example
302
ex_admm.c
Built-in Functions
Files:
Also See:
setup_adc_reference( )
Syntax:
setup_adc_reference(reference)
Parameters:
reference - the voltage reference to set the ADC. The valid options depend on
the device, see the device's .h file for all options. Typical options include:
VSS_VDD
VSS_VREF
VREF_VREF
VREF_VDD
Returns:
undefined
Function:
Requires:
To set the positive and negative voltage reference for the Analog to Digital
Converter (ADC) uses.
Only on devices with an ADC and has ANSELx, x being the port letter, registers
for setting which pins are analog or digital.
Nothing
Examples:
set_adc_reference(VSS_VREF);
Availability:
Example
Files:
Also See:
setup_at( )
Syntax:
setup_at(settings);
Parameters:
settings - the setup of the AT module. See the device's header file for all
options. Some typical options include:
AT_ENABLED
AT_DISABLED
AT_MULTI_PULSE_MODE
AT_SINGLE_PULSE_MODE
303
PCD_May 2015
Returns:
Nothing
Function:
Availability:
Requires:
Examples:
setup_at(AT_ENABLED|AT_MULTI_PULSE_MODE|AT_INPUT_ATIN);
Example
Files:
Also See:
None
at_set_resolution(), at_get_resolution(), at_set_missing_pulse_delay(),
at_get_missing_pulse_delay(), at_get_period(), at_get_phase_counter(),
at_set_set_point(), at_get_set_point(), at_get_set_point_error(),
at_enable_interrupts(), at_disable_interrupts(), at_clear_interrupts(),
at_interrupt_active(), at_setup_cc(), at_set_compare_time(), at_get_capture(),
at_get_status()
setup_capture( )
Syntax:
setup_capture(x, mode)
Parameters:
Returns:
None
Function:
This function specifies how the input capture module is going to function based
on the value of mode. The device specific options are listed in the device .h file.
Availability:
Requires:
None
Examples:
setup_timer3(TMR_INTERNAL | TMR_DIV_BY_8);
setup_capture(2, CAPTURE_FE | CAPTURE_TIMER3);
while(TRUE) {
timerValue = get_capture(2, TRUE);
printf(Capture 2 occurred at: %LU, timerValue);
}
Example
Files:
Also See:
None
304
Built-in Functions
setup_ccp1( )
setup_ccp2( )
setup_ccp3( )
setup_ccp4( )
setup_ccp5( )
setup_ccp6( )
Syntax:
setup_ccpx(mode,[pwm]);//PIC24FxxKLxxx devices
setup_ccpx(mode1,[mode2],[mode3],[dead_time]);//PIC24FxxKMxxx
devices
Parameters:
mode and mode1 are constants used for setting up the CCP module.
Valid constants are defined in the device's .h file, refer to the device's .h
file for all options. Some typical options are as follows:
CCP_OFF
CCP_COMPARE_INT_AND_TOGGLE
CCP_CAPTURE_FE
CCP_CAPTURE_RE
CCP_CAPTURE_DIV_4
CCP_CAPTURE_DIV_16
CCP_COMPARE_SET_ON_MATCH
CCP_COMPARE_CLR_ON_MATCH
CCP_COMPARE_INT
CCP_COMPARE_RESET_TIMER
CCP_PWM
mode2 is an optional parameter for setting up more settings of the CCP
module. Valid constants are defined in the device's .h file, refer to the
device's .h file for all options.
mode3 is an optional parameter for setting up more settings of the CCP
module. Valid constants are defined in the device's .h file, refer to the
device's .h file for all options.
pwm is an optional parameter for devices that have an
ECCP module. this parameter allows setting the shutdown
time. The value may be 0-255.
dead_time is an optional parameter for setting the dead
305
PCD_May 2015
time when the CCP module is operating in PWM mode
with complementary outputs. The value may be 0-63, 0 is
the default setting if not specified.
Returns:
Undefined
Function:
306
Built-in Functions
source to reset the timer. The functions set_ccpx_compare_time() and
set_pwmx_duty() are provided for setting the compare registers.
Availability:
Requires:
Examples:
setup_ccp1(CCP_CAPTURE_FE);
setup_ccp1(CCP_COMPARE_TOGGLE);
setup_ccp1(CCP_PWM);
Example Files:
Also See:
setup_clc1()
setup_clc2()
setup_clc3()
setup_clc4()
Syntax:
setup_clc1(mode);
setup_clc2(mode);
setup_clc3(mode);
setup_clc4(mode);
Parameters:
Returns:
Undefined.
Function:
Availability:
Returns:
Undefined.
307
PCD_May 2015
Examples:
setup_clc1(CLC_ENABLED | CLC_MODE_AND_OR);
Example Files:
None
Also See:
clcx_setup_gate(), clcx_setup_input()
setup_comparator( )
Syntax:
setup_comparator (mode)
Parameters:
Returns:
void
Function:
Availability:
308
Built-in Functions
Requires
Examples:
Example Files:
setup_compare( )
Syntax:
setup_compare(x, mode)
Parameters:
Returns:
None
Function:
Availability:
Requires:
None
Examples:
Example Files:
Also See:
None
set_compare_time(), set_pwm_duty(), setup_capture(), Output Compare
/ PWM Overview
setup_crc(mode)
Syntax:
setup_crc(polynomial terms)
Parameters:
polynomial - This will setup the actual polynomial in the CRC engine.
The power of each term is passed separated by a comma. 0 is allowed,
but ignored. The following define is added to the device's header file
(32-bit CRC Moduel Only), to enable little-endian shift direction:
CRC_LITTLE_ENDIAN
309
PCD_May 2015
Returns:
undefined
Function:
Availability:
Requires:
Nothing
Examples:
Example Files:
ex.c
Also See:
setup_cog( )
Syntax:
setup_cog(mode, [shutdown]);
setup_cog(mode, [shutdown], [sterring]);
Parameters:
mode- the setup of the COG module. See the device's .h file for all
options.
Some typical options include:
COG_ENABLED
COG_DISABLED
COG_CLOCK_HFINTOSC
COG_CLOCK_FOSC
310
COG_AUTO_RESTART
COG_SHUTDOWN_ON_C1OUT
COG_SHUTDOWN_ON_C2OUT
Built-in Functions
steering- optional parameter for steering the PWM signal to COG
output pins and/or selecting
the COG pins static level. Used when COG is set for steered PWM
or synchronous steered
PWM modes. Not available on all devices, see the device's .h file if
available and for all options.
Some typical options include:
COG_PULSE_STEERING_A
COG_PULSE_STEERING_B
COG_PULSE_STEERING_C
COG_PULSE_STEERING_D
Returns:
undefined
Function:
Availability:
Examples:
Example
Files:
Also See:
None
setup_crc( )
Syntax:
setup_crc(polynomial terms)
Parameters:
Returns:
Nothing
311
PCD_May 2015
Function:
Availability:
Examples:
Example
Files:
Also See:
// CRC Polynomial is
// CRC Polynomial is
None
crc_init(), crc_calc(), crc_calc8()
setup_cwg( )
Syntax:
setup_cwg(mode,shutdown,dead_time_rising,dead_time_falling)
Parameters:
mode- the setup of the CWG module. See the device's .h file for all
options.
Some typical options include:
CWG_ENABLED
CWG_DISABLED
CWG_OUTPUT_B
CWG_OUTPUT_A
312
undefined
Built-in Functions
Function:
Availability:
Examples:
setup_cwg(CWG_ENABLED|CWG_OUTPUT_A|CWG_OUTPUT_B|
CWG_INPUT_PWM1,CWG_SHUTDOWN_ON_FLT,60,30);
Example Files:
None
Also See:
cwg_status( ), cwg_restart( )
setup_dac( )
Syntax:
setup_dac(mode);
setup_dac(mode, divisor);
Parameters:
mode- The valid options vary depending on the device. See the devices
.h file for all options. Some typical options include:
DAC_OUTPUT
divisor- Divides the provided clock
Returns:
undefined
Function:
Availability:
Requires:
Examples:
setup_dac(DAC_VDD | DAC_OUTPUT);
dac_write(value);
setup_dac(DAC_RIGHT_ON, 5);
Example Files:
None
Also See:
313
PCD_May 2015
setup_dci( )
Syntax:
Parameters:
Returns:
sample rate-The desired number of frames per second that the DCI
module should produce. Use a numeric value for this parameter. Keep
in mind that not all rates are achievable with a given clock. Consult the
device datasheet for more information on selecting an adequate clock.
undefined
Function:
Availability:
Requires:
Examples:
314
Built-in Functions
SAMPLE_RISING_EDGE | UNDERFLOW_LAST
|
MULTI_DEVICE_BUS),
DCI_1WORD_FRAME | DCI_16BIT_WORD |
DCI_2WORD_INTERRUPT,
RECEIVE_SLOT0 | RECEIVE_SLOT1,
TRANSMIT_SLOT0 | TRANSMIT_SLOT1,
44100);
Example Files:
None
Also See:
DCI Overview, dci start( ), dci write( ), dci read( ), dci transmit ready( ),
dci data received( )
setup_dma( )
Syntax:
setup_dma(channel, peripheral,mode);
Parameters:
Returns:
void
Function:
Configures the DMA module to copy data from the specified peripheral
to RAM allocated for the DMA channel.
Availability:
Requires
Nothing
Examples:
Example Files:
Also See
None
dma_start(), dma_status()
setup_high_speed_adc( )
Syntax:
setup_high_speed_adc (mode);
315
PCD_May 2015
Parameters:
mode Analog to digital mode. The valid options vary depending on the device.
See the devices .h file for all options. Some typical options include:
ADC_OFF
ADC_CLOCK_DIV_1
ADC_HALT_IDLE The ADC will not run when PIC is idle.
Returns:
Undefined
Function:
Configures the High-Speed ADC clock speed and other High-Speed ADC options
including, when the ADC interrupts occurs, the output result format, the
conversion order, whether the ADC pair is sampled sequentially or
simultaneously, and whether the dedicated sample and hold is continuously
sampled or samples when a trigger event occurs.
Availability:
Requires:
Examples:
setup_high_speed_adc_pair(0, INDIVIDUAL_SOFTWARE_TRIGGER);
setup_high_speed_adc(ADC_CLOCK_DIV_4);
read_high_speed_adc(0, START_AND_READ, result);
setup_high_speed_adc(ADC_OFF);
Example
Files:
Also See:
None
setup_high_speed_adc_pair(), read_high_speed_adc(), high_speed_adc_done()
setup_high_speed_adc_pair( )
Syntax:
setup_high_speed_adc_pair(pair, mode);
Parameters:
pair The High-Speed ADC pair number to setup, valid values are 0 to total
number of ADC pairs. 0 sets up ADC pair AN0 and AN1, 1 sets up ADC pair
AN2 and AN3, etc.
mode ADC pair mode. The valid options vary depending on the device. See
the devices .h file for all options. Some typical options include:
INDIVIDUAL_SOFTWARE_TRIGGER
GLOBAL_SOFTWARE_TRIGGER
PWM_PRIMARY_SE_TRIGGER
PWM_GEN1_PRIMARY_TRIGGER
PWM_GEN2_PRIMARY_TRIGGER
316
Built-in Functions
Returns:
Undefined
Function:
Sets up the analog pins and trigger source for the specified ADC pair. Also sets
up whether ADC conversion for the specified pair triggers the common ADC
interrupt.
If zero is passed for the second parameter the corresponding analog pins will be
set to digital pins.
Availability:
Requires:
Examples:
setup_high_speed_adc_pair(0, INDIVIDUAL_SOFTWARE_TRIGGER);
setup_high_speed_adc_pair(1, GLOBAL_SOFTWARE_TRIGGER);
setup_high_speed_adc_pair(2, 0) sets AN4 and AN5 as digital pins.
Example
Files:
Also See:
None
setup_high_speed_adc(), read_high_speed_adc(), high_speed_adc_done()
setup_hspwm_blanking( )
Syntax:
Parameters:
Returns:
undefined
Function:
PCD_May 2015
Availability:
Requires:
None
Examples:
Example
Files:
Also See:
None
setup_hspwm_unit(), set_hspwm_phase(), set_hspwm_duty(),
set_hspwm_event(),
setup_hspwm_trigger(), set_hspwm_override(),
get_hspwm_capture(), setup_hspwm_chop_clock(),
setup_hspwm_unit_chop_clock()
setup_hspwm(), setup_hspwm_secondary()
setup_hspwm_chop_clock( )
Syntax:
setup_hspwm_chop_clock(settings);
Parameters:
settings - a value from 1 to 1024 to set the chop clock divider. Also one of the
following can be or'd with the value:
HSPWM_CHOP_CLK_GENERATOR_ENABLED
HSPWM_CHOP_CLK_GENERATOR_DISABLED
Returns:
Undefined
Function:
Setup and High Speed PWM Chop Clock Generator and divisor.
Availability:
Requires:
None
Examples:
setup_hspwm_chop_clock(HSPWM_CHOP_CLK_GENERATOR_ENABLED|32);
Example
Files:
Also See:
None
318
Built-in Functions
set_hspwm_event(),
setup_hspwm_blanking(), setup_hspwm_trigger(), set_hspwm_override(),
get_hspwm_capture(), setup_hspwm_unit_chop_clock()
setup_hspwm(), setup_hspwm_secondary()
setup_hspwm_trigger( )
Syntax:
Parameters:
undefined
Function:
Sets up the Leading-Edge Blanking and leading-edge blanking time of the High
Speed PWM.
Availability:
Requires:
None
Examples:
setup_hspwm_blanking(HSPWM_RE_PWMH_TRIGGERS_LE_BLANKING, 10);
Example
Files:
Also See:
None
setup_hspwm_unit(), set_hspwm_phase(), set_hspwm_duty(),
set_hspwm_event(),
setup_hspwm_blanking(), set_hspwm_override(),
319
PCD_May 2015
get_hspwm_capture(), setup_hspwm_chop_clock(),
setup_hspwm_unit_chop_clock()
setup_hspwm(), setup_hspwm_secondary()
setup_hspwm_unit( )
Syntax:
Parameters:
Returns:
undefined
Function:
Availability:
Requires:
Examples:
setup_hspwm_unit(1,HSPWM_ENABLE|SHPWM_COMPLEMENTARY, 100,100);
Example
Files:
Also See:
None
320
Built-in Functions
setup_hspwm(), setup_hspwm_secondary()
setup_hspwm( )
setup_hspwm_secondary( )
Syntax:
Parameters:
setup_hspwm(mode, value);
setup_hspwm_secondary(mode, value);
//if available
mode - Mode to setup the High Speed PWM module in. The valid options vary
depending on the device. See the device's .h file for all options. Some typical
options include:
HSPWM_ENABLED
HSPWM_HALT_WHEN_IDLE
HSPWM_CLOCK_DIV_1
value - 16-bit constant or variable to specify the time bases period.
Returns:
undefined
Function:
To enable the High Speed PWM module and set up the Primary and Secondary
Time base of the module.
Availability:
Requires:
Examples:
Example
Files:
Also See:
None
setup_hspwm_unit(), set_hspwm_phase(), set_hspwm_duty(),
set_hspwm_event(),
setup_hspwm_blanking(), setup_hspwm_trigger(), set_hspwm_override(),
get_hspwm_capture(), setup_hspwm_chop_clock(),
setup_hspwm_unit_chop_clock()
setup_hspwm_secondary()
setup_hspwm_unit_chop_clock( )
321
PCD_May 2015
Syntax:
setup_hspwm_unit_chop_clock(unit, settings);
Parameters:
Returns:
Undefined
Function:
Availability:
Requires:
None
Examples:
setup_hspwm_unit_chop_clock(1,HSPWM_PWMH_CHOPPING_ENABLED|
HSPWM_PWML_CHOPPIJNG_ENABLED|
HSPWM_CLOP_CLK_SOURCE_PWM2H);
Example
Files:
Also See:
None
322
Built-in Functions
setup_low_volt_detect( )
Syntax:
setup_low_volt_detect(mode)
Parameters:
Returns:
undefined
Function:
Availability:
This function is only available with devices that have the high/low
voltage detect module.
Requires
Examples:
This would trigger the interrupt when the voltage is below 3.6 volts
setup_motor_pwm( )
Syntax:
setup_motor_pwm(pwm,options, timebase);
setup_motor_pwm(pwm,options,prescale,postscale,timebase)
Parameters:
PCD_May 2015
postscale- This will select the PWM timebase postscale setting
Returns:
void
Function:
Availability:
Requires:
None
Examples:
setup_motor_pwm(1,MPWM_FREE_RUN | MPWM_SYNC_OVERRIDES,
timebase);
Example
Files:
Also See:
None
get motor pwm count(), set motor pwm event(), set motor unit(),
set motor pwm duty();
setup_oscillator( )
Syntax:
Parameters:
324
Built-in Functions
Returns:
None
Function:
Availability:
Requires:
Examples:
Example Files:
None
Also See:
setup_pid( )
Syntax:
setup_pid(,pde.[mode,[K1],[K2],[K3]);
Parameters:
mode- the setup of the PID module. The options for setting up the
module are defined in the device's header file as:
PID_MODE_PID
PID_MODE_SIGNED_ADD_MULTIPLY_WITH_ACCUMULATION
PID_MODE_SIGNED_ADD_MULTIPLY
PID_MODE_UNSIGNED_ADD_MULTIPLY_WITH_ACCUMULATION
PID_MODE_UNSIGNED_ADD_MULTIPLY
PID_OUTPUT_LEFT_JUSTIFIED
PID_OUTPUT_RIGHT_JUSTIFIED
K1 - optional parameter specifying the K1 coefficient, defaults to zero if
not specified. The K1 coefficient is used in the PID and ADD_MULTIPLY
modes. When in PID mode the K1 coefficient can be calculated with the
following formula:
K1 = Kp + Ki * T + Kd/T
When in one of the ADD_MULTIPLY modes K1 is the multiple value.
K2 - optional parameter specifying the K2 coefficient, defaults to zero if
not specified. The K2 coefficient is used in the PID mode only and is
325
PCD_May 2015
calculated with the following formula:
K2 = -(Kp + 2Kd/T)
K3 - optional parameter specifying the K3 coefficient, defaults to zero if
not specified. The K3 coefficient is used in the PID mode, only and is
calculated with the following formula:
K3 = Kd/T
T is the sampling period in the above formulas.
Returns:
Nothing
Function:
To setup the Proportional Integral Derivative (PID) module, and to set the
input coefficients (K1, K2 and K3).
Availability:
Requires:
Examples:
Example Files:
None
Also See:
setup_pmp(option,address_mask)
Syntax:
setup_pmp(options,address_mask);
Parameters:
options- The mode of the Parallel Master Port that allows to set the
Master Port mode, read-write strobe options and other functionality of the
PMPort module. See the device's .h file for all options. Some typical
options include:
PAR_PSP_AUTO_INC
PAR_CONTINUE_IN_IDLE
PAR_INTR_ON_RW
PAR_INC_ADDR
every
PAR_MASTER_MODE_1
PAR_WAITE4
after
326
Built-in Functions
// strobe
address_mask- this allows the user to setup the address enable register
with a 16-bit value. This value determines which address lines are active
from the available 16 address lines PMA0:PMA15.
Returns:
Undefined.
Function:
Configures various options in the PMP module. The options are present
in the device's .h file and they are used to setup the module. The PMP
module is highly configurable and this function allows users to setup
configurations like the Slave module, Interrupt options, address
increment/decrement options, Address enable bits, and various strobe
and delay options.
Availability:
Requires:
Examples:
setup_psp(PAR_ENABLE|
address
PAR_MASTER_MODE_1|PAR_
STOP_IN_IDLE,0x00FF);
Example Files:
None
Also See:
setup_power_pwm_pins( )
Syntax:
setup_power_pwm_pins(module0,module1,module2,module3)
Parameters:
Returns:
undefined
Function:
Availability:
PCD_May 2015
Requires:
None
Examples:
setup_power_pwm_pins(PWM_PINS_DISABLED, PWM_PINS_DISABLED,
PWM_PINS_DISABLED,
PWM_PINS_DISABLED);
setup_power_pwm_pins(PWM_COMPLEMENTARY,
PWM_COMPLEMENTARY, PWM_PINS_DISABLED,
PWM_PINS_DISABLED);
Example Files:
None
Also See:
setup_power_pwm(),
set_power_pwm_override(),set_power_pwmX_duty()
setup_psp(option,address_mask)
Syntax:
setup_psp (options,address_mask);
setup_psp(options);
Parameters:
Option- The mode of the Parallel slave port. This allows to set the
slave port mode, read-write strobe options and other functionality of the
PMP/EPMP module. See the devices .h file for all options. Some
typical options include:
PAR_PSP_AUTO_INC
PAR_CONTINUE_IN_IDLE
PAR_INTR_ON_RW
PAR_INC_ADDR
every
PAR_WAITE4
hold after
Undefined.
Function:
328
Built-in Functions
address increment/decrement options, Address enable bits and various
strobe and delay options.
Availability:
Requires:
Examples:
setup_psp(PAR_PSP_AUTO_INC|
PAR_STOP_IN_IDLE,0x00FF );
Example Files:
Also See:
//Sets
//mode
//read
//auto
up legacy slave
with
and write buffers
increment.
None
setup_pmp() , pmp_address() , pmp_read() , psp_read() , psp_write() ,
pmp_write() , psp_output_full(), psp_input_full(), psp_overflow(),
pmp_output_full() , pmp_input_full() , pmp_overflow()
See header file for device selected.
setup_pwm1( )
setup_pwm2( )
setup_pwm3( )
setup_pwm4( )
Syntax:
setup_pwm1(settings);
setup_pwm2(settings);
setup_pwm3(settings);
setup_pwm4(settings);
Parameters:
settings- setup of the PWM module. See the device's .h file for all
options.
Some typical options include:
PWM_ENABLED
PWM_OUTPUT
PWM_ACTIVE_LOW
Returns:
Undefined
Function:
Availability:
Examples:
setup_pwm1(PWM_ENABLED|PWM_OUTPUT);
329
PCD_May 2015
Example
Files:
Also See:
None
set_pwm_duty( )
setup_qei( )
Syntax:
Parameters:
Options- The mode of the QEI module. See the devices .h file for all
options
Some common options are:
QEI_MODE_X2
QEI_TIMER_GATED
QEI_TIMER_DIV_BY_1
filter - This parameter is optional and the user can specify the digital filter
clock divisor.
maxcount - This will specify the value at which to reset the position
counter.
unit - Optional unit number, defaults to 1.
Returns:
void
Function:
Availability:
Requires:
Nothing.
Examples:
setup_qei(QEI_MODE_X2|QEI_TIMER_INTERNAL,QEI_FILTER_DIV_2,
QEI_FORWARD);
Example Files:
None
Also See:
330
Built-in Functions
setup_rtc( )
Syntax:
Parameters:
Options- The mode of the RTCC module. See the devices .h file for all options
Returns:
Calibration- This parameter is optional and the user can specify an 8 bit value
that will get written to the calibration configuration register.
void
Function:
Configures the Real Time Clock and Calendar module. The module requires an
external 32.768 kHz clock crystal for operation.
Availability:
Requires:
Nothing.
Examples:
Example
Files:
Also See:
None
rtc_read(), rtc_alarm_read(), rtc_alarm_write(), setup_rtc_alarm(),
rtc_write(, setup_rtc()
setup_rtc_alarm( )
Syntax:
Parameters:
options- The mode of the RTCC module. See the devices .h file for all options
mask- specifies the alarm mask bits for the alarm configuration.
repeat- Specifies the number of times the alarm will repeat. It can have a max
value of 255.
Returns:
void
Function:
Availability:
Requires:
Nothing.
331
PCD_May 2015
Examples:
Example Files:
None
Also See:
setup_sd_adc( )
Syntax:
Parameters:
settings1- settings for the SD1CON1 register of the SD ADC module. See the
device's .h file for all options. Some options include:
1
SDADC_ENABLED
2
SDADC_NO_HALT
3
SDADC_GAIN_1
4
SDADC_NO_DITHER
5
SDADC_SVDD_SVSS
6
SDADC_BW_NORMAL
settings2- settings for the SD1CON2 register of the SD ADC module. See the
device's .h file for all options. Some options include:
7
SDADC_CHOPPING_ENABLED
8
SDADC_INT_EVERY_SAMPLE
9
SDADC_RES_UPDATED_EVERY_INT
10 SDADC_NO_ROUNDING
settings3- settings for the SD1CON3 register of the SD ADC module. See the
device's .h file for all options. Some options include:
11 SDADC_CLOCK_DIV_1
12 SDADC_OSR_1024
13 SDADC_CLK_SYSTEM
Returns:
Nothing
Function:
Availability:
Examples:
setup_sd_adc(SDADC_ENABLED | SDADC_DITHER_LOW,
SDADC_CHOPPING_ENABLED |
SDADC_INT_EVERY_5TH_SAMPLE |
332
Built-in Functions
SDADC_RES_UPDATED_EVERY_INT, SDADC_CLK_SYSTEM |
SDADC_CLOCK_DIV_4);
Example
Files:
Also See:
None
set_sd_adc_channel(), read_sd_adc(), set_sd_adc_calibration()
setup_smtx( )
Syntax:
setup_smt1(mode,[period]);
setup_smt2(mode,[period]);
Parameters:
mode - The setup of the SMT module. See the device's .h file for all aoptions. So
typical options include:
SMT_ENABLED
SMT_MODE_TIMER
SMT_MODE_GATED_TIMER
SMT_MODE_PERIOD_DUTY_CYCLE_ACQ
period - Optional parameter for specifying the overflow value of the SMT timer, de
to maximum value if not specified.
Returns:
Nothing
Function:
Availability:
Examples:
Example
Files:
Also See:
None
setup_smt1(SMT_ENABLED | SMT_MODE_PERIOD_DUTY_CYCLE_ACQ|
SMT_REPEAT_DATA_ACQ_MODE | SMT_CLK_FOSC);
setup_spi( ) setup_spi2( )
Syntax:
setup_spi (mode)
setup_spi2 (mode)
333
PCD_May 2015
Parameters:
with |.
Returns:
undefined
Function:
Availability:
Requires:
Examples:
Example Files:
ex_spi.c
Also See:
setup_timerx( )
Syntax:
setup_timerX(mode)
setup_timerX(mode,period)
Parameters:
334
Built-in Functions
TMR_EXTERNAL: Uses a clock source that is connected to the
SOSCI/SOSCO pins
T1_EXTERNAL_SYNC: Uses a clock source that is connected to the
SOSCI/SOSCO pins. The timer will increment on the rising edge of the
external clock which is synchronized to the internal clock phases. This
mode is available only for Timer1.
T1_EXTERNAL_RTC: Uses a low power clock source connected to the
SOSCI/SOSCO pins; suitable for use as a real time clock. If this mode is
used, the low power oscillator will be enabled by the setup_timer
function. This mode is available only for Timer1.
TMR_DIV_BY_X: X is the number of input clock cycles to pass before
the timer is incremented. X may be 1, 8, 64 or 256.
TMR_32_BIT: This configuration concatenates the timers into 32 bit
mode. This constant should be used with timers 2, 4, 6 and 8 only.
Period is an optional 16 bit integer parameter that specifies the timer
period. The default value is 0xFFFF.
Returns:
void
Function:
Availability:
This function is available on all devices that have a valid timer X. Use
getenv or refer to the target datasheet to determine which timers are
valid.
Requires:
Examples:
Example Files:
None
Also See:
PCD_May 2015
set_timerXY()
setup_timer_A( )
Syntax:
setup_timer_A (mode);
Parameters:
Returns:
undefined
Function:
sets up Timer A.
Availability:
Requires:
Examples:
setup_timer_A(TA_OFF);
setup_timer_A(TA_INTERNAL | TA_DIV_256);
setup_timer_A(TA_EXT_L_TO_H | TA_DIV_1);
Example Files:
none
Also See:
setup_timer_B( )
Syntax:
setup_timer_B (mode);
Parameters:
Returns:
undefined
336
Built-in Functions
Function:
sets up Timer B
Availability:
Requires:
Examples:
setup_timer_B(TB_OFF);
setup_timer_B(TB_INTERNAL | TB_DIV_256);
setup_timer_B(TA_EXT_L_TO_H | TB_DIV_1);
Example Files:
none
Also See:
setup_timer_0( )
Syntax:
setup_timer_0 (mode)
Parameters:
Returns:
undefined
Function:
Warning:
On older PIC16 devices, set-up of the prescaler may undo the WDT
prescaler.
Availability:
All devices.
Requires:
Examples:
setup_timer_0 (RTCC_DIV_2|RTCC_EXT_L_TO_H);
Example Files:
337
PCD_May 2015
Also See:
setup_timer_1( )
Syntax:
setup_timer_1 (mode)
Parameters:
T1_CLK_OUT
Returns:
undefined
Function:
Initializes timer 1. The timer value may be read and written to using
SET_TIMER1() and GET_TIMER1()Timer 1 is a 16 bit timer.
With an internal clock at 20mhz and with the T1_DIV_BY_8 mode, the
timer will increment every 1.6us. It will overflow every 104.8576ms.
Availability:
Requires:
Examples:
setup_timer_1 ( T1_DISABLED );
setup_timer_1 ( T1_INTERNAL | T1_DIV_BY_4 );
setup_timer_1 ( T1_INTERNAL | T1_DIV_BY_8 );
Example Files:
Also See:
setup_timer_2( )
Syntax:
Parameters:
T2_DISABLED
338
Built-in Functions
Period is a int 0-255 that determines when the clock value is reset
Postscale is a number 1-16 that determines how many timer overflows
before an interrupt: (1 means once, 2 means twice, an so on)
Returns:
undefined
Function:
Initializes timer 2. The mode specifies the clock divisor (from the
oscillator clock).
The timer value may be read and written to using GET_TIMER2() and
SET_TIMER2().
2 is a 8-bit counter/timer.
Availability:
Requires:
Examples:
800ns
//will overflow
every 154.4us,
//and will
interrupt every 308.us
Example Files:
Also See:
setup_timer_3( )
Syntax:
setup_timer_3 (mode)
Parameters:
Mode may be one of the following constants from each group or'ed
(via |) together:
Returns:
undefined
Function:
Initializes timer 3 or 4.The mode specifies the clock divisor (from the
oscillator clock). The timer value may be read and written to using
GET_TIMER3() and SET_TIMER3(). Timer 3 is a 16 bit counter/timer.
Availability:
PCD_May 2015
Requires:
Examples:
Example Files:
None
Also See:
get_timer3(), set_timer3()
setup_timer_4( )
Syntax:
Parameters:
Returns:
undefined
Function:
Initializes timer 4. The mode specifies the clock divisor (from the oscillator
clock).
The timer value may be read and written to using GET_TIMER4() and
SET_TIMER4().
Timer 4 is a 8 bit counter/timer.
Availability:
Requires:
Examples:
Example Files:
Also See:
340
get_timer4(), set_timer4()
Built-in Functions
setup_timer_5( )
Syntax:
setup_timer_5 (mode)
Parameters:
mode may be one or two of the constants defined in the devices .h file.
undefined
Function:
Initializes timer 5. The mode specifies the clock divisor (from the
oscillator clock). The timer value may be read and written to using
GET_TIMER5() and SET_TIMER5(). Timer 5 is a 16 bit counter/timer.
Availability:
Requires:
Examples:
Example Files:
None
Also See:
setup_uart( )
Syntax:
setup_uart(baud, stream)
setup_uart(baud)
setup_uart(baud, stream, clock)
Parameters:
baud is a constant representing the number of bits per second. A one or zero
may also be passed to control the on/off status.
Stream is an optional stream identifier.
Chips with the advanced UART may also use the following constants:
UART_ADDRESS UART only accepts data with 9th bit=1
UART_DATA UART accepts all data
341
PCD_May 2015
Chips with the EUART H/W may use the following constants:
UART_AUTODETECT Waits for 0x55 character and sets the UART baud rate to
match.
UART_AUTODETECT_NOWAIT Same as above function, except returns before
0x55 is received. KBHIT() will be true when the match is made. A call to GETC()
will clear the character.
UART_WAKEUP_ON_RDA Wakes PIC up out of sleep when RCV goes from
high to low
clock - If specified this is the clock rate this function should assume. The default
comes from the #USE DELAY.
Returns:
undefined
Function:
Availability:
Requires:
#USE RS232
Examples:
setup_uart(9600);
setup_uart(9600, rsOut);
Example
Files:
Also See:
None
#USE RS232, putc(), getc(), RS232 I/O Overview
setup_vref( )
Syntax:
setup_vref (mode )
Parameters:
Returns:
undefined
Function:
342
Built-in Functions
reference or you may specify VREF_ANALOG to use supplied Vdd and Vss.
Voltages may also be tuned to specific values in steps, 0 through 15. That value
must be ored to the configuration constants.
Availability:
Requires:
Examples:
Example
Files:
None
setup_wdt( )
Syntax:
setup_wdt (mode)
Parameters:
Function:
Availability:
Examples:
setup_wdt(WDT_ON);
Example
Files:
Also See:
ex_wdt.c
Internal Oscillator Overview
343
PCD_May 2015
setup_zdc( )
Syntax:
setup_zdc(mode);
Parameters:
mode- the setup of the ZDC module. The options for setting up the
module include:
ZCD_ENABLED
ZCD_DISABLED
ZCD_INVERTED
ZCD_INT_L_TO_H
ZCD_INT_H_TO_L
Returns:
Function:
Nothing
To set-up the Zero_Cross Detection (ZCD) module.
Availability:
Examples:
setup_zcd(ZCD_ENABLE|ZCD_INT_H_TO_L);
Example Files:
None
Also See:
zcd_status()
shift_left( )
Syntax:
Parameters:
Returns:
Function:
Shifts a bit into an array or structure. The address may be an array identifier or an
address to a structure (such as &data). Bit 0 of the lowest byte in RAM is treated
as the LSB.
Availability:
All devices
Requires:
Nothing
Examples:
byte buffer[3];
for(i=0; i<=24; ++i){
344
Built-in Functions
// Wait for clock high
while (!input(PIN_A2));
shift_left(buffer,3,input(PIN_A3));
// Wait for clock low
while (input(PIN_A2));
}
// reads 24 bits from pin A3,each bit is read
// on a low to high on pin A2
Example
Files:
Also See:
ex_extee.c, 9356.c
shift_right(), rotate_right(), rotate_left(),
shift_right( )
Syntax:
Parameters:
Returns:
Function:
Shifts a bit into an array or structure. The address may be an array identifier or an
address to a structure (such as &data). Bit 0 of the lowest byte in RAM is treated
as the LSB.
Availability:
All devices
Requires:
Nothing
Examples:
Example
ex_extee.c, 9356.c
345
PCD_May 2015
Files:
Also See:
sleep( )
Syntax:
sleep(mode)
Parameters:
Returns:
Undefined
Function:
Availability:
All devices
Requires:
Nothing
Examples:
disable_interrupts(INT_GLOBAL);
enable_interrupt(INT_EXT);
clear_interrupt();
sleep(SLEEP_FULL);
//sleep until an INT_EXT interrupt
//after INT_EXT wake-up, will resume operation from this
point
Example Files:
ex_wakup.c
Also See:
reset cpu()
346
Built-in Functions
sleep_ulpwu( )
Syntax:
sleep_ulpwu(time)
Parameters:
time specifies how long, in us, to charge the capacitor on the ultra-low
power wakeup pin (by outputting a high on PIN_B0).
Returns:
undefined
Function:
Availability:
Requires:
#USE DELAY
Examples:
while(TRUE)
{
if (input(PIN_A1))
//do something
else
sleep_ulpwu(10);
Example Files:
None
Also See:
#USE DELAY
smtx_read( )
Syntax:
value_smt1_read(which);
value_smt2_read(which);
Parameters:
347
PCD_May 2015
Returns:
32-bit value
Function:
Availability:
Examples:
Example Files:
None
Also See:
smtx_reset_timer( )
Syntax:
smt1_reset_timer();
smt2_reset_timer();
Parameters:
None
Returns:
Nothing
Function:
Availability:
Examples:
smt1_reset_timer();
Example Files:
None
Also See:
348
Built-in Functions
smtx_start( )
Syntax:
smt1_start();
smt2_start();
Parameters:
None
Returns:
Nothing
Function:
Availability:
Examples:
smt1_start();
Example Files:
None
Also See:
smtx_status( )
Syntax:
value = smt1_status();
value = smt2_status();
Parameters:
None
Returns:
Function:
Availability:
Examples:
status = smt1_status();
Example Files:
None
Also See:
PCD_May 2015
smtx_stop( )
Syntax:
smt1_stop();
smt2_stop();
Parameters:
None
Returns:
Nothing
Function:
Availability:
Examples:
smt1_stop()
Example Files:
None
Also See:
smtx_write( )
Syntax:
smt1_write(which,value);
smt2_write(which,value);
Parameters:
Returns:
350
Nothing
Built-in Functions
Function:
Availability:
Examples:
Example Files:
None
Also See:
smt1_write(SMT_PERIOD_REG, 0x100000000);
smtx_update( )
Syntax:
smt1_update(which);
smt2_update(which);
Parameters:
Returns:
Nothing
Function:
Availability:
Examples:
Example Files:
None
Also See:
smt1_update(SMT_CAPTURED_PERIOD_REG);
351
PCD_May 2015
spi_data_is_in( )
spi_data_is_in2( )
Syntax:
result = spi_data_is_in()
result = spi_data_is_in2()
Parameters:
None
Returns:
0 (FALSE) or 1 (TRUE)
Function:
Availability:
Requires:
Nothing
Examples:
while
Example Files:
None
Also See:
spi_init()
Syntax:
spi_init(baud);
spi_init(stream,baud);
Parameters:
Returns:
Nothing.
Function:
Availability:
Requires:
#USE SPI
Examples:
352
while
Built-in Functions
stream=SPI1_MODE0)
spi_inspi_init(SPI1_MODE0, TRUE); //initialize and enable SPI1 to
setting in #USE SPI
spi_inspi_init(FALSE); //disable SPI1
spi_inspi_init(250000);//initialize and enable SPI1 to a baud rate
of 250K
Example Files:
None
Also See:
spi_prewrite(data);
Syntax:
spi_prewrite(data);
spi_prewrite(stream, data);
Parameters:
Returns:
Function:
Availability:
Requires:
Writes data into the SPI buffer without waiting for transfer to be
completed. Can be used in conjunction with spi_xfer() with no
parameters to transfer more then 8 bits for PCM and PCH device, or
more then 8 bits or 16 bits (XFER16 option) for PCD. Function is useful
when using the SSP or SSP2 interrupt service routines for PCM and
PCH device, or the SPIx interrupt service routines for PCD device.
This function is only available on devices with SPI hardware.
Examples:
Example Files:
#USE SPI, and the option SLAVE is used in #USE SPI to setup PIC as
a SPI slave device
spi_prewrite(data_out);
ex_spi_slave.c
Also See:
spi_read( )
spi_read2( )
spi_read3( )
spi_read4( )
Syntax:
PCD_May 2015
value = spi_read2 ([data])
value = spi_read3([data])
value = spi_read4 ([data])
Parameters:
Returns:
An 8 bit int
Function:
Availability:
If this device is a SLAVE then either call spi_read() to wait for the
clock and data or use_spi_data_is_in() to determine if data is ready.
This function is only available on devices with SPI hardware.
Requires:
Nothing
Examples:
data_in = spi_read(out_data);
Example Files:
ex_spi.c
Also See:
spi_read_16()
spi_read2_16()
spi_read3_16()
spi_read4_16()
Syntax:
value = spi_read_16([data]);
value = spi_read2_16([data]);
value = spi_read3_16([data]);
value = spi_read4_16([data]);
Parameters:
354
Built-in Functions
Returns:
A 16 bit int
Function:
Return a value read by the SPI. If a value is passed to the spi_read_16() the
data will be clocked out and the data received will be returned. If no data is
ready, spi_read_16() will wait for the data is a SLAVE or return the last DATA
clocked in from spi_write_16().
If this device is the MASTER then either do a spi_write_16(data) followed by a
spi_read_16() or do a spi_read_16(data). These both do the same thing and will
generate a clock. If there is no data to send just do a spi_read_16(0) to get the
clock.
If this device is a slave then either call spi_read_16() to wait for the clock and
data or use_spi_data_is_in() to determine if data is ready.
Availability:
Requires:
Examples:
data_in = spi_read_16(out_data);
Example
Files:
Also See:
None
spi_read(), spi_write(), spi_write_16(), spi_data_is_in(), SPI Overview
spi_speed
Syntax:
spi_speed(baud);
spi_speed(stream,baud);
spi_speed(stream,baud,clock);
Parameters:
Returns:
Nothing.
Function:
Availability:
Requires:
#USE SPI
Examples:
spi_speed(250000);
spi_speed(SPI1_MODE0, 250000);
355
PCD_May 2015
Example Files:
Also See:
spi_write( )
spi_write2( )
spi_write3( )
spi_write4( )
Syntax:
spi_write([wait],value);
spi_write2([wait],value);
spi_write3([wait],value);
spi_write4([wait],value);
Parameters:
Returns:
Nothing
Function:
Sends a byte out the SPI interface. This will cause 8 clocks to be
generated. This function will write the value out to the SPI. At the
same time data is clocked out data is clocked in and stored in a
receive buffer. spi_read() may be used to read the buffer.
Availability:
Requires:
Nothing
Examples:
spi_write( data_out );
data_in = spi_read();
Example Files:
ex_spi.c
Also See:
356
Built-in Functions
spi_xfer( )
Syntax:
spi_xfer(data)
spi_xfer(stream, data)
spi_xfer(stream, data, bits)
result = spi_xfer(data)
result = spi_xfer(stream, data)
result = spi_xfer(stream, data, bits)
Parameters:
data is the variable or constant to transfer via SPI. The pin used to
transfer data is defined in the DO=pin option in #use spi. stream is the
SPI stream to use as defined in the STREAM=name option in #USE
SPI.
bits is how many bits of data will be transferred.
Returns:
The data read in from the SPI. The pin used to transfer result is defined
in the DI=pin option in #USE SPI.
Function:
Availability:
Requires:
#USE SPI
Examples:
int i = 34;
spi_xfer(i);
// transfers the number 34 via SPI
int trans = 34, res;
res = spi_xfer(trans);
// transfers the number 34 via SPI
// also reads the number coming in from SPI
Example Files:
None
Also See:
#USE SPI
SPII_XFER_IN()
Syntax:
value = spi_xfer_in();
value = spi_xfer_in(bits);
value = spi_xfer_in(stream,bits);
Parameters:
Returns:
357
PCD_May 2015
Function:
Reads data from the SPI, without writing data into the transmit buffer first.
Availability:
Requires:
#USE SPI, and the option SLAVE is used in #USE SPI to setup PIC as a
SPI slave device.
Examples:
data_in = spi_xfer_in();
Example Files:
ex_spi_slave.c
Also See:
sprintf( )
Syntax:
Parameters:
Returns:
Function:
This function operates like printf() except that the output is placed into the
specified string. The output string will be terminated with a null. No checking is
done to ensure the string is large enough for the data. See printf() for details on
formatting.
Availability:
All devices.
Requires:
Nothing
Examples:
char mystring[20];
long mylong;
mylong=1234;
sprintf(mystring,"<%lu>",mylong);
// mystring now has:
//
< 1 2 3 4 > \0
Example
Files:
Also See:
358
None
printf()
Built-in Functions
sqrt( )
Syntax:
Parameters:
Returns:
Function:
Availability:
All devices.
Requires:
#INCLUDE <math.h>
Examples:
Example Files:
None
Also See:
None
srand( )
Syntax:
srand(n)
Parameters:
Returns:
No value.
Function:
The srand() function uses the argument as a seed for a new sequence
of pseudo-random numbers to be returned by subsequent calls to
rand. If srand() is then called with same seed value, the sequence of
random numbers shall be repeated. If rand is called before any call to
srand() have been made, the same sequence shall be generated as
359
PCD_May 2015
when srand() is first called with a seed value of 1.
Availability:
All devices.
Requires:
#INCLUDE <STDLIB.H>
Examples:
srand(10);
I=rand();
Example Files:
None
Also See:
rand()
360
Concatenate s2 onto s1
Find c in s1 and return &s1[i]
Same but search in reverse
Compare s1 to s2
Compare s1 to s2 (n bytes)
Compare and ignore case
Copy up to n characters s2->s1
Count of initial chars in s1 not in s2
Count of initial chars in s1 also in s2
Number of characters in s1
Convert string to lower case
Search s1 for first char also in s2
Search for s2 in s1
Concatenates up to n bytes of s2 onto
s1
Compares s1 to s2, both interpreted as
appropriate to the current locale.
Transforms maximum of n characters of
s2 and places them in s1, such that
Built-in Functions
iresult=memcmp(m1,m2,n)
ptr=memchr(m1,c,n)
ptr=strerror(errnum)
Parameters:
Returns:
Function:
Availability:
All devices.
Requires:
#include <string.h>
Examples:
Example Files:
ex_str.c
Also See:
strcpy(), strtok()
361
PCD_May 2015
strcpy( ) strcopy( )
Syntax:
Parameters:
Returns:
undefined
Function:
Availability:
All devices.
Requires:
Nothing
Examples:
Example Files:
ex_str.c
Also See:
strxxxx()
strtod( )
strtof( )
strtof48( )
Syntax:
result=strtod(nptr,& endptr)
result=strtof(nptr,& endptr)
result=strtof48(nptr,& endptr)
Parameters:
Returns:
362
Built-in Functions
performed, zero is returned.
Function:
The strtod function converts the initial portion of the string pointed to
by nptr to a float representation. The part of the string after conversion
is stored in the object pointed to endptr, provided that endptr is not a
null pointer. If nptr is empty or does not have the expected form, no
conversion is performed and the value of nptr is stored in the object
pointed to by endptr, provided endptr is not a null pointer.
Availability:
All devices.
Requires:
#INCLUDE <stdlib.h>
Examples:
double result;
char str[12]="123.45hello";
char *ptr;
result=strtod(str,&ptr);
//result is 123.45 and ptr is "hello"
Example Files:
None
Also See:
strtol(), strtoul()
strtok( )
Syntax:
Parameters:
Returns:
Function:
PCD_May 2015
token. Function saves pointer to following character from which next
search will start.
Each subsequent call, with 0 as first argument, starts searching from
the saved pointer.
Availability:
All devices.
Requires:
#INCLUDE <string.h>
Examples:
Example Files:
ex_str.c
Also See:
strxxxx(), strcpy()
strtol( )
Syntax:
Parameters:
Returns:
Function:
The strtol function converts the initial portion of the string pointed to
by nptr to a signed long int representation in some radix determined
by the value of base. The part of the string after conversion is stored
in the object pointed to endptr, provided that endptr is not a null
pointer. If nptr is empty or does not have the expected form, no
conversion is performed and the value of nptr is stored in the object
pointed to by endptr, provided endptr is not a null pointer.
364
Built-in Functions
Availability:
All devices.
Requires:
#INCLUDE <stdlib.h>
Examples:
Example Files:
None
Also See:
strtod(), strtoul()
strtoul( )
Syntax:
result=strtoul(nptr,endptr, base)
Parameters:
nptr and endptr are strings pointers and base is an integer 2-36.
Returns:
Function:
The strtoul function converts the initial portion of the string pointed to
by nptr to a long int representation in some radix determined by the
value of base. The part of the string after conversion is stored in the
object pointed to endptr, provided that endptr is not a null pointer. If
nptr is empty or does not have the expected form, no conversion is
performed and the value of nptr is stored in the object pointed to by
endptr, provided endptr is not a null pointer.
Availability:
All devices.
Requires:
Examples:
long result;
char str[9]="123hello";
char *ptr;
result=strtoul(str,&ptr,10);
//result is 123 and ptr is "hello"
365
PCD_May 2015
Example Files:
None
Also See:
strtol(), strtod()
swap( )
Syntax:
swap (lvalue)
result = swap(lvalue)
Parameters:
Returns:
A byte
Function:
Swaps the upper nibble with the lower nibble of the specified
byte. This is the same as:
byte = (byte << 4) | (byte >> 4);
Availability:
All devices.
Requires:
Nothing
Examples:
x=0x45;
swap(x);
//x now is 0x54
int x = 0x42;
int result;
result = swap(x);
// result is 0x24;
Example Files:
None
Also See:
rotate_right(), rotate_left()
tolower( ) toupper( )
Syntax:
Parameters:
cvalue is a character
366
Built-in Functions
Returns:
An 8 bit character
Function:
Availability:
All devices.
Requires:
Nothing
Examples:
switch(
case
case
case
}
Example Files:
ex_str.c
Also See:
None
toupper(getc()) ) {
'R' : read_cmd(); break;
'W' : write_cmd(); break;
'Q' : done=TRUE;
break;
touchpad_getc( )
Syntax:
input = TOUCHPAD_GETC( );
Parameters:
None
Returns:
Function:
Availability:
Requires:
Examples:
367
PCD_May 2015
void main(void){
char c;
enable_interrupts(GLOBAL);
c = TOUCHPAD_GETC();
//will wait until one of declared pins is detected
//if PIN_B0 is pressed, c will get value 'A'
}
Example Files:
None
Also See:
touchpad_hit( )
Syntax:
value = TOUCHPAD_HIT( )
Parameters:
None
Returns:
TRUE or FALSE
Function:
Availability:
Requires:
Examples:
Example Files:
368
None
Built-in Functions
Also See:
touchpad_state( )
Syntax:
TOUCHPAD_STATE (state);
Parameters:
state is a literal 0, 1, or 2.
Returns:
None
Function:
Availability:
Requires:
Examples:
Example Files:
None
Also See:
369
PCD_May 2015
tx_buffer_available()
Syntax:
value = tx_buffer_available([stream]);
Parameters:
Returns:
Function:
Function to determine the number of bytes that can still be put into
transmit buffer before it overflows. Transmit buffer is implemented has a
circular buffer, so be sure to check to make sure there is room for at least
one more then what is actually needed.
Availability:
All devices
Requires:
#USE RS232
Examples:
#USE_RS232(UART1,BAUD=9600,TRANSMIT_BUFFER=5
0)
void main(void) {
unsigned int8 Count = 0;
while(TRUE){
if(tx_buffer_available()>13)
printf("/r/nCount=%3u",Count++);
}
}
Example Files:
None
Also See:
370
Built-in Functions
tx_buffer_bytes()
Syntax:
value = tx_buffer_bytes([stream]);
Parameters:
Returns:
Function:
Availability:
All devices
Requires:
#USE RS232
Examples:
#USE_RS232(UART1,BAUD=9600,TRANSMIT_BUFFER=
50)
void main(void) {
char string[] = Hello;
if(tx_buffer_bytes() <= 45)
printf(%s,string);
}
Example Files:
None
Also See:
tx_buffer_full( )
Syntax:
value = tx_buffer_full([stream])
Parameters:
PCD_May 2015
in #USE RS232
Returns:
Function:
Availability:
All devices
Requires:
#USE RS232
Examples:
#USE_RS232(UART1,BAUD=9600,TRANSMIT_BUFFER=
50)
void main(void) {
char c;
if(!tx_buffer_full())
putc(c);
}
Example Files:
None
Also See:
va_arg( )
Syntax:
va_arg(argptr, type)
Parameters:
Returns:
The first call to va_arg after va_start return the value of the parameters
after that specified by the last parameter. Successive invocations return
the values of the remaining arguments in succession.
Function:
The function will return the next argument every time it is called.
Availability:
All devices.
372
Built-in Functions
Requires:
#INCLUDE <stdarg.h>
Examples:
Example Files:
None
Also See:
va_end( )
Syntax:
va_end(argptr)
Parameters:
Returns:
None
Function:
A call to the macro will end variable processing. This will facillitate a
normal return from the function whose variable argument list was
referred to by the expansion of va_start().
Availability:
All devices.
Requires:
#INCLUDE <stdarg.h>
Examples:
Example Files:
None
373
PCD_May 2015
Also See:
va_start
Syntax:
va_start(argptr, variable)
Parameters:
Returns:
None
Function:
The function will initialize the argptr using a call to the macro va_start().
Availability:
All devices.
Requires:
#INCLUDE <stdarg.h>
Examples:
Example Files:
None
Also See:
write_configuration_memory( )
Syntax:
Parameters:
374
Built-in Functions
memory to start writing to, offset defaults to zero if not used.
Returns:
undefined
Function:
Erases all fuses and writes count bytes from the dataptr to the
configuration memory.
Availability:
Requires:
Nothing
Examples:
int data[6];
write_configuration_memory(data,6)
Example Files:
None
Also See:
write_eeprom( )
Syntax:
Parameters:
Returns:
undefined
Function:
This function will write the specified value to the given address of
EEPROM. If pointers are used than the function will write n bytes of
data from the pointer to EEPROM starting at the value of address.
In order to allow interrupts to occur while using the write operation, use
the #DEVICE option WRITE_EEPROM = NOINT. This will allow
interrupts to occur while the write_eeprom() operations is polling the
done bit to check if the write operations has completed. Can be used as
long as no EEPROM operations are performed during an ISR.
This function is only available on devices with supporting hardware on
chip.
Availability:
Requires:
Nothing
Examples:
#define LAST_VOLUME
10
// Location in EEPROM
volume++;
375
PCD_May 2015
write_eeprom(LAST_VOLUME,volume);
Example Files:
None
Also See:
write_extended_ram( )
Syntax:
write_extended_ram (page,address,data,count);
Parameters:
Returns:
undefined
Function:
Availability:
Requires:
Nothing
Examples:
Example Files:
None
Also See:
376
Built-in Functions
write_program_memory( )
Syntax:
Parameters:
address is 32 bits .
dataptr is a pointer to one or more bytes
count is a 16 bit integer on PIC16 and 16-bit for PIC18
Returns:
undefined
Function:
Availability:
Requires:
Nothing
Examples:
for(i=0x1000;i<=0x1fff;i++) {
value=read_adc();
write_program_memory(i, value, 2);
delay_ms(1000);
}
int8 write_data[4] = {0x10,0x20,0x30,0x00};
write_program_memory (0x2000, write_data, 4);
Example Files:
None
377
PCD_May 2015
zdc_status( )
Syntax:
value=zcd_status()
Parameters:
None
Returns:
value - the status of the ZCD module. The following defines are
made in the device's
header file and are as follows:
ZCD_IS_SINKING
ZCD_IS_SOURCING
Function:
Availability:
Examples:
value=zcd_status():
Example
Files:
Also See:
None
378
setup_zcd()
float.h
float.h
FLT_RADIX:
FLT_MANT_DIG:
FLT_DIG:
FLT_MIN_EXP:
FLT_MIN_10_EXP:
FLT_MAX_EXP:
FLT_MAX_10_EXP:
FLT_MAX:
FLT_EPSILON:
FLT_MIN:
DBL_MANT_DIG:
DBL_DIG:
DBL_MIN_EXP:
DBL_MIN_10_EXP:
DBL_MAX_EXP:
PCD_May 2015
DBL_MAX_10_EXP:
DBL_MAX:
DBL_EPSILON:
DBL_MIN:
LDBL_MANT_DIG:
LDBL_DIG:
LDBL_MIN_EXP:
LDBL_MIN_10_EXP:
LDBL_MAX_EXP:
LDBL_MAX_10_EXP:
LDBL_MAX:
LDBL_EPSILON:
LDBL_MIN:
limits.h
limits.h
CHAR_BIT:
SCHAR_MIN:
SCHAR_MAX:
UCHAR_MAX:
CHAR_MIN:
CHAR_MAX:
MB_LEN_MAX:
SHRT_MIN:
SHRT_MAX:
USHRT_MAX:
INT_MIN:
INT_MAX:
UINT_MAX:
LONG_MIN:
LONG_MAX:
ULONG_MAX:
380
locale.h
locale.h
locale.h
lconv
SETLOCALE()
LOCALCONV()
localization structure
returns null
returns clocale
setjmp.h
setjmp.h
jmp_buf:
setjmp:
longjmp:
stddef.h
stddef.h
ptrdiff_t:
size_t:
wchar_t
NULL
stdio.h
stdio.h
stderr The standard error s stream (USE RS232 specified as stream or the first USE RS232)
stdout The standard output stream (USE RS232 specified as stream last USE RS232)
stdin The standard input s stream (USE RS232 specified as stream last USE RS232)
381
PCD_May 2015
stdlib.h
stdlib.h
div_t
ldiv_t
EXIT_FAILURE
EXIT_SUCCESS
RAND_MAXMBCUR_MAX1
SYSTEM()
Returns 0( not supported)
Multibyte character and string
Multibyte characters not supported
functions:
MBLEN()
Returns the length of the string.
MBTOWC()
Returns 1.
WCTOMB()
Returns 1.
MBSTOWCS()
Returns length of string.
WBSTOMBS()
Returns length of string.
Stdlib.h functions included just for compliance with ANSI C.
382
PCD_May 2015
384