Echelon Neuron C User Manual

Neuron
®
C Programmer’s Guide
®
0 7 8 - 0 0 0 2 -02H
Echelon, LONWORKS, LONMARK, NodeBuild er, 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.
Neuron Chips and other OEM Products were not designed for use in equipment or systems, which involve danger to human health or safety, or a risk of property damage and Echelon assumes no responsibility or liability for use of the Neuron Chips in such applications.
Parts manufactured by vendors other than Echelon and referenced in this document have been described for illustrative purposes only, and may not have been tested by Echelon. It is the responsibility of the customer to determine the suitability of these parts for each application.
ECHELON MAKES AND YOU RECEIVE NO WARRANTIES OR CONDITIONS, EXPRESS, IMPLIED, STATUTORY OR IN ANY COMMUNICATION WITH YOU, AND ECHELON SP ECIFICALLY DISCLAIMS A N Y IMPLIED WARR A N T Y OF M ER C H ANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
No part of this publication may be reproduced, stored in a retrieval s ystem, or transmitted, in any form or by any means, electronic, mechanical, photocopying, recording, or otherwise, without the prior written permission of Echelon Corporation.
Printed in the United States of America. Copyright © 1990, 2009 Echelon Corporation.
Echelon Corporation
www.echelon.com

Welcome

This guide describes how to write programs using the Neuron® C Version 2.2 language. Neuron C is a programming language based on ANSI C that is designed for Neuron Chips and Smart Transceivers. It includes network communication, I/O, and event-handling extensions to ANSI C, which make it a powerful tool for the development of L programming with Neuron C are explained through the use of specific code examples and diagrams. A general methodology for designing and implementing
ONWORKS application is also presented.
a L
A subset of the Neuron C language is also used to describe the interoperable interface of host-based applications that are designed with the ShortStack® Developer’s Kit, FTXL™ Developer’s Kit, or the interoperable interface is contained within a file called a contains Neuron C declarations and definitions for the device interface. In addition to describing the Neuron C Version 2.2 language, this guide also provides a brief introduction to model file compilation, and points out syntactical differences between compilation for Neuron-hosted devices and compilation for host-based devices that use a model file.
ONWORKS
®
applications. Key concepts in
i
.LON® SmartServer. This
model file
, which
The Neuron C Programmer’s Guide
Outlines a recommended general approach to developing a L
Explains key concepts of programming in Neuron C through the use of

Audience

The
Neuron C Programmer’s Guide
are developing L familiar with the ANSI C programming language, and have some C programming experience.
For a complete description of ANSI C, consult the following references:
—. 1989.
—. 2007.
Harbison, Samuel P. and Guy L. Steele, Jr. 2002.
:
application, and
code fragments and examples.
is intended for application programmers who
ONWORKS applications. Readers of this guide are assumed to be
American National Standard for Information Systems
Programming Language C
NY: American National Standards Institute.
. Standard number X3.159-1989. New York,
International Standard ISO/IEC 9899:1999. Programming
languages – C
Standardization.
Manual
. Geneva, Switzerland: International Organization for
, 5th edition. Upper Saddle River, NJ: Prentice Hall, Inc.
ONWORKS
C: A Reference
Kernighan, Brian W. and Dennis M. Ritchie. 1988.
Language
Plauger, P.J. and Jim Brodie. 1989.
Reference Series
Plauger, P.J. and Jim Brodie. 1992.
Programmer's Reference
Neuron C Programmer’s Guide iii
, 2nd edition. Upper Saddle River, NJ: Prentice Hall, Inc.
Standard C: Programmer’s Quick
. Buffalo, NY: Microsoft Press.
ANSI and ISO Standard C
. Buffalo, NY: Microsoft Press.
The C Programming

Related Documentation

The following manuals are available from the Echelon Web site
www.echelon.com) and provide additional information that can help you develop
( Neuron C applications for L
ONWORKS devices:
Introduction to the LONW
ORKS
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 L
ONWORKS 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
(078­0392-01A). This manual describes the I/O models that are available for Echelon’s Smart Transceivers and Neuron Chips.
LonMaker User's Guide
use the LonMaker control, maintain, and manage a L
LONM
®
ARK
Application Layer Interoperability Guidelines.
(078-0333-01A). This manual describes how to
®
Integration Tool to design, commission, monitor and
ONWORKS network.
This manual describes design guidelines for developing applications for open interoperable L Web site,
Mini FX User’s Guide
ONWORKS devices, and is available from the LONMARK
www.lonmark.org.
(078-0398-01A). This manual describes how to use the Mini FX Evaluation Kit. You can use the Mini FX to develop a prototype or production control system that requires networking, or to evaluate the development of applications for such control networks using
ONWORKS platform.
the L
Neuron C Reference Guide
(078-0140-01F). This manual provides
reference information for writing programs using the Neuron C Version
2.2 programming language.
Neuron Tools Errors Guide
(078-0402-01A). This manual documents and explains the various warning and error messages that can occur for the various Neuron C development tools.
NodeBuilder® FX User’s Guide
how to develop a L
ONWORKS device using the NodeBuilder tool.
All of the Echelon documentation is available in Adobe
(078-0405-01A). This manual describes
®
PDF files, you must have a current version of the Adobe Reader download from Adobe at:
www.adobe.com/products/acrobat/readstep2.html.

Typographic Conventions for Syntax

Table 1 on page v lists the typographic conventions used in this manual for displaying Neuron C syntax.
iv
PDF format. To view the
®
, which you can
Table 1. Typographic Conventions
Typeface or Symbol Used for Example
boldface type keywords
literal characters
italic type
[square brackets] optional fields [
| vertical bar a choice between two
Example: The syntax for declaring a network variable is:
network input | output [
abstract elements
elements
netvar modifier] [class] type [bind-info] identifier
You type the keywords network, input, and output as shown
You replace the abstract elements
identifier
and identifier for the network variable
The declaration must include either input or output, but not both
with the actual modifier, class, type, bind information, and
netvar modifier, class, type, bind-info
network
{
identifier
bind-info
input | output
]
,
The elements
When a particular element or expression includes punctuation, such as quotation marks, parentheses, and semicolons (but not including square brackets and vertical bars), you must type that punctuation as shown.
Code examples appear in the monospace Courier font:
#include <mem.h>
unsigned array1[40], array2[40];
// See if array1 matches array2 if (memcmp(array1, array2, 40) != 0) { // The contents of the two areas do not match }
netvar modifier, class
, and
bind-info
are all optional
Neuron C Programmer’s Guide v
Table of Contents
Welcome.........................................................................................................iii
Audience ........................................................................................................iii
Related Documentation ................................................................................iv
Typographic Conventions for Syntax...........................................................iv
Chapter 1. Overview .......................................................................................... 1
What Is Neuron C?......................................................................................... 2
Comparing Neuron C Version 2 to Version 1 ........................................ 2
Unique Aspects of Neuron C .........................................................................3
Neuron C Integer Constants................................................................... 4
Neuron C Variables ................................................................................. 5
Neuron C Variable Types .................................................................5
Neuron C Storage Classes ................................................................ 6
Variable Initialization ......................................................................7
Neuron C Declarations .....................................................................7
Network Variables, SNVTs, and UNVTs............................................... 8
Configuration Properties......................................................................... 9
Functional Blocks and Functional Profiles.......................................... 10
Data-Driven Compared with Command-Driven Protocols........... 11
Event-Driven Scheduling or Polled Scheduling .................................. 11
Low-Level Messaging ............................................................................11
I/O Devices ............................................................................................. 11
Neuron-Hosted and Host-Based Compilation ............................................ 12
Differences between Neuron C and ANSI C............................................... 13
Chapter 2. Focusing on a Single Device.......................................................... 15
What Happens on a Single Device? ............................................................ 16
The Scheduler............................................................................................... 16
When Clauses ........................................................................................16
When Statement .................................................................................... 17
Types of Events Used in When Clauses............................................... 18
Predefined Events ................................................................................. 18
Event Processing............................................................................. 20
Reset Event ..................................................................................... 21
User-Defined Events .............................................................................22
Scheduling of When Clauses................................................................. 22
Priority When Clauses ..........................................................................23
Interrupts............................................................................................... 24
Function Prototypes ..............................................................................24
Timers ........................................................................................................... 25
Declaring Timers ................................................................................... 25
Examples .........................................................................................26
The timer_expires Event....................................................................... 26
Input/Output ................................................................................................27
I/O Object Types ....................................................................................28
Declaring I/O Objects in Neuron C....................................................... 29
Device Self-Documentation .........................................................................30
Examples ......................................................................................................30
Example 1: Thermostat Interface........................................................ 31
Example 2: Simple Light Dimmer Interface....................................... 33
Example 3: Seven-Segment LED Display Interface........................... 35
Input Clock Frequency and Timer Accuracy.............................................. 36
Neuron C Programmer’s Guide vii
Fixed Timers .......................................................................................... 36
Scaled Timers and I/O Objects ............................................................. 37
Calculating Accuracy for Software Timers .......................................... 37
Accuracy of Millisecond Timers ..................................................... 37
Accuracy of Second Timers............................................................. 40
Delay Functions..................................................................................... 40
EEPROM Write Timer .......................................................................... 41
Chapter 3. How Devices Communicate Using Network Variables ................ 43
Major Topics ................................................................................................. 44
Overview ....................................................................................................... 45
Behavior of Writer and Reader Devices ............................................... 46
When Updates Occur............................................................................. 47
Declaring Network Variables ...................................................................... 47
Examples of Network Variable Declarations....................................... 48
Connecting Network Variables ................................................................... 49
Use of the is_bound( ) Function ............................................................ 50
Network Variable Events ............................................................................51
The nv_update_occurs Event ................................................................ 51
The nv_update_succeeds and nv_update_fails Events ....................... 52
The nv_update_completes Event .......................................................... 53
Synchronous Network Variables................................................................. 53
Declaring Synchronous Network Variables......................................... 54
Synchronous vs. Nonsynchronous Network Variables........................ 54
Updating Synchronous Network Variables .........................................54
Preemption Mode ............................................................................ 55
Processing Completion Events for Network Variables.............................. 55
Partial Completion Event Testing........................................................ 55
Comprehensive Completion Event Testing ......................................... 55
Tradeoffs................................................................................................. 56
Polling Network Variables .......................................................................... 56
Declaring an Input Network Variable as Polled .................................58
Declaring an Output Network Variable as Polled............................... 58
Explicit Propagation of Network Variables................................................ 60
Initial Value Updates for Input Network Variables.................................. 62
Monitoring Network Variables.................................................................... 65
Authentication.............................................................................................. 66
Setting Up Devices to Use Authentication .......................................... 66
Declaring Authenticated Variables and Messages ....................... 67
Specifying the Authentication Key ................................................ 67
How Authentication Works................................................................... 67
Changeable-Type Network Variables ......................................................... 68
Processing Changes to a SCPTnvType CP .......................................... 71
Validating a Type Change .............................................................. 72
Processing a Type Change.............................................................. 73
Processing a Size Change ...............................................................74
Rejecting a Type Change ................................................................75
Changeable-Type Example ...................................................................75
Chapter 4. Using CPs to Configure Device Behavior ..................................... 83
Overview ....................................................................................................... 84
Declaring Configuration Properties............................................................ 84
Declaration of Configuration Network Variables................................ 85
Declaring Configuration Properties within Files ................................ 86
viii
Instantiation of Configuration Properties .................................................. 88
Device Property Lists ............................................................................ 89
Network Variable Property Lists ......................................................... 90
Accessing Property Values from a Program............................................... 91
Advanced Configuration Property Features .............................................. 92
Configuration Properties Applying to Arrays...................................... 92
Initialization of Configuration Properties at Instantiation ................ 95
Sharing of Configuration Properties .................................................... 96
Configuration Property Sharing Rules ................................................97
Type-Inheriting Configuration Properties ........................................... 98
Type-Inheriting CPs for NVs of Changeable Type........................ 99
Chapter 5. Using Functional Blocks to Implement a Device Interface.........101
Overview ..................................................................................................... 102
Functional Block Declarations ..................................................................104
Functional Block Property Lists......................................................... 107
Shared Functional Block Properties .................................................. 108
Scope Rules................................................................................................. 109
Accessing Members and Properties of an FB from a Program................ 110
Accessing Members and Properties of an FB from a Network Tool .......112
The Director Function................................................................................ 113
Sharing of Configuration Properties......................................................... 115
Chapter 6. How Devices Communicate Using Application Messages...........117
Introduction to Application Messages ......................................................118
Layers of Neuron Software........................................................................ 119
Implicit Messages: Network Variables .................................................... 119
Application Messages................................................................................. 120
Constructing a Message............................................................................. 120
The msg_out Object Definition ........................................................... 121
Message Tags ................................................................................122
Message Codes .............................................................................. 123
Block Transfers of Data ...................................................................... 124
Sending a Message..................................................................................... 125
Receiving a Message ..................................................................................126
The msg_arrives Event ....................................................................... 126
The msg_receive( ) Function ............................................................... 127
Format of an Incoming Message......................................................... 127
Importance of a Default When Clause ............................................... 128
Application Message Examples................................................................. 129
Lamp Program ..................................................................................... 129
Switch Program ................................................................................... 129
Connecting Message Tags ................................................................... 130
Explicit Addressing.................................................................................... 130
Sending a Message with the Acknowledged Service ............................... 131
Message Completion Events ...............................................................131
Processing Completion Events for Messages ..............................133
Preemption Mode and Messages............................................................... 134
Asynchronous and Direct Event Processing............................................. 135
Using the Request/Response Mechanism ................................................. 136
Constructing a Response.....................................................................137
Sending a Response............................................................................. 138
Receiving a Response ..........................................................................138
The resp_arrives Event................................................................. 138
Neuron C Programmer’s Guide ix
The resp_receive( ) Function ........................................................ 139
Format of a Response.................................................................... 139
Request/Response Examples............................................................... 140
Comparison of resp_arrives and msg_succeeds ................................. 141
Idempotent Versus Non-Idempotent Requests.................................. 141
Application Buffers ....................................................................................142
Allocating Application Buffers............................................................ 143
Chapter 7. Additional Features......................................................................145
The Scheduler............................................................................................. 146
Scheduler Reset Mechanism ..................................................................... 146
Scheduler Example..............................................................................148
Bypass Mode............................................................................................... 149
The post_events( ) Function................................................................ 149
Watchdog Timer ......................................................................................... 150
Additional Predefined Events ...................................................................151
Going Offline in Bypass Mode ............................................................152
Wink Event ..........................................................................................152
Interrupts ...................................................................................................153
Interrupt Sources ................................................................................ 153
I/O Interrupts ................................................................................ 154
Timer/Counter Interrupts ............................................................ 154
Periodic System Timer Interrupts ............................................... 154
Defining an Interrupt Task ................................................................ 155
Defining an I/O Interrupt Task.................................................... 155
Defining a Timer/Counter Interrupt Task ..................................156
Defining a System Timer Interrupt Task.................................... 158
Controlling Interrupts.........................................................................159
Sharing Data with an Interrupt Task................................................ 161
Interrupt Latency ................................................................................162
Debugging Interrupt Tasks................................................................. 164
Restrictions for Using Interrupts ....................................................... 165
Sleep Mode.................................................................................................. 165
Flushing the Neuron Chip or Smart Transceiver ............................. 166
The flush( ) and flush_cancel( ) Functions ..................................166
flush_completes Event .................................................................. 166
Putting the Device to Sleep................................................................. 166
Forced Sleep......................................................................................... 168
Error Handling........................................................................................... 168
Resetting the Device............................................................................ 169
Restarting the Application.................................................................. 169
Taking an Application Offline ............................................................170
Disabling a Functional Block.............................................................. 170
Changing Functional Block Status..................................................... 171
Logging Application Errors.................................................................171
System Errors ......................................................................................171
Access to Device Status and Statistics .....................................................172
Chapter 8. Memory Management...................................................................173
Memory Use................................................................................................ 174
RAM Use .............................................................................................. 174
EEPROM Use ......................................................................................174
Using Neuron Chip Memory .....................................................................176
Chips with Off-Chip Memory.............................................................. 176
x
Chips without Off-Chip Memory ........................................................ 177
Memory Regions ..................................................................................177
Memory Areas...................................................................................... 178
Default Memory Usage ....................................................................... 180
Controlling Non-Default Memory Usage ........................................... 181
eeprom Keyword (for Functions and Data Declarations) ........... 181
far Keyword (for Data Declarations) ........................................... 182
offchip Keyword (for Functions and Data Declarations) ............183
onchip Keyword (for Functions and Data Declarations) ............183
ram Keyword (for Functions) .......................................................183
uninit Keyword (for Data Declarations) ......................................184
Compiler Directives ............................................................................. 184
When the Program Is Relinked ..........................................................184
Use of Flash Memory........................................................................... 184
Use of Flash Memory for Series 3100 Chips ............................... 185
Use of Flash Memory for Series 5000 Chips ............................... 186
The eeprom_memcpy( ) Function .......................................................187
Reallocating On-Chip EEPROM ............................................................... 188
Address Table ......................................................................................188
Alias Table ...........................................................................................189
Domain Table....................................................................................... 190
Allocating Buffers ...................................................................................... 190
Buffer Size............................................................................................ 191
Application Buffer Size................................................................. 191
Network Buffer Size...................................................................... 192
Errors............................................................................................. 192
Buffer Counts.......................................................................................192
Compiler Directives for Buffer Allocation.......................................... 193
Outgoing Application Buffers....................................................... 194
Outgoing Network Buffers ...........................................................194
Incoming Network Buffers ...........................................................195
Incoming Application Buffers....................................................... 195
Number of Receive Transactions ................................................. 195
Usage Tip for Memory-Mapped I/O ..........................................................198
What to Try When a Program Does Not Fit on a Neuron Chip .............. 199
Reduce the Size of the Configuration Property Template File ......... 200
Reduce the Number of Address Table Entries .................................. 200
Remove Self-Identification Data if Not Needed ................................ 200
Remove Network Variable Names if Not Needed ............................. 201
Declare Constant Data Properly ........................................................ 201
Use Efficient Constant Values............................................................ 202
Take Advantage of Neuron Firmware Default Initialization ...........202
Use Neuron C Utility Functions Effectively ...................................... 202
Be Aware of Library Usage................................................................. 203
Use More Efficient Data Types........................................................... 203
Observe Declaration Order ................................................................. 204
Use the Optional fastaccess Feature.................................................. 205
Eliminate Common Sub-Expressions................................................. 205
Use Function Calls Liberally ..............................................................206
Use the Alternate Initialization Sequence......................................... 207
Use C Operators Effectively................................................................ 207
Use Neuron C Extensions Effectively ................................................208
Using the Link Map ................................................................................... 209
Neuron C Programmer’s Guide xi
Appendix A.
Neuron C Tools Stand-Alone Use..............................................211
Stand-Alone Tools ...................................................................................... 212
Common Stand-Alone Tool Use .......................................................... 212
Common Syntax ............................................................................212
Common Set of Basic Commands ................................................ 214
Command Switches for Stand-alone Tools ............................................... 215
Neuron C Compiler.............................................................................. 215
Neuron Assembler ............................................................................... 216
Neuron Linker .....................................................................................216
Neuron Exporter.................................................................................. 217
Neuron Librarian................................................................................. 219
Appendix B. Neuron C Function Libraries ....................................................221
Definitions ..................................................................................................222
NodeBuilder Support for Libraries ........................................................... 222
Tradeoffs, Advantages, and Disadvantages ............................................. 223
Advantages of a Library...................................................................... 223
Disadvantages of a Library................................................................. 223
Library Construction Using the Librarian............................................... 224
Performing Neuron C Functions from Libraries...................................... 225
Appendix C. Neuron C Custom System Images ............................................227
Definitions ..................................................................................................228
NodeBuilder Use of Custom System Images............................................ 229
Tradeoffs, Advantages, and Disadvantages ............................................. 230
Advantages of a Custom System Image............................................. 230
Disadvantages of a Custom System Image........................................ 230
Constructing a Custom System Image ..................................................... 231
Providing a Large RAM Space ..................................................................234
Performing Neuron C Functions ............................................................... 234
Appendix D. Neuron C Language Implementation Characteristics .............237
Neuron C Language Implementation Characteristics ............................ 238
Translation (J.3.1) ............................................................................... 238
Environment (J.3.2)............................................................................. 239
Identifiers (J.3.3) .................................................................................239
Identifiers (F.3.3 of ANSI C Standard)........................................ 239
Characters (J.3.4) ................................................................................240
Characters (F.3.4 of ANSI C Standard)....................................... 240
Integers (J.3.5)..................................................................................... 241
Integers (F.3.5 of ANSI C Standard) ...........................................241
Floating Point (J.3.6)........................................................................... 242
Arrays and Pointers (J.3.7) ................................................................. 242
Arrays and Pointers (F.3.7 of ANSI C Standard) .......................242
Hints (J.3.8) .........................................................................................243
Structures, Unions, Enumerations, and Bit-Fields (J.3.9) ............... 243
Structures, Unions, Enumerations, and Bit-Fields (F.3.9) ........ 243
Qualifiers (J.3.10) ................................................................................244
Declarators (F.3.11 of ANSI C Standard)....................................244
Statements (F.3.12 of ANSI C Standard) .................................... 244
Preprocessing Directives (J.3.11) ....................................................... 244
Library Functions (J.3.12) ..................................................................245
Index................................................................................................................247
xii
1

Overview

This chapter introduces the Neuron C Version 2.2 programming language. It describes the basic aspects of the language and provides an overview to using the L platform and the Neuron C programming language to construct interoperable devices and systems. The chapter also introduces key concepts of Neuron C such as event­driven scheduling, network variables, configuration properties, and functional blocks (which are implementations of functional profiles).
A secondary purpose of this chapter is to introduce fundamental material on Neuron C concerning Neuron C types, storage classes, data objects, and how the Neuron C language compares to the ANSI C language.
ONWORKS
Neuron C Programmer’s Guide 1

What Is Neuron C?

Neuron C Version 2 is a programming language based on ANSI C that is designed for Neuron Chips and Smart Transceivers. It includes network communication, I/O, and event-handling extensions to ANSI C, which make it a powerful tool for the development of L few of these new
1
features:
ONWORKS applications. Following are a
A new network communication model, based on
network variables
like or disparate devices.
A new network configuration model, based on functional blocks and
configuration properties
configuration tools.
A new type model based on standard and user
the market for interoperable devices by simplifying integration of devices from multiple manufacturers.
An extensive built-in set of
capabilities of Neuron Chips and Smart Transceivers.
Powerful
statements, provide easy handling of network, I/O, and timer events.
A high-level programming model that supports application-specific
interrupt handlers and synchronization tools.
Neuron C provides a rich set of language extensions to ANSI C tailored to the unique requirements of distributed control applications. Experienced C programmers will find Neuron C a natural extension to the familiar ANSI C paradigm. Neuron C offers built-in type checking and allows the programmer to generate highly efficient code for distributed L
Neuron C omits ANSI C features that are not required by the standard for free­standing implementations. For example, certain standard C libraries are not part of Neuron C. Other differences between Neuron C and ANSI C are described in
event-driven programming
Differences between Neuron C and ANSI C
, that simplifies and promotes data sharing between
, that facilitates interoperable network
I/O models
that support the powerful I/O
extensions, based on new when
ONWORKS applications.
functional blocks
resource files
on page 13.
that expands
and

Comparing Neuron C Version 2 to Version 1

Neuron C version 2 includes major enhancements to the language that greatly simplify the development of devices that use functional blocks and configuration properties. Prior to version 2, developers had to manually construct self­documentation strings for each device, network variable, and configuration property. This process could be both time-consuming and error-prone. With Neuron C version 2, the Neuron C compiler can automatically create and manage these strings.
If any of the following Neuron C keywords appear in an application, the Neuron C compiler automatically generates and manages the self-documentation strings:
fblock
1
"New" means relative to the ANSI Standard C language.
2 Overview
fb_properties
nv_properties
device_properties
cp
cp_family
You can still manually create the self-documentation strings, if necessary, by avoiding the use of any of these keywords and by declaring the self­documentation strings using the Neuron C version 1 syntax. Using this syntax could be useful for migrating older applications (created with the NodeBuilder 1.5 or LonBuilder tools) to the NodeBuilder FX Development Tool. Applications that do not use these keywords still get the benefit of access to resource definitions contained within resource files.

Unique Aspects of Neuron C

Neuron C implements all of 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.
ONWORKS applications. Network variables are data constructs that have
L language and system firmware support to provide something that looks like a variable in a C program, but has additional properties for propagating across a
ONWORKS network to or from one or more other devices on that network. The
L network variables make up part of the
Network variables
device interface
are fundamental to Neuron C and
for a LONWORKS device.
Configuration properties
the device interface. Configuration properties allow the device’s behavior to be customized using a network tool such as the LonMaker tool or a customized plug­in created for the device.
Neuron C also provides a way to organize the network variables and configuration properties in the device into provides 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
Each network variable, configuration property, and functional block is defined by a type definition contained in a configuration properties are defined by
configuration property types profiles
Network variables, configuration properties, and functional blocks in Neuron C can use promotes the interconnection of disparate devices on a L configuration properties, the standard types are called standard configuration property types (SCPTs; pronounced standard types are called standard network variable types (SNVTs; pronounced
snivets
profiles. If you cannot find standard types or profiles that meet your requirements, Neuron C also provides full support for user network variable types (UNVTs; pronounced pronounced
(which are also called
standardized, interoperable types
). For functional blocks, the standard types are called standard functional
u-keep-its
are Neuron C data constructs that are another part of
functional blocks
functional block members
resource file
. Network variables and
.
network variable types
(CPTs). Functional blocks are defined by
functional profile templates
. The use of standardized data types
skip-its
u-nivets
), and user functional profiles.
), user configuration property types (UCPTs;
). For network variables, the
, each of which
(NVTs) and
functional
).
ONWORKS network. For
Neuron C Programmer’s Guide 3
Neuron C is designed to execute in the environment provided by the Neuron system firmware. This firmware provides an part of the Neuron C language’s run-time environment.
event-driven scheduling system
as
Neuron C also provides a lower-level language in addition to the network variable model, but the network variable model has the advantage of being a standardized method of information interchange, whereas the messaging service is not standardized (with the exception of its usage by the L 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 manipulated like variables. When a timer expires, the system firmware automatically manages the timer events and notifies the program of those events.
Neuron C provides many built-in
objects
Chip or Smart Transceiver I/O hardware. Each I/O model fits into the event­driven programming model. A function-call interface is provided to interact with each I/O object.
Some I/O models, all I/O pins, and a dedicated, high-resolution system timer, can also be used to trigger asynchronous interrupts.
The rest of this chapter discusses these various aspects of Neuron C in more detail, and the remaining chapters cover these aspects in greater detail, accompanied by many examples.
. These I/O models are standardized I/O “device drivers” for the Neuron
ONWORKS file transfer protocol, LW-FTP). The use
messaging service
timer
. Timers can be declared and
I/O models
, which are instantiated as
integrated into the
I/O

Neuron C Integer Constants

Negative constants are treated as a unary minus operation on a positive constant, for example, -128 is a signed long, not a signed short. Likewise, -32768 is an unsigned long, not a signed long. To construct a signed short value of -128, you must use a cast:
((signed short)(-128))
To construct a signed long value of –32768, you must also use a cast:
((signed long)(-32768))
Decimal integer constants have the following default types:
0 .. 127 signed short 128 .. 32767 signed long 32768 .. 65535 unsigned long
The default type can be modified with the u, U, l, and L suffixes. For example:
0L signed long 127U unsigned short 127UL unsigned long 256U unsigned long
Hexadecimal constants have the following default types, which can also be modified as described above with the u, U, l, and L suffixes:
4 Overview
0x0 .. 0x7F signed short 0x80 .. 0xFF unsigned short 0x100 .. 0x7FFF signed long 0x8000 .. 0xFFFF unsigned long
Octal constants have the following default types, which can also be modified as described above with the u, U, l, and L suffixes:
0 .. 0177 signed short 0200 .. 0377 unsigned short 0400 .. 077777 signed long 0100000 .. 0177777 unsigned long
Binary constants have the following default types, which can also be modified as described above with the u, U, l, and L suffixes:
0b0 .. 0b01111111 signed short 0b10000000 .. 0b11111111 unsigned short 0b0000000100000000 .. 0b0111111111111111 signed long 0b1000000000000000 .. 0b1111111111111111 unsigned long

Neuron C Variables

The following sections briefly discuss various aspects of variable declarations. Data types affect what sort of data the variable represents. Storage classes affect where the variable is stored, whether it can be modified (and if so, how often), and whether there are any device interface aspects to modifying the data.
Neuron C Variable Types
Neuron C supports the following C variable types. The keywords shown in square brackets are optional; if omitted, they are assumed by the Neuron C language, per the rules of the ANSI C standard.
[signed] long [int] 16-bit quantity
unsigned long [int] 16-bit quantity
signed char 8-bit quantity
[unsigned] char 8-bit quantity
[signed] [short] [int] 8-bit quantity
unsigned [short] [int] 8-bit quantity
enum 8-bit quantity (int type)
Neuron C provides some predefined enum types. One example is shown below:
typedef enum {FALSE, TRUE} boolean;
Neuron C also provides predefined objects that, in many ways, provide the look and feel of an ANSI C language variable. These objects include Neuron C timer and I/O objects. See the see the timer objects.
Timers
chapter in the
I/O Model Reference
Neuron C Reference Guide
for more details on I/O objects, and
for more details on
The extended arithmetic library also defines float_type and s32_type for IEEE 754 and signed 32-bit integer data respectively. These types are discussed in great detail in the
Neuron C Programmer’s Guide 5
Functions
chapter of the
Neuron C Reference Guide
.
Neuron C Storage Classes
If no class is specified and the declaration is at file scope, the data or function is global. a function or a task. Global data (including all data declared with the static keyword) is present throughout the entire execution of the program, starting from the point where the symbol was declared. Declarations using extern references can be used to provide forward references to variables, and function prototypes must be declared to provide forward references to functions.
Upon power-up or reset of a Neuron Chip or Smart Transceiver, the global data in RAM is initialized to its initial-value expression, if present, otherwise to zero (variables declared with the eeprom or config class, as well as configuration properties declared with the config_prop or cp_family keywords, are only initialized when the application image is first loaded).
Neuron C supports the following ANSI C storage classes and type qualifiers:
auto Declares a variable of local scope. Typically, this would be within a
const Declares a value that cannot be modified by the application program.
File scope
is that part of a Neuron C program that is not contained within
function body. This is the default storage class within a local scope and the keyword is normally not specified. Variables of auto scope that are not also static are not initialized upon entry to the local scope. The value of the variable is not preserved once program execution leaves the scope.
Affects self-documentation (SD) data generated by the Neuron C compiler when used in conjunction with the declaration of CP families or configuration network variables.
extern Declares a data item or function that is defined in another module, in
a library, or in the system image.
not
static Declares a data item or function which is
other modules at link time. Furthermore, if the data item is local to a function or to a when task, the data value is to be preserved between invocations, and is not made available to other functions at compile time.
In addition to the ANSI C storage classes, Neuron C provides the following classes and class modifiers:
config Can be combined only with an input network variable declaration. A
config network variable is used for application configuration. It is equivalent to const eeprom. Such a network variable is initialized only when the application image is first loaded. The config class is obsolete and is included only for legacy applications. The Neuron C compiler does not generate self-documentation data for config-class network variables. New applications should use the configuration network variable syntax described Chapter
Properties to Configure Device Behavior
network Begins a network variable declaration. See Chapter
Communicate Using Network Variables
system Used in Neuron C solely to access the Neuron firmware function
library. Do not use this keyword for data or function declarations.
to be made available to
4,
Using Configuration
, on page 83.
3,
How Devices
, on page 43, for more details.
6 Overview
uninit When combined with the eeprom keyword (see below), specifies that
the EEPROM variable is not initialized or altered on program load or reload over the network.
The following Neuron C keywords allow you to direct portions of application code and data to specific memory sections:
eeprom
far
offchip (only for Neuron Chips and Smart Transceivers
with external memory)
onchip
ram (only for Neuron Chips and Smart Transceivers
with external memory)
These keywords are particularly useful on the Neuron 3150 Chip and 3150 Smart Transceivers, because a majority of the address space for these parts is mapped off chip. See description of memory usage and the use of these keywords.
Using Neuron Chip Memory
on page 176 for a more detailed
Variable Initialization
Initialization of variables occurs at different times for different classes. The
must
const variables, except for network variables, of const variables occurs when the application image is first loaded into the Neuron Chip or Smart Transceiver. The const ram variables are placed in off­chip RAM that must be non-volatile. Therefore, the eeprom and config variables are also initialized at load time, except when the uninit class modifier is included in these variable definitions.
Automatic variables cannot be declared const because Neuron C does not implement initializers in declarations of automatic variables.
Global RAM variables are initialized at reset (that is, when the device is reset or powered up). By default, all global RAM variables (including static variables) are initialized to zero at this time. Initialization to zero costs no extra code space, as it is a firmware feature.
Initialization of I/O objects, input network variables (except for eeprom, config, config_prop, or const network variables), and timers also occurs at reset. Zero is the default initial value for network variables and timers.
Local variables (except static ones) are not automatically initialized, nor are their values preserved when the program execution leaves the local scope.
be initialized. Initialization
Neuron C Declarations
Both ANSI C and Neuron C support the declarations listed in Table 2.
Table 2. ANSI C and Neuron C Declarations
Declaration Example
Simple data items int a, b, c;
Neuron C Programmer’s Guide 7
Declaration Example
Data types typedef unsigned long ULONG;
Enumerations enum hue {RED, GREEN, BLUE};
Pointers char *p;
Functions int f(int a, int b);
Arrays int a[4];
Structures and unions struct s {
int field1; unsigned field2 : 3; unsigned field3 : 4; };
In addition, Neuron C Version 2 supports the declarations listed in Table 3.
Table 3. Neuron C Version 2 Declarations
Declaration Example
I/O Objects IO_0 output oneshot relay_trigger;
(See Chapter 2)
Timers mtimer led_on_timer;
(See Chapter 2)
Network Variables network input SNVT_temp temperature;
(See Chapter 3)
Configuration Properties
Functional Blocks fblock SFPTnodeObject { … } myNode;
Message Tags msg_tag command;
cp_family SCPTdefOutput defaultOut;
(See Chapter 4)
(See Chapter 5)
(See Chapter 6)

Network Variables, SNVTs, and UNVTs

A
network variable
variables on one or more additional devices. A device’s network variables define its inputs and outputs from a network point of view and allow the sharing of data in a distributed application. Whenever a program writes into one of its network variables (with the exception of output network variables that are
is an object on one device that can be
connected
to network
output
8 Overview
declared with the polled modifier), the new value of the network variable is
propagated
connected to that output network variable. If the output network variable is not currently a member of any network variable connection, no transaction and no error occurs.
across the network to all devices with
input
network variables
Although the propagation of network variables occurs through L messages, these messages are sent implicitly. The application program does not require any explicit instructions for sending, receiving, managing, retrying, authenticating, or acknowledging network variable updates. A Neuron C application provides the most recent value by writing into an output network variable, and it obtains the most recent data from the network by reading an input network variable.
Example:
network input SNVT_temp nviTemperature;
network output SNVT_temp nvoTemperature;
void f(void)
{
nvoTemperature = 2 * nviTemperature;
}
Network variables greatly simplify the process of developing and installing distributed systems because devices can be defined individually, then connected and reconnected easily into many new L variables are discussed in detail in Chapter
Network Variables
Network variables promote interoperability between devices by providing a well­defined interface that devices use to communicate. Interoperability simplifies installation of devices into different types of networks by keeping the network configuration independent of the device’s application. A device can be installed in a network and logically connected to other devices in the network as long as the data types (for example, SNVT_switch or SNVT_temp_p) match. To further promote interoperability, the L profiles that define standard functional interfaces for devices, and standard network variable types (SNVTs) that define standard data encoding, scaling, and units, such as degrees C, volts, or meters. There are standard functional profiles for a variety of functions and industries. There are SNVT definitions for essentially every physical quantity, and other more abstract definitions tailored for certain industries and common applications.
, on page 43, and also in the
ONWORKS platform provides standard functional
ONWORKS applications. Network
3,
How Devices Communicate Using
Neuron C Reference Guide
ONWORKS
.
You can also create your own user functional profiles and user network variable types (UNVTs). You can define resource files for your custom types and profiles to enable your devices to be used with devices from other manufacturers. The NodeBuilder Resource Editor included with the NodeBuilder tool provides a simple interface for viewing existing resources and defining your own resources.

Configuration Properties

A configuration property is a data item that, like a network variable, is part of the device interface for a device. A configuration property can be modified by a network tool. Configuration properties facilitate interoperable installation and configuration tools by providing a standardized network interface for device
Neuron C Programmer’s Guide 9
configuration data. Like network variables, configuration properties also provide a well-defined interface. Each configuration property type is defined in a resource file that specifies the data encoding, scaling, units, default value, invalid value, range, and behavior for configuration properties based on the type. A rich variety of standard configuration property types (SCPTs) are available. You can also create your own user configuration property types (UCPTs) that are defined in resource files that you create with the NodeBuilder Resource Editor.

Functional Blocks and Functional Profiles

The
device interface
network variables, and configuration properties. A 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
for a LONWORKS device consists of its functional blocks,
functional block
.
is a collection
Functional blocks are defined by to describe common units of functional behavior. Each functional profile defines mandatory and optional network variables and mandatory and optional configuration properties. Each functional block implements an instance of a functional profile. A functional block must implement all of the mandatory network variables and configuration properties that are defined by the functional profile, and can also implement any of the optional network variables and configuration properties that are defined by the functional profile. In addition, a functional block can implement network variables and configuration properties that are not defined by the functional profile – these are called
specific
Functional profiles are defined in profiles or you can define your own functional profiles in your own resource files by using the NodeBuilder Resource Editor. A functional profile defined in a resource file is also called a
L L requirements as specified by the
Guidelines
network variables and configuration properties.
ONMARK International provides a procedure for developers to certify devices. ONMARK interoperable devices conform to all LonTalk
, and conform to all aspects of application design, as described in the
LonMark Application Layer Interoperability Guidelines
Contact L becoming a member and certifying your devices.
You can automatically embed data within your device that identifies its device interface to network tools that are used to install the device. This data is called
self-identification
compiler generates this data based on the functional blocks, network variables, and configuration properties that you declare, as well as the resource files that you provide. You can add your own documentation to the SD data to further document your device and its interface.
ONMARK International at www.lonmark.org for more details about
(SI) data and
functional profiles
resource files
functional profile template
. A functional profile is used
. You can use standard functional
(FPT).
®
protocol layer 1 – 6
LonMark Layer 1 – 6 Interoperability
.
self-documentation
(SD) data. The Neuron C
implementation-
You can include network variable names in the SD data using the #pragma enable_sd_nv_names directive. You can also include a rate estimate in tenths-of­messages/second and a maximum rate estimate in tenths-of-messages/second in the SD data for each network variable. The rate estimate and maximum rate estimate values are provided through the bind_info feature. (See the discussion
10 Overview
of this feature in Chapter
Variables
An application image for a device created by the Neuron C compiler contains SD information unless the #pragma disable_snvt_si directive is used. (See the
Compiler Directives
information.)
, on page 43, and also in the
3,
How Devices Communicate Using Network
chapter of the
Neuron C Reference Guide
Neuron C Reference Guide
.)
for more
Data-Driven Compared with Command­Driven Protocols
Network variables are used to communicate data and state information between devices. This data-driven model provides a different communication model than in command-based systems. In command-based messaging systems, designers are faced with having a large number of commands, specific to each application, that must be managed, updated, and maintained. Each device has to have knowledge of every command. This leads to ever-growing command tables and application code.
With network variables, the command or action portion of a message is not in the message. Instead, with network variables, this information is in the application program, and each application program only needs have the knowledge required to perform its function. A network integrator can add new types of devices at any time, and connect them to existing devices in the network to perform new applications not envisioned by the original designers of the devices.

Event-Driven Scheduling or Polled Scheduling

Although the Neuron C language is principally designed to make event-driven scheduling natural and easy, Neuron C also allows you to construct polled applications that implement a centralized control application. Chapter
Devices Communicate Using Network Variables
information on polling.
, on page 43, provides further

Low-Level Messaging

In addition to the functional block and network variable communication model, Neuron C also supports application messages. You can use application messages – in place of or in conjunction with the network variables approach – to implement proprietary interfaces to your devices. They are also used for the
ONWORKS file transfer protocol. Application messages are described in Chapter
L 6,
How Devices Communicate Using Application Messages
, on page 117.

I/O Devices

A Neuron Chip or Smart Transceiver can be connected to one or more physical I/O devices. Examples of simple I/O devices include temperature and position sensors, valves, switches, and LED displays. Neuron Chips and Smart Transceivers can also be connected to other microprocessors. The Neuron firmware implements numerous devices for a Neuron C application. I/O models are discussed in detail in Chapter 2,
Focusing on a Single Device
I/O models
, on page 15, and in the
that manage the interface to these
I/O Model Reference
3,
How
.
Neuron C Programmer’s Guide 11

Neuron-Hosted and Host-Based Compilation

Compilation for Neuron-hosted devices, that is, devices based on a Neuron Chip or Smart Transceiver as the main processor, use Neuron C to define all aspects of the device’s application:
The application’s interoperable interface, including its set of network
variables, configuration properties, and functional blocks, and the self­identification and self-documentation data
Device configuration information, such as buffer configuration
Application code including, when tasks, interrupt tasks, I/O device
declarations, and functions
Compilation for host-based devices, that is, devices that implement the application on a different processor (the Neuron C language to model the device’s interoperable interface. For these devices, the Neuron C source code acts as a model for the finished application, and the primary source file is called the devices uses Neuron C to define only the following aspect of the device’s application:
The application’s interoperable interface, including its set of network
variables, configuration properties, and functional blocks, and the self­identification and self-documentation data
The ShortStack Developer’s Kit, FTXL Developer’s Kit, and the SmartServer all use model files. See the related product documentation for information about compiling a model file, and about implementing the device’s application (including the device configuration information and application code).
host processor
model file
), often use a subset of the
. Compilation for host-based
i
.LON
Syntactically, a Neuron C application and a model file differ in the following ways:
Declaration of the interoperable interface is largely identical, however, a
few exceptions exist which are identified throughout this book, as necessary.
Device configuration is typically adjusted using a product-specific tool,
such as the LonTalk Interface Developer utility, and is not specified in a model file. When encountered within a model file, device configuration constructs can trigger a compiler error or warning.
Application code, including I/O device declarations, application timer
declarations and any form of executable code, is ignored in a model file. Such code results in a warning for model file compilation, and the code has no effect.
You can use conditional compilation to prepare the same source code for use as Neuron C application and a model file. The _MODEL_FILE preprocessor symbol is automatically predefined for model file compilation, and is not predefined for application compilation. See the about predefined preprocessor symbols.
Neuron C Reference Guide
for more information
12 Overview

Differences between Neuron C and ANSI C

Neuron C adheres closely to the ANSI C language standard; however, Neuron C is not a "conforming implementation" of Standard C, as defined by the American National Standards Institute committee X3-J11.
The following list outlines the major differences between Neuron C and ANSI C:
Neuron C does not support floating-point computation with C syntax or
operators. However, a floating-point library is provided to allow use of floating-point data that conforms to the IEEE 754 standard.
ANSI C defines a short int as 16 bits or more and a long int as 32 bits or
more. Neuron C defines a short int as 8 bits and a long int as 16 bits. In Neuron C, int defaults to a short int. A 32-bit signed integer library is available to allow use of 32-bit quantities.
Neuron C does not support the register or volatile classes. These storage
classes can be specified but are ignored.
Neuron C does not implement initializers in declarations of automatic
variables.
Neuron C does not support structures or unions as procedure parameters
or as function return values.
Neuron C does not support declaration of bitfields as members of unions.
However, an equivalent declaration can be accomplished by defining a structure as a member of the union, where the structure contains the bitfields.
Network variable structures cannot contain pointers. Configuration
property structures also cannot contain pointers.
Pointers to timers, to message tags, or to I/O objects are not supported.
Pointers to network variables, configuration properties, and EEPROM
variables are treated as pointers to constants (that is, the contents of the variable referenced by the pointer can be read, but not modified). Under special circumstances, and with certain restrictions, the pointers can be used to modify the memory. See the discussion of the eeprom_memcpy( )
8,
function in Chapter
Functions
discussion of the #pragma relaxed_casting_on compiler directive in the
chapter of the
Compiler Directives
Macro arguments are not rescanned until after the macro is expanded,
thus the macro operators # and ## might not yield results as defined in the ANSI C standard when they occur in nested macro expansions.
Names of network variables and message tags are limited to 16
characters. Names of functional blocks are limited to 16 characters unless they are declared using the external_name feature, in which case the external name is limited to 16 characters, and the internal name of the functional block is limited to 64 characters.
Memory Management
Neuron C Reference Guide
chapter of the
Neuron C Reference Guide
, on page 173, and also in the
. Also refer to the
.
A few ANSI C library functions are included in Neuron C, such as
memcpy( ) and memset( ). A string and byte operation library is provided to allow use of a subset of the ANSI C functions defined in the <string.h>
Neuron C Programmer’s Guide 13
include file. Other ANSI C library functions, such as file I/O and storage allocation functions, are not included in Neuron C. Consult the
Reference Guide
The Neuron C implementation includes three ANSI include files:
<stddef.h>, <stdlib.h>, and <limits.h>.
Neuron C requires use of the function prototype feature whenever a call
to the function precedes the function definition (see Chapter
on a Single Device
Neuron C does not support the use of the ellipsis (...) in function
prototypes or definitions.
Neuron C contains additional reserved words and syntax not found in
ANSI C. See the the list of reserved words.
Neuron C supports binary constants in addition to octal and hexadecimal.
Binary constants are specified as 0b 0b1101 equals decimal 13.
Neuron C supports the // comment style from C++, in addition to the
traditional /* */ C coment style. In the // style, two slashes (//) begin a comment. The comment is terminated by the end of the line, without further punctuation.
C code /* An ANSI C and NEURON C comment */ C code // A line-style NEURON C comment
for a complete and detailed list.
, on page 15).
Neuron C Reference Guide
for the syntax summary and
<binary_number>
. For example,
Neuron C
2,
Focusing
The main( ) construct is not used. Instead, a Neuron C program’s
executable objects consist of when statements in addition to functions. A thread of execution always begins with a when statement, as described in
2,
Chapter
Neuron C does not support multiple source files in separate compilation
units (however, the #include directive is supported).
The ANSI C preprocessor directives #if, #elif, and #line are not supported.
However, #ifdef, #ifndef, #else, and #endif are supported.
The Neuron C implementation of the #error directive requires a double-
quoted string for the error message; the ANSI C directive does not.
See Appendix 237 for a description of how the Neuron C language conforms to “implementation­specific” aspects of the ISO and ANSI C language definitions.
Focusing on a Single Device
D,
Neuron C Language Implementation Characteristics
, on page 15.
, on page
14 Overview
2

Focusing on a Single Device

This chapter describes the Neuron C event scheduler and I/O objects. The concepts of introduced. I/O and timer objects, and I/O functions.
Objects that can be defined for each Neuron C application include
timers variables
in Chapter 4;
application messages
and
, described in Chapter 3;
predefined events
Code examples in this chapter illustrate the use of events,
input/output (I/O) objects
functional blocks
, described in Chapter 6.
and
user-defined events
, described here;
configuration properties
, described in Chapter 5; and
network
, described
are
Neuron C Programmer’s Guide 15

What Happens on a Single Device?

In this chapter, you begin to learn about programming a Neuron Chip or Smart Transceiver by focusing first on a single device. Each Neuron Chip and each Smart Transceiver has standard firmware, called the hardware support that implement a scheduler, timers, and I/O device drivers and interfaces. Series 5000 chips also provide hardware support for interrupts; see
Interrupts
The Neuron C language includes predefined objects that provide access to these firmware features. These objects are described briefly here, and in more detail later in this chapter:
on page 153 for more information.
Neuron firmware
, and
The Neuron firmware's
application program. This chapter explains how to use the Neuron C language to define events and tasks, how the scheduler evaluates nonpriority events, and how you can define priority events.
The Neuron C language offers two types of
second timers. These timers can be used to affect the scheduling of tasks, as described in
A number of
ANSI C. These I/O objects, as well as related I/O functions and events, are described in

The Scheduler

The scheduling of application program tasks is event driven: when a given condition becomes TRUE, a body of code (called a condition is executed. The scheduler allows you to define tasks that run as the result of certain events, such as a change in the state of an input pin, receiving a new value for a network variable, or the expiration of a timer. You can also specify certain tasks as priority
Priority When Clauses
(see specify interrupt tasks that are serviced independently of the scheduler; see
Interrupts
on page 153 for more information.
event scheduler
Timers
I/O objects
on page 25.
can be declared using Neuron C extensions to
Input/Output
on page 23). Series 5000 chips also allow you to
on page 27.
tasks, so that they receive preferential service
handles task scheduling for the
timer
objects: millisecond and
task
) associated with that

When Clauses

Events are defined through when clauses. A when clause contains an expression
task
that, if evaluated as TRUE, causes the body of code (the expression to be executed to completion. Multiple when clauses can be associated with a single task. A simple when clause and its associated task are shown below. The when clause or clauses and the associated task are frequently referred to as one entity known as a
when (timer_expires(led timer))
when task
or a
when statement
{
// Turn off the LED
io_out(io_led, OFF);
}
16 Focusing on a Single Device
) following the
.
when clause
task
In this example above, when the led_timer application timer (definition not shown in this example) expires, the body of code (the task) that follows the when clause is executed to turn off the specified I/O object, io_led (also defined elsewhere in the program). After this task has been executed, the timer_expires event is automatically cleared. Its task is then ignored until the LED timer expires again and the when clause again evaluates to TRUE.
The following examples demonstrate various ways of using tasks and events.
7,
More information about tasks and events can be found in Chapter
Features
The when clauses cannot be nested. For example, the following nested when clause is not valid:
, on page 145, and Figure 14 on page 147.
when (reset)
when (io_changes(io_switch))
when (!timer_expires)
when (flush_completes && (y == 5))
when (x == 3)
{
// Turn on the LED and start the timer
. . .
}
when (io_changes(io_switch))
{
when (x == 3) { // Can't nest!
...
}
}
Additional
An equivalent result may be achieved by testing the event with an if statement:
when (io_changes(io_switch))
{
if (x == 3) {
...
}
}

When Statement

The syntax for a when statement (the when clause or clauses plus the associated task) is:
when-clause
[when-clause ... ]
task
The syntax for
[priority] [preempt_safe] when (
priority Forces evaluation of the following when clause each time the
preempt_safe Allows the scheduler to execute the associated when task
when-clause
scheduler runs. See
even if the application is in preemption mode. See the discussions on preemption mode in Chapter
Application Messages
is:
event
)
Priority When Clauses
6,
How Devices Communicate Using
, on page 117.
on page 23.
Neuron C Programmer’s Guide 17
event
This expression is either a predefined event (see the following section)
or any valid Neuron C expression (which can contain a predefined event). Predefined events as well as expressions are enclosed in parentheses. One or more when clauses can be associated with the same task.
task
A Neuron C compound statement, consisting of a series of Neuron C
declarations and statements, enclosed in braces, which are identical to those found in a Neuron C function definition. The task is identical to the body of a void function (that is, it cannot return a value). A return statement can be used to terminate execution of the task but is not required.

Types of Events Used in When Clauses

The events defined in a when clause fall into two general categories: predefined events and user-defined events. compiler. Examples of predefined events include input pin state changes, network variable changes, timer expiration, and message reception.
defined events
to a Boolean value.
The distinction between user-defined events and predefined events is not critical. Use predefined events whenever possible, because they require less code space.
There is one exception to the statement that a when clause can be any valid C expression. The offline, online, and wink predefined events must appear by themselves if used. All other predefined events may be combined into any arbitrary expressions. This restriction only applies to when clauses.
can be any valid Neuron C expression that evaluates or converts

Predefined events

use keywords built into the
User-
Examples:
when (msg_arrives) // O.K.
when (msg_arrives && flag == TRUE) // O.K.
when (online) // O.K.
when (online && flag == TRUE) // Not permitted.
Predefined Events
The timer_expires event shown earlier is one type of predefined event. Table 4 lists other predefined events that are represented by unique keywords.
Predefined Event Where Described in This Manual
flush_completes Chapter 7
io_changes this chapter
io_in_ready this chapter
io_out_ready this chapter
io_update_occurs this chapter
Table 4. Predefined Events
18 Focusing on a Single Device
Loading...
+ 238 hidden pages