Neuron® C Reference Guide ® 0 7 8 - 0 1 4 0 -02 F
Echelon, LONWORKS, LONMARK, NodeBuilder, LonTalk, Neuron, 3120, 3150, ShortStack, LonMaker, and the Echelon logo are trademarks of Echelon Corporation registered in the United States and other countries. 3170 is a trademark of the Echelon Corporation. Other brand and product names are trademarks or registered trademarks of their respective holders.
Welcome This manual describes the Neuron® C Version 2.2 programming language. It is a companion piece to the Neuron C Programmer's Guide. It provides reference information for writing programs using Neuron C. Neuron C is a programming language based on ANSI C that is designed for applications that run on Neuron Chips and Smart Transceivers (Neuron-hosted devices).
• Introduction to the LONWORKS Platform (078-0391-01A). This manual provides an introduction to the ISO/IEC 14908 (ANSI/CEA-709.1 and EN14908) Control Network Protocol, and provides a high-level introduction to LONWORKS networks and the tools and components that are used for developing, installing, operating, and maintaining them. • I/O Model Reference for Smart Transceivers and Neuron Chips (0780392-01A).
Typeface or Symbol Used for Example italic type abstract elements identifier [square brackets] optional fields [bind-info] | vertical bar a choice between two elements input | output Example: The syntax for declaring a network variable is: network input | output [netvar modifier] [class] type [bind-info] identifier • You type the keywords network, input, and output as shown • You replace the abstract elements netvar modifier, class, type, bind-info, and identifier with the actual modifier, cl
Table of Contents Welcome .........................................................................................................iii Audience ........................................................................................................iii Related Documentation ................................................................................iii Typographic Conventions for Syntax........................................................... iv Neuron C Overview........................................
nv_update_succeeds Event ................................................................... 13 Syntax .............................................................................................. 14 Example 1 – Event for a Single Network Variable....................... 14 Example 2 – Event for a Network Variable Array........................ 14 Example 3 – Event for a Range of Network Variables ................. 14 offline Event..............................................................................
Conversion of Floating-Point to ASCII String .............................. 65 Conversion of ASCII String to Floating-Point .............................. 67 Floating-Point Performance ........................................................... 67 Using the NXT Neuron C Extended Arithmetic Translator............... 69 Function Directory ....................................................................................... 69 abs( ) Built-in Function .........................................................
delay( ) Function .................................................................................... 78 Syntax .............................................................................................. 79 Example ........................................................................................... 79 eeprom_memcpy( ) Function................................................................. 79 Syntax ..............................................................................................
Syntax .............................................................................................. 90 Example ........................................................................................... 90 io_idis( ) Function .................................................................................. 90 Syntax .............................................................................................. 91 Example .....................................................................................
Syntax ............................................................................................ 108 Example ......................................................................................... 109 memchr( ) Function ............................................................................. 109 Syntax ............................................................................................ 109 Example .........................................................................................
nv_table_index( ) Built-in Function ................................................... 118 Syntax ............................................................................................ 118 Example ......................................................................................... 118 offline_confirm( ) Function.................................................................. 118 Syntax ............................................................................................ 118 Example ....
Syntax ............................................................................................ 129 Example ......................................................................................... 129 rotate_short_right( ) Function ............................................................ 129 Syntax ............................................................................................ 129 Example .........................................................................................
Example ......................................................................................... 140 strncmp( ) Function ............................................................................. 140 Syntax ............................................................................................ 141 Example ......................................................................................... 141 strncpy( ) Function ..............................................................................
Syntax ............................................................................................ 152 Example ......................................................................................... 152 update_config_data( ) Function .......................................................... 152 Syntax ............................................................................................ 153 Example .........................................................................................
cp_template_file_len Variable ............................................................ 193 fblock_index_map Variable ................................................................. 193 input_is_new Variable......................................................................... 193 input_value Variable ........................................................................... 193 msg_tag_index Variable ......................................................................
Neuron C Overview Neuron C is a programming language based on ANSI C that is designed for Neuron Chips and Smart Transceivers. It includes network communication, input/output (I/O), and event- and interrupt-handling extensions to ANSI C, which make it a powerful tool for the development of LONWORKS applications. Neuron C implements all the basic ANSI C types and type conversions as necessary. In addition to the ANSI C data constructs, Neuron C provides some unique data elements.
whereas the messaging service is not standardized with the exception of its usage by the LONWORKS file transfer protocol (LW-FTP). The use of network variables, both standard types and user types, promotes interoperability between multiple devices from multiple vendors. The lower-level messaging service allows for proprietary solutions in addition to the file transfer protocol. Another Neuron C data object is the timer.
1 Predefined Events This chapter provides reference information on predefined events. The predefined events described in this chapter apply only to application development for Neuron-hosted devices. However, the development tools for host-based device development support a similar API.
Introduction to Predefined Events An event is a programmatic notification provided by the Neuron firmware that there has been an occurrence of something significant to the application program. For example, a network variable update has been received from the network, or an input pin has changed state. Events are used in when-clauses to enable the execution of a when-task, using the following general syntax: when( ) { ...
offline online reset timer_expires (unqualified) wink All other predefined events can be used in multiple when clauses. Predefined events (except for the reset event) can also be used in any Neuron C expression. Event Directory The following sections list Neuron C events alphabetically, providing relevant syntax information and a detailed description of each event.
The reference value is the value read the last time the change event evaluated to TRUE. For the unqualified io_changes event, the event equates to TRUE when the current value is different from the reference value. A task can access the input value for the I/O object through the input_value keyword. The input_value is always a signed long. For the bit, byte, and nibble I/O objects, changes are not latched. The change must persist until the io_changes event is processed.
} Example 2 IO_7 input pulsecount total_ticks; when (io_changes(total_ticks) by 100) { ... } io_in_ready Event The io_in_ready event evaluates to TRUE when a block of data is available to be read on some asynchronous I/O models. When data is available, the application then calls io_in( ) to retrieve the data. The io_in_ready event is used with the parallel, sci, and spi I/O models; see the I/O Model Reference for more information about these I/O models.
when (io_out_ready(io_bus)) { io_out(io_bus, &data); } io_update_occurs Event The io_update_occurs event evaluates to TRUE when the input object specified by io-object-name has an updated value. The io_update_occurs event applies only to timer/counter input object types listed in Table 3. Table 3.
msg_arrives Event The msg_arrives event evaluates to TRUE once for each a message that arrives. This event can be qualified by a specific message code specified by the sender of the message. See Chapter 6, How Devices Communicate Using Application Messages, of the Neuron C Programmer's Guide, for a list of message code ranges and their associated meanings. You can reduce scheduling overhead by using an unqualified msg_arrives event followed by a switch statement on the code field of the msg_in object.
} msg_fails Event The msg_fails event evaluates to TRUE when a message fails to be acknowledged after all retries have been attempted. This event can be qualified by a specific message tag. Checking the completion event (msg_completes, or msg_fails in combination with msg_succeeds) is optional by message tag. If a program checks for either the msg_succeeds or msg_fails event for a given message tag, it must check for both events for that tag. The alternative is to check only for msg_completes.
... msg_out.tag = tag_out; msg_send(); ... when (msg_succeeds(tag_out)) { ... } nv_update_completes Event The nv_update_completes event evaluates to TRUE when an output network variable update completes (that is, either fails or succeeds) or a poll operation completes. Checking the completion event (nv_update_completes, or nv_update_fails in combination with nv_update_succeeds) is optional by network variable. If an array name is used, then each element of the array is checked for completion.
Example 1 – Event for a Single Network Variable network output SVNT_abs_humid nvoHumidity; ... nvoHumidity = 32; // This initiates an NV update ... when (nv_update_completes(nvoHumidity)) { ... } Example 2 – Event for a Network Variable Array network output SVNT_abs_humid nvoHumidity[4]; ... nvoHumidity[1] = 32; // This initiates an NV update ... when (nv_update_completes(nvoHumidity)) { ...
array, the nv_array_index built-in variable indicates the relative index of the element to which the event applies. The nv_array_index variable’s type is a short int. If a network variable range is used, then the network variable at the beginning of the range must have a lower global index than the network variable at the end of the range. Each network variable in the range is checked for failure until the first such network variable with an event is found.
... when (nv_update_fails(nvoHumidity)) { ... } Example 3 – Event for a Range of Network Variables network output SVNT_abs_humid nvoHumidity1, nvoHumidity2, nvoHumidity3; ... nvoHumidity2 = 32; ... when (nv_update_fails(nvoHumidity1 .. nvoHumidity3)) { ... } nv_update_occurs Event The nv_update_occurs event evaluates to TRUE when a value has been received for an input network variable. If an array name is used, then each element of the array is checked to see if a value has been received.
Example 1 – Event for a Single Network Variable network input SNVT_switch nviSwitch; when (nv_update_occurs(nviSwitch)) { ... } Example 2 – Event for a Network Variable Array network input SNVT_switch nviSwitch[4]; when (nv_update_occurs(nviSwitch)) { ... } Example 3 – Event for a Range of Network Variables network input SNVT_switch nviSwitch1, nviSwitch2, nviSwitch3; when (nv_update_occurs(nviSwitch1 .. nviSwitch3)) { ...
If a program checks for the nv_update_succeeds event, it must check for the nv_update_fails event as well. The alternative is to check only for nv_update_completes. A program is also permitted to check only for nv_update_fails as long as there is no use of nv_update_completes or nv_update_succeeds for any network variable. Syntax nv_update_succeeds [(network-var)] nv_update_succeeds [(network-var1 ..
nvoHumidity3; ... nvoHumidity2 = 32; ... when (nv_update_succeeds(nvoHumidity1 .. nvoHumidity3)) { ... } offline Event The offline event evaluates to TRUE only if the device is online and an Offline network management message is received from a network tool, or when a program calls go_offline( ). The offline event is handled as the first priority when clause. It can be used in no more than one when clause in a program.
online Event The online event evaluates to TRUE only if the device is offline and an Online network management message is received from a network tool. The online event can be used in no more than one when clause in a program. The task associated with the online event in a when clause can be used to bring a device back into operation in a well-defined state.
Syntax reset Example when (reset) { // initialize peripheral devices, and so on } resp_arrives Event The resp_arrives event evaluates to TRUE when a response arrives. This event can be qualified by a specific message tag. Syntax resp_arrives [(message-tag)] message-tag An optional message tag. If this field is omitted, the event is TRUE for receipt of any response message. Example msg_tag tag_out; ... msg_out.tag = tag_out; msg_out.service = REQUEST; msg_send(); ... when (resp_arrives(tag_out)) { ..
Example mtimer countdown; ... countdown = 100; ... when (timer_expires(countdown)) { ... } wink Event The wink event evaluates to TRUE whenever a Wink network management message is received from a network tool. The device can be configured or unconfigured, but it must have a program running on it. The wink event is unique in that it can evaluate to TRUE even though the device is unconfigured.
2 Compiler Directives This chapter provides reference information for compiler directives, also known as pragmas. The ANSI C language standard permits each compiler to implement a set of pragmas that control certain compiler features that are not part of the language syntax. Many compiler directives apply to both Neuron-hosted and host-based application development, but some directives are not allowed in a model file.
Compiler Directives ANSI C permits compiler extensions through the #pragma directive. These directives are implementation-specific. The ANSI standard states that a compiler can define any sort of language extensions through the use of these directives. Unknown directives can be ignored or discarded. The Neuron C Compiler issues warning messages for unrecognized directives.
#pragma app_buf_in_size size [, modifier] See Allocating Buffers in Chapter 8, Memory Management, of the Neuron C Programmer’s Guide for detailed information on this pragma and its use. This directive is not supported in model files. #pragma app_buf_out_count count [, modifier] See Allocating Buffers in Chapter 8, Memory Management, of the Neuron C Programmer’s Guide for detailed information on this pragma and its use. This directive is not supported in model files.
The create_cp_value_files_uninit option is used to prevent the compiler from generating configuration value files that contain initial values. Instead, the value files are generated with no initial value, such that the Neuron loader does not load anything into the block of memory; instead, the contents prior to load are unaltered. This can be helpful if an application image needs to be reloaded, but its configuration data is to remain unchanged.
In certain situations when linking a program for a Neuron 3150 Chip or a 3150 Smart Transceiver, it might be necessary to force the configuration property value files into offchip memory rather than letting the linker choose between offchip or onchip memory. Specify the put_cp_value_files_offchip option to force the value files into offchip memory.
#pragma debug option This pragma allows selection of various network debugger features. A program using network debugger features can only be used with version 6 and later versions of the Neuron firmware. The valid options are shown in the list below. This pragma can be used multiple times to combine options, but not all options can be combined.
#pragma disable_servpin_pullup Disables the internal pullup resistor on the service pin. This pullup resistor is normally enabled. The pragma takes effect during I/O initialization. This directive has no effect when used for a Series 5000 chip. This directive is not supported in model files. #pragma disable_snvt_si Disables generation of the self-identification (SI) data. The SI data is generated by default, but can be disabled using this pragma to reclaim program memory when the feature is not needed.
This directive has no effect for a Series 5000 chip because Series 5000 chips do not have on-chip programmable pull-up resistors. The linker issues the NLD#507 warning message if you include this directive for a Series 5000 device. This directive is not supported in model files. #pragma enable_multiple_baud Must be used in a program with multiple serial I/O devices that have differing bit rates. If needed, this pragma must appear prior to the use of any I/O function (for example, io_in( ) and io_out( )).
#pragma idempotent_duplicate_off #pragma idempotent_duplicate_on These pragmas control the idempotent request retry bit in the application buffer. This feature only applies to MIP or ShortStack Micro Server applications. One of these pragmas is required when compiling, if the #pragma micro_interface directive also is used. See the LonWorks Microprocessor Interface Program (MIP) User's Guide or the ShortStack User’s Guide for more information. These directives are not supported in model files.
directive defines the myToolkit.lib file within the “c:\LonWorks\myProjects” directory: #pragma library “$MYPROJ$\myToolkit.lib” If the environment variable “MYPROJ” is not defined, the linker replaces the unknown macro with an empty string; it does not issue an error message for the undefined macro. The system macros listed in Table 4 are always automatically pre-defined, and do not need defining in the system environment. Table 4.
This directive is not supported in model files. #pragma net_buf_in_count count [, modifier] See Allocating Buffers in Chapter 8, Memory Management, of the Neuron C Programmer’s Guide for more detailed information on this pragma and its use. This directive is not supported in model files. #pragma net_buf_in_size size [, modifier] See Allocating Buffers in Chapter 8, Memory Management, of the Neuron C Programmer’s Guide for detailed information on this pragma and its use.
Development Tool, valid values for num are 0 to 127. In Neuron C Version 2.2 (and later), there is no compiler default for this value. A Neuron C program must specify a value using this pragma. You can use this pragma to trade EEPROM space for alias table entries (see Chapter 8, Memory Management, of the Neuron C Programmer’s Guide). This directive is not supported in model files. #pragma num_domain_entries num Sets the number of domain table entries to num. Valid values for num are 1 or 2.
Level Optimization Performed Notes 1 No optimization Default for debug targets 2 Minimal optimization CP templates are not compressed 3 General optimization 4 General optimization, plus optimization of space for cp_family definitions 5 Maximum optimization Default for release targets You can use the following keywords instead of the numeric level indicators: • none for level 0 • debug for level 1 • standard for level 3 • all for level 5 The keyword level indicators are generally prefe
The #pragma optimization directive replaces the following directives: #pragma codegen cp_family_space_optimization #pragma codegen optimization_on #pragma codegen optimization_off #pragma codegen no_cp_template_compression While all of these directives continue to work, the compiler issues the NCC#589 warning message if you use these deprecated directives. If your application uses any of these directives with the #pragma optimization directive, the compiler issues the NCC#588 warning message.
#pragma relaxed_casting_off #pragma relaxed_casting_on These pragmas control whether the compiler treats a cast that removes the const attribute as an error or as a warning. The cast can either be explicit or implicit (as in an automatic conversion due to assignment or function parameter passing). Normally, the compiler considers any conversion that removes the const attribute to be an error. Turning on the relaxed casting feature causes the compiler to treat this condition as a warning instead.
Note this directive can be used to state compatibility with a guidelines version that is not actually supported by the compiler. Future versions of the guidelines that require a different syntax for SI/SD data are likely to require an update to the compiler. This directive only has the effect described above, and does not change the syntax of SD strings generated. The set_guidelines_version directive is typically used to specify a version string in the major.minor form (for example, “3.4”).
#pragma set_std_prog_id hh:hh:hh:hh:hh:hh:hh:hh Provides a mechanism for setting the device’s 8-byte program ID. This directive is provided for legacy application support and should not be used for new programs. The program ID should be set in the NodeBuilder device template instead. If this pragma is present, the value must agree with the program ID set by the NodeBuilder tool.
#pragma specify_io_clock string Specify this directive to inform the compiler of the value of the Neuron clock speed (external crystal frequency for Series 3100 devices, or the I/O clock frequency for Series 5000 devices). The directive is generally not required for Series 5000 chips because the I/O clock frequency is fixed for those chips.
Neuron 3120E1 Chip, Neuron 3120E2 Chip, and 3120 Smart Transceiver, firmware version 6 (or later) supports either algorithm. For the Neuron 3120 Chip, firmware version 4 (or later) supports either algorithm. For a Series 5000 device, firmware version 18 (or later) supports either algorithm.
... #else #ifdef YYY ... #else #error “You must define either XXX or YYY” #endif #endif This directive differs from the ANSI C #error directive in that the Neuron C version requires a quoted string. #warning “text” This directive allows you to issue a custom warning message. When this directive is processed, program compilation continues. This directive is useful for managing conditional compilation, for example: #ifdef XXX ... #else #ifdef YYY ...
3 Functions This chapter provides reference information on the Neuron C built-in and library functions. Built-in and library functions are used with executable code, and do not apply to host-based device development with model files.
Introduction This chapter lists Neuron C functions, providing syntax information, descriptions, and examples of each function. Some functions are built-in functions. This means they are used as if they were function calls, but they are permanently part of the Neuron C language and are implemented by the compiler without necessarily mapping into an actual function call. Some built-in functions have special behaviors depending on their context and usage. The rest of the functions are library calls.
variables and floating-point arithmetic, and a discussion of the use of extended precision variables and extended precision arithmetic is included in the following list of functions. Any existing application program developed for a Neuron 3120 Chip or 3120 Smart Transceiver using any system library functions might require more EEPROM memory on a Neuron 3120 Chip or 3120 Smart Transceiver than it would on a Neuron 3150 Chip, 3150 Smart Transceiverm or Series 5000 chip.
Function Description go_offline( ) Cease execution of the application program interrupt_control( ) Enable or disable interrupts msec_delay( ) Delay processing for a specified number of milliseconds post_events( ) Define a critical section boundary for network variable and message processing power_up( ) Determine whether last processor reset was due to power up preemption_mode( ) Determine whether the application processor scheduler is currently running in preemption mode.
Function Description addr_table_index( ) Determine address table index of message tag application_restart( ) Begin application program over again get_current_nv_length( ) Read a network variable's current length go_unconfigured( ) Reset this device to an uninstalled state node_reset( ) Activate the reset pin, and reset all CPUs nv_table_index( ) Determine global index of a network variable offline_confirm( ) Inform network tool that this device is going offline update_address( ) Write devic
44 Function Description bin2bcd( ) Convert binary data to binary coded decimal high_byte( ) Extract the high byte of a 16-bit number low_byte( ) Extract the low byte of a 16-bit number make_long( ) Create a 16-bit number from two 8-bit numbers max( ) Arithmetic maximum of two values min( ) Arithmetic minimum of two values muldiv( ) Unsigned multiply/divide with 32-bit intermediate result muldiv24( ) Unsigned multiply/divide with 24-bit intermediate result muldiv24s( ) Signed multiply/div
Function Description s32_div( ) Divide two signed 32-bit numbers s32_div2( ) Divide a 32-bit signed number by 2 s32_eq( ) Return TRUE if first argument equals second argument s32_from_ascii( ) Convert an ASCII string into a 32-bit signed number s32_from_slong( ) Convert a signed long number into a 32-bit signed number s32_from_ulong( ) Convert an unsigned long number into a 32-bit signed number s32_ge( ) Return TRUE if first argument is greater than or equal to second argument s32_gt( ) Ret
Function Description s32_rem( ) Return the remainder of a division of two signed 32-bit numbers s32_sign( ) Return the sign of a 32-bit signed number s32_sub( ) Subtract two signed 32-bit numbers s32_to_ascii( ) Convert a 32-bit signed number into an ASCII string s32_to_slong( ) Convert a 32-bit signed number into signed long Floating-Point Math Table 9 lists the floating-point mathematics functions. Table 9.
Function Description fl_from_ulong( ) Convert an unsigned long number to a floating-point number fl_ge( ) Return TRUE if first argument is greater than or equal to second argument fl_gt( ) Return TRUE if first argument is greater than second argument fl_le( ) Return TRUE if first argument is less than or equal to second argument fl_lt( ) Return TRUE if first argument is less than second argument fl_max( ) Find the maximum of two floatingpoint numbers fl_min( ) Find the minimum of two floating
Function Description fl_to_ascii_fmt( ) Convert a floating-point number to a formatted ASCII string fl_to_s32( ) Convert a floating-point number to signed 32-bit fl_to_slong( ) Convert a floating-point number to signed long fl_to_ulong( ) Convert a floating-point number to unsigned long fl_trunc( ) Return the whole number part of a floating-point number Strings Table 10 lists the string functions. Table 10.
Table 11.
Function Description memset( ) Set a block of memory to a specified value: • length greater than or equal to 256 bytes • others retrieve_status( ) Read statistics from protocol processor service_pin_msg_send( ) Send a service pin message service_pin_state( ) Read the service pin state set_bit( ) Set a bit in a bit array set_eeprom_lock( ) Set the state of the checksummed EEPROM's lock tst_bit( ) Return TRUE if bit tested was set Input/Output Table 12 lists the I/O functions. Table 12.
Function Description io_in( ) Input data from I/O object: • Dualslope input • Edgelog input • Infrared input • Magcard input • Neurowire I/O slave mode • Neurowire I/O with invert option • Serial input • Touch I/O • Wiegand input • others io_in_ready( ) Event function which evaluates to TRUE when a block of data is available from the parallel I/O object io_in_request( ) Start dualslope A/D conversion io_out( ) Output data to I/O object: • Bitshift output • Neurowire I/O slave
Function Description io_set_clock( ) Set timer/counter clock rate io_set_direction( ) Change direction of I/O pins sci_abort( ) Abort pending sci transfer sci_get_error( ) Read most recent sci error code spi_abort( ) Abort pending spi transfer spi_get_error( ) Read most recent spi error code Signed 32-Bit Integer Support Functions The Neuron C compiler does not directly support the use of the C arithmetic and comparison operators with 32-bit integers.
s32_type some_number = {0, 0, 0, 4}; // initialized to 4 on reset s32_type another_number = {-1, -1, -1, -16}; // initialized to -16 A number of constants are defined for use by the application if desired. s32_zero, s32_one, s32_minus_one represent the numbers 0, 1, and -1. If other constants are desired, they can be converted at runtime from ASCII strings using the function s32_from_ascii( ).
Table 13. Binary Arithmetic Operators Short Name add Function void s32_add(const s32_type *arg1, const s32_type *arg2, s32_type *arg3); Adds two signed 32-bit integers. (arg3 = arg1 + arg2). sub void s32_sub(const s32_type *arg1, const s32_type *arg2, s32_type *arg3); Subtracts two signed 32-bit integers. (arg3 = arg1 - arg2). mul void s32_mul(const s32_type *arg1, const s32_type *arg2, s32_type *arg3); Multiplies two signed 32-bit integers. (arg3 = arg1 *arg2).
Short Name Function neg void s32_neg(const s32_type *arg1, s32_type *arg2); Returns the negative of a signed 32-bit integer. (arg2 = - arg1). Comparison Operators Table 15 lists the comparison operator functions. Table 15. Comparison Operators Short Name eq Function boolean s32_eq(const s32_type *arg1, const s32_type *arg2); Returns TRUE if the first argument is equal to the second argument, otherwise FALSE. (arg1 == arg2).
Miscellaneous Signed 32-bit Functions Table 16 lists miscellaneous signed 32-bit functions. Table 16. Signed 32-Bit Functions Short Name Function sign int s32_sign(const s32_type *arg); Sign function, returns +1 if the argument is positive, 0 if the argument is zero, and -1 if the argument is negative. inc void s32_inc(s32_type *arg); Increments a signed 32-bit integer. dec void s32_dec(s32_type *arg); Decrements a signed 32-bit integer.
Short Name Function from ulong void s32_from_ulong(unsigned long arg1, s32_type *arg2); Converts a Neuron C unsigned long integer (range 0 to +65,535) to a signed 32-bit integer. Conversion of Signed 32-bit to ASCII String Table 18 lists the conversion function for a signed 32-bit number to an ASCII string. Table 18.
Table 20. Signed 32-Bit Function Performance Function Maximum Average Add/subtract 0.10 0.08 Multiply 2.07 1.34 Divide 3.17 2.76 Remainder 3.15 2.75 Maximum/minimum 0.33 0.26 Absolute value 0.25 0.12 Negation 0.20 0.20 Arithmetic Comparison 0.33 0.26 Conversion to ASCII 26.95 16.31 Conversion from ASCII 7.55 4.28 Conversion to 16-bit integer 0.12 0.10 Conversion from 16-bit integer 0.10 0.10 Random number generation 0.12 0.11 Sign of number 0.15 0.
float_type X, A, B, C; fl_mul(&B, &C, &X); fl_add(&X, &A, &X); The floating-point format can represent numbers in the range of approximately 1*101038 to +1*101038, with a relative resolution of approximately ±1*10-7. A float_type structure data type is defined by means of a typedef in the file. It defines a structure that represents a floating-point number in IEEE 754 single precision format. This has one sign bit, eight exponent bits and 23 mantissa bits, and is stored in big-endian order.
A number of #define literals are defined for use by the application to initialize floating-point structures. FL_ZERO, FL_HALF, FL_ONE, FL_MINUS_ONE and FL_TEN can be used to initialize floating-point variables to 0.0, 0.5, 1.0, -1.0, and 10.0 respectively. Example: float_type some_number = FL_ONE; // initialized to 1.0 at reset Five floating-point constants are pre-defined: fl_zero, fl_half, fl_one, fl_minus_one, and fl_ten represent 0.0, 0.5, 1.0, -1.0, and 10.0 respectively.
Example: float_type local_angle; // internal variable network output SNVT_angle_f nvoAngle; // network variable void f(void) { nvoAngle = *(SNVT_angle_f *) &local_angle; } The following example shows how an input SNVT_length_f network variable can be used as an input parameter to one of the functions in this library. Example: network input SNVT_length_f nvoLength; // network variable when(nv_update_occurs(nvoLength)) { if(fl_eq((const float_type *)&nvoLength, &fl_zero)) // compare length to zero . . .
Table 21. Binary Arithmetic Operators Short Name add Function void fl_add(const float_type *arg1, const float_type *arg2, float_type *arg3); Adds two floating-point numbers: (arg3 = arg1 + arg2). sub void fl_sub(const float_type *arg1, const float_type *arg2, float_type *arg3); Subtracts two floating-point numbers: (arg3 = arg1 - arg2). mul void fl_mul(const float_type *arg1, const float_type *arg2, float_type *arg3); Multiplies two floating-point numbers: (arg3 = arg1 *arg2).
Short Name Function trunc void fl_trunc(const float_type *arg1, float_type *arg2); Returns the whole number part of a floating-point number: (arg2 = trunc(arg1)). Truncation is towards zero. For example, trunc(-3.45) = 3.0. floor void fl_floor(const float_type *arg1, float_type *arg2); Returns the largest whole number less than or equal to a given floatingpoint number: (arg2 = floor(arg1)). Truncation is towards minus infinity. For example, floor(-3.45) = -4.0.
Short Name gt Function boolean fl_gt(const float_type *arg1, const float_type *arg2); Returns TRUE if the first argument is greater than the second argument, otherwise FALSE: (arg1 > arg2). lt boolean fl_lt(const float_type *arg1, const float_type *arg2); Returns TRUE if the first argument is less than the second argument, otherwise FALSE: (arg1 < arg2).
Table 25. Floating-Point Conversion Functions Short Name to slong to ulong to s32 Function signed long fl_to_slong(const float_type *arg); Converts a floating-point number to a Neuron C signed long integer (range -32,768 to +32,767). Truncation is towards zero. For example, fl_to_slong(-4.56) = -4. If the closest integer is desired, call fl_round( ) before calling fl_to_slong( ).
Table 26. Conversions of Floating-Point Numbers to ASCII Strings Short Name Function to ascii void fl_to_ascii(const float_type *arg1, char *arg2, int decimals, unsigned buf_size); Converts a floating-point number *arg1 to an ASCII string followed by a terminating NUL character. The decimals value is the required number of decimal places after the point. The buf_size value is the length of the output buffer pointed to by arg2, including the terminating null.
Conversion of ASCII String to FloatingPoint Table 27 lists the conversion functions for an ASCII srtring to a floating-point number. Table 27. Conversions of ASCII Strings to Floating-Point Numbers Short Name from ascii Function void fl_from_ascii(const char *arg1, float_type *arg2); Converts an ASCII string to a floating-point number. The conversion stops at the first invalid character in the input buffer—there is no error notification. The acceptable format is the following: [+/-][xx][.
68 Function Maximum Average Multiply 1.61 1.33 Divide 2.43 2.08 Square Root 10.31 8.89 Multiply/Divide by two 0.15 0.13 Maximum 0.61 0.53 Minimum 0.66 0.60 Integer Floor 0.25 0.21 Integer Ceiling 0.92 0.63 Integer Rounding 1.17 1.01 Integer Truncation 0.23 0.17 Negation 0.10 0.08 Absolute Value 0.10 0.08 Arithmetic Comparison 0.18 0.09 Conversion to ASCII 22.37 12.49 Conversion from ASCII 27.54 22.34 Conversion to 16-bit integer 2.84 1.
Using the NXT Neuron C Extended Arithmetic Translator You can use the NXT Neuron C Extended Arithmetic Translator to create initializers for signed 32-bit integers and floating-point variables in a Neuron C program. To use the NXT translator, open a Windows command prompt and enter the following command: nxt input-file output-file (where input-file contains Neuron C variable definitions) The source file can contain only one variable per line.
Syntax type abs (a); Example int i; long l; void f(void) { i = abs(-3); l = abs(-300); } access_address( ) Function The access_address( ) function returns a const pointer to the address structure that corresponds to the index parameter. This pointer can be stored, used to perform a structure copy, or used in other ways common to C pointers, except that the pointer cannot be used for writes. See the ISO/IEC 14908 (ANSI/EIA/CEA-709.1) Control Network Specification for a description of the data structure.
Syntax #include const alias_struct *access_alias (int index); Example #include alias_struct alias_copy; void f(void) { alias_copy = *(access_alias(2)); } access_domain( ) Function The access_domain( ) function returns a const pointer to the domain structure that corresponds to the index parameter. This pointer can be stored, used to perform a structure copy, or used in other ways common to C pointers, except that the pointer cannot be used for writes.
Example #include network output SNVT_amp nvoAmpere; nv_struct nv_copy; void f(void) { nv_copy = *(access_nv(nv_table_index(nvoAmpere)); } addr_table_index( ) Built-in Function The addr_table_index( ) built-in function is used to determine the address table index of a message tag as allocated by the Neuron C compiler. The returned value is in the range of 0 to 14.
Example #include unsigned buf[40]; unsigned *p; void f(void) { p = ansi_memcpy(buf, "Hello World", 11); } ansi_memset( ) Function The ansi_memset( ) function sets the first len bytes of the block pointed to by p to the character c. It also returns the value p. This function cannot be used to write into EEPROM or flash memory. The ansi_memset( ) function as implemented here conforms to the ANSI definition for memset( ), as it returns the pointer p.
Syntax #include void application_restart (void); Example #define MAX_ERRS 50 int error_count; ... when (error_count > MAX_ERRS) { application_restart(); } bcd2bin( ) Built-in Function The bcd2bin( ) built-in function converts a binary-coded decimal structure to a binary number. The structure definition is built into the compiler. The most significant digit is d1. Note that d1 should always be 0.
Syntax void bin2bcd (unsigned long value, struct bcd *p); For a definition of struct bcd, see bcd2bin, above. Example void f(void) { struct bcd digits; unsigned long value; ... value = 1234; bin2bcd(value, &digits); // digits.d1 now contains // digits.d2 now contains // digits.d3 now contains // digits.d4 now contains // digits.d5 now contains // digits.
Syntax #include void clr_bit (void *array, unsigned bitnum); Example #include
x16 + x15 + x 2 + 1 This function is useful in conjunction with the support for the Touch I/O model, but can also be used whenever a CRC is needed. Syntax #include unsigned long crc16 (unsigned long crc, unsigned new_data); Example #include
len Specifies the length of the data buffer, 1 to 255 bytes. A value of 0 represents 256 bytes. Example #include unsigned data[SIZE]; void f(void) { long seed = 0x04C1; long crc; crc = crc16_ccitt(seed, *data, SIZE); } delay( ) Function The delay( ) function allows an application to suspend processing for a given time. This function provides more precise timing than can be achieved with application timers. Table 29 lists the formulas for determining the duration of the delay. Table 29.
Series 3100 Input Clock Series 5000 System Clock Delay (in microseconds) 625 kHz — 9.6*((max(1,floor(count/16))*42)+206) For example, for a Series 3100 device with a 10 MHz input clock, the formula above yields durations in the range of 88.8 microseconds to 840 milliseconds by increments of 25.2 microseconds. Using a count greater than 33,333 (for a Series 3100 device at 10 MHz) could cause the watchdog timer to time out.
Example #pragma relaxed_casting_on eeprom far unsigned int widget[100]; far unsigned int ram_buf[100]; void f(void) { eeprom_memcpy(widget, ram_buf, 100); } Because the compiler regards a pointer to a location in EEPROM or FLASH as a pointer to constant data, #pragma relaxed_casting_on must be used to allow for the const attribute to be removed from the first argument, using an implicit or explicit cast operation.
associated with the functional block specified, passes the cmd parameter on to that director function, and returns when the called director function completes. Syntax void fblock_director (unsigned int index, int cmd); index A decimal number between 0 and 254 representing a functional block global index. cmd A decimal number between –128 and 127, interpreted as an application-specific command.
void fl_neg (const float_type *arg1, float_type *arg2); void fl_rand (float_type *arg1); void fl_round (const float_type *arg1, float_type *arg2); int fl_sign (const float_type *arg1); void fl_sqrt (const float_type *arg1, float_type *arg2); void fl_sub (const float_type *arg1, const float_type *arg2, float_type *arg3); void fl_to_ascii (const float_type *arg1, char *arg2, int decimals, unsigned buf-size); void fl_to_ascii_fmt (const float_type *arg1, char *arg2, int decimals, unsigned buf-size, format_type
when (flush_completes) { // Go to sleep nothing_to_do = FALSE; sleep(); } flush_cancel( ) Function The flush_cancel( ) function cancels a flush in progress. Syntax #include void flush_cancel (void); Example boolean nothing_to_do; ...
when (...) { msg_out.tag = TAG1; msg_out.code = 3; msg_send(); flush_wait(); nvoVoltage = 3; while (TRUE) { post_events(); if (nv_update_completes(nvoVoltage)) break; } } when (msg_completes(TAG1)) { ... } get_current_nv_length( ) Function The get_current_nv_length( ) function returns the currently defined length of a network variable, given the global index, netvar-index, of that network variable. This is useful when working with changeable-type network variables.
get_fblock_count( ) Built-in Function The get_fblock_count( ) built-in function is a compiler special function that returns the number of functional block (fblock) declarations in the program. For an array of functional blocks, each element counts as a separate fblock declaration.
Example void f(void) { unsigned int start, delta; start = get_tick_count(); ... delta = get_tick_count() - start; } go_offline( ) Function The go_offline( ) function takes an application offline. This function call has the same effect on the device as receiving an Offline network management message. The offline request takes effect as soon as the task that called go_offline( ) exits. When that task exits, the when(offline) task is executed and the application stops.
go_unconfigured( ) Function The go_unconfigured( ) function puts the device into an unconfigured state. It also overwrites all the domain information, which clears authentication keys as well. The go_unconfigured( ) function can be used after detecting and logging a serious, unrecoverable error. Some security devices also call this function when they detect a attempt to tamper with the device, and thus render the device inoperational and erase the secret authentication keys. Syntax #include
provided by Series 5000 devices, and is only available to an application that defines at least one interrupt task. If you need to disable or enable all interrupts at the same time, you can also use the io_idis() function to disable interrupts and the io_iena() function to enable interrupts. Syntax void interrupt_control(unsigned irqSelect); irqSelect Specifies the type of interrupts to enable.
io_change_init( ) Built-in Function The io_change_init( ) built-in function initializes the I/O object for the io_changes event. If this function is not used, the I/O object’s initial reference value defaults to 0. Syntax void io_change_init (input-io-object-name [, init-value]); input-io-object-name init-value Specifies the I/O object name, which corresponds to io-object-name in the I/O declaration. Sets the initial reference value used by the io_changes event.
value A value between 1 and 65535 defining the maximum value for each period measurement. Example IO_4 input edgelog elog; when (reset) { io_edgelog_preload(0x4000); // One fourth timeout // value: 16384 } io_edgelog_single_preload( ) Built-in Function The io_edgelog_single_preload( ) built-in function is optionally used with the edgelog I/O model when declared with the single_tc option keyword.
For Series 5000 devices, the io_idis( ) function disables all application interrupts. This function does not affect the I/O interrupt used in the hardware support for the sci and spi I/O models. Syntax void io_idis (void); Example when (...) { io_idis(); } io_iena( ) Function For Series 3100 devices, the io_iena( ) function enables the I/O interrupt used in the hardware support for the sci and spi I/O models.
dualslope input unsigned long edgelog input unsigned short i2c unsigned short infrared input unsigned short leveldetect input unsigned short magcard input signed short magcard_generic input unsigned long magtrack1 input unsigned short muxbus input unsigned short neurowire master void neurowire slave unsigned short nibble input unsigned short ontime input unsigned long parallel void period input unsigned long pulsecount input unsigned long quadrature input signed long serial
io_in (input-obj); The type of the return-value of the io_in( ) call is listed in the table above. bitshift For bitshift input objects, the syntax is: io_in (bitshift-input-obj [, numbits]); numbits The number of bits to be shifted in, from 1 to 127. Only the last 16 bits shifted in are returned. The unused bits are 0 if fewer than 16 bits are shifted in. edgelog For edgelog input objects, the syntax is: io_in (edgelog-input-obj, buf, count); buf A pointer to a buffer of unsigned long values.
The io_in( ) call has an unsigned short return-value that is the actual number of bits read. magcard For magcard input objects, the syntax is: io_in (magcard-input-obj, buf); buf A pointer to a 20 byte buffer of unsigned short bytes, which can contain up to 40 hex digits, packed 2 per byte. The io_in( ) call has a signed short return-value that is the actual number of hex digits read. A value of -1 is returned in case of error.
The io_in( ) call has an unsigned short return-value signifying the number of bits actually transferred for a neurowire slave object. For other neurowire I/O object types, the return-value is void. See the Driving a Seven Segment Display with the Neuron Chip engineering bulletin (part number 005-0014-01) for more information. parallel For parallel I/O objects, the syntax is: io_in (parallel-io-obj, buf); buf A pointer to the parallel_io_interface structure.
Example IO_0 input bit d0; boolean value; ... void f(void) { value = io_in(d0); } io_in_request( ) Built-in Function The io_in_request( ) built-in function is used with a dualslope I/O object to start the dualslope A/D conversion process. Syntax void io_in_request (input-io-object-name, control-value); input-io-object-name Specifies the I/O object name, which corresponds to io-object-name in the I/O declaration. This built-in function is used only for dualslope and sci I/O models.
io_out( ) Built-in Function The io_out( ) built-in function writes data to an I/O object. The include file contains optional type definitions for each of the I/O object types. The type names are the I/O object type name followed by “_t”. For example bit_t is the type name for a bit I/O object. The data type of output-value is listed below for each object type.
output-io-object-name Specifies the I/O object name, which corresponds to io-object-name in the I/O declaration. output-value Specifies the value to be written to the I/O object. args Arguments, which depend on the object type, as described below. Some of these arguments can also appear in the object declaration. If specified in both places, the value of the function argument overrides the declared value for that call only.
model in the I/O Model Reference for a detailed explanation of this restriction. muxbus For muxbus I/O objects, the syntax is: io_out (muxbus-io-obj, [addr,] data); addr An optional address to write (from 0 to 255). Omission of the address causes the firmware to rewrite the last address read or written (muxbus is a bi-directional I/O device). data A single byte of data to write.
touch For touch I/O objects, the syntax is: io_out (touch-io-obj, buf, count); buf A (void *) pointer to a buffer. count The number of bits to be written (from 1 to 255). Example boolean value; IO_0 output bit d0; void f(void) { io_out(d0, value); } io_out_request( ) Built-in Function The io_out_request( ) built-in function is used with the parallel I/O object and the sci I/O object. The io_out_request( ) sets up the system for an io_out( ) on the specified parallel I/O object.
io_preserve_input( ) Built-in Function The io_preserve_input( ) built-in function is used with an input timer/counter I/O object. If this function is not called, the Neuron firmware discards the first reading on a timer/counter object after a reset (or after a device on the multiplexed timer/counter is selected using the io_select( ) function because the data might be suspect due to a partial update).
infrared ontime period pulsecount totalcount clock-value Specifies an optional clock value, in the range 0 to 7, or a variable name for the clock. This value permanently overrides a clock value specified in the object’s declaration. The clock value option can only be specified for the infrared, ontime, and period objects.
{ io_set_baud(iosci, SCI_38400); // Optional baud change } io_set_clock( ) Built-in Function The io_set_clock( ) built-in function allows an application to specify an alternate clock value for any input or output timer/counter object that permits a clock argument in its declaration syntax. The objects are listed below: dualslope edgelog frequency infrared oneshot ontime period pulsecount pulsewidth stretchedtriac triac For multiplexed inputs, use the io_select( ) function to specify an alternate clock.
cannot specify TCCLK_40MHz or TCCLK_20MHz – no error is issued, but the effective value used in this case is TCCLK_10MHz). Example IO_1 output pulsecount clock(3) pcout; when(...) { io_set_clock(pcout, 5); // equivalent to io_set_clock(pcout, TCCLK_156k2Hz); ... } io_set_direction( ) Built-in Function The io_set_direction( ) built-in function allows the application to change the direction of any bit, nibble, or byte type I/O pin at runtime. The dir parameter is optional.
Example IO_0 output bit b0; IO_0 input byte byte0; int read_byte; void f(void) { io_set_direction(b0, IO_DIR_OUT); io_out(b0, 0); io_set_direction(byte0); // Defaults to IO_DIR_IN read_byte = io_in(byte0); } io_set_terminal_count( ) Built-in Function The io_set_terminal_count( ) built-in function allows the application to change the terminal count for the stretched triac I/O object at runtime.
} when (...) { io_out(ioTriac, 0); } // full off is_bound( ) Built-in Function The is_bound( ) built-in function indicates whether the specified network variable or message tag is connected (bound). The function returns TRUE if the network variable or message tag is connected, otherwise it returns FALSE. Typically, the function is used to override error detection algorithms.
low_byte( ) Built-in Function The low_byte( ) built-in function extracts the lower single-byte value from the double-byte operand a. This function operates without regard to signedness. See also high_byte( ), make_long( ), and swap_bytes( ).
Table 30. Result Types for the max() Function Larger Type Smaller Type Result unsigned long (any) unsigned long signed long signed long unsigned short signed short signed long unsigned short unsigned short signed short unsigned short signed short signed short signed short If the result type is unsigned, the comparison is unsigned, else the comparison is signed. Arguments can be cast, which affects the result type.
Example #include unsigned array1[40]; void f(void) { // Copy up to 40 bytes to array1, // but stop if an ASCII “W” value is copied. unsigned *p; p = memccpy(array1, “Hello World”, ‘W’, sizeof(array1)); } When the function returns, array1 contains “Hello W”, but no terminating ‘\0’ character, and p points to the 8th byte in the array1 array (following the ‘W’).
Syntax #include int memcmp (void *buf1, const void *buf2, unsigned long len); Example #include unsigned array1[40], array2[40]; void f(void) { // See if array1 matches array2 if (memcmp(array1, array2, sizeof(array1)) != 0) { // The contents of the two areas does not match } } memcpy( ) Built-in Function The memcpy( ) built-in function copies a block of len bytes from src to dest. It does not return any value.
Syntax void memset (void *p, int c, unsigned long len); Example unsigned target[20]; void f(void) { memset(target, 0, sizeof(target)); } min( ) Built-in Function The min( ) built-in function compares a and b and returns the smaller value. The result type is determined by the types of a and b, as described for max( ) on page 107.
when (io_changes(io_push_button)) { msec_delay(10); // Delay 10ms at any clock rate debounced_button_state = (boolean)io_in(io_push_button); } msg_alloc( ) Built-in Function The msg_alloc( ) built-in function allocates a nonpriority buffer for an outgoing message. The function returns TRUE if a msg_out object can be allocated. The function returns FALSE if a msg_out object cannot be allocated.
} } msg_cancel( ) Built-in Function The msg_cancel( ) built-in function cancels the message currently being built and frees the associated buffer, allowing another message to be constructed. If a message is constructed but not sent before the critical section (for example, a task) is exited, the message is automatically cancelled. This function is used to cancel both priority and nonpriority messages.
} ... } msg_receive( ) Built-in Function The msg_receive( ) built-in function receives a message into the msg_in object. The function returns TRUE if a new message is received, otherwise it returns FALSE. If no message is pending at the head of the message queue, this function does not wait for one. A program might need to use this function if it receives more than one message in a single task, as in bypass mode.
Example msg_tag motor; # define MOTOR_ON 0 # define ON_FULL 1 when (io_changes(switch1)to ON) { // Send a message to the motor msg_out.tag = motor; msg_out.code = MOTOR_ON; msg_out.data[0] = ON_FULL; msg_send(); } muldiv( ) Function The muldiv( ) function permits the computation of (A*B)/C where A, B, and C are all 16-bit values, but the intermediate product of (A*B) is a 32-bit value. Thus, the accuracy of the result is improved. There are two versions of this function: muldiv( ) and muldivs( ).
always use muldiv24() without loss of precision, compared to muldiv(), if neither A nor B ever exceeds 256. Syntax #include unsigned long muldiv24 (unsigned long A, unsigned int B, unsigned int C); Example #include unsigned long a, d; unsigned int b, c; ...
muldivs( ) Function The muldivs( ) function permits the computation of (A*B)/C where A, B, and C are all 16-bit values, but the intermediate product of (A*B) is a 32-bit value. Thus, the accuracy of the result is improved. There are two versions of this function: muldivs( ) and muldiv( ). The muldivs( ) function uses signed arithmetic, while the muldiv( ) function (see above) uses unsigned arithmetic.
{ application_restart(); } nv_table_index( ) Built-in Function The nv_table_index( ) built-in function is used to determine the index of a network variable as allocated by the Neuron C compiler. The returned value is limited by the application’s number of static network variables, and is never more than 61 for devices that are limited to 62 static network variables, or 253 for devices that are limited to 254 static network variables.
... if (offline){ // Perform offline cleanup ... offline_confirm(); } } poll( ) Built-in Function The poll( ) built-in function allows a device to request the latest value for one or more of its input network variables. Any input network variable can be polled at any time. If an array name without an index is used, then each element of the array is polled. An individual element can be polled by using an array index.
when (nv_update_occurs(nviZone)) { // New value of nviZone arrived } post_events( ) Function The post_events( ) function defines a boundary of a critical section at which network variable updates and messages are sent and incoming network variable update and message events are posted. The post_events( ) function is called implicitly by the scheduler at the end of every task body.
if (power_up()) initialize_hardware(); else { // hardware already initialized ... } } preemption_mode( ) Function The preemption_mode( ) function returns a TRUE if the application is currently running in preemption mode, or FALSE if the application is not in preemption mode. Preemption mode is discussed in Chapter 3, How Devices Communicate Using Network Variables, of the Neuron C Programmer's Guide. Syntax #include
device interface (XIF) file. Thus, network tools can handle the network address assignment for the variable properly. If any member of an array is propagated, the polled attribute is blocked for all elements of the array. If a propagate( ) call appears without arguments, all output variables’ polled attributes are blocked. Syntax void propagate ( [network-var] ); network-var A network variable identifier, array name, or array element.
Example void f(void) { unsigned value; ... value = random(); } resp_alloc( ) Built-in Function The resp_alloc( ) built-in function allocates an object for an outgoing response. The function returns TRUE if a resp_out object can be allocated. The function returns FALSE if a resp_out object cannot be allocated. When this function returns FALSE, a program can continue with other processing, if necessary, rather than waiting for a free message buffer.
if (offline()) { // Requested to go offline resp_cancel(); } else { resp_send(); } } } resp_free( ) Built-in Function The resp_free( ) built-in function frees the resp_in object for a response. See Chapter 6, How Devices Communicate Using Application Messages, of the Neuron C Programmer's Guide. Syntax void resp_free (void); Example void f(void) { ... if (resp_receive()) { // Process message ... resp_free(); } ...
Example void f(void) { ... if (resp_receive()) { // Process message ... resp_free(); } ... } resp_send( ) Built-in Function The resp_send( ) built-in function sends a response using the resp_out object. See Chapter 6, How Devices Communicate Using Application Messages, of the Neuron C Programmer's Guide for more information. Syntax void resp_send (void); Example # define DATA_REQUEST 0 # define OK 1 when (msg_arrives(DATA_REQUEST))) { unsigned x, y; x = msg_in.data[0]; y = get_response(x); resp_out.
unsigned long status_rcv_transaction_full; unsigned long status_lost_msgs; unsigned long status_missed_msgs; unsigned status_reset_cause; unsigned status_node_state; unsigned status_version_number unsigned status_error_log; unsigned status_model_number; } status_struct; status_xmit_errors A count of the transmission errors that have been detected on the network. A transmission error is detected through a CRC error during packet reception.
status_version_number The version number, which reflects the Neuron firmware version. status_error_log status_model_number The most recent error logged by the Neuron firmware or application. A value of 0 indicates no error. An error in the range of 1 to 127 is an application error and is unique to the application. An error in the range of 128 to 255 is a system error (system errors are documented in the Neuron Tools Errors Guide). The system errors are also available in the include file.
value = reverse(value); // now value is 0xC7 } rotate_long_left( ) Function The rotate_long_left( ) function returns the bit-rotated value of arg. The bit positions are rotated the number of places determined by the count argument. The signedness of the argument does not affect the result. Bits that are rotated out from the upper end of the value are rotated back in at the lower end. See also rotate_long_right( ), rotate_short_left( ), and rotate_short_right( ). Syntax #include
// k now contains 0x87E0 } rotate_short_left( ) Function The rotate_short_left( ) function returns the bit-rotated value of arg. The bit positions are rotated the number of places determined by the count argument. The signedness of the argument does not affect the result. Bits that are rotated out from the upper end of the value are rotated back in at the lower end. See also rotate_long_left( ), rotate_long_right( ), and rotate_short_right( ). Syntax #include
} scaled_delay( ) Function The scaled_delay( ) function generates a delay that scales with the input clock for the Neuron Chip or the Smart Transceiver. The formula for determining the duration of the delay is the following: delay = (25.2 *count + 7.2) *S (delay is in microseconds) In the formula above, the scaling factor S is determined by the input clock, as shown in Table 31. Table 31. Determining S Input Clock Rate System Clock Rate S (Series 3100) (Series 5000) 0.063 — 80 MHz 0.
void f(void) { io_out(software_one_shot, 1); //turn it on scaled_delay(4); //approx. 108 µsec at 10MHz io_out(software_one_shot, 0); //turn it off } sci_abort( ) Built-in Function The sci_abort( ) built-in function terminates any outstanding SCI I/O operation in progress. Syntax void sci_abort (io_object_name); Example IO_8 sci twostopbits baud(SCI_2400) iosci; when (...
} } service_pin_msg_send( ) Function The service_pin_msg_send( ) function attempts to send a service pin message. It returns non-zero if it is successful (queued for transmission in the network processor) and zero if not. This function is useful for automatic installation scenarios. For example, a device can automatically transfer its service pin message a random amount of time after powering up.
when (timer_expires(three_sec_timer)) { if (service_pin_state()) { // Service pin still depressed // go to unconfigured state go_unconfigured(); } } Note this example is functional, but incomplete: the device would go unconfigured if the service pin is still being pressed after three seconds, or when it has been released and, by chance, is pressed again when the three seconds expire. A more robust device would stop the timer when the service pin is being released, to facilitate the press-and-hold scheme.
The function enables or disables the lock (with a TRUE or FALSE argument, respectively). The EEPROM lock feature reduces the chances that a hardware failure or application anomaly can lead to a corruption of checksummed onchip EEPROM or offchip EEPROM or flash memory. The lock is automatically suspended while a device is offline to allow network management operations to occur. The application must release the lock prior to performing self-configuration. Application EEPROM variables are not locked.
void s32_ge (const s32_type *arg1, const s32_type *arg2); void s32_gt (const s32_type *arg1, const s32_type *arg2); void s32_inc (s32_type *arg1); void s32_le (const s32_type *arg1, const s32_type *arg2); void s32_lt (const s32_type *arg1, const s32_type *arg2); void s32_max (const s32_type *arg1, const s32_type *arg2, s32_type *arg3); void s32_min (const s32_type *arg1, const s32_type *arg2, s32_type *arg3); void s32_mul (const s32_type *arg1, const s32_type *arg2, s32_type *arg3); void s32_mul2 (s32_type
void sleep (unsigned int flags , io-object-name); void sleep (unsigned int flags , io-pin); flags One or more of the following three flags, or 0 if no flag is specified: COMM_IGNORE Causes incoming messages to be ignored PULLUPS_ON Enables all I/O pullup resistors (the service pin pullup is not affected) TIMERS_OFF Turns off all timers in the program If two or more flags are used, they must be combined using either the + or the | operator.
spi_get_error( ) Function The spi_get_error( ) built-in function returns a cumulative OR of the bits shown below to specify data errors. Calling this function clears the SPI error state.
strchr( ) Function The strchr( ) function searches the string s for the first occurrence of the character c. If the string does not contain c, the strchr( ) function returns the null pointer. The NUL character terminator ('\0') is considered to be part of the string, thus strchr(s,'\0') returns a pointer to the NUL terminator. See also strcat( ), strcmp( ), strcpy( ), strlen( ), strncat( ), strncmp( ), strncpy( ), and strrchr( ). Syntax #include
{ int val; char s1[20], s2[20]; val = strcmp(s1, s2); if (!val) { // Strings are equal } else if (val < 0) { // String s1 is less than s2 } else { // String s1 is greater than s2 } } strcpy( ) Function The strcpy( ) function copies the string pointed to by the parameter src into the string buffer pointed to by the parameter dest. The copy ends implicitly, when the terminating NUL ('\0') character is copied—no string length information is available to the function.
Syntax #include unsigned long strlen (const char *s); Example #include void f(void) { unsigned long length; length = strlen("Hello, world!"); } strncat( ) Function The strncat( ) function appends a copy of the first len characters from the string src to the end of the string dest, and then adds a NUL ('\0') character, resulting in concatenated strings (thus the name strncat, from string concatenate).
When a mismatch occurs, the characters from both strings at the mismatch are compared. If the first string’s character is greater using an unsigned comparison, the return value is positive. If the second string’s character is greater, the return value is negative. The terminating NUL character is compared just as any other character. See also strcat( ), strchr( ), strcmp( ), strcpy( ), strlen( ), strncat( ), strncpy( ), and strrchr( ). Syntax #include
Example #include char s[20]; void f(char *p) { strncpy(s, p, 19); // Prevent overflow s[19] = '\0'; // Force termination } strrchr( ) Function The strrchr( ) function scans a string for the last occurrence of a given character. The function scans a string in the reverse direction (hence the extra ‘r’ in the name of the function), looking for a specific character. The strrchr( ) function finds the last occurrence of the character c in string s.
Example long k; void f(void) { k = 0x1234L; k = swap_bytes(k); } // k now contains 0x3412L timers_off( ) Function The timers_off( ) function turns off all software timers. This function could be called, for example, before an application goes offline. Syntax #include void timers_off (void); Example when (...) { timers_off(); go_offline(); } touch_bit( ) Built-in Function The touch_bit( ) function writes and reads a single bit of data on a 1-Wire® bus.
touch_byte( ) Built-in Function The touch_byte( ) function sequentially writes and reads eight bits of data on a 1Wire bus. It can be used for either reading or writing. For reading, the write-data argument should be all ones (0xFF), and the return value contains the eight bits as read from the bus. For writing, the bits in the write-data argument are placed on the 1-WIRE bus, and the return value normally contains those same bits.
... dataOut = 42; touch_byte_spu(1WIREPIN, dataOut); } touch_first( ) Built-in Function The touch_first( ) function executes the ROM Search algorithm as described in application note 937, Book of iButton Standards, from Maxim Integrated Products. Both functions make use of a search_data_s data structure for intermediate storage of a bit marker and the current ROM data. This data structure is automatically defined in Neuron C, regardless of whether a program references the touch I/O functions.
touch_next( ) Built-in Function The touch_next( ) function executes the ROM Search algorithm as described in application note 937, Book of iButton Standards, from Maxim Integrated Products. Both functions make use of a search_data_s data structure for intermediate storage of a bit marker and the current ROM data. This data structure is automatically defined in Neuron C, regardless of whether a program references the touch I/O functions.
touch_read_spu( ) Built-in Function This function applies to 1-Wire bus devices that require the bus to be actively held high during certain device operations. These devices require more current than a typical external pull-up resistor can provide for device operations. An example of such a device is the Maxim Integrated Products DS18S20 HighPrecision 1-Wire Digital Thermometer. For other 1-Wire devices, use the standard touch_byte( ) function.
The touch_reset( ) function does not return until the end of the presence pulse has been detected. Syntax int touch_reset (io-object-name); Example void f(void) { touch_reset(ioObj); } touch_reset_spu( ) Built-in Function This function applies to 1-Wire bus devices that require the bus to be actively held high during certain device operations. These devices require more current than a typical external pull-up resistor can provide for device operations.
{ ... int rc; rc = touch_reset_spu(1WIREPIN); } touch_write_spu( ) Built-in Function This function applies to 1-Wire bus devices that require the bus to be actively held high during certain device operations. These devices require more current than a typical external pull-up resistor can provide for device operations. An example of such a device is the Maxim Integrated Products DS18S20 HighPrecision 1-Wire Digital Thermometer. For other 1-Wire devices, use the standard touch_byte( ) function.
that are all similar, a bit array can be more code-efficient than a series of bitfields because the array can be accessed using an array index rather than separate lines of code for each bitfield. See also clr_bit( ) and set_bit( ). Syntax #include boolean tst_bit (void *array, unsigned bitnum); Example #include
void f(void) { address_copy = *access_address( addr_table_index(my_mt)); // Modify the address_copy here as necessary ... update_address(&address_copy, addr_table_index(my_mt)); } update_alias( ) Function The update_alias( ) function copies from the structure referenced by the alias pointer parameter to the alias table entry specified by the index parameter. The Neuron 3120 Chip with version 4 firmware does not support aliasing.
domain/subnet/node address on the network. Typically, cloned devices are intended for low-end systems where network tools are not used for installation. The LonTalk protocol inherently disallows this configuration because devices reject messages that have the same source address as their own address. The update_clone_domain( ) function enables a device to receive a message with a source address equal to its own address.
See the ISO/IEC 14908 (ANSI/EIA/CEA-709.1) Control Network Specification for a description of the data structure. Syntax #include void update_config_data (const config_data_struct *p); Example #include
} update_nv( ) Function The update_nv( ) function copies from the structure referenced by the nv-entry pointer parameter to the network variable configuration table entry as specified by the index parameter. Important: This function has a mechanism that ensures that a reset or power cycle during an EEPROM modification does not cause the device to go unconfigured. This mechanism uses the error log to serve as a semaphore.
Syntax #include void update_program_id (unsigned char * pid_p); Example #include unsigned char progID_copy[8]; void f(void) { update_program_id(progID_copy); } watchdog_update( ) Function The watchdog_update( ) function updates the watchdog timer. For Series 3100 devices, the watchdog timer times out in the range of .84 to 1.68 seconds with a 10 MHz Neuron input clock. The watchdog timer period scales inversely with the input clock frequency.
4 Timer Declarations This chapter provides reference information for declaring and using Neuron C timers. Neuron C timers are an application development feature for Neuron-hosted devices and do not apply to model files.
Timer Object A timer object is declared using one of the following: mtimer [repeating] timer-name [=initial-value]; stimer [repeating] timer-name [=initial-value]; mtimer Indicates a millisecond timer. stimer Indicates a second timer. repeating An option for the timer to restart itself automatically upon expiration. With this option, accurate timing intervals can be maintained even if the application cannot respond immediately to an expiration event. timer-name A user-supplied name for the timer.
5 Network Variable, Configuration Property, and Message Tag Declarations This chapter describes the network variable, configuration property, and application message tag declarations for use in Neuron C programs. It also describes how configuration properties are associated with a device, with a functional block on the device, or with a network variable on the device. Finally, this chapter describes the syntax for accessing the configuration properties from the device’s program.
Introduction The external application interface of a LONWORKS device consists of its functional blocks, network variables, and configuration properties. The network variables are the device’s means of sending and receiving data using interoperable data types and using an event-driven programming model. The configuration properties are the device’s means of providing externally exposed configuration data, again using interoperable data types.
Network Variable Declarations Syntax The complete syntax for declaring a network variable is one of the following: network input | output [netvar-modifier] [class] type [connection-info] [config_prop [cp-modifiers]] identifier [= initial-value] [nv-property-list] ; network input | output [netvar-modifier] [class] type [connection-info] [config_prop [cp-modifiers]] identifier [array-bound] [= initializer-list] [nv-property-list] ; The brackets around array-bound are shown in bold type.
sd_string ( concatenated-string-constant ) Sets a network variable’s self-documentation (SD) string of up to 1023 characters. This modifier can only appear once per network variable declaration. If any of the sync, polled, or changeable_type keywords are used, then the sd_string modifier must follow these other keywords. Concatenated string constants are permitted. Each variable’s SD string can have a maximum length of 1023 bytes.
connections can still cause changes to such a configuration network variable. eeprom The network variable is placed in EEPROM or flash memory instead of RAM. All variables are placed in RAM by default. EEPROM and flash memory are only appropriate for variables that change infrequently, due to the overhead and execution delays inherent in writing such memory, and due to the limited number of writes for such memory devices. far The network variable is placed in the far section of the variable space.
[signed] long [int] unsigned long [int] signed char [unsigned] char [signed] [short] [int] unsigned [short] [int] enum (An enum is int type) Structures and unions of the above types up to 31 bytes long. Structures and unions cannot exceed 31 bytes in length when used as the type of a network variable. Single-dimension arrays of the above types. For interoperability, SNVTs and UNVTs defined in resource files should be used for network variables instead of these base types. • A typedef.
property-reference-list : property-reference-list , property-reference property-reference property-reference : property-identifier [= initializer] [range-mod] property-identifier [range-mod] [= initializer] range-mod : range_mod_string ( concatenated-string-constant ) property-identifier : [property-qualifier] cpnv-prop-ident [property-qualifier] cp-family-prop-ident property-qualifier : static | global cpnv-prop-ident : identifier [ constant-array-index-expr ] identifier cp-family-prop-ident : identifi
page 171. A range-modification string provided in the instantiation of a CP family member overrides any range-modification string provided in the declaration of a CP family. Unlike device properties, network variable properties can be shared between two or more network variables. The use of the global keyword creates a CP family member that is shared between two or more network variables.
network output SNVT_lev_percent nvoValue[4] nv_properties { static cpMaxSendT // MUST be shared }; Network Variable Connection Information (connection-info) The following optional fields can be included in the declaration of each network variable. The fields can be specified in any order. This information can be used by a network tool, as described in the NodeBuilder FX User’s Guide.
ackd (the default) — acknowledged service; with retry; if acknowledgments are not received from all receiving devices before the layer 4 retransmission timer expires, the message is sent again, up to the retry count. An unacknowledged (unackd) network variable uses minimal network resources to propagate its values to other devices. As a result, propagation failures are more likely to occur, and failures are not detected by the sending device.
priority | nonpriority [( config | nonconfig )] Specifies whether a network variable update has priority access to the communications channel. This field specifies the default value. The config and nonconfig keywords specify whether the priority designation can be changed by a network tool. The default is config. All priority network variables in a device use the same priority time slot because each device is configured to have no more than one priority time slot. The default is nonpriority (config).
Configuration Property Declarations You can implement a configuration property as a configuration network variable or as part of a configuration file. To implement a configuration property as a configuration network variable, declare it using the network … config_prop syntax described in Network Variable Declarations Syntax on page 161. To implement a configuration property as a part of a configuration file, declare it with the cp_family syntax described in this section.
the NodeBuilder tool. There could be many similar resource files containing UCPT definitions, and these are managed on the computer by the NodeBuilder Resource Editor as described in the NodeBuilder FX User’s Guide. A configuration property family can be declared with an optional array-bound. This declares the family such that each member of the configuration property family is a separate array (of identical size). Each instantiation of a member of the configuration property family becomes a separate array.
cp-option-list : cp-option-list , cp-option cp-option cp-option : device_specific | manufacturing_only | object_disabled | offline | reset_required range-mod : range_mod_string ( concatenated-string-constant ) There must be at least one keyword in the option list. For multiple keywords, the keywords can occur in any order, but the same keyword must not appear more than once. Keywords must be separated by commas.
point numbers delimited by a colon. The first number is the lower limit and the second number is the high limit. If either the high limit or the low limit should be the maximum or minimum specified in the configuration property type definition, then the field should be empty. In the case of a structure or an array, if one member of the structure or array has a range modification, then all members must have a range modification specified.
device_properties { property-reference-list }; property-reference-list : property-reference-list , property-reference property-reference property-reference : property-identifier [= initializer] [range-mod] property-identifier [range-mod] [= initializer] range-mod : range_mod_string ( concatenated-string-constant ) property-identifier : cpnv-prop-ident cp-family-prop-ident cpnv-prop-ident : identifier [ constant-array-index-expr ] identifier cp-family-prop-ident : identifier The device property list beg
page 171. A range-modification string provided in the instantiation of a CP family member overrides any range-modification string provided in the declaration of the CP family.
}; void f(void) { ... if (nvoValue::cpMaxSendT.seconds > 0) { ... } } The particular family member is identified by a qualifier that precedes it. This qualifier is called the context. The context is followed by two consecutive colon characters, and then the name of the property. Because there cannot be two or more properties with the same configuration property type that apply to the same network variable, each property is unique within a particular context.
A message tag declaration can optionally include connection information. The syntax for declaring a message tag is as follows: msg_tag [connection-info] tag-identifier [, tag-identifier ...]; The connection-info field is an optional specification for connection options, in the following form: bind_info (options) The following connection options apply to message tags: nonbind Denotes a message tag that carries no implicit addressing information and does not consume an address table entry.
6 Functional Block Declarations This chapter provides reference information for functional block declarations. The Neuron C language allows creation of functional blocks to group network variables and configuration properties that perform a single task together. Functional blocks are an important part of a device’s interface definition. Functional block declarations apply to both Neuron-hosted applications and host-based applications with a model file.
Introduction The external application interface of a LONWORKS device consists of its functional blocks, network variables, and configuration properties. A functional block is a collection of network variables and configuration properties that are used together to perform one task. These network variables and configuration properties are called the functional block members. Functional blocks are defined by functional profiles. A functional profile is used to describe common units of functional behavior.
ext-name : external_name ( C-string-const ) external_resource_name ( C-string-const ) external_resource_name ( const-expr : const-expr ) fblock-body : [fblock-member-list] [director-function] fblock-member-list : fblock-member-list fblock-member ; fblock-member ; fblock-member : nv-reference implements member-name nv-reference impl-specific impl-specific : implementation_specific ( const-expr ) member-name nv-reference : nv-identifier array-index nv-identifier array-index : [ const-expr ] dire
A Neuron C program can also implement additional network variables in the functional block that are not in the list of optional members of the profile. Such additional network variable members beyond the profile are called implementation-specific members. These extra members are declared in the member list using the implementation_specific keyword, followed by a unique index number, and a unique name.
the external_name string described above. In this case, the device interface information contains a scope and index pair (the first number is a scope, then a colon character, and then the second number is an index). The scope and index pair identifies a language string in the resource files, which a network tool can access for a language-dependent name of the functional block.
The functional block property list begins with the fb_properties keyword. It then contains a list of property references, separated by commas, exactly like the device property list and the network variable property list. Each property reference must be the name of a previously declared CP family or the name of a previously declared configuration network variable. The rest of the syntax is very similar to the network variable property list syntax discussed in the previous chapter.
fb_properties { cpOffset, // offset for each fblock static cpGain, // gain shared in MyFb1 global cpLocation // location shared in all 4 }; fblock SFPTopenLoopSensor { nvoData[2] implements nvoValue; } MyFb2[2] fb_properties { cpOffset, // offset for each fblock static cpGain, // gain shared in MyFb2 global cpLocation // location shared in all 4 }; Like network variable properties, functional block properties can be shared between two or more functional blocks.
the program. The array entry is an unsigned short. Its declaration, in the file, is: extern const unsigned short fblock_index_map[ ]; The value for each network variable is set to the global index of the functional block of which it is a member. If the network variable is not a member of any functional block, the value for its entry in the fblock_index_map array is set to the value 0xFF.
Just like for network variable properties, even though a configuration network variable can be uniquely accessed through its variable identifier, it can also be accessed through the context expression, just like the CP family members. Also, the network variable members of the functional block can be accessed through a similar syntax.
7 Built-In Variables, Objects, Symbols, and Semaphore This chapter provides reference information about the builtin variables, objects, symbols, and semaphore in Neuron C. Built-in variables, objects, and semaphores apply only to Neuron-hosted application development, and are ignored in model files. Built-in symbols apply to both Neuron-hosted and host-based development.
Introduction Neuron C Version 2 provides built-in variables and built-in objects. The term “built-in” means that the definition is part of the Neuron C language, and is directly generated by the compiler, rather than being a reference to a normal variable.
Built-In Variables The following sections list the Neuron C built-in variables alphabetically, providing relevant syntax information and a detailed description of each function. activate_service_led Variable The activate_service_led variable can be assigned a value by the application program to control the service LED status. Assign a non-zero value to activate_service_led to turn the service LED on. Assign a zero value to turn the service LED off. The
unsigned input_clock : 3; unsigned comm_type : 3; // offset unsigned comm_pin_dir : 5; unsigned preamble_length; // offset unsigned packet_cycle; // offset unsigned beta2_control; // offset unsigned xmit_interpacket; // offset unsigned recv_interpacket; // offset unsigned node_priority; // offset unsigned channel_priorities; // offset union { // offset unsigned xcvr_params[NUM_COMM_PARAMS]; direct_param_struct dir_params; } params; unsigned non_group_timer : 4; // offset unsigned nm_auth : 1; unsigned preem
cp_readonly_value_file_len Variable The cp_readonly_value_file_len variable contains the length of the cp_readonly_value_file array. The type is unsigned long. See Chapter 5, Network Variable, Configuration Property, and Message Tag Declarations, on page 159, for more information about configuration properties. cp_template_file Variable The cp_template_file variable contains the configuration property template file.
Example 1: signed long switch_state; when (io_changes(switch_in)) { switch_state = input_value; } Here, the value of the network variable switch_state is set to the value of input_value (the switch value that was read in the io_changes clause). However, there are some I/O models, such as pulsecount, where the true type of the input value is an unsigned long. An explicit cast should be used to convert the value returned by input_value to an unsigned long variable in this case.
When an nv_update_occurs event is TRUE, the nv_in_addr variable is set to contain the LONWORKS addressing information of the sending device.
nv_in_index Variable The nv_in_index variable contains the network variable global index for an nv_update_completes, nv_update_fails, nv_update_succeeds, or nv_update_occurs event. When one of these events evaluates to TRUE, nv_in_index contains the network variable global index to which the event applies. The contents of nv_in_index are undefined if no network variable events have occurred.
unsigned : 0; unsigned : 4; unsigned receive_trans_count : 4; unsigned app_buf_out_size : 4; unsigned app_buf_in_size : 4; unsigned net_buf_out_size : 4; unsigned net_buf_in_size : 4; unsigned net_buf_out_priority_count unsigned app_buf_out_priority_count unsigned app_buf_out_count : 4; unsigned app_buf_in_count : 4; unsigned net_buf_out_count : 4; unsigned net_buf_in_count : 4; unsigned reserved1 [6]; unsigned : 6; unsigned tx_by_address : 1; unsigned idempotent_duplicate : 1; } read_only_data_struct; : 4
Built-In Objects The following sections list the Neuron C built-in objects alphabetically, providing relevant syntax information and a detailed description of each function. msg_in Object The msg_in object contains an incoming application or foreign-frame message.
struct { boolean msg_tag int int boolean service_type msg_out_addr } msg_out; priority_on; tag; code; data[MAXDATA]; authenticated; service; dest_addr; The various fields of the msg_out object are: priority_on TRUE if a priority message. Defaults to FALSE. tag Message tag of the outgoing message. This field must be set. code Message code of the outgoing message. This field must be set. data Message data. authenticated Specifies message is to be authenticated. Defaults to FALSE.
resp_out Object The resp_out object contains an outgoing response message to be sent in response to an incoming request message. The response message inherits its priority and authentication designation from the request to which it is replying. Because the response is returned to the origin of the request, no message tag is necessary.
Symbol Description _NCC5 Defined for version 5 of the Neuron C compiler. This version corresponds to Version 2.2 of the Neuron C language. _NEURONC Defined for all versions of the Neuron C compiler. _NODEBUILDER Defined for the Neuron C compiler that is included with the NodeBuilder FX Development Tool, and later versions. _SHORTSTACK Defined for the Neuron C compiler that is included with the ShortStack LonTalk Interface Developer utility for model files.
__lock { // acquire semaphore f(); } // release semaphore ... // more unguarded code } This code results in a deadlock because the interrupt task owns the semaphore, thus function f() can never succeed in acquiring it. The Neuron firmware resolves the deadlock by resetting the chip after the watchdog timer expires, but you must be sure to release the semaphore before acquiring it again. Defining a lock with target hardware or firmware that does not support semaphores yields a linker error, NLD#506.
A Syntax Summary This appendix provides a summary of Neuron C Version 2.2 syntax, with some explanatory material interspersed. In general, the syntax presentation starts with the highest, most general level of syntactic constructs and works its way down to the lowest, most concrete level as the appendix progresses. The syntax is divided into sections for ease of use, with declaration syntax first, statement syntax next, and expression syntax last.
Syntax Conventions In this syntax section, syntactic categories (nonterminals) are indicated by italic type, and literal words and character set members (terminals) by bold type. In the example below, basic-net-var is a nonterminal, meaning it represents a syntactic category, or construct, rather than a literal string of characters to be typed. The symbols network, input, and output are terminals, meaning they are to be typed in exactly as shown.
Neuron-C-declaration : task-declaration io-object-declaration ; functional-block-declaration ; device-property-list-declaration A data declaration is an ANSI C variable declaration. data-declaration : variable-declaration variable-list Variable Declarations The following is ANSI C variable declaration syntax.
declaration-specifier-list : declaration-specifier-list declaration-specifier declaration-specifier declaration-specifier : timer-type type-specifier storage-class-specifier cv-type-qualifier configuration-property-specifier msg_tag net-var-types connection-information type-specifier : type-identifier type-keyword struct-or-union-specifier enum-specifier Timer Declarations Timer objects are declared with one of the following sequences of keywords. Timer objects are specific to Neuron C.
Storage Classes The ANSI C storage classes are augmented in Neuron C with the additional classes config, eeprom, far, fastaccess, offchip, onchip, ram, system, and uninit. The ANSI C register storage class is not supported in Neuron C (it is ignored by the compiler). class-keyword : auto config eeprom extern far fastaccess offchip onchip ram register static system typedef uninit Type Qualifiers The ANSI C language also defines type qualifiers for declarations.
enum-const-list : enum-const-list , enum-const enum-const enum-const : variable-identifier = constant-expr variable-identifier Structure/Union Syntax The following is ANSI C struct/union type syntax.
cp-info : cp-option-list : cp-option : range-mod : cp_info ( cp-option-list ) cp-option-list , cp-option cp-option-list cp-option cp-option one of device_specific | manufacturing_only | object_disabled | offline | reset_required range_mod_string ( concatenated-string-constant ) Network Variable Declarations Network variables are declared with one of the following sequences of keywords. Network variables are specific to Neuron C.
bind-info-option : auth ( configurable-keyword ) authenticated ( configurable-keyword ) auth authenticated bind nonbind offline priority ( configurable-keyword ) priority nonpriority ( configurable-keyword ) nonpriority rate-est-keyword ( constant-expr ) service-type-keyword ( configurable-keyword ) service-type-keyword rate-est-keyword : max_rate_est rate_est service-type-keyword : ackd unackd unackd_rpt configurable-keyword : config nonconfig Declarator Syntax The following is ANSI C declarator s
function-parameter-declaration : formal-parameter-declaration prototype-parameter-declaration formal-parameter-declaration : ( identifier-list ) () identifier-list : identifier-list , variable-identifier variable-identifier prototype-parameter-declaration : ( prototype-parameter-list ) ( prototype-parameter-list , ...
abstract-decl-specifier : type-specifier cv-type-qualifier Task Declarations Neuron C contains task declarations. Task declarations are similar to function declarations. A task declaration consists of a when or an interrupt clause list, followed by a task. A task is a compound statement (like an ANSI C function body).
parm-declaration : declaration-specifier-list parm-declarator-list ; parm-declarator-list : parm-declarator-list , declarator declarator Conditional Events In Neuron C, an event is an expression which can evaluate to either TRUE or FALSE. Neuron C extends the ANSI C concept of conditional expressions through special built-in functions that test for the presence of special Neuron firmware events.
message-event : message-event-keyword ( expression ) message-event-keyword message-event-keyword : msg_arrives msg_completes msg_fails msg_succeeds resp_arrives net-var-event : nv-event-keyword ( net-var-identifier ..
modified-io-object-declarator : io-object-declarator [ io-option-list ] io-option-list : io-option-list io-option io-option The I/O object declarator begins with a pin name, followed by the I/O object type.
select ( io-object-pin-name ) short single_tc slave slave_b __slow sync ( io-object-pin-name ) synchronized ( io-object-pin-name ) timing( constant-expr , constant-expr , constant-expr ) twostopbits use_stop_condition The clock-edge option is specified using either the plus or the minus character, or both characters in the case of a dual-edge clock. The dual-edge clock (+-) is not available on minor model 0 of the Neuron 3150 Chip.
The functional block name can specify either a scalar or a single-dimensioned array (like a network variable declaration). The functional block can also optionally have an external name, and this external name can either be a string constant or a resource file reference.
property-instantiation : [ property-qualifier ] cpnv-prop-ident [ property-qualifier ] cp-family-prop-ident property-qualifier : one of global | static cpnv-prop-ident : net-var-identifier [ constant-expression ] net-var-identifier cp-family-prop-ident : variable-identifier Statements The following is ANSI C statement syntax. Compound statements begin and end with left and right braces, respectively. Compound statements contain a variable declaration list, a statement list, or both.
incomplete-stmt : label : incomplete-stmt for-head incomplete-stmt if-else-head incomplete-stmt if-head statement switch-head incomplete-stmt while-clause incomplete-stmt These are the various pieces that make up the statement syntax from above.
choice-expr : logical-or-expr ? expression : choice-expr logical-or-expr logical-or-expr : logical-or-expr || logical-and-expr logical-and-expr logical-and-expr : logical-and-expr && bit-or-expr bit-or-expr bit-or-expr : bit-xor-expr : bit-or-expr | bit-xor-expr bit-xor-expr bit-xor-expr ^ bit-and-expr bit-and-expr bit-and-expr : bit-and-expr & equality-comparison equality-comparison equality-comparison : equality-comparison == relational-comparison equality-comparison != relational-comparison relat
add-op : one of +|- multiplicative-expr : multiplicative-expr mul-op cast-expr cast-expr mul-op : cast-expr : one of *|/|% ( abstract-type ) cast-expr unary-expr unary-expr : unary-op : postfix-expr : unary-op cast-expr sizeof unary-expr sizeof ( abstract-type ) predefined-event one of * | & | ! | ~ | + | - | ++ | -- postfix-expr [ expression ] postfix-expr -> identifier postfix-expr .
Primary Expressions, Built-in Variables, and Built-in Functions In addition to the ANSI C definitions of a primary expression, Neuron C adds some built-in variables and built-in functions. Neuron C removes float-constant from the standard list of primary expressions.
eeprom_memcpy fblock_director get_fblock_count | get_nv_count get_tick_count high_byte interrupt_control io_change_init io_in | io_in_ready | io_in_request io_out | io_out_ready | io_out_request io_preserve_input io_select io_set_baud | io_set_clock | io_set_direction io_set_terminal_count is_bound low_byte make_long max memcpy | memset min nv_table_index poll propagate sci_abort | sci_get_error sleep spi_abort | spi_get_error swap_bytes touch_bit | touch_byte | touch_first touch_next | touch_reset touch_by
224 #define INT_MAX #define INT_MIN 127 ((int)(-128)) #define UINT_MAX 255 #define LONG_MAX #define LONG_MIN 32767 ((signed long)(-32768)) #define ULONG_MAX 65535 #define MB_LEN_MAX 2 Syntax Summary
B Reserved Keywords This chapter lists all Neuron C Version 2.2 reserved keywords, including the standard reserved keywords of the ANSI C language.
Reserved Words List The following list of reserved words includes keywords in the Neuron C language as well as Neuron C built-in symbols. Each of these reserved words should be used only as it is defined elsewhere in this reference guide. A Neuron C programmer should avoid the use of any of these reserved words for other purposes, such as variable declarations, function definitions, or typedef names.
case (c) extern (c) changeable_type (2) external_name (2) char (c) external_resource_name (2) charge_pump_enable (f) FALSE (e) clock (1) far (1) clockedge (1) __fast (2.
228 invert (1) leveldetect (1) IO_0 (1) __lock (2.2) IO_1 (1) long (c) IO_10 (1) low_byte (f) IO_11 (2.1) magcard (1) IO_2 (1) magcard_bitstream (2.
nonauthenticated (1) pulsewidth (1) nonbind (1) quad (1) nonconfig (1) quadrature (1) nonpriority (1) ram (1) numbits (1) random (f) nv_array_index (v) range_mod_string (2) nv_in_addr (v) rate_est (1) nv_in_addr_t (st,t) register (c) nv_in_index (v) repeating (1) nv_len (p) REQUEST (e) nv_properties (2) reset (w) nv_table_index (f) reset_required (2) nv_update_completes (w) resp_alloc (f) nv_update_fails (w) resp_arrives (w) nv_update_occurs (w) resp_cancel (f) nv_update_succee
slave (1) touch_byte_spu (f, 2.2) slave_b (1) touch_first (f) sleep (f) touch_next (f) sleep_flags (et,t) touch_read_spu (f, 2.2) __slow touch_reset (f) spi (2.1) touch_reset_spu (f, 2.2) spi_abort (2.1) touch_write_spu (f, 2.2) spi_get_error (2.1) triac (1) static (c) triggeredcount (1) stimer (1) TRUE (e) stretchedtriac (2.2) twostopbits (2.
_bcd2bin _i2c_read0 _bin2bcd _i2c_read8 _bit_input _i2c_read_opt0 _bit_input_ext _i2c_read_opt8 _bit_output_ext _i2c_write _bit_output_hi _i2c_write0 _bit_output_lo1 _i2c_write8 _bit_output_lo2 _i2c_write_opt0 _bitshift_input _i2c_write_opt8 _bitshift_output _i2cs_read0 _bound_mt _i2cs_read8 _bound_nv _i2cs_read_opt0 burst_sequence_output _i2cs_read_opt8 _byte_input _i2cs_write0 _byte_output _i2cs_write8 cp_modifiable_value_file_len_fake _i2cs_write_opt0 cp_readonly_value_fil
232 _io_sci_set_buffer_out _msg_completes _io_scispi_abort _msg_data_blockget _io_scispi_input_ready _msg_data_blockset _io_scispi_output_ready _msg_data_get _io_set_clock _msg_data_set _io_set_clock_x2 _msg_domain_get _io_spi_clock _msg_domain_set _io_spi_init _msg_duplicate_get _io_spi_initram _msg_fails _io_spi_set_buffer _msg_format_get _io_update_occurs _msg_free _ir_input _msg_len_get _leveldetect_input _msg_node_set _magcard_input _msg_priority_set _magt1_input _msg_rcvt
_nv_array_update_succeeds _resp_data_set _nv_poll _resp_free _nv_poll_all _resp_receive _nv_update_completes _resp_send _nv_update_fails _select_input_fn _nv_update_occurs _serial_input _nv_update_request _serial_output _nv_update_request_all _sleep _nv_update_succeeds _timer_expires _offline _timer_expires_any _oneshot_output _totalize_input _online _touch_bit _parallel_input _touch_byte _parallel_input_ready _touch_first _parallel_output _touch_next _parallel_output_ready _t
Index _ __lock keyword, 201 3 32-bit integers. See signed 32-bit integers A A/D converter, 96, 100 a2d.h include file. See include files abs( ) function, 43 definition, syntax and example, 69 absolute value, 69 abstract declarator, syntax, 211 access.h include file.
bypass mode, 114, 118, 124, 155 byte I/O object, 4, 91, 104, 105 byte.h include file. See include files C cancel message function, 113 cast operation, 33 syntax, 221 changeable type network variables. See network variables, changeable types changeable_type keyword, 161 CHAR_BIT, 223 CHAR_MAX, 223 CHAR_MIN, 223 classes of network variables. See network variables, classes clear_status( ) function, 49 definition, syntax and example, 75 clock for I/O objects.
declarator syntax, 210 delay fixed, 79 scalable, 130 delay( ) function, 41, 130 definition, syntax and example, 78 table of formulas for calculating delays, 78 dest_addr field of nv_in_addr_t, 195 device copy protection, 32 interface, xix, 160 model number, 127 power-up, 120 reset, 16, 155 effect on timer/counter I/O objects, 101 scheduler.
fl_sqrt( ) function, 47, 62 fl_sub( ) function, 47, 62 fl_to_ascii( ) function, 47, 66 fl_to_ascii_fmt( ) function, 48, 66 fl_to_s32( ) function, 48, 65 fl_to_slong( ) function, 48, 65 fl_to_ulong( ) function, 48, 65 fl_trunc( ) function, 48, 63 FL_UNDERFLOW, 59 flex_domain field of nv_in_addr_t, 195 float.h include file.
sci_abort( ), 131 sci_get_error( ), 131 service_pin_msg_send( ), 132 service_pin_state( ), 132 set_bit( ), 133 set_eeprom_lock( ), 133 sleep( ), 135 spi_abort( ), 136 spi_get_error( ), 137 strcat( ), 137 strchr( ), 138 strcmp( ), 138 strcpy( ), 139 strlen( ), 139 strncat( ), 140 strncmp( ), 140 strncpy( ), 141 strrchr( ), 142 swap_bytes( ), 142 timers_off( ), 143 touch_bit( ), 143 touch_byte( ), 144 touch_byte_spu( ), 144 touch_first( ), 145 touch_next( ), 146 touch_read_spu( ), 147 touch_reset( ), 147 touc
I/O object type names, 91 I/O object types optional definitions, 97 I/O objects, xx clock value of, 103 declaration, syntax, 214 input_is_new. See input_is_new variable input_value. See input_value variable I/O type names, 97 I/O types.
M magcard I/O object, 92, 94 magtrack1 I/O object, 92, 94 make_long( ) function, 44 definition, syntax and example, 107 manufacturing_only keyword, 172 max( ) function, 44 definition, syntax and example, 107 max_rate_est keyword, 169 max_rate_est option, 177 MB_LEN_MAX, 224 mem.h include file. See include files member lists.
configuration property, 164 connection information, 167 const keyword, 162 controlling propagation of output values, 121 cp keyword, 164 declaring, 161, 209 definition, xix destination address, 195 eeprom keyword, 163 events, 2 nv_update_completes. See nv_update_completes event nv_update_fails. See nv_update_fails event nv_update_occurs. See nv_update_occurs event nv_update_succeeds.
O object_disabled keyword, 172 objects built-in, 198 offchip keyword, 163 off-chip memory, 20 offline event, 86, 114, 118, 120 definition, syntax and example, 15 offline keyword, 167, 172 offline_confirm( ) function, 15, 43 definition, syntax and example, 118 onchip keyword, 163 one_domain pragma, 30 oneshot I/O object, 103, 104 online event, 86, 114, 120 definition, syntax and example, 16 ontime I/O object, 4, 6, 92, 102, 103 optimization pragma, 30 outgoing message, defined, 198 output buffer allocation n
repeating timer, 158 reserved words, 226 reset, 191 determining cause of, 120 reset cause register clearing, 75 reset event, 89, 90, 101, 117, 120 definition, syntax and example, 17 reset task limits on execution time, 16 reset_required keyword, 172 resource files, xix, 28, 171, 180 resp_alloc( ) function definition, syntax and example, 123 resp_arrives event, 194 definition, syntax and example, 17 resp_cancel( ) function definition, syntax and example, 123 resp_free( ) function definition, syntax and examp
set_netvar_count pragma, 34 set_node_sd_string pragma, 34 set_std_prog_id pragma, 35 SFPTs, xix SHRT_MAX, 223 SHRT_MIN, 223 signed 32-bit integers, 52 displaying in debugger, 53 functions, 134 performance, 57 sizeof( ) function, 36 skip_ram_test_except_on_power_up pragma, 35 sleep( ) function, 3, 42, 135 definition, syntax and example, 135 smaller value function, 111 snvt_si_eecode pragma, 35 snvt_si_ramcode pragma, 35 SNVTs, xix, 26, 60, 163 source addresses, 152 nv_in_addr.
alternate clock assignment, 103 I/O input, 101 timer_expires event, 158 definition, syntax and example, 17 unqualified, 17 timers, xx, 136, 158 events timer_expires.
www.echelon.